]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Add js2-language-version check for template literals
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20141118
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 (defvar js2-harmony-externs
207 (mapcar 'symbol-name
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
211
212 ;;; Variables
213
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
219
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
226 :group 'js2-mode
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
231
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
234
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
237 :group 'languages)
238
239 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
240 (numberp c-basic-offset))
241 c-basic-offset
242 4)
243 "Number of spaces to indent nested statements.
244 Similar to `c-basic-offset'."
245 :group 'js2-mode
246 :type 'integer)
247 (js2-mark-safe-local 'js2-basic-offset 'integerp)
248
249 (defcustom js2-bounce-indent-p nil
250 "Non-nil to have indent-line function choose among alternatives.
251 If nil, the indent-line function will indent to a predetermined column
252 based on heuristic guessing. If non-nil, then if the current line is
253 already indented to that predetermined column, indenting will choose
254 another likely column and indent to that spot. Repeated invocation of
255 the indent-line function will cycle among the computed alternatives.
256 See the function `js2-bounce-indent' for details. When it is non-nil,
257 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
258 :type 'boolean
259 :group 'js2-mode)
260
261 (defcustom js2-pretty-multiline-declarations t
262 "Non-nil to line up multiline declarations vertically:
263
264 var a = 10,
265 b = 20,
266 c = 30;
267
268 If the value is not `all', and the first assigned value in
269 declaration is a function/array/object literal spanning several
270 lines, it won't be indented additionally:
271
272 var o = { var bar = 2,
273 foo: 3 vs. o = {
274 }, foo: 3
275 bar = 2; };"
276 :group 'js2-mode
277 :type 'symbol)
278 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
279
280 (defcustom js2-indent-switch-body nil
281 "When nil, case labels are indented on the same level as the
282 containing switch statement. Otherwise, all lines inside
283 switch statement body are indented one additional level."
284 :type 'boolean
285 :group 'js2-mode)
286 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
287
288 (defcustom js2-idle-timer-delay 0.2
289 "Delay in secs before re-parsing after user makes changes.
290 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
291 :type 'number
292 :group 'js2-mode)
293 (make-variable-buffer-local 'js2-idle-timer-delay)
294
295 (defcustom js2-dynamic-idle-timer-adjust 0
296 "Positive to adjust `js2-idle-timer-delay' based on file size.
297 The idea is that for short files, parsing is faster so we can be
298 more responsive to user edits without interfering with editing.
299 The buffer length in characters (typically bytes) is divided by
300 this value and used to multiply `js2-idle-timer-delay' for the
301 buffer. For example, a 21k file and 10k adjust yields 21k/10k
302 == 2, so js2-idle-timer-delay is multiplied by 2.
303 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
304 `js2-idle-timer-delay' is not dependent on the file size."
305 :type 'number
306 :group 'js2-mode)
307
308 (defcustom js2-concat-multiline-strings t
309 "When non-nil, `js2-line-break' in mid-string will make it a
310 string concatenation. When `eol', the '+' will be inserted at the
311 end of the line, otherwise, at the beginning of the next line."
312 :type '(choice (const t) (const eol) (const nil))
313 :group 'js2-mode)
314
315 (defcustom js2-mode-show-parse-errors t
316 "True to highlight parse errors."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-mode-show-strict-warnings t
321 "Non-nil to emit Ecma strict-mode warnings.
322 Some of the warnings can be individually disabled by other flags,
323 even if this flag is non-nil."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-trailing-comma-warning t
328 "Non-nil to warn about trailing commas in array literals.
329 Ecma-262-5.1 allows them, but older versions of IE raise an error."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-var-redeclaration-warning t
366 "Non-nil to warn about redeclaring variables in a script or function."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-var-hides-function-arg-warning t
371 "Non-nil to warn about a var decl hiding a function argument."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-skip-preprocessor-directives nil
376 "Non-nil to treat lines beginning with # as comments.
377 Useful for viewing Mozilla JavaScript source code."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-language-version 200
382 "Configures what JavaScript language version to recognize.
383 Currently versions 150, 160, 170, 180 and 200 are supported,
384 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
385 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
386 yield, and Array comprehensions, and 1.8 adds function closures."
387 :type 'integer
388 :group 'js2-mode)
389
390 (defcustom js2-instanceof-has-side-effects nil
391 "If non-nil, treats the instanceof operator as having side effects.
392 This is useful for xulrunner apps."
393 :type 'boolean
394 :group 'js2-mode)
395
396 (defcustom js2-move-point-on-right-click t
397 "Non-nil to move insertion point when you right-click.
398 This makes right-click context menu behavior a bit more intuitive,
399 since menu operations generally apply to the point. The exception
400 is if there is a region selection, in which case the point does -not-
401 move, so cut/copy/paste can work properly.
402
403 Note that IntelliJ moves the point, and Eclipse leaves it alone,
404 so this behavior is customizable."
405 :group 'js2-mode
406 :type 'boolean)
407
408 (defcustom js2-allow-rhino-new-expr-initializer t
409 "Non-nil to support a Rhino's experimental syntactic construct.
410
411 Rhino supports the ability to follow a `new' expression with an object
412 literal, which is used to set additional properties on the new object
413 after calling its constructor. Syntax:
414
415 new <expr> [ ( arglist ) ] [initializer]
416
417 Hence, this expression:
418
419 new Object {a: 1, b: 2}
420
421 results in an Object with properties a=1 and b=2. This syntax is
422 apparently not configurable in Rhino - it's currently always enabled,
423 as of Rhino version 1.7R2."
424 :type 'boolean
425 :group 'js2-mode)
426
427 (defcustom js2-allow-member-expr-as-function-name nil
428 "Non-nil to support experimental Rhino syntax for function names.
429
430 Rhino supports an experimental syntax configured via the Rhino Context
431 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
432
433 function <member-expr> ( [ arg-list ] ) { <body> }
434
435 Where member-expr is a non-parenthesized 'member expression', which
436 is anything at the grammar level of a new-expression or lower, meaning
437 any expression that does not involve infix or unary operators.
438
439 When <member-expr> is not a simple identifier, then it is syntactic
440 sugar for assigning the anonymous function to the <member-expr>. Hence,
441 this code:
442
443 function a.b().c[2] (x, y) { ... }
444
445 is rewritten as:
446
447 a.b().c[2] = function(x, y) {...}
448
449 which doesn't seem particularly useful, but Rhino permits it."
450 :type 'boolean
451 :group 'js2-mode)
452
453 ;; scanner variables
454
455 (defmacro js2-deflocal (name value &optional comment)
456 "Define a buffer-local variable NAME with VALUE and COMMENT."
457 `(progn
458 (defvar ,name ,value ,comment)
459 (make-variable-buffer-local ',name)))
460
461 (defvar js2-EOF_CHAR -1
462 "Represents end of stream. Distinct from js2-EOF token type.")
463
464 ;; I originally used symbols to represent tokens, but Rhino uses
465 ;; ints and then sets various flag bits in them, so ints it is.
466 ;; The upshot is that we need a `js2-' prefix in front of each name.
467 (defvar js2-ERROR -1)
468 (defvar js2-EOF 0)
469 (defvar js2-EOL 1)
470 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
471 (defvar js2-LEAVEWITH 3)
472 (defvar js2-RETURN 4)
473 (defvar js2-GOTO 5)
474 (defvar js2-IFEQ 6)
475 (defvar js2-IFNE 7)
476 (defvar js2-SETNAME 8)
477 (defvar js2-BITOR 9)
478 (defvar js2-BITXOR 10)
479 (defvar js2-BITAND 11)
480 (defvar js2-EQ 12)
481 (defvar js2-NE 13)
482 (defvar js2-LT 14)
483 (defvar js2-LE 15)
484 (defvar js2-GT 16)
485 (defvar js2-GE 17)
486 (defvar js2-LSH 18)
487 (defvar js2-RSH 19)
488 (defvar js2-URSH 20)
489 (defvar js2-ADD 21) ; infix plus
490 (defvar js2-SUB 22) ; infix minus
491 (defvar js2-MUL 23)
492 (defvar js2-DIV 24)
493 (defvar js2-MOD 25)
494 (defvar js2-NOT 26)
495 (defvar js2-BITNOT 27)
496 (defvar js2-POS 28) ; unary plus
497 (defvar js2-NEG 29) ; unary minus
498 (defvar js2-NEW 30)
499 (defvar js2-DELPROP 31)
500 (defvar js2-TYPEOF 32)
501 (defvar js2-GETPROP 33)
502 (defvar js2-GETPROPNOWARN 34)
503 (defvar js2-SETPROP 35)
504 (defvar js2-GETELEM 36)
505 (defvar js2-SETELEM 37)
506 (defvar js2-CALL 38)
507 (defvar js2-NAME 39) ; an identifier
508 (defvar js2-NUMBER 40)
509 (defvar js2-STRING 41)
510 (defvar js2-NULL 42)
511 (defvar js2-THIS 43)
512 (defvar js2-FALSE 44)
513 (defvar js2-TRUE 45)
514 (defvar js2-SHEQ 46) ; shallow equality (===)
515 (defvar js2-SHNE 47) ; shallow inequality (!==)
516 (defvar js2-REGEXP 48)
517 (defvar js2-BINDNAME 49)
518 (defvar js2-THROW 50)
519 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
520 (defvar js2-IN 52)
521 (defvar js2-INSTANCEOF 53)
522 (defvar js2-LOCAL_LOAD 54)
523 (defvar js2-GETVAR 55)
524 (defvar js2-SETVAR 56)
525 (defvar js2-CATCH_SCOPE 57)
526 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
527 (defvar js2-ENUM_INIT_VALUES 59)
528 (defvar js2-ENUM_INIT_ARRAY 60)
529 (defvar js2-ENUM_NEXT 61)
530 (defvar js2-ENUM_ID 62)
531 (defvar js2-THISFN 63)
532 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
533 (defvar js2-ARRAYLIT 65) ; array literal
534 (defvar js2-OBJECTLIT 66) ; object literal
535 (defvar js2-GET_REF 67) ; *reference
536 (defvar js2-SET_REF 68) ; *reference = something
537 (defvar js2-DEL_REF 69) ; delete reference
538 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
539 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
540 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
541
542 ;; XML support
543 (defvar js2-DEFAULTNAMESPACE 73)
544 (defvar js2-ESCXMLATTR 74)
545 (defvar js2-ESCXMLTEXT 75)
546 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
547 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
548 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
549 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
550
551 (defvar js2-first-bytecode js2-ENTERWITH)
552 (defvar js2-last-bytecode js2-REF_NS_NAME)
553
554 (defvar js2-TRY 80)
555 (defvar js2-SEMI 81) ; semicolon
556 (defvar js2-LB 82) ; left and right brackets
557 (defvar js2-RB 83)
558 (defvar js2-LC 84) ; left and right curly-braces
559 (defvar js2-RC 85)
560 (defvar js2-LP 86) ; left and right parens
561 (defvar js2-RP 87)
562 (defvar js2-COMMA 88) ; comma operator
563
564 (defvar js2-ASSIGN 89) ; simple assignment (=)
565 (defvar js2-ASSIGN_BITOR 90) ; |=
566 (defvar js2-ASSIGN_BITXOR 91) ; ^=
567 (defvar js2-ASSIGN_BITAND 92) ; &=
568 (defvar js2-ASSIGN_LSH 93) ; <<=
569 (defvar js2-ASSIGN_RSH 94) ; >>=
570 (defvar js2-ASSIGN_URSH 95) ; >>>=
571 (defvar js2-ASSIGN_ADD 96) ; +=
572 (defvar js2-ASSIGN_SUB 97) ; -=
573 (defvar js2-ASSIGN_MUL 98) ; *=
574 (defvar js2-ASSIGN_DIV 99) ; /=
575 (defvar js2-ASSIGN_MOD 100) ; %=
576
577 (defvar js2-first-assign js2-ASSIGN)
578 (defvar js2-last-assign js2-ASSIGN_MOD)
579
580 (defvar js2-HOOK 101) ; conditional (?:)
581 (defvar js2-COLON 102)
582 (defvar js2-OR 103) ; logical or (||)
583 (defvar js2-AND 104) ; logical and (&&)
584 (defvar js2-INC 105) ; increment/decrement (++ --)
585 (defvar js2-DEC 106)
586 (defvar js2-DOT 107) ; member operator (.)
587 (defvar js2-FUNCTION 108) ; function keyword
588 (defvar js2-EXPORT 109) ; export keyword
589 (defvar js2-IMPORT 110) ; import keyword
590 (defvar js2-IF 111) ; if keyword
591 (defvar js2-ELSE 112) ; else keyword
592 (defvar js2-SWITCH 113) ; switch keyword
593 (defvar js2-CASE 114) ; case keyword
594 (defvar js2-DEFAULT 115) ; default keyword
595 (defvar js2-WHILE 116) ; while keyword
596 (defvar js2-DO 117) ; do keyword
597 (defvar js2-FOR 118) ; for keyword
598 (defvar js2-BREAK 119) ; break keyword
599 (defvar js2-CONTINUE 120) ; continue keyword
600 (defvar js2-VAR 121) ; var keyword
601 (defvar js2-WITH 122) ; with keyword
602 (defvar js2-CATCH 123) ; catch keyword
603 (defvar js2-FINALLY 124) ; finally keyword
604 (defvar js2-VOID 125) ; void keyword
605 (defvar js2-RESERVED 126) ; reserved keywords
606
607 (defvar js2-EMPTY 127)
608
609 ;; Types used for the parse tree - never returned by scanner.
610
611 (defvar js2-BLOCK 128) ; statement block
612 (defvar js2-LABEL 129) ; label
613 (defvar js2-TARGET 130)
614 (defvar js2-LOOP 131)
615 (defvar js2-EXPR_VOID 132) ; expression statement in functions
616 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
617 (defvar js2-JSR 134)
618 (defvar js2-SCRIPT 135) ; top-level node for entire script
619 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
620 (defvar js2-USE_STACK 137)
621 (defvar js2-SETPROP_OP 138) ; x.y op= something
622 (defvar js2-SETELEM_OP 139) ; x[y] op= something
623 (defvar js2-LOCAL_BLOCK 140)
624 (defvar js2-SET_REF_OP 141) ; *reference op= something
625
626 ;; For XML support:
627 (defvar js2-DOTDOT 142) ; member operator (..)
628 (defvar js2-COLONCOLON 143) ; namespace::name
629 (defvar js2-XML 144) ; XML type
630 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
631 (defvar js2-XMLATTR 146) ; @
632 (defvar js2-XMLEND 147)
633
634 ;; Optimizer-only tokens
635 (defvar js2-TO_OBJECT 148)
636 (defvar js2-TO_DOUBLE 149)
637
638 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
639 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
640 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
641 (defvar js2-CONST 153)
642 (defvar js2-SETCONST 154)
643 (defvar js2-SETCONSTVAR 155)
644 (defvar js2-ARRAYCOMP 156)
645 (defvar js2-LETEXPR 157)
646 (defvar js2-WITHEXPR 158)
647 (defvar js2-DEBUGGER 159)
648
649 (defvar js2-COMMENT 160)
650 (defvar js2-TRIPLEDOT 161) ; for rest parameter
651 (defvar js2-ARROW 162) ; function arrow (=>)
652 (defvar js2-CLASS 163)
653 (defvar js2-EXTENDS 164)
654 (defvar js2-STATIC 165)
655 (defvar js2-SUPER 166)
656 (defvar js2-TEMPLATE_HEAD 167) ; part of template literal before substitution
657 (defvar js2-NO_SUBS_TEMPLATE 168) ; template literal without substitutions
658 (defvar js2-TAGGED_TEMPLATE 169) ; tagged template literal
659
660 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
661
662 (defconst js2-debug-print-trees nil)
663
664 ;; Rhino accepts any string or stream as input. Emacs character
665 ;; processing works best in buffers, so we'll assume the input is a
666 ;; buffer. JavaScript strings can be copied into temp buffers before
667 ;; scanning them.
668
669 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
670 ;; They're the Emacs equivalent of instance variables, more or less.
671
672 (js2-deflocal js2-ts-dirty-line nil
673 "Token stream buffer-local variable.
674 Indicates stuff other than whitespace since start of line.")
675
676 (js2-deflocal js2-ts-hit-eof nil
677 "Token stream buffer-local variable.")
678
679 ;; FIXME: Unused.
680 (js2-deflocal js2-ts-line-start 0
681 "Token stream buffer-local variable.")
682
683 (js2-deflocal js2-ts-lineno 1
684 "Token stream buffer-local variable.")
685
686 ;; FIXME: Unused.
687 (js2-deflocal js2-ts-line-end-char -1
688 "Token stream buffer-local variable.")
689
690 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
691 "Token stream buffer-local variable.
692 Current scan position.")
693
694 ;; FIXME: Unused.
695 (js2-deflocal js2-ts-is-xml-attribute nil
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-xml-is-tag-content nil
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-xml-open-tags-count 0
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-string-buffer nil
705 "Token stream buffer-local variable.
706 List of chars built up while scanning various tokens.")
707
708 (defstruct (js2-token
709 (:constructor nil)
710 (:constructor make-js2-token (beg)))
711 "Value returned from the token stream."
712 (type js2-EOF)
713 (beg 1)
714 (end -1)
715 (string "")
716 number
717 regexp-flags
718 comment-type
719 follows-eol-p)
720
721 (defstruct (js2-ts-state
722 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
723 (cursor js2-ts-cursor)
724 (tokens (copy-sequence js2-ti-tokens))
725 (tokens-cursor js2-ti-tokens-cursor)
726 (lookahead js2-ti-lookahead))))
727 lineno
728 cursor
729 tokens
730 tokens-cursor
731 lookahead)
732
733 ;;; Parser variables
734
735 (js2-deflocal js2-parsed-errors nil
736 "List of errors produced during scanning/parsing.")
737
738 (js2-deflocal js2-parsed-warnings nil
739 "List of warnings produced during scanning/parsing.")
740
741 (js2-deflocal js2-recover-from-parse-errors t
742 "Non-nil to continue parsing after a syntax error.
743
744 In recovery mode, the AST will be built in full, and any error
745 nodes will be flagged with appropriate error information. If
746 this flag is nil, a syntax error will result in an error being
747 signaled.
748
749 The variable is automatically buffer-local, because different
750 modes that use the parser will need different settings.")
751
752 (js2-deflocal js2-parse-hook nil
753 "List of callbacks for receiving parsing progress.")
754
755 (defvar js2-parse-finished-hook nil
756 "List of callbacks to notify when parsing finishes.
757 Not called if parsing was interrupted.")
758
759 (js2-deflocal js2-is-eval-code nil
760 "True if we're evaluating code in a string.
761 If non-nil, the tokenizer will record the token text, and the AST nodes
762 will record their source text. Off by default for IDE modes, since the
763 text is available in the buffer.")
764
765 (defvar js2-parse-ide-mode t
766 "Non-nil if the parser is being used for `js2-mode'.
767 If non-nil, the parser will set text properties for fontification
768 and the syntax table. The value should be nil when using the
769 parser as a frontend to an interpreter or byte compiler.")
770
771 ;;; Parser instance variables (buffer-local vars for js2-parse)
772
773 (defconst js2-ti-after-eol (lsh 1 16)
774 "Flag: first token of the source line.")
775
776 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
777
778 (js2-deflocal js2-compiler-generate-debug-info t)
779 (js2-deflocal js2-compiler-use-dynamic-scope nil)
780 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
781 (js2-deflocal js2-compiler-xml-available t)
782 (js2-deflocal js2-compiler-optimization-level 0)
783 (js2-deflocal js2-compiler-generating-source t)
784 (js2-deflocal js2-compiler-strict-mode nil)
785 (js2-deflocal js2-compiler-report-warning-as-error nil)
786 (js2-deflocal js2-compiler-generate-observer-count nil)
787 (js2-deflocal js2-compiler-activation-names nil)
788
789 ;; SKIP: sourceURI
790
791 ;; There's a compileFunction method in Context.java - may need it.
792 (js2-deflocal js2-called-by-compile-function nil
793 "True if `js2-parse' was called by `js2-compile-function'.
794 Will only be used when we finish implementing the interpreter.")
795
796 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
797
798 ;; SKIP: node factory - we're going to just call functions directly,
799 ;; and eventually go to a unified AST format.
800
801 (js2-deflocal js2-nesting-of-function 0)
802
803 (js2-deflocal js2-recorded-identifiers nil
804 "Tracks identifiers found during parsing.")
805
806 (js2-deflocal js2-is-in-destructuring nil
807 "True while parsing destructuring expression.")
808
809 (defcustom js2-global-externs nil
810 "A list of any extern names you'd like to consider always declared.
811 This list is global and is used by all `js2-mode' files.
812 You can create buffer-local externs list using `js2-additional-externs'.
813
814 There is also a buffer-local variable `js2-default-externs',
815 which is initialized by default to include the Ecma-262 externs
816 and the standard browser externs. The three lists are all
817 checked during highlighting."
818 :type 'list
819 :group 'js2-mode)
820
821 (js2-deflocal js2-default-externs nil
822 "Default external declarations.
823
824 These are currently only used for highlighting undeclared variables,
825 which only worries about top-level (unqualified) references.
826 As js2-mode's processing improves, we will flesh out this list.
827
828 The initial value is set to `js2-ecma-262-externs', unless some
829 of the `js2-include-?-externs' variables are set to t, in which
830 case the browser, Rhino and/or Node.js externs are also included.
831
832 See `js2-additional-externs' for more information.")
833
834 (defcustom js2-include-browser-externs t
835 "Non-nil to include browser externs in the master externs list.
836 If you work on JavaScript files that are not intended for browsers,
837 such as Mozilla Rhino server-side JavaScript, set this to nil.
838 See `js2-additional-externs' for more information about externs."
839 :type 'boolean
840 :group 'js2-mode)
841
842 (defcustom js2-include-rhino-externs nil
843 "Non-nil to include Mozilla Rhino externs in the master externs list.
844 See `js2-additional-externs' for more information about externs."
845 :type 'boolean
846 :group 'js2-mode)
847
848 (defcustom js2-include-node-externs nil
849 "Non-nil to include Node.js externs in the master externs list.
850 See `js2-additional-externs' for more information about externs."
851 :type 'boolean
852 :group 'js2-mode)
853
854 (js2-deflocal js2-additional-externs nil
855 "A buffer-local list of additional external declarations.
856 It is used to decide whether variables are considered undeclared
857 for purposes of highlighting.
858
859 Each entry is a Lisp string. The string should be the fully qualified
860 name of an external entity. All externs should be added to this list,
861 so that as js2-mode's processing improves it can take advantage of them.
862
863 You may want to declare your externs in three ways.
864 First, you can add externs that are valid for all your JavaScript files.
865 You should probably do this by adding them to `js2-global-externs', which
866 is a global list used for all js2-mode files.
867
868 Next, you can add a function to `js2-init-hook' that adds additional
869 externs appropriate for the specific file, perhaps based on its path.
870 These should go in `js2-additional-externs', which is buffer-local.
871
872 Third, you can use JSLint's global declaration, as long as
873 `js2-include-jslint-globals' is non-nil, which see.
874
875 Finally, you can add a function to `js2-post-parse-callbacks',
876 which is called after parsing completes, and `js2-mode-ast' is bound to
877 the root of the parse tree. At this stage you can set up an AST
878 node visitor using `js2-visit-ast' and examine the parse tree
879 for specific import patterns that may imply the existence of
880 other externs, possibly tied to your build system. These should also
881 be added to `js2-additional-externs'.
882
883 Your post-parse callback may of course also use the simpler and
884 faster (but perhaps less robust) approach of simply scanning the
885 buffer text for your imports, using regular expressions.")
886
887 ;; SKIP: decompiler
888 ;; SKIP: encoded-source
889
890 ;;; The following variables are per-function and should be saved/restored
891 ;;; during function parsing...
892
893 (js2-deflocal js2-current-script-or-fn nil)
894 (js2-deflocal js2-current-scope nil)
895 (js2-deflocal js2-nesting-of-with 0)
896 (js2-deflocal js2-label-set nil
897 "An alist mapping label names to nodes.")
898
899 (js2-deflocal js2-loop-set nil)
900 (js2-deflocal js2-loop-and-switch-set nil)
901 (js2-deflocal js2-has-return-value nil)
902 (js2-deflocal js2-end-flags 0)
903
904 ;;; ...end of per function variables
905
906 ;; These flags enumerate the possible ways a statement/function can
907 ;; terminate. These flags are used by endCheck() and by the Parser to
908 ;; detect inconsistent return usage.
909 ;;
910 ;; END_UNREACHED is reserved for code paths that are assumed to always be
911 ;; able to execute (example: throw, continue)
912 ;;
913 ;; END_DROPS_OFF indicates if the statement can transfer control to the
914 ;; next one. Statement such as return dont. A compound statement may have
915 ;; some branch that drops off control to the next statement.
916 ;;
917 ;; END_RETURNS indicates that the statement can return (without arguments)
918 ;; END_RETURNS_VALUE indicates that the statement can return a value.
919 ;;
920 ;; A compound statement such as
921 ;; if (condition) {
922 ;; return value;
923 ;; }
924 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
925
926 (defconst js2-end-unreached #x0)
927 (defconst js2-end-drops-off #x1)
928 (defconst js2-end-returns #x2)
929 (defconst js2-end-returns-value #x4)
930
931 ;; Rhino awkwardly passes a statementLabel parameter to the
932 ;; statementHelper() function, the main statement parser, which
933 ;; is then used by quite a few of the sub-parsers. We just make
934 ;; it a buffer-local variable and make sure it's cleaned up properly.
935 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
936
937 ;; Similarly, Rhino passes an inForInit boolean through about half
938 ;; the expression parsers. We use a dynamically-scoped variable,
939 ;; which makes it easier to funcall the parsers individually without
940 ;; worrying about whether they take the parameter or not.
941 (js2-deflocal js2-in-for-init nil)
942 (js2-deflocal js2-temp-name-counter 0)
943 (js2-deflocal js2-parse-stmt-count 0)
944
945 (defsubst js2-get-next-temp-name ()
946 (format "$%d" (incf js2-temp-name-counter)))
947
948 (defvar js2-parse-interruptable-p t
949 "Set this to nil to force parse to continue until finished.
950 This will mostly be useful for interpreters.")
951
952 (defvar js2-statements-per-pause 50
953 "Pause after this many statements to check for user input.
954 If user input is pending, stop the parse and discard the tree.
955 This makes for a smoother user experience for large files.
956 You may have to wait a second or two before the highlighting
957 and error-reporting appear, but you can always type ahead if
958 you wish. This appears to be more or less how Eclipse, IntelliJ
959 and other editors work.")
960
961 (js2-deflocal js2-record-comments t
962 "Instructs the scanner to record comments in `js2-scanned-comments'.")
963
964 (js2-deflocal js2-scanned-comments nil
965 "List of all comments from the current parse.")
966
967 (defcustom js2-mode-indent-inhibit-undo nil
968 "Non-nil to disable collection of Undo information when indenting lines.
969 Some users have requested this behavior. It's nil by default because
970 other Emacs modes don't work this way."
971 :type 'boolean
972 :group 'js2-mode)
973
974 (defcustom js2-mode-indent-ignore-first-tab nil
975 "If non-nil, ignore first TAB keypress if we look indented properly.
976 It's fairly common for users to navigate to an already-indented line
977 and press TAB for reassurance that it's been indented. For this class
978 of users, we want the first TAB press on a line to be ignored if the
979 line is already indented to one of the precomputed alternatives.
980
981 This behavior is only partly implemented. If you TAB-indent a line,
982 navigate to another line, and then navigate back, it fails to clear
983 the last-indented variable, so it thinks you've already hit TAB once,
984 and performs the indent. A full solution would involve getting on the
985 point-motion hooks for the entire buffer. If we come across another
986 use cases that requires watching point motion, I'll consider doing it.
987
988 If you set this variable to nil, then the TAB key will always change
989 the indentation of the current line, if more than one alternative
990 indentation spot exists."
991 :type 'boolean
992 :group 'js2-mode)
993
994 (defvar js2-indent-hook nil
995 "A hook for user-defined indentation rules.
996
997 Functions on this hook should expect two arguments: (LIST INDEX)
998 The LIST argument is the list of computed indentation points for
999 the current line. INDEX is the list index of the indentation point
1000 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1001 indent function is not going to change the current line indentation.
1002
1003 If a hook function on this list returns a non-nil value, then
1004 `js2-bounce-indent' assumes the hook function has performed its own
1005 indentation, and will do nothing. If all hook functions on the list
1006 return nil, then `js2-bounce-indent' will use its computed indentation
1007 and reindent the line.
1008
1009 When hook functions on this hook list are called, the variable
1010 `js2-mode-ast' may or may not be set, depending on whether the
1011 parse tree is available. If the variable is nil, you can pass a
1012 callback to `js2-mode-wait-for-parse', and your callback will be
1013 called after the new parse tree is built. This can take some time
1014 in large files.")
1015
1016 (defface js2-warning
1017 `((((class color) (background light))
1018 (:underline "orange"))
1019 (((class color) (background dark))
1020 (:underline "orange"))
1021 (t (:underline t)))
1022 "Face for JavaScript warnings."
1023 :group 'js2-mode)
1024
1025 (defface js2-error
1026 `((((class color) (background light))
1027 (:foreground "red"))
1028 (((class color) (background dark))
1029 (:foreground "red"))
1030 (t (:foreground "red")))
1031 "Face for JavaScript errors."
1032 :group 'js2-mode)
1033
1034 (defface js2-jsdoc-tag
1035 '((t :foreground "SlateGray"))
1036 "Face used to highlight @whatever tags in jsdoc comments."
1037 :group 'js2-mode)
1038
1039 (defface js2-jsdoc-type
1040 '((t :foreground "SteelBlue"))
1041 "Face used to highlight {FooBar} types in jsdoc comments."
1042 :group 'js2-mode)
1043
1044 (defface js2-jsdoc-value
1045 '((t :foreground "PeachPuff3"))
1046 "Face used to highlight tag values in jsdoc comments."
1047 :group 'js2-mode)
1048
1049 (defface js2-function-param
1050 '((t :foreground "SeaGreen"))
1051 "Face used to highlight function parameters in javascript."
1052 :group 'js2-mode)
1053
1054 (defface js2-function-call
1055 '((t :inherit default))
1056 "Face used to highlight function name in calls."
1057 :group 'js2-mode)
1058
1059 (defface js2-instance-member
1060 '((t :foreground "DarkOrchid"))
1061 "Face used to highlight instance variables in javascript.
1062 Not currently used."
1063 :group 'js2-mode)
1064
1065 (defface js2-private-member
1066 '((t :foreground "PeachPuff3"))
1067 "Face used to highlight calls to private methods in javascript.
1068 Not currently used."
1069 :group 'js2-mode)
1070
1071 (defface js2-private-function-call
1072 '((t :foreground "goldenrod"))
1073 "Face used to highlight calls to private functions in javascript.
1074 Not currently used."
1075 :group 'js2-mode)
1076
1077 (defface js2-jsdoc-html-tag-name
1078 '((((class color) (min-colors 88) (background light))
1079 (:foreground "rosybrown"))
1080 (((class color) (min-colors 8) (background dark))
1081 (:foreground "yellow"))
1082 (((class color) (min-colors 8) (background light))
1083 (:foreground "magenta")))
1084 "Face used to highlight jsdoc html tag names"
1085 :group 'js2-mode)
1086
1087 (defface js2-jsdoc-html-tag-delimiter
1088 '((((class color) (min-colors 88) (background light))
1089 (:foreground "dark khaki"))
1090 (((class color) (min-colors 8) (background dark))
1091 (:foreground "green"))
1092 (((class color) (min-colors 8) (background light))
1093 (:foreground "green")))
1094 "Face used to highlight brackets in jsdoc html tags."
1095 :group 'js2-mode)
1096
1097 (defface js2-external-variable
1098 '((t :foreground "orange"))
1099 "Face used to highlight undeclared variable identifiers.")
1100
1101 (defcustom js2-init-hook nil
1102 "List of functions to be called after `js2-mode' or
1103 `js2-minor-mode' has initialized all variables, before parsing
1104 the buffer for the first time."
1105 :type 'hook
1106 :group 'js2-mode
1107 :version "20130608")
1108
1109 (defcustom js2-post-parse-callbacks nil
1110 "List of callback functions invoked after parsing finishes.
1111 Currently, the main use for this function is to add synthetic
1112 declarations to `js2-recorded-identifiers', which see."
1113 :type 'hook
1114 :group 'js2-mode)
1115
1116 (defcustom js2-build-imenu-callbacks nil
1117 "List of functions called during Imenu index generation.
1118 It's a good place to add additional entries to it, using
1119 `js2-record-imenu-entry'."
1120 :type 'hook
1121 :group 'js2-mode)
1122
1123 (defcustom js2-highlight-external-variables t
1124 "Non-nil to highlight undeclared variable identifiers.
1125 An undeclared variable is any variable not declared with var or let
1126 in the current scope or any lexically enclosing scope. If you use
1127 such a variable, then you are either expecting it to originate from
1128 another file, or you've got a potential bug."
1129 :type 'boolean
1130 :group 'js2-mode)
1131
1132 (defcustom js2-include-jslint-globals t
1133 "Non-nil to include the identifiers from JSLint global
1134 declaration (see http://www.jslint.com/lint.html#global) in the
1135 buffer-local externs list. See `js2-additional-externs' for more
1136 information."
1137 :type 'boolean
1138 :group 'js2-mode)
1139
1140 (defvar js2-mode-map
1141 (let ((map (make-sparse-keymap)))
1142 (define-key map [mouse-1] #'js2-mode-show-node)
1143 (define-key map (kbd "M-j") #'js2-line-break)
1144 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1145 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1146 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1147 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1148 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1149 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1150 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1151 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1152 (when js2-bounce-indent-p
1153 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1154
1155 (define-key map [menu-bar javascript]
1156 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1157
1158 (define-key map [menu-bar javascript customize-js2-mode]
1159 '(menu-item "Customize js2-mode" js2-mode-customize
1160 :help "Customize the behavior of this mode"))
1161
1162 (define-key map [menu-bar javascript js2-force-refresh]
1163 '(menu-item "Force buffer refresh" js2-mode-reset
1164 :help "Re-parse the buffer from scratch"))
1165
1166 (define-key map [menu-bar javascript separator-2]
1167 '("--"))
1168
1169 (define-key map [menu-bar javascript next-error]
1170 '(menu-item "Next warning or error" next-error
1171 :enabled (and js2-mode-ast
1172 (or (js2-ast-root-errors js2-mode-ast)
1173 (js2-ast-root-warnings js2-mode-ast)))
1174 :help "Move to next warning or error"))
1175
1176 (define-key map [menu-bar javascript display-errors]
1177 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1178 :visible (not js2-mode-show-parse-errors)
1179 :help "Turn on display of warnings and errors"))
1180
1181 (define-key map [menu-bar javascript hide-errors]
1182 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1183 :visible js2-mode-show-parse-errors
1184 :help "Turn off display of warnings and errors"))
1185
1186 (define-key map [menu-bar javascript separator-1]
1187 '("--"))
1188
1189 (define-key map [menu-bar javascript js2-toggle-function]
1190 '(menu-item "Show/collapse element" js2-mode-toggle-element
1191 :help "Hide or show function body or comment"))
1192
1193 (define-key map [menu-bar javascript show-comments]
1194 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1195 :visible js2-mode-comments-hidden
1196 :help "Expand all hidden block comments"))
1197
1198 (define-key map [menu-bar javascript hide-comments]
1199 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1200 :visible (not js2-mode-comments-hidden)
1201 :help "Show block comments as /*...*/"))
1202
1203 (define-key map [menu-bar javascript show-all-functions]
1204 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1205 :visible js2-mode-functions-hidden
1206 :help "Expand all hidden function bodies"))
1207
1208 (define-key map [menu-bar javascript hide-all-functions]
1209 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1210 :visible (not js2-mode-functions-hidden)
1211 :help "Show {...} for all top-level function bodies"))
1212
1213 map)
1214 "Keymap used in `js2-mode' buffers.")
1215
1216 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1217
1218 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1219 "Matches a //-comment line. Must be first non-whitespace on line.
1220 First match-group is the leading whitespace.")
1221
1222 (defvar js2-mode-hook nil)
1223
1224 (js2-deflocal js2-mode-ast nil "Private variable.")
1225 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1226 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1227 (js2-deflocal js2-mode-parsing nil "Private variable.")
1228 (js2-deflocal js2-mode-node-overlay nil)
1229
1230 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1231 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1232
1233 (js2-deflocal js2-mode-fontifications nil "Private variable")
1234 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1235 (js2-deflocal js2-imenu-recorder nil "Private variable")
1236 (js2-deflocal js2-imenu-function-map nil "Private variable")
1237
1238 (defvar js2-paragraph-start
1239 "\\(@[[:alpha:]]+\\>\\|$\\)")
1240
1241 ;; Note that we also set a 'c-in-sws text property in html comments,
1242 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1243 (defvar js2-syntactic-ws-start
1244 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1245
1246 (defvar js2-syntactic-ws-end
1247 "\\s \\|[\n\r/]\\|\\s!")
1248
1249 (defvar js2-syntactic-eol
1250 (concat "\\s *\\(/\\*[^*\n\r]*"
1251 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1252 "\\*+/\\s *\\)*"
1253 "\\(//\\|/\\*[^*\n\r]*"
1254 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1255 "\\|\\\\$\\|$\\)")
1256 "Copied from `java-mode'. Needed for some cc-engine functions.")
1257
1258 (defvar js2-comment-prefix-regexp
1259 "//+\\|\\**")
1260
1261 (defvar js2-comment-start-skip
1262 "\\(//+\\|/\\*+\\)\\s *")
1263
1264 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1265 "Non-nil to emit status messages during parsing.")
1266
1267 (defvar js2-mode-functions-hidden nil "Private variable.")
1268 (defvar js2-mode-comments-hidden nil "Private variable.")
1269
1270 (defvar js2-mode-syntax-table
1271 (let ((table (make-syntax-table)))
1272 (c-populate-syntax-table table)
1273 table)
1274 "Syntax table used in `js2-mode' buffers.")
1275
1276 (defvar js2-mode-abbrev-table nil
1277 "Abbrev table in use in `js2-mode' buffers.")
1278 (define-abbrev-table 'js2-mode-abbrev-table ())
1279
1280 (defvar js2-mode-pending-parse-callbacks nil
1281 "List of functions waiting to be notified that parse is finished.")
1282
1283 (defvar js2-mode-last-indented-line -1)
1284
1285 ;;; Localizable error and warning messages
1286
1287 ;; Messages are copied from Rhino's Messages.properties.
1288 ;; Many of the Java-specific messages have been elided.
1289 ;; Add any js2-specific ones at the end, so we can keep
1290 ;; this file synced with changes to Rhino's.
1291
1292 (defvar js2-message-table
1293 (make-hash-table :test 'equal :size 250)
1294 "Contains localized messages for `js2-mode'.")
1295
1296 ;; TODO(stevey): construct this table at compile-time.
1297 (defmacro js2-msg (key &rest strings)
1298 `(puthash ,key (concat ,@strings)
1299 js2-message-table))
1300
1301 (defun js2-get-msg (msg-key)
1302 "Look up a localized message.
1303 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1304 the correct number of ARGS must be provided."
1305 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1306 (args (if (listp msg-key) (cdr msg-key)))
1307 (msg (gethash key js2-message-table)))
1308 (if msg
1309 (apply #'format msg args)
1310 key))) ; default to showing the key
1311
1312 (js2-msg "msg.dup.parms"
1313 "Duplicate parameter name '%s'.")
1314
1315 (js2-msg "msg.too.big.jump"
1316 "Program too complex: jump offset too big.")
1317
1318 (js2-msg "msg.too.big.index"
1319 "Program too complex: internal index exceeds 64K limit.")
1320
1321 (js2-msg "msg.while.compiling.fn"
1322 "Encountered code generation error while compiling function '%s': %s")
1323
1324 (js2-msg "msg.while.compiling.script"
1325 "Encountered code generation error while compiling script: %s")
1326
1327 ;; Context
1328 (js2-msg "msg.ctor.not.found"
1329 "Constructor for '%s' not found.")
1330
1331 (js2-msg "msg.not.ctor"
1332 "'%s' is not a constructor.")
1333
1334 ;; FunctionObject
1335 (js2-msg "msg.varargs.ctor"
1336 "Method or constructor '%s' must be static "
1337 "with the signature (Context cx, Object[] args, "
1338 "Function ctorObj, boolean inNewExpr) "
1339 "to define a variable arguments constructor.")
1340
1341 (js2-msg "msg.varargs.fun"
1342 "Method '%s' must be static with the signature "
1343 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1344 "to define a variable arguments function.")
1345
1346 (js2-msg "msg.incompat.call"
1347 "Method '%s' called on incompatible object.")
1348
1349 (js2-msg "msg.bad.parms"
1350 "Unsupported parameter type '%s' in method '%s'.")
1351
1352 (js2-msg "msg.bad.method.return"
1353 "Unsupported return type '%s' in method '%s'.")
1354
1355 (js2-msg "msg.bad.ctor.return"
1356 "Construction of objects of type '%s' is not supported.")
1357
1358 (js2-msg "msg.no.overload"
1359 "Method '%s' occurs multiple times in class '%s'.")
1360
1361 (js2-msg "msg.method.not.found"
1362 "Method '%s' not found in '%s'.")
1363
1364 ;; IRFactory
1365
1366 (js2-msg "msg.bad.for.in.lhs"
1367 "Invalid left-hand side of for..in loop.")
1368
1369 (js2-msg "msg.mult.index"
1370 "Only one variable allowed in for..in loop.")
1371
1372 (js2-msg "msg.bad.for.in.destruct"
1373 "Left hand side of for..in loop must be an array of "
1374 "length 2 to accept key/value pair.")
1375
1376 (js2-msg "msg.cant.convert"
1377 "Can't convert to type '%s'.")
1378
1379 (js2-msg "msg.bad.assign.left"
1380 "Invalid assignment left-hand side.")
1381
1382 (js2-msg "msg.bad.decr"
1383 "Invalid decerement operand.")
1384
1385 (js2-msg "msg.bad.incr"
1386 "Invalid increment operand.")
1387
1388 (js2-msg "msg.bad.yield"
1389 "yield must be in a function.")
1390
1391 (js2-msg "msg.yield.parenthesized"
1392 "yield expression must be parenthesized.")
1393
1394 ;; NativeGlobal
1395 (js2-msg "msg.cant.call.indirect"
1396 "Function '%s' must be called directly, and not by way of a "
1397 "function of another name.")
1398
1399 (js2-msg "msg.eval.nonstring"
1400 "Calling eval() with anything other than a primitive "
1401 "string value will simply return the value. "
1402 "Is this what you intended?")
1403
1404 (js2-msg "msg.eval.nonstring.strict"
1405 "Calling eval() with anything other than a primitive "
1406 "string value is not allowed in strict mode.")
1407
1408 (js2-msg "msg.bad.destruct.op"
1409 "Invalid destructuring assignment operator")
1410
1411 ;; NativeCall
1412 (js2-msg "msg.only.from.new"
1413 "'%s' may only be invoked from a `new' expression.")
1414
1415 (js2-msg "msg.deprec.ctor"
1416 "The '%s' constructor is deprecated.")
1417
1418 ;; NativeFunction
1419 (js2-msg "msg.no.function.ref.found"
1420 "no source found to decompile function reference %s")
1421
1422 (js2-msg "msg.arg.isnt.array"
1423 "second argument to Function.prototype.apply must be an array")
1424
1425 ;; NativeGlobal
1426 (js2-msg "msg.bad.esc.mask"
1427 "invalid string escape mask")
1428
1429 ;; NativeRegExp
1430 (js2-msg "msg.bad.quant"
1431 "Invalid quantifier %s")
1432
1433 (js2-msg "msg.overlarge.backref"
1434 "Overly large back reference %s")
1435
1436 (js2-msg "msg.overlarge.min"
1437 "Overly large minimum %s")
1438
1439 (js2-msg "msg.overlarge.max"
1440 "Overly large maximum %s")
1441
1442 (js2-msg "msg.zero.quant"
1443 "Zero quantifier %s")
1444
1445 (js2-msg "msg.max.lt.min"
1446 "Maximum %s less than minimum")
1447
1448 (js2-msg "msg.unterm.quant"
1449 "Unterminated quantifier %s")
1450
1451 (js2-msg "msg.unterm.paren"
1452 "Unterminated parenthetical %s")
1453
1454 (js2-msg "msg.unterm.class"
1455 "Unterminated character class %s")
1456
1457 (js2-msg "msg.bad.range"
1458 "Invalid range in character class.")
1459
1460 (js2-msg "msg.trail.backslash"
1461 "Trailing \\ in regular expression.")
1462
1463 (js2-msg "msg.re.unmatched.right.paren"
1464 "unmatched ) in regular expression.")
1465
1466 (js2-msg "msg.no.regexp"
1467 "Regular expressions are not available.")
1468
1469 (js2-msg "msg.bad.backref"
1470 "back-reference exceeds number of capturing parentheses.")
1471
1472 (js2-msg "msg.bad.regexp.compile"
1473 "Only one argument may be specified if the first "
1474 "argument to RegExp.prototype.compile is a RegExp object.")
1475
1476 ;; Parser
1477 (js2-msg "msg.got.syntax.errors"
1478 "Compilation produced %s syntax errors.")
1479
1480 (js2-msg "msg.var.redecl"
1481 "TypeError: redeclaration of var %s.")
1482
1483 (js2-msg "msg.const.redecl"
1484 "TypeError: redeclaration of const %s.")
1485
1486 (js2-msg "msg.let.redecl"
1487 "TypeError: redeclaration of variable %s.")
1488
1489 (js2-msg "msg.parm.redecl"
1490 "TypeError: redeclaration of formal parameter %s.")
1491
1492 (js2-msg "msg.fn.redecl"
1493 "TypeError: redeclaration of function %s.")
1494
1495 (js2-msg "msg.let.decl.not.in.block"
1496 "SyntaxError: let declaration not directly within block")
1497
1498 ;; NodeTransformer
1499 (js2-msg "msg.dup.label"
1500 "duplicated label")
1501
1502 (js2-msg "msg.undef.label"
1503 "undefined label")
1504
1505 (js2-msg "msg.bad.break"
1506 "unlabelled break must be inside loop or switch")
1507
1508 (js2-msg "msg.continue.outside"
1509 "continue must be inside loop")
1510
1511 (js2-msg "msg.continue.nonloop"
1512 "continue can only use labels of iteration statements")
1513
1514 (js2-msg "msg.bad.throw.eol"
1515 "Line terminator is not allowed between the throw "
1516 "keyword and throw expression.")
1517
1518 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1519 "function statement requires a name")
1520
1521 (js2-msg "msg.no.paren.parms"
1522 "missing ( before function parameters.")
1523
1524 (js2-msg "msg.no.parm"
1525 "missing formal parameter")
1526
1527 (js2-msg "msg.no.paren.after.parms"
1528 "missing ) after formal parameters")
1529
1530 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1531 "parameter without default follows parameter with default")
1532
1533 (js2-msg "msg.param.after.rest" ; added by js2-mode
1534 "parameter after rest parameter")
1535
1536 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1537 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1538
1539 (js2-msg "msg.no.brace.body"
1540 "missing '{' before function body")
1541
1542 (js2-msg "msg.no.brace.after.body"
1543 "missing } after function body")
1544
1545 (js2-msg "msg.no.paren.cond"
1546 "missing ( before condition")
1547
1548 (js2-msg "msg.no.paren.after.cond"
1549 "missing ) after condition")
1550
1551 (js2-msg "msg.no.semi.stmt"
1552 "missing ; before statement")
1553
1554 (js2-msg "msg.missing.semi"
1555 "missing ; after statement")
1556
1557 (js2-msg "msg.no.name.after.dot"
1558 "missing name after . operator")
1559
1560 (js2-msg "msg.no.name.after.coloncolon"
1561 "missing name after :: operator")
1562
1563 (js2-msg "msg.no.name.after.dotdot"
1564 "missing name after .. operator")
1565
1566 (js2-msg "msg.no.name.after.xmlAttr"
1567 "missing name after .@")
1568
1569 (js2-msg "msg.no.bracket.index"
1570 "missing ] in index expression")
1571
1572 (js2-msg "msg.no.paren.switch"
1573 "missing ( before switch expression")
1574
1575 (js2-msg "msg.no.paren.after.switch"
1576 "missing ) after switch expression")
1577
1578 (js2-msg "msg.no.brace.switch"
1579 "missing '{' before switch body")
1580
1581 (js2-msg "msg.bad.switch"
1582 "invalid switch statement")
1583
1584 (js2-msg "msg.no.colon.case"
1585 "missing : after case expression")
1586
1587 (js2-msg "msg.double.switch.default"
1588 "double default label in the switch statement")
1589
1590 (js2-msg "msg.no.while.do"
1591 "missing while after do-loop body")
1592
1593 (js2-msg "msg.no.paren.for"
1594 "missing ( after for")
1595
1596 (js2-msg "msg.no.semi.for"
1597 "missing ; after for-loop initializer")
1598
1599 (js2-msg "msg.no.semi.for.cond"
1600 "missing ; after for-loop condition")
1601
1602 (js2-msg "msg.in.after.for.name"
1603 "missing in or of after for")
1604
1605 (js2-msg "msg.no.paren.for.ctrl"
1606 "missing ) after for-loop control")
1607
1608 (js2-msg "msg.no.paren.with"
1609 "missing ( before with-statement object")
1610
1611 (js2-msg "msg.no.paren.after.with"
1612 "missing ) after with-statement object")
1613
1614 (js2-msg "msg.no.paren.after.let"
1615 "missing ( after let")
1616
1617 (js2-msg "msg.no.paren.let"
1618 "missing ) after variable list")
1619
1620 (js2-msg "msg.no.curly.let"
1621 "missing } after let statement")
1622
1623 (js2-msg "msg.bad.return"
1624 "invalid return")
1625
1626 (js2-msg "msg.no.brace.block"
1627 "missing } in compound statement")
1628
1629 (js2-msg "msg.bad.label"
1630 "invalid label")
1631
1632 (js2-msg "msg.bad.var"
1633 "missing variable name")
1634
1635 (js2-msg "msg.bad.var.init"
1636 "invalid variable initialization")
1637
1638 (js2-msg "msg.no.colon.cond"
1639 "missing : in conditional expression")
1640
1641 (js2-msg "msg.no.paren.arg"
1642 "missing ) after argument list")
1643
1644 (js2-msg "msg.no.bracket.arg"
1645 "missing ] after element list")
1646
1647 (js2-msg "msg.bad.prop"
1648 "invalid property id")
1649
1650 (js2-msg "msg.no.colon.prop"
1651 "missing : after property id")
1652
1653 (js2-msg "msg.no.brace.prop"
1654 "missing } after property list")
1655
1656 (js2-msg "msg.no.paren"
1657 "missing ) in parenthetical")
1658
1659 (js2-msg "msg.reserved.id"
1660 "'%s' is a reserved identifier")
1661
1662 (js2-msg "msg.no.paren.catch"
1663 "missing ( before catch-block condition")
1664
1665 (js2-msg "msg.bad.catchcond"
1666 "invalid catch block condition")
1667
1668 (js2-msg "msg.catch.unreachable"
1669 "any catch clauses following an unqualified catch are unreachable")
1670
1671 (js2-msg "msg.no.brace.try"
1672 "missing '{' before try block")
1673
1674 (js2-msg "msg.no.brace.catchblock"
1675 "missing '{' before catch-block body")
1676
1677 (js2-msg "msg.try.no.catchfinally"
1678 "'try' without 'catch' or 'finally'")
1679
1680 (js2-msg "msg.no.return.value"
1681 "function %s does not always return a value")
1682
1683 (js2-msg "msg.anon.no.return.value"
1684 "anonymous function does not always return a value")
1685
1686 (js2-msg "msg.return.inconsistent"
1687 "return statement is inconsistent with previous usage")
1688
1689 (js2-msg "msg.generator.returns"
1690 "TypeError: legacy generator function '%s' returns a value")
1691
1692 (js2-msg "msg.anon.generator.returns"
1693 "TypeError: anonymous legacy generator function returns a value")
1694
1695 (js2-msg "msg.syntax"
1696 "syntax error")
1697
1698 (js2-msg "msg.unexpected.eof"
1699 "Unexpected end of file")
1700
1701 (js2-msg "msg.XML.bad.form"
1702 "illegally formed XML syntax")
1703
1704 (js2-msg "msg.XML.not.available"
1705 "XML runtime not available")
1706
1707 (js2-msg "msg.too.deep.parser.recursion"
1708 "Too deep recursion while parsing")
1709
1710 (js2-msg "msg.no.side.effects"
1711 "Code has no side effects")
1712
1713 (js2-msg "msg.extra.trailing.comma"
1714 "Trailing comma is not supported in some browsers")
1715
1716 (js2-msg "msg.array.trailing.comma"
1717 "Trailing comma yields different behavior across browsers")
1718
1719 (js2-msg "msg.equal.as.assign"
1720 (concat "Test for equality (==) mistyped as assignment (=)?"
1721 " (parenthesize to suppress warning)"))
1722
1723 (js2-msg "msg.var.hides.arg"
1724 "Variable %s hides argument")
1725
1726 (js2-msg "msg.destruct.assign.no.init"
1727 "Missing = in destructuring declaration")
1728
1729 ;; ScriptRuntime
1730 (js2-msg "msg.no.properties"
1731 "%s has no properties.")
1732
1733 (js2-msg "msg.invalid.iterator"
1734 "Invalid iterator value")
1735
1736 (js2-msg "msg.iterator.primitive"
1737 "__iterator__ returned a primitive value")
1738
1739 (js2-msg "msg.assn.create.strict"
1740 "Assignment to undeclared variable %s")
1741
1742 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1743 "Undeclared variable or function '%s'")
1744
1745 (js2-msg "msg.ref.undefined.prop"
1746 "Reference to undefined property '%s'")
1747
1748 (js2-msg "msg.prop.not.found"
1749 "Property %s not found.")
1750
1751 (js2-msg "msg.invalid.type"
1752 "Invalid JavaScript value of type %s")
1753
1754 (js2-msg "msg.primitive.expected"
1755 "Primitive type expected (had %s instead)")
1756
1757 (js2-msg "msg.namespace.expected"
1758 "Namespace object expected to left of :: (found %s instead)")
1759
1760 (js2-msg "msg.null.to.object"
1761 "Cannot convert null to an object.")
1762
1763 (js2-msg "msg.undef.to.object"
1764 "Cannot convert undefined to an object.")
1765
1766 (js2-msg "msg.cyclic.value"
1767 "Cyclic %s value not allowed.")
1768
1769 (js2-msg "msg.is.not.defined"
1770 "'%s' is not defined.")
1771
1772 (js2-msg "msg.undef.prop.read"
1773 "Cannot read property '%s' from %s")
1774
1775 (js2-msg "msg.undef.prop.write"
1776 "Cannot set property '%s' of %s to '%s'")
1777
1778 (js2-msg "msg.undef.prop.delete"
1779 "Cannot delete property '%s' of %s")
1780
1781 (js2-msg "msg.undef.method.call"
1782 "Cannot call method '%s' of %s")
1783
1784 (js2-msg "msg.undef.with"
1785 "Cannot apply 'with' to %s")
1786
1787 (js2-msg "msg.isnt.function"
1788 "%s is not a function, it is %s.")
1789
1790 (js2-msg "msg.isnt.function.in"
1791 "Cannot call property %s in object %s. "
1792 "It is not a function, it is '%s'.")
1793
1794 (js2-msg "msg.function.not.found"
1795 "Cannot find function %s.")
1796
1797 (js2-msg "msg.function.not.found.in"
1798 "Cannot find function %s in object %s.")
1799
1800 (js2-msg "msg.isnt.xml.object"
1801 "%s is not an xml object.")
1802
1803 (js2-msg "msg.no.ref.to.get"
1804 "%s is not a reference to read reference value.")
1805
1806 (js2-msg "msg.no.ref.to.set"
1807 "%s is not a reference to set reference value to %s.")
1808
1809 (js2-msg "msg.no.ref.from.function"
1810 "Function %s can not be used as the left-hand "
1811 "side of assignment or as an operand of ++ or -- operator.")
1812
1813 (js2-msg "msg.bad.default.value"
1814 "Object's getDefaultValue() method returned an object.")
1815
1816 (js2-msg "msg.instanceof.not.object"
1817 "Can't use instanceof on a non-object.")
1818
1819 (js2-msg "msg.instanceof.bad.prototype"
1820 "'prototype' property of %s is not an object.")
1821
1822 (js2-msg "msg.bad.radix"
1823 "illegal radix %s.")
1824
1825 ;; ScriptableObject
1826 (js2-msg "msg.default.value"
1827 "Cannot find default value for object.")
1828
1829 (js2-msg "msg.zero.arg.ctor"
1830 "Cannot load class '%s' which has no zero-parameter constructor.")
1831
1832 (js2-msg "msg.ctor.multiple.parms"
1833 "Can't define constructor or class %s since more than "
1834 "one constructor has multiple parameters.")
1835
1836 (js2-msg "msg.extend.scriptable"
1837 "%s must extend ScriptableObject in order to define property %s.")
1838
1839 (js2-msg "msg.bad.getter.parms"
1840 "In order to define a property, getter %s must have zero "
1841 "parameters or a single ScriptableObject parameter.")
1842
1843 (js2-msg "msg.obj.getter.parms"
1844 "Expected static or delegated getter %s to take "
1845 "a ScriptableObject parameter.")
1846
1847 (js2-msg "msg.getter.static"
1848 "Getter and setter must both be static or neither be static.")
1849
1850 (js2-msg "msg.setter.return"
1851 "Setter must have void return type: %s")
1852
1853 (js2-msg "msg.setter2.parms"
1854 "Two-parameter setter must take a ScriptableObject as "
1855 "its first parameter.")
1856
1857 (js2-msg "msg.setter1.parms"
1858 "Expected single parameter setter for %s")
1859
1860 (js2-msg "msg.setter2.expected"
1861 "Expected static or delegated setter %s to take two parameters.")
1862
1863 (js2-msg "msg.setter.parms"
1864 "Expected either one or two parameters for setter.")
1865
1866 (js2-msg "msg.setter.bad.type"
1867 "Unsupported parameter type '%s' in setter '%s'.")
1868
1869 (js2-msg "msg.add.sealed"
1870 "Cannot add a property to a sealed object: %s.")
1871
1872 (js2-msg "msg.remove.sealed"
1873 "Cannot remove a property from a sealed object: %s.")
1874
1875 (js2-msg "msg.modify.sealed"
1876 "Cannot modify a property of a sealed object: %s.")
1877
1878 (js2-msg "msg.modify.readonly"
1879 "Cannot modify readonly property: %s.")
1880
1881 ;; TokenStream
1882 (js2-msg "msg.missing.exponent"
1883 "missing exponent")
1884
1885 (js2-msg "msg.caught.nfe"
1886 "number format error")
1887
1888 (js2-msg "msg.unterminated.string.lit"
1889 "unterminated string literal")
1890
1891 (js2-msg "msg.unterminated.comment"
1892 "unterminated comment")
1893
1894 (js2-msg "msg.unterminated.re.lit"
1895 "unterminated regular expression literal")
1896
1897 (js2-msg "msg.invalid.re.flag"
1898 "invalid flag after regular expression")
1899
1900 (js2-msg "msg.no.re.input.for"
1901 "no input for %s")
1902
1903 (js2-msg "msg.illegal.character"
1904 "illegal character")
1905
1906 (js2-msg "msg.invalid.escape"
1907 "invalid Unicode escape sequence")
1908
1909 (js2-msg "msg.bad.namespace"
1910 "not a valid default namespace statement. "
1911 "Syntax is: default xml namespace = EXPRESSION;")
1912
1913 ;; TokensStream warnings
1914 (js2-msg "msg.bad.octal.literal"
1915 "illegal octal literal digit %s; "
1916 "interpreting it as a decimal digit")
1917
1918 (js2-msg "msg.missing.hex.digits"
1919 "missing hexadecimal digits after '0x'")
1920
1921 (js2-msg "msg.missing.binary.digits"
1922 "missing binary digits after '0b'")
1923
1924 (js2-msg "msg.missing.octal.digits"
1925 "missing octal digits after '0o'")
1926
1927 (js2-msg "msg.script.is.not.constructor"
1928 "Script objects are not constructors.")
1929
1930 ;; Arrays
1931 (js2-msg "msg.arraylength.bad"
1932 "Inappropriate array length.")
1933
1934 ;; Arrays
1935 (js2-msg "msg.arraylength.too.big"
1936 "Array length %s exceeds supported capacity limit.")
1937
1938 ;; URI
1939 (js2-msg "msg.bad.uri"
1940 "Malformed URI sequence.")
1941
1942 ;; Number
1943 (js2-msg "msg.bad.precision"
1944 "Precision %s out of range.")
1945
1946 ;; NativeGenerator
1947 (js2-msg "msg.send.newborn"
1948 "Attempt to send value to newborn generator")
1949
1950 (js2-msg "msg.already.exec.gen"
1951 "Already executing generator")
1952
1953 (js2-msg "msg.StopIteration.invalid"
1954 "StopIteration may not be changed to an arbitrary object.")
1955
1956 ;; Interpreter
1957 (js2-msg "msg.yield.closing"
1958 "Yield from closing generator")
1959
1960 ;; Classes
1961 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1962 "class statement requires a name")
1963
1964 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1965 "unexpected ',' between class properties")
1966
1967 (js2-msg "msg.unexpected.static" ; added by js2-mode
1968 "unexpected 'static'")
1969
1970 (js2-msg "msg.missing.extends" ; added by js2-mode
1971 "name is required after extends")
1972
1973 (js2-msg "msg.no.brace.class" ; added by js2-mode
1974 "missing '{' before class body")
1975
1976 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1977 "missing ']' after computed property expression")
1978
1979 ;;; Tokens Buffer
1980
1981 (defconst js2-ti-max-lookahead 2)
1982 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1983
1984 ;; Have to call `js2-init-scanner' to initialize the values.
1985 (js2-deflocal js2-ti-tokens nil)
1986 (js2-deflocal js2-ti-tokens-cursor nil)
1987 (js2-deflocal js2-ti-lookahead nil)
1988
1989 (defun js2-new-token (offset)
1990 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1991 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1992 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1993 token))
1994
1995 (defsubst js2-current-token ()
1996 (aref js2-ti-tokens js2-ti-tokens-cursor))
1997
1998 (defsubst js2-current-token-string ()
1999 (js2-token-string (js2-current-token)))
2000
2001 (defsubst js2-current-token-type ()
2002 (js2-token-type (js2-current-token)))
2003
2004 (defsubst js2-current-token-beg ()
2005 (js2-token-beg (js2-current-token)))
2006
2007 (defsubst js2-current-token-end ()
2008 (js2-token-end (js2-current-token)))
2009
2010 (defun js2-current-token-len ()
2011 (let ((token (js2-current-token)))
2012 (- (js2-token-end token)
2013 (js2-token-beg token))))
2014
2015 (defun js2-ts-seek (state)
2016 (setq js2-ts-lineno (js2-ts-state-lineno state)
2017 js2-ts-cursor (js2-ts-state-cursor state)
2018 js2-ti-tokens (js2-ts-state-tokens state)
2019 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2020 js2-ti-lookahead (js2-ts-state-lookahead state)))
2021
2022 ;;; Utilities
2023
2024 (defun js2-delete-if (predicate list)
2025 "Remove all items satisfying PREDICATE in LIST."
2026 (loop for item in list
2027 if (not (funcall predicate item))
2028 collect item))
2029
2030 (defun js2-position (element list)
2031 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2032 Returns nil if element is not found in the list."
2033 (let ((count 0)
2034 found)
2035 (while (and list (not found))
2036 (if (eq element (car list))
2037 (setq found t)
2038 (setq count (1+ count)
2039 list (cdr list))))
2040 (if found count)))
2041
2042 (defun js2-find-if (predicate list)
2043 "Find first item satisfying PREDICATE in LIST."
2044 (let (result)
2045 (while (and list (not result))
2046 (if (funcall predicate (car list))
2047 (setq result (car list)))
2048 (setq list (cdr list)))
2049 result))
2050
2051 (defmacro js2-time (form)
2052 "Evaluate FORM, discard result, and return elapsed time in sec."
2053 (declare (debug t))
2054 (let ((beg (make-symbol "--js2-time-beg--"))
2055 (delta (make-symbol "--js2-time-end--")))
2056 `(let ((,beg (current-time))
2057 ,delta)
2058 ,form
2059 (/ (truncate (* (- (float-time (current-time))
2060 (float-time ,beg))
2061 10000))
2062 10000.0))))
2063
2064 (defsubst js2-same-line (pos)
2065 "Return t if POS is on the same line as current point."
2066 (and (>= pos (point-at-bol))
2067 (<= pos (point-at-eol))))
2068
2069 (defun js2-code-bug ()
2070 "Signal an error when we encounter an unexpected code path."
2071 (error "failed assertion"))
2072
2073 (defsubst js2-record-text-property (beg end prop value)
2074 "Record a text property to set when parsing finishes."
2075 (push (list beg end prop value) js2-mode-deferred-properties))
2076
2077 ;; I'd like to associate errors with nodes, but for now the
2078 ;; easiest thing to do is get the context info from the last token.
2079 (defun js2-record-parse-error (msg &optional arg pos len)
2080 (push (list (list msg arg)
2081 (or pos (js2-current-token-beg))
2082 (or len (js2-current-token-len)))
2083 js2-parsed-errors))
2084
2085 (defun js2-report-error (msg &optional msg-arg pos len)
2086 "Signal a syntax error or record a parse error."
2087 (if js2-recover-from-parse-errors
2088 (js2-record-parse-error msg msg-arg pos len)
2089 (signal 'js2-syntax-error
2090 (list msg
2091 js2-ts-lineno
2092 (save-excursion
2093 (goto-char js2-ts-cursor)
2094 (current-column))
2095 js2-ts-hit-eof))))
2096
2097 (defun js2-report-warning (msg &optional msg-arg pos len face)
2098 (if js2-compiler-report-warning-as-error
2099 (js2-report-error msg msg-arg pos len)
2100 (push (list (list msg msg-arg)
2101 (or pos (js2-current-token-beg))
2102 (or len (js2-current-token-len))
2103 face)
2104 js2-parsed-warnings)))
2105
2106 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2107 (if js2-compiler-strict-mode
2108 (js2-report-warning msg-id msg-arg beg
2109 (and beg end (- end beg)))))
2110
2111 (put 'js2-syntax-error 'error-conditions
2112 '(error syntax-error js2-syntax-error))
2113 (put 'js2-syntax-error 'error-message "Syntax error")
2114
2115 (put 'js2-parse-error 'error-conditions
2116 '(error parse-error js2-parse-error))
2117 (put 'js2-parse-error 'error-message "Parse error")
2118
2119 (defmacro js2-clear-flag (flags flag)
2120 `(setq ,flags (logand ,flags (lognot ,flag))))
2121
2122 (defmacro js2-set-flag (flags flag)
2123 "Logical-or FLAG into FLAGS."
2124 `(setq ,flags (logior ,flags ,flag)))
2125
2126 (defsubst js2-flag-set-p (flags flag)
2127 (/= 0 (logand flags flag)))
2128
2129 (defsubst js2-flag-not-set-p (flags flag)
2130 (zerop (logand flags flag)))
2131
2132 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2133 "Evaluate BODY with the _ character set to be word-syntax."
2134 (declare (indent 0) (debug t))
2135 (let ((old-syntax (make-symbol "old-syntax")))
2136 `(let ((,old-syntax (string (char-syntax ?_))))
2137 (unwind-protect
2138 (progn
2139 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2140 ,@body)
2141 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2142
2143 ;;; AST struct and function definitions
2144
2145 ;; flags for ast node property 'member-type (used for e4x operators)
2146 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2147 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2148 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2149
2150 (defsubst js2-relpos (pos anchor)
2151 "Convert POS to be relative to ANCHOR.
2152 If POS is nil, returns nil."
2153 (and pos (- pos anchor)))
2154
2155 (defun js2-make-pad (indent)
2156 (if (zerop indent)
2157 ""
2158 (make-string (* indent js2-basic-offset) ? )))
2159
2160 (defun js2-visit-ast (node callback)
2161 "Visit every node in ast NODE with visitor CALLBACK.
2162
2163 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2164 called twice: once to visit the node, and again after all the node's
2165 children have been processed. The END-P argument is nil on the first
2166 call and non-nil on the second call. The return value of the callback
2167 affects the traversal: if non-nil, the children of NODE are processed.
2168 If the callback returns nil, or if the node has no children, then the
2169 callback is called immediately with a non-nil END-P argument.
2170
2171 The node traversal is approximately lexical-order, although there
2172 are currently no guarantees around this."
2173 (when node
2174 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2175 ;; visit the node
2176 (when (funcall callback node nil)
2177 ;; visit the kids
2178 (cond
2179 ((eq vfunc 'js2-visit-none)
2180 nil) ; don't even bother calling it
2181 ;; Each AST node type has to define a `js2-visitor' function
2182 ;; that takes a node and a callback, and calls `js2-visit-ast'
2183 ;; on each child of the node.
2184 (vfunc
2185 (funcall vfunc node callback))
2186 (t
2187 (error "%s does not define a visitor-traversal function"
2188 (aref node 0)))))
2189 ;; call the end-visit
2190 (funcall callback node t))))
2191
2192 (defstruct (js2-node
2193 (:constructor nil)) ; abstract
2194 "Base AST node type."
2195 (type -1) ; token type
2196 (pos -1) ; start position of this AST node in parsed input
2197 (len 1) ; num characters spanned by the node
2198 props ; optional node property list (an alist)
2199 parent) ; link to parent node; null for root
2200
2201 (defsubst js2-node-get-prop (node prop &optional default)
2202 (or (cadr (assoc prop (js2-node-props node))) default))
2203
2204 (defsubst js2-node-set-prop (node prop value)
2205 (setf (js2-node-props node)
2206 (cons (list prop value) (js2-node-props node))))
2207
2208 (defun js2-fixup-starts (n nodes)
2209 "Adjust the start positions of NODES to be relative to N.
2210 Any node in the list may be nil, for convenience."
2211 (dolist (node nodes)
2212 (when node
2213 (setf (js2-node-pos node) (- (js2-node-pos node)
2214 (js2-node-pos n))))))
2215
2216 (defun js2-node-add-children (parent &rest nodes)
2217 "Set parent node of NODES to PARENT, and return PARENT.
2218 Does nothing if we're not recording parent links.
2219 If any given node in NODES is nil, doesn't record that link."
2220 (js2-fixup-starts parent nodes)
2221 (dolist (node nodes)
2222 (and node
2223 (setf (js2-node-parent node) parent))))
2224
2225 ;; Non-recursive since it's called a frightening number of times.
2226 (defun js2-node-abs-pos (n)
2227 (let ((pos (js2-node-pos n)))
2228 (while (setq n (js2-node-parent n))
2229 (setq pos (+ pos (js2-node-pos n))))
2230 pos))
2231
2232 (defsubst js2-node-abs-end (n)
2233 "Return absolute buffer position of end of N."
2234 (+ (js2-node-abs-pos n) (js2-node-len n)))
2235
2236 ;; It's important to make sure block nodes have a Lisp list for the
2237 ;; child nodes, to limit printing recursion depth in an AST that
2238 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2239 ;; a sufficiently large vector tree.
2240
2241 (defstruct (js2-block-node
2242 (:include js2-node)
2243 (:constructor nil)
2244 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2245 (pos (js2-current-token-beg))
2246 len
2247 props
2248 kids)))
2249 "A block of statements."
2250 kids) ; a Lisp list of the child statement nodes
2251
2252 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2253 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2254
2255 (defun js2-visit-block (ast callback)
2256 "Visit the `js2-block-node' children of AST."
2257 (dolist (kid (js2-block-node-kids ast))
2258 (js2-visit-ast kid callback)))
2259
2260 (defun js2-print-block (n i)
2261 (let ((pad (js2-make-pad i)))
2262 (insert pad "{\n")
2263 (dolist (kid (js2-block-node-kids n))
2264 (js2-print-ast kid (1+ i)))
2265 (insert pad "}")))
2266
2267 (defstruct (js2-scope
2268 (:include js2-block-node)
2269 (:constructor nil)
2270 (:constructor make-js2-scope (&key (type js2-BLOCK)
2271 (pos (js2-current-token-beg))
2272 len
2273 kids)))
2274 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2275 ;; I don't have one of those handy, so I'll use an alist for now.
2276 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2277 ;; and is much lighter-weight to construct (both CPU and mem).
2278 ;; The keys are interned strings (symbols) for faster lookup.
2279 ;; Should switch to hybrid alist/hashtable eventually.
2280 symbol-table ; an alist of (symbol . js2-symbol)
2281 parent-scope ; a `js2-scope'
2282 top) ; top-level `js2-scope' (script/function)
2283
2284 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2285 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2286
2287 (defun js2-node-get-enclosing-scope (node)
2288 "Return the innermost `js2-scope' node surrounding NODE.
2289 Returns nil if there is no enclosing scope node."
2290 (let ((parent (js2-node-parent node)))
2291 (while (not (js2-scope-p parent))
2292 (setq parent (js2-node-parent parent)))
2293 parent))
2294
2295 (defun js2-get-defining-scope (scope name)
2296 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2297 Returns `js2-scope' in which NAME is defined, or nil if not found."
2298 (let ((sym (if (symbolp name)
2299 name
2300 (intern name)))
2301 table
2302 result
2303 (continue t))
2304 (while (and scope continue)
2305 (if (and (setq table (js2-scope-symbol-table scope))
2306 (assq sym table))
2307 (setq continue nil
2308 result scope)
2309 (setq scope (js2-scope-parent-scope scope))))
2310 result))
2311
2312 (defun js2-scope-get-symbol (scope name)
2313 "Return symbol table entry for NAME in SCOPE.
2314 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2315 (and (js2-scope-symbol-table scope)
2316 (cdr (assq (if (symbolp name)
2317 name
2318 (intern name))
2319 (js2-scope-symbol-table scope)))))
2320
2321 (defun js2-scope-put-symbol (scope name symbol)
2322 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2323 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2324 (let* ((table (js2-scope-symbol-table scope))
2325 (sym (if (symbolp name) name (intern name)))
2326 (entry (assq sym table)))
2327 (if entry
2328 (setcdr entry symbol)
2329 (push (cons sym symbol)
2330 (js2-scope-symbol-table scope)))))
2331
2332 (defstruct (js2-symbol
2333 (:constructor nil)
2334 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2335 "A symbol table entry."
2336 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2337 ;; js2-LET, or js2-CONST
2338 decl-type
2339 name ; string
2340 ast-node) ; a `js2-node'
2341
2342 (defstruct (js2-error-node
2343 (:include js2-node)
2344 (:constructor nil) ; silence emacs21 byte-compiler
2345 (:constructor make-js2-error-node (&key (type js2-ERROR)
2346 (pos (js2-current-token-beg))
2347 len)))
2348 "AST node representing a parse error.")
2349
2350 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2351 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2352
2353 (defstruct (js2-script-node
2354 (:include js2-scope)
2355 (:constructor nil)
2356 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2357 (pos (js2-current-token-beg))
2358 len
2359 ;; FIXME: What are those?
2360 var-decls
2361 fun-decls)))
2362 functions ; Lisp list of nested functions
2363 regexps ; Lisp list of (string . flags)
2364 symbols ; alist (every symbol gets unique index)
2365 (param-count 0)
2366 var-names ; vector of string names
2367 consts ; bool-vector matching var-decls
2368 (temp-number 0)) ; for generating temp variables
2369
2370 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2371 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2372
2373 (defun js2-print-script (node indent)
2374 (dolist (kid (js2-block-node-kids node))
2375 (js2-print-ast kid indent)))
2376
2377 (defstruct (js2-ast-root
2378 (:include js2-script-node)
2379 (:constructor nil)
2380 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2381 (pos (js2-current-token-beg))
2382 len
2383 buffer)))
2384 "The root node of a js2 AST."
2385 buffer ; the source buffer from which the code was parsed
2386 comments ; a Lisp list of comments, ordered by start position
2387 errors ; a Lisp list of errors found during parsing
2388 warnings ; a Lisp list of warnings found during parsing
2389 node-count) ; number of nodes in the tree, including the root
2390
2391 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2392 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2393
2394 (defun js2-visit-ast-root (ast callback)
2395 (dolist (kid (js2-ast-root-kids ast))
2396 (js2-visit-ast kid callback))
2397 (dolist (comment (js2-ast-root-comments ast))
2398 (js2-visit-ast comment callback)))
2399
2400 (defstruct (js2-comment-node
2401 (:include js2-node)
2402 (:constructor nil)
2403 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2404 (pos (js2-current-token-beg))
2405 len
2406 format)))
2407 format) ; 'line, 'block, 'jsdoc or 'html
2408
2409 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2410 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2411
2412 (defun js2-print-comment (n i)
2413 ;; We really ought to link end-of-line comments to their nodes.
2414 ;; Or maybe we could add a new comment type, 'endline.
2415 (insert (js2-make-pad i)
2416 (js2-node-string n)))
2417
2418 (defstruct (js2-expr-stmt-node
2419 (:include js2-node)
2420 (:constructor nil)
2421 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2422 (pos js2-ts-cursor)
2423 len
2424 expr)))
2425 "An expression statement."
2426 expr)
2427
2428 (defsubst js2-expr-stmt-node-set-has-result (node)
2429 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2430 (setf (js2-node-type node) js2-EXPR_RESULT))
2431
2432 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2433 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2434
2435 (defun js2-visit-expr-stmt-node (n v)
2436 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2437
2438 (defun js2-print-expr-stmt-node (n indent)
2439 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2440 (insert ";\n"))
2441
2442 (defstruct (js2-loop-node
2443 (:include js2-scope)
2444 (:constructor nil))
2445 "Abstract supertype of loop nodes."
2446 body ; a `js2-block-node'
2447 lp ; position of left-paren, nil if omitted
2448 rp) ; position of right-paren, nil if omitted
2449
2450 (defstruct (js2-do-node
2451 (:include js2-loop-node)
2452 (:constructor nil)
2453 (:constructor make-js2-do-node (&key (type js2-DO)
2454 (pos (js2-current-token-beg))
2455 len
2456 body
2457 condition
2458 while-pos
2459 lp
2460 rp)))
2461 "AST node for do-loop."
2462 condition ; while (expression)
2463 while-pos) ; buffer position of 'while' keyword
2464
2465 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2466 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2467
2468 (defun js2-visit-do-node (n v)
2469 (js2-visit-ast (js2-do-node-body n) v)
2470 (js2-visit-ast (js2-do-node-condition n) v))
2471
2472 (defun js2-print-do-node (n i)
2473 (let ((pad (js2-make-pad i)))
2474 (insert pad "do {\n")
2475 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2476 (js2-print-ast kid (1+ i)))
2477 (insert pad "} while (")
2478 (js2-print-ast (js2-do-node-condition n) 0)
2479 (insert ");\n")))
2480
2481 (defstruct (js2-while-node
2482 (:include js2-loop-node)
2483 (:constructor nil)
2484 (:constructor make-js2-while-node (&key (type js2-WHILE)
2485 (pos (js2-current-token-beg))
2486 len body
2487 condition lp
2488 rp)))
2489 "AST node for while-loop."
2490 condition) ; while-condition
2491
2492 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2493 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2494
2495 (defun js2-visit-while-node (n v)
2496 (js2-visit-ast (js2-while-node-condition n) v)
2497 (js2-visit-ast (js2-while-node-body n) v))
2498
2499 (defun js2-print-while-node (n i)
2500 (let ((pad (js2-make-pad i)))
2501 (insert pad "while (")
2502 (js2-print-ast (js2-while-node-condition n) 0)
2503 (insert ") {\n")
2504 (js2-print-body (js2-while-node-body n) (1+ i))
2505 (insert pad "}\n")))
2506
2507 (defstruct (js2-for-node
2508 (:include js2-loop-node)
2509 (:constructor nil)
2510 (:constructor make-js2-for-node (&key (type js2-FOR)
2511 (pos js2-ts-cursor)
2512 len body init
2513 condition
2514 update lp rp)))
2515 "AST node for a C-style for-loop."
2516 init ; initialization expression
2517 condition ; loop condition
2518 update) ; update clause
2519
2520 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2521 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2522
2523 (defun js2-visit-for-node (n v)
2524 (js2-visit-ast (js2-for-node-init n) v)
2525 (js2-visit-ast (js2-for-node-condition n) v)
2526 (js2-visit-ast (js2-for-node-update n) v)
2527 (js2-visit-ast (js2-for-node-body n) v))
2528
2529 (defun js2-print-for-node (n i)
2530 (let ((pad (js2-make-pad i)))
2531 (insert pad "for (")
2532 (js2-print-ast (js2-for-node-init n) 0)
2533 (insert "; ")
2534 (js2-print-ast (js2-for-node-condition n) 0)
2535 (insert "; ")
2536 (js2-print-ast (js2-for-node-update n) 0)
2537 (insert ") {\n")
2538 (js2-print-body (js2-for-node-body n) (1+ i))
2539 (insert pad "}\n")))
2540
2541 (defstruct (js2-for-in-node
2542 (:include js2-loop-node)
2543 (:constructor nil)
2544 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2545 (pos js2-ts-cursor)
2546 len body
2547 iterator
2548 object
2549 in-pos
2550 each-pos
2551 foreach-p forof-p
2552 lp rp)))
2553 "AST node for a for..in loop."
2554 iterator ; [var] foo in ...
2555 object ; object over which we're iterating
2556 in-pos ; buffer position of 'in' keyword
2557 each-pos ; buffer position of 'each' keyword, if foreach-p
2558 foreach-p ; t if it's a for-each loop
2559 forof-p) ; t if it's a for-of loop
2560
2561 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2562 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2563
2564 (defun js2-visit-for-in-node (n v)
2565 (js2-visit-ast (js2-for-in-node-iterator n) v)
2566 (js2-visit-ast (js2-for-in-node-object n) v)
2567 (js2-visit-ast (js2-for-in-node-body n) v))
2568
2569 (defun js2-print-for-in-node (n i)
2570 (let ((pad (js2-make-pad i))
2571 (foreach (js2-for-in-node-foreach-p n))
2572 (forof (js2-for-in-node-forof-p n)))
2573 (insert pad "for ")
2574 (if foreach
2575 (insert "each "))
2576 (insert "(")
2577 (js2-print-ast (js2-for-in-node-iterator n) 0)
2578 (insert (if forof " of " " in "))
2579 (js2-print-ast (js2-for-in-node-object n) 0)
2580 (insert ") {\n")
2581 (js2-print-body (js2-for-in-node-body n) (1+ i))
2582 (insert pad "}\n")))
2583
2584 (defstruct (js2-return-node
2585 (:include js2-node)
2586 (:constructor nil)
2587 (:constructor make-js2-return-node (&key (type js2-RETURN)
2588 (pos js2-ts-cursor)
2589 len
2590 retval)))
2591 "AST node for a return statement."
2592 retval) ; expression to return, or 'undefined
2593
2594 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2595 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2596
2597 (defun js2-visit-return-node (n v)
2598 (js2-visit-ast (js2-return-node-retval n) v))
2599
2600 (defun js2-print-return-node (n i)
2601 (insert (js2-make-pad i) "return")
2602 (when (js2-return-node-retval n)
2603 (insert " ")
2604 (js2-print-ast (js2-return-node-retval n) 0))
2605 (insert ";\n"))
2606
2607 (defstruct (js2-if-node
2608 (:include js2-node)
2609 (:constructor nil)
2610 (:constructor make-js2-if-node (&key (type js2-IF)
2611 (pos js2-ts-cursor)
2612 len condition
2613 then-part
2614 else-pos
2615 else-part lp
2616 rp)))
2617 "AST node for an if-statement."
2618 condition ; expression
2619 then-part ; statement or block
2620 else-pos ; optional buffer position of 'else' keyword
2621 else-part ; optional statement or block
2622 lp ; position of left-paren, nil if omitted
2623 rp) ; position of right-paren, nil if omitted
2624
2625 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2626 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2627
2628 (defun js2-visit-if-node (n v)
2629 (js2-visit-ast (js2-if-node-condition n) v)
2630 (js2-visit-ast (js2-if-node-then-part n) v)
2631 (js2-visit-ast (js2-if-node-else-part n) v))
2632
2633 (defun js2-print-if-node (n i)
2634 (let ((pad (js2-make-pad i))
2635 (then-part (js2-if-node-then-part n))
2636 (else-part (js2-if-node-else-part n)))
2637 (insert pad "if (")
2638 (js2-print-ast (js2-if-node-condition n) 0)
2639 (insert ") {\n")
2640 (js2-print-body then-part (1+ i))
2641 (insert pad "}")
2642 (cond
2643 ((not else-part)
2644 (insert "\n"))
2645 ((js2-if-node-p else-part)
2646 (insert " else ")
2647 (js2-print-body else-part i))
2648 (t
2649 (insert " else {\n")
2650 (js2-print-body else-part (1+ i))
2651 (insert pad "}\n")))))
2652
2653 (defstruct (js2-try-node
2654 (:include js2-node)
2655 (:constructor nil)
2656 (:constructor make-js2-try-node (&key (type js2-TRY)
2657 (pos js2-ts-cursor)
2658 len
2659 try-block
2660 catch-clauses
2661 finally-block)))
2662 "AST node for a try-statement."
2663 try-block
2664 catch-clauses ; a Lisp list of `js2-catch-node'
2665 finally-block) ; a `js2-finally-node'
2666
2667 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2668 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2669
2670 (defun js2-visit-try-node (n v)
2671 (js2-visit-ast (js2-try-node-try-block n) v)
2672 (dolist (clause (js2-try-node-catch-clauses n))
2673 (js2-visit-ast clause v))
2674 (js2-visit-ast (js2-try-node-finally-block n) v))
2675
2676 (defun js2-print-try-node (n i)
2677 (let ((pad (js2-make-pad i))
2678 (catches (js2-try-node-catch-clauses n))
2679 (finally (js2-try-node-finally-block n)))
2680 (insert pad "try {\n")
2681 (js2-print-body (js2-try-node-try-block n) (1+ i))
2682 (insert pad "}")
2683 (when catches
2684 (dolist (catch catches)
2685 (js2-print-ast catch i)))
2686 (if finally
2687 (js2-print-ast finally i)
2688 (insert "\n"))))
2689
2690 (defstruct (js2-catch-node
2691 (:include js2-node)
2692 (:constructor nil)
2693 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2694 (pos js2-ts-cursor)
2695 len
2696 param
2697 guard-kwd
2698 guard-expr
2699 block lp
2700 rp)))
2701 "AST node for a catch clause."
2702 param ; destructuring form or simple name node
2703 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2704 guard-expr ; catch condition, a `js2-node'
2705 block ; statements, a `js2-block-node'
2706 lp ; buffer position of left-paren, nil if omitted
2707 rp) ; buffer position of right-paren, nil if omitted
2708
2709 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2710 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2711
2712 (defun js2-visit-catch-node (n v)
2713 (js2-visit-ast (js2-catch-node-param n) v)
2714 (when (js2-catch-node-guard-kwd n)
2715 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2716 (js2-visit-ast (js2-catch-node-block n) v))
2717
2718 (defun js2-print-catch-node (n i)
2719 (let ((pad (js2-make-pad i))
2720 (guard-kwd (js2-catch-node-guard-kwd n))
2721 (guard-expr (js2-catch-node-guard-expr n)))
2722 (insert " catch (")
2723 (js2-print-ast (js2-catch-node-param n) 0)
2724 (when guard-kwd
2725 (insert " if ")
2726 (js2-print-ast guard-expr 0))
2727 (insert ") {\n")
2728 (js2-print-body (js2-catch-node-block n) (1+ i))
2729 (insert pad "}")))
2730
2731 (defstruct (js2-finally-node
2732 (:include js2-node)
2733 (:constructor nil)
2734 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2735 (pos js2-ts-cursor)
2736 len body)))
2737 "AST node for a finally clause."
2738 body) ; a `js2-node', often but not always a block node
2739
2740 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2741 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2742
2743 (defun js2-visit-finally-node (n v)
2744 (js2-visit-ast (js2-finally-node-body n) v))
2745
2746 (defun js2-print-finally-node (n i)
2747 (let ((pad (js2-make-pad i)))
2748 (insert " finally {\n")
2749 (js2-print-body (js2-finally-node-body n) (1+ i))
2750 (insert pad "}\n")))
2751
2752 (defstruct (js2-switch-node
2753 (:include js2-node)
2754 (:constructor nil)
2755 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2756 (pos js2-ts-cursor)
2757 len
2758 discriminant
2759 cases lp
2760 rp)))
2761 "AST node for a switch statement."
2762 discriminant ; a `js2-node' (switch expression)
2763 cases ; a Lisp list of `js2-case-node'
2764 lp ; position of open-paren for discriminant, nil if omitted
2765 rp) ; position of close-paren for discriminant, nil if omitted
2766
2767 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2768 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2769
2770 (defun js2-visit-switch-node (n v)
2771 (js2-visit-ast (js2-switch-node-discriminant n) v)
2772 (dolist (c (js2-switch-node-cases n))
2773 (js2-visit-ast c v)))
2774
2775 (defun js2-print-switch-node (n i)
2776 (let ((pad (js2-make-pad i))
2777 (cases (js2-switch-node-cases n)))
2778 (insert pad "switch (")
2779 (js2-print-ast (js2-switch-node-discriminant n) 0)
2780 (insert ") {\n")
2781 (dolist (case cases)
2782 (js2-print-ast case i))
2783 (insert pad "}\n")))
2784
2785 (defstruct (js2-case-node
2786 (:include js2-block-node)
2787 (:constructor nil)
2788 (:constructor make-js2-case-node (&key (type js2-CASE)
2789 (pos js2-ts-cursor)
2790 len kids expr)))
2791 "AST node for a case clause of a switch statement."
2792 expr) ; the case expression (nil for default)
2793
2794 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2795 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2796
2797 (defun js2-visit-case-node (n v)
2798 (js2-visit-ast (js2-case-node-expr n) v)
2799 (js2-visit-block n v))
2800
2801 (defun js2-print-case-node (n i)
2802 (let ((pad (js2-make-pad i))
2803 (expr (js2-case-node-expr n)))
2804 (insert pad)
2805 (if (null expr)
2806 (insert "default:\n")
2807 (insert "case ")
2808 (js2-print-ast expr 0)
2809 (insert ":\n"))
2810 (dolist (kid (js2-case-node-kids n))
2811 (js2-print-ast kid (1+ i)))))
2812
2813 (defstruct (js2-throw-node
2814 (:include js2-node)
2815 (:constructor nil)
2816 (:constructor make-js2-throw-node (&key (type js2-THROW)
2817 (pos js2-ts-cursor)
2818 len expr)))
2819 "AST node for a throw statement."
2820 expr) ; the expression to throw
2821
2822 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2823 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2824
2825 (defun js2-visit-throw-node (n v)
2826 (js2-visit-ast (js2-throw-node-expr n) v))
2827
2828 (defun js2-print-throw-node (n i)
2829 (insert (js2-make-pad i) "throw ")
2830 (js2-print-ast (js2-throw-node-expr n) 0)
2831 (insert ";\n"))
2832
2833 (defstruct (js2-with-node
2834 (:include js2-node)
2835 (:constructor nil)
2836 (:constructor make-js2-with-node (&key (type js2-WITH)
2837 (pos js2-ts-cursor)
2838 len object
2839 body lp rp)))
2840 "AST node for a with-statement."
2841 object
2842 body
2843 lp ; buffer position of left-paren around object, nil if omitted
2844 rp) ; buffer position of right-paren around object, nil if omitted
2845
2846 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2847 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2848
2849 (defun js2-visit-with-node (n v)
2850 (js2-visit-ast (js2-with-node-object n) v)
2851 (js2-visit-ast (js2-with-node-body n) v))
2852
2853 (defun js2-print-with-node (n i)
2854 (let ((pad (js2-make-pad i)))
2855 (insert pad "with (")
2856 (js2-print-ast (js2-with-node-object n) 0)
2857 (insert ") {\n")
2858 (js2-print-body (js2-with-node-body n) (1+ i))
2859 (insert pad "}\n")))
2860
2861 (defstruct (js2-label-node
2862 (:include js2-node)
2863 (:constructor nil)
2864 (:constructor make-js2-label-node (&key (type js2-LABEL)
2865 (pos js2-ts-cursor)
2866 len name)))
2867 "AST node for a statement label or case label."
2868 name ; a string
2869 loop) ; for validating and code-generating continue-to-label
2870
2871 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2872 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2873
2874 (defun js2-print-label (n i)
2875 (insert (js2-make-pad i)
2876 (js2-label-node-name n)
2877 ":\n"))
2878
2879 (defstruct (js2-labeled-stmt-node
2880 (:include js2-node)
2881 (:constructor nil)
2882 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2883 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2884 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2885 (pos js2-ts-cursor)
2886 len labels stmt)))
2887 "AST node for a statement with one or more labels.
2888 Multiple labels for a statement are collapsed into the labels field."
2889 labels ; Lisp list of `js2-label-node'
2890 stmt) ; the statement these labels are for
2891
2892 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2893 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2894
2895 (defun js2-get-label-by-name (lbl-stmt name)
2896 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2897 Returns nil if no such label is in the list."
2898 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2899 result)
2900 (while (and label-list (not result))
2901 (if (string= (js2-label-node-name (car label-list)) name)
2902 (setq result (car label-list))
2903 (setq label-list (cdr label-list))))
2904 result))
2905
2906 (defun js2-visit-labeled-stmt (n v)
2907 (dolist (label (js2-labeled-stmt-node-labels n))
2908 (js2-visit-ast label v))
2909 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2910
2911 (defun js2-print-labeled-stmt (n i)
2912 (dolist (label (js2-labeled-stmt-node-labels n))
2913 (js2-print-ast label i))
2914 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2915
2916 (defun js2-labeled-stmt-node-contains (node label)
2917 "Return t if NODE contains LABEL in its label set.
2918 NODE is a `js2-labels-node'. LABEL is an identifier."
2919 (loop for nl in (js2-labeled-stmt-node-labels node)
2920 if (string= label (js2-label-node-name nl))
2921 return t
2922 finally return nil))
2923
2924 (defsubst js2-labeled-stmt-node-add-label (node label)
2925 "Add a `js2-label-node' to the label set for this statement."
2926 (setf (js2-labeled-stmt-node-labels node)
2927 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2928
2929 (defstruct (js2-jump-node
2930 (:include js2-node)
2931 (:constructor nil))
2932 "Abstract supertype of break and continue nodes."
2933 label ; `js2-name-node' for location of label identifier, if present
2934 target) ; target js2-labels-node or loop/switch statement
2935
2936 (defun js2-visit-jump-node (n v)
2937 ;; We don't visit the target, since it's a back-link.
2938 (js2-visit-ast (js2-jump-node-label n) v))
2939
2940 (defstruct (js2-break-node
2941 (:include js2-jump-node)
2942 (:constructor nil)
2943 (:constructor make-js2-break-node (&key (type js2-BREAK)
2944 (pos js2-ts-cursor)
2945 len label target)))
2946 "AST node for a break statement.
2947 The label field is a `js2-name-node', possibly nil, for the named label
2948 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2949 is the target of the break - a label node or enclosing loop/switch statement.")
2950
2951 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2952 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2953
2954 (defun js2-print-break-node (n i)
2955 (insert (js2-make-pad i) "break")
2956 (when (js2-break-node-label n)
2957 (insert " ")
2958 (js2-print-ast (js2-break-node-label n) 0))
2959 (insert ";\n"))
2960
2961 (defstruct (js2-continue-node
2962 (:include js2-jump-node)
2963 (:constructor nil)
2964 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2965 (pos js2-ts-cursor)
2966 len label target)))
2967 "AST node for a continue statement.
2968 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2969 It is nil if continue specifies no label. The target field is the jump target:
2970 a `js2-label-node' or the innermost enclosing loop.")
2971
2972 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2973 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2974
2975 (defun js2-print-continue-node (n i)
2976 (insert (js2-make-pad i) "continue")
2977 (when (js2-continue-node-label n)
2978 (insert " ")
2979 (js2-print-ast (js2-continue-node-label n) 0))
2980 (insert ";\n"))
2981
2982 (defstruct (js2-function-node
2983 (:include js2-script-node)
2984 (:constructor nil)
2985 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2986 (pos js2-ts-cursor)
2987 len
2988 (ftype 'FUNCTION)
2989 (form 'FUNCTION_STATEMENT)
2990 (name "")
2991 params rest-p
2992 body
2993 generator-type
2994 lp rp)))
2995 "AST node for a function declaration.
2996 The `params' field is a Lisp list of nodes. Each node is either a simple
2997 `js2-name-node', or if it's a destructuring-assignment parameter, a
2998 `js2-array-node' or `js2-object-node'."
2999 ftype ; FUNCTION, GETTER or SETTER
3000 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3001 name ; function name (a `js2-name-node', or nil if anonymous)
3002 params ; a Lisp list of destructuring forms or simple name nodes
3003 rest-p ; if t, the last parameter is rest parameter
3004 body ; a `js2-block-node' or expression node (1.8 only)
3005 lp ; position of arg-list open-paren, or nil if omitted
3006 rp ; position of arg-list close-paren, or nil if omitted
3007 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3008 needs-activation ; t if we need an activation object for this frame
3009 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3010 member-expr) ; nonstandard Ecma extension from Rhino
3011
3012 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3013 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3014
3015 (defun js2-visit-function-node (n v)
3016 (js2-visit-ast (js2-function-node-name n) v)
3017 (dolist (p (js2-function-node-params n))
3018 (js2-visit-ast p v))
3019 (js2-visit-ast (js2-function-node-body n) v))
3020
3021 (defun js2-print-function-node (n i)
3022 (let* ((pad (js2-make-pad i))
3023 (getter (js2-node-get-prop n 'GETTER_SETTER))
3024 (name (or (js2-function-node-name n)
3025 (js2-function-node-member-expr n)))
3026 (params (js2-function-node-params n))
3027 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3028 (rest-p (js2-function-node-rest-p n))
3029 (body (js2-function-node-body n))
3030 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3031 (unless (or getter arrow)
3032 (insert pad "function")
3033 (when (eq (js2-function-node-generator-type n) 'STAR)
3034 (insert "*")))
3035 (when name
3036 (insert " ")
3037 (js2-print-ast name 0))
3038 (insert "(")
3039 (loop with len = (length params)
3040 for param in params
3041 for count from 1
3042 do
3043 (when (and rest-p (= count len))
3044 (insert "..."))
3045 (js2-print-ast param 0)
3046 (when (< count len)
3047 (insert ", ")))
3048 (insert ") ")
3049 (when arrow
3050 (insert "=> "))
3051 (insert "{")
3052 ;; TODO: fix this to be smarter about indenting, etc.
3053 (unless expr
3054 (insert "\n"))
3055 (if (js2-block-node-p body)
3056 (js2-print-body body (1+ i))
3057 (js2-print-ast body 0))
3058 (insert pad "}")
3059 (unless expr
3060 (insert "\n"))))
3061
3062 (defun js2-function-name (node)
3063 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3064 (and (js2-function-node-name node)
3065 (js2-name-node-name (js2-function-node-name node))))
3066
3067 ;; Having this be an expression node makes it more flexible.
3068 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3069 ;; that work better if you assume it's an expression. Whenever we have
3070 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3071 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3072 (defstruct (js2-var-decl-node
3073 (:include js2-node)
3074 (:constructor nil)
3075 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3076 (pos (js2-current-token-beg))
3077 len kids
3078 decl-type)))
3079 "AST node for a variable declaration list (VAR, CONST or LET).
3080 The node bounds differ depending on the declaration type. For VAR or
3081 CONST declarations, the bounds include the var/const keyword. For LET
3082 declarations, the node begins at the position of the first child."
3083 kids ; a Lisp list of `js2-var-init-node' structs.
3084 decl-type) ; js2-VAR, js2-CONST or js2-LET
3085
3086 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3087 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3088
3089 (defun js2-visit-var-decl (n v)
3090 (dolist (kid (js2-var-decl-node-kids n))
3091 (js2-visit-ast kid v)))
3092
3093 (defun js2-print-var-decl (n i)
3094 (let ((pad (js2-make-pad i))
3095 (tt (js2-var-decl-node-decl-type n)))
3096 (insert pad)
3097 (insert (cond
3098 ((= tt js2-VAR) "var ")
3099 ((= tt js2-LET) "let ")
3100 ((= tt js2-CONST) "const ")
3101 (t
3102 (error "malformed var-decl node"))))
3103 (loop with kids = (js2-var-decl-node-kids n)
3104 with len = (length kids)
3105 for kid in kids
3106 for count from 1
3107 do
3108 (js2-print-ast kid 0)
3109 (if (< count len)
3110 (insert ", ")))))
3111
3112 (defstruct (js2-var-init-node
3113 (:include js2-node)
3114 (:constructor nil)
3115 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3116 (pos js2-ts-cursor)
3117 len target
3118 initializer)))
3119 "AST node for a variable declaration.
3120 The type field will be js2-CONST for a const decl."
3121 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3122 initializer) ; initializer expression, a `js2-node'
3123
3124 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3125 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3126
3127 (defun js2-visit-var-init-node (n v)
3128 (js2-visit-ast (js2-var-init-node-target n) v)
3129 (js2-visit-ast (js2-var-init-node-initializer n) v))
3130
3131 (defun js2-print-var-init-node (n i)
3132 (let ((pad (js2-make-pad i))
3133 (name (js2-var-init-node-target n))
3134 (init (js2-var-init-node-initializer n)))
3135 (insert pad)
3136 (js2-print-ast name 0)
3137 (when init
3138 (insert " = ")
3139 (js2-print-ast init 0))))
3140
3141 (defstruct (js2-cond-node
3142 (:include js2-node)
3143 (:constructor nil)
3144 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3145 (pos js2-ts-cursor)
3146 len
3147 test-expr
3148 true-expr
3149 false-expr
3150 q-pos c-pos)))
3151 "AST node for the ternary operator"
3152 test-expr
3153 true-expr
3154 false-expr
3155 q-pos ; buffer position of ?
3156 c-pos) ; buffer position of :
3157
3158 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3159 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3160
3161 (defun js2-visit-cond-node (n v)
3162 (js2-visit-ast (js2-cond-node-test-expr n) v)
3163 (js2-visit-ast (js2-cond-node-true-expr n) v)
3164 (js2-visit-ast (js2-cond-node-false-expr n) v))
3165
3166 (defun js2-print-cond-node (n i)
3167 (let ((pad (js2-make-pad i)))
3168 (insert pad)
3169 (js2-print-ast (js2-cond-node-test-expr n) 0)
3170 (insert " ? ")
3171 (js2-print-ast (js2-cond-node-true-expr n) 0)
3172 (insert " : ")
3173 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3174
3175 (defstruct (js2-infix-node
3176 (:include js2-node)
3177 (:constructor nil)
3178 (:constructor make-js2-infix-node (&key type
3179 (pos js2-ts-cursor)
3180 len op-pos
3181 left right)))
3182 "Represents infix expressions.
3183 Includes assignment ops like `|=', and the comma operator.
3184 The type field inherited from `js2-node' holds the operator."
3185 op-pos ; buffer position where operator begins
3186 left ; any `js2-node'
3187 right) ; any `js2-node'
3188
3189 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3190 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3191
3192 (defun js2-visit-infix-node (n v)
3193 (js2-visit-ast (js2-infix-node-left n) v)
3194 (js2-visit-ast (js2-infix-node-right n) v))
3195
3196 (defconst js2-operator-tokens
3197 (let ((table (make-hash-table :test 'eq))
3198 (tokens
3199 (list (cons js2-IN "in")
3200 (cons js2-TYPEOF "typeof")
3201 (cons js2-INSTANCEOF "instanceof")
3202 (cons js2-DELPROP "delete")
3203 (cons js2-COMMA ",")
3204 (cons js2-COLON ":")
3205 (cons js2-OR "||")
3206 (cons js2-AND "&&")
3207 (cons js2-INC "++")
3208 (cons js2-DEC "--")
3209 (cons js2-BITOR "|")
3210 (cons js2-BITXOR "^")
3211 (cons js2-BITAND "&")
3212 (cons js2-EQ "==")
3213 (cons js2-NE "!=")
3214 (cons js2-LT "<")
3215 (cons js2-LE "<=")
3216 (cons js2-GT ">")
3217 (cons js2-GE ">=")
3218 (cons js2-LSH "<<")
3219 (cons js2-RSH ">>")
3220 (cons js2-URSH ">>>")
3221 (cons js2-ADD "+") ; infix plus
3222 (cons js2-SUB "-") ; infix minus
3223 (cons js2-MUL "*")
3224 (cons js2-DIV "/")
3225 (cons js2-MOD "%")
3226 (cons js2-NOT "!")
3227 (cons js2-BITNOT "~")
3228 (cons js2-POS "+") ; unary plus
3229 (cons js2-NEG "-") ; unary minus
3230 (cons js2-TRIPLEDOT "...")
3231 (cons js2-SHEQ "===") ; shallow equality
3232 (cons js2-SHNE "!==") ; shallow inequality
3233 (cons js2-ASSIGN "=")
3234 (cons js2-ASSIGN_BITOR "|=")
3235 (cons js2-ASSIGN_BITXOR "^=")
3236 (cons js2-ASSIGN_BITAND "&=")
3237 (cons js2-ASSIGN_LSH "<<=")
3238 (cons js2-ASSIGN_RSH ">>=")
3239 (cons js2-ASSIGN_URSH ">>>=")
3240 (cons js2-ASSIGN_ADD "+=")
3241 (cons js2-ASSIGN_SUB "-=")
3242 (cons js2-ASSIGN_MUL "*=")
3243 (cons js2-ASSIGN_DIV "/=")
3244 (cons js2-ASSIGN_MOD "%="))))
3245 (loop for (k . v) in tokens do
3246 (puthash k v table))
3247 table))
3248
3249 (defun js2-print-infix-node (n i)
3250 (let* ((tt (js2-node-type n))
3251 (op (gethash tt js2-operator-tokens)))
3252 (unless op
3253 (error "unrecognized infix operator %s" (js2-node-type n)))
3254 (insert (js2-make-pad i))
3255 (js2-print-ast (js2-infix-node-left n) 0)
3256 (unless (= tt js2-COMMA)
3257 (insert " "))
3258 (insert op)
3259 (insert " ")
3260 (js2-print-ast (js2-infix-node-right n) 0)))
3261
3262 (defstruct (js2-assign-node
3263 (:include js2-infix-node)
3264 (:constructor nil)
3265 (:constructor make-js2-assign-node (&key type
3266 (pos js2-ts-cursor)
3267 len op-pos
3268 left right)))
3269 "Represents any assignment.
3270 The type field holds the actual assignment operator.")
3271
3272 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3273 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3274
3275 (defstruct (js2-unary-node
3276 (:include js2-node)
3277 (:constructor nil)
3278 (:constructor make-js2-unary-node (&key type ; required
3279 (pos js2-ts-cursor)
3280 len operand)))
3281 "AST node type for unary operator nodes.
3282 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3283 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3284 property is added if the operator follows the operand."
3285 operand) ; a `js2-node' expression
3286
3287 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3288 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3289
3290 (defun js2-visit-unary-node (n v)
3291 (js2-visit-ast (js2-unary-node-operand n) v))
3292
3293 (defun js2-print-unary-node (n i)
3294 (let* ((tt (js2-node-type n))
3295 (op (gethash tt js2-operator-tokens))
3296 (postfix (js2-node-get-prop n 'postfix)))
3297 (unless op
3298 (error "unrecognized unary operator %s" tt))
3299 (insert (js2-make-pad i))
3300 (unless postfix
3301 (insert op))
3302 (if (or (= tt js2-TYPEOF)
3303 (= tt js2-DELPROP))
3304 (insert " "))
3305 (js2-print-ast (js2-unary-node-operand n) 0)
3306 (when postfix
3307 (insert op))))
3308
3309 (defstruct (js2-let-node
3310 (:include js2-scope)
3311 (:constructor nil)
3312 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3313 (pos (js2-current-token-beg))
3314 len vars body
3315 lp rp)))
3316 "AST node for a let expression or a let statement.
3317 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3318 vars ; a `js2-var-decl-node'
3319 body ; a `js2-node' representing the expression or body block
3320 lp
3321 rp)
3322
3323 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3324 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3325
3326 (defun js2-visit-let-node (n v)
3327 (js2-visit-ast (js2-let-node-vars n) v)
3328 (js2-visit-ast (js2-let-node-body n) v))
3329
3330 (defun js2-print-let-node (n i)
3331 (insert (js2-make-pad i) "let (")
3332 (let ((p (point)))
3333 (js2-print-ast (js2-let-node-vars n) 0)
3334 (delete-region p (+ p 4)))
3335 (insert ") ")
3336 (js2-print-ast (js2-let-node-body n) i))
3337
3338 (defstruct (js2-keyword-node
3339 (:include js2-node)
3340 (:constructor nil)
3341 (:constructor make-js2-keyword-node (&key type
3342 (pos (js2-current-token-beg))
3343 (len (- js2-ts-cursor pos)))))
3344 "AST node representing a literal keyword such as `null'.
3345 Used for `null', `this', `true', `false' and `debugger'.
3346 The node type is set to js2-NULL, js2-THIS, etc.")
3347
3348 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3349 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3350
3351 (defun js2-print-keyword-node (n i)
3352 (insert (js2-make-pad i)
3353 (let ((tt (js2-node-type n)))
3354 (cond
3355 ((= tt js2-THIS) "this")
3356 ((= tt js2-SUPER) "super")
3357 ((= tt js2-NULL) "null")
3358 ((= tt js2-TRUE) "true")
3359 ((= tt js2-FALSE) "false")
3360 ((= tt js2-DEBUGGER) "debugger")
3361 (t (error "Invalid keyword literal type: %d" tt))))))
3362
3363 (defsubst js2-this-or-super-node-p (node)
3364 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3365 (let ((type (js2-node-type node)))
3366 (or (eq type js2-THIS) (eq type js2-SUPER))))
3367
3368 (defstruct (js2-new-node
3369 (:include js2-node)
3370 (:constructor nil)
3371 (:constructor make-js2-new-node (&key (type js2-NEW)
3372 (pos (js2-current-token-beg))
3373 len target
3374 args initializer
3375 lp rp)))
3376 "AST node for new-expression such as new Foo()."
3377 target ; an identifier or reference
3378 args ; a Lisp list of argument nodes
3379 lp ; position of left-paren, nil if omitted
3380 rp ; position of right-paren, nil if omitted
3381 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3382
3383 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3384 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3385
3386 (defun js2-visit-new-node (n v)
3387 (js2-visit-ast (js2-new-node-target n) v)
3388 (dolist (arg (js2-new-node-args n))
3389 (js2-visit-ast arg v))
3390 (js2-visit-ast (js2-new-node-initializer n) v))
3391
3392 (defun js2-print-new-node (n i)
3393 (insert (js2-make-pad i) "new ")
3394 (js2-print-ast (js2-new-node-target n))
3395 (insert "(")
3396 (js2-print-list (js2-new-node-args n))
3397 (insert ")")
3398 (when (js2-new-node-initializer n)
3399 (insert " ")
3400 (js2-print-ast (js2-new-node-initializer n))))
3401
3402 (defstruct (js2-name-node
3403 (:include js2-node)
3404 (:constructor nil)
3405 (:constructor make-js2-name-node (&key (type js2-NAME)
3406 (pos (js2-current-token-beg))
3407 (len (- js2-ts-cursor
3408 (js2-current-token-beg)))
3409 (name (js2-current-token-string)))))
3410 "AST node for a JavaScript identifier"
3411 name ; a string
3412 scope) ; a `js2-scope' (optional, used for codegen)
3413
3414 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3415 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3416
3417 (defun js2-print-name-node (n i)
3418 (insert (js2-make-pad i)
3419 (js2-name-node-name n)))
3420
3421 (defsubst js2-name-node-length (node)
3422 "Return identifier length of NODE, a `js2-name-node'.
3423 Returns 0 if NODE is nil or its identifier field is nil."
3424 (if node
3425 (length (js2-name-node-name node))
3426 0))
3427
3428 (defstruct (js2-number-node
3429 (:include js2-node)
3430 (:constructor nil)
3431 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3432 (pos (js2-current-token-beg))
3433 (len (- js2-ts-cursor
3434 (js2-current-token-beg)))
3435 (value (js2-current-token-string))
3436 (num-value (js2-token-number
3437 (js2-current-token))))))
3438 "AST node for a number literal."
3439 value ; the original string, e.g. "6.02e23"
3440 num-value) ; the parsed number value
3441
3442 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3443 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3444
3445 (defun js2-print-number-node (n i)
3446 (insert (js2-make-pad i)
3447 (number-to-string (js2-number-node-num-value n))))
3448
3449 (defstruct (js2-regexp-node
3450 (:include js2-node)
3451 (:constructor nil)
3452 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3453 (pos (js2-current-token-beg))
3454 (len (- js2-ts-cursor
3455 (js2-current-token-beg)))
3456 value flags)))
3457 "AST node for a regular expression literal."
3458 value ; the regexp string, without // delimiters
3459 flags) ; a string of flags, e.g. `mi'.
3460
3461 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3462 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3463
3464 (defun js2-print-regexp (n i)
3465 (insert (js2-make-pad i)
3466 "/"
3467 (js2-regexp-node-value n)
3468 "/")
3469 (if (js2-regexp-node-flags n)
3470 (insert (js2-regexp-node-flags n))))
3471
3472 (defstruct (js2-string-node
3473 (:include js2-node)
3474 (:constructor nil)
3475 (:constructor make-js2-string-node (&key (type js2-STRING)
3476 (pos (js2-current-token-beg))
3477 (len (- js2-ts-cursor
3478 (js2-current-token-beg)))
3479 (value (js2-current-token-string)))))
3480 "String literal.
3481 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3482 You can tell the quote type by looking at the first character."
3483 value) ; the characters of the string, including the quotes
3484
3485 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3486 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3487
3488 (defun js2-print-string-node (n i)
3489 (insert (js2-make-pad i)
3490 (js2-node-string n)))
3491
3492 (defstruct (js2-template-node
3493 (:include js2-node)
3494 (:constructor nil)
3495 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3496 beg len kids)))
3497 "Template literal."
3498 kids) ; `js2-string-node' is used for string segments, other nodes
3499 ; for substitutions inside.
3500
3501 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3502 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3503
3504 (defun js2-visit-template (n callback)
3505 (dolist (kid (js2-template-node-kids n))
3506 (js2-visit-ast kid callback)))
3507
3508 (defun js2-print-template (n i)
3509 (insert (js2-make-pad i))
3510 (dolist (kid (js2-template-node-kids n))
3511 (if (js2-string-node-p kid)
3512 (insert (js2-node-string kid))
3513 (js2-print-ast kid))))
3514
3515 (defstruct (js2-tagged-template-node
3516 (:include js2-node)
3517 (:constructor nil)
3518 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3519 beg len tag template)))
3520 "Tagged template literal."
3521 tag ; `js2-node' with the tag expression.
3522 template) ; `js2-template-node' with the template.
3523
3524 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3525 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3526
3527 (defun js2-visit-tagged-template (n callback)
3528 (js2-visit-ast (js2-tagged-template-node-tag n) kid callback)
3529 (js2-visit-ast (js2-tagged-template-node-template n) kid callback))
3530
3531 (defun js2-print-tagged-template (n i)
3532 (insert (js2-make-pad i))
3533 (js2-print-ast (js2-tagged-template-node-tag n))
3534 (js2-print-ast (js2-tagged-template-node-template n)))
3535
3536 (defstruct (js2-array-node
3537 (:include js2-node)
3538 (:constructor nil)
3539 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3540 (pos js2-ts-cursor)
3541 len elems)))
3542 "AST node for an array literal."
3543 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3544
3545 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3546 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3547
3548 (defun js2-visit-array-node (n v)
3549 (dolist (e (js2-array-node-elems n))
3550 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3551
3552 (defun js2-print-array-node (n i)
3553 (insert (js2-make-pad i) "[")
3554 (let ((elems (js2-array-node-elems n)))
3555 (js2-print-list elems)
3556 (when (and elems (null (car (last elems))))
3557 (insert ",")))
3558 (insert "]"))
3559
3560 (defstruct (js2-class-node
3561 (:include js2-node)
3562 (:constructor nil)
3563 (:constructor make-js2-class-node (&key (type js2-CLASS)
3564 (pos js2-ts-cursor)
3565 (form 'CLASS_STATEMENT)
3566 (name "")
3567 extends len elems)))
3568 "AST node for an class expression.
3569 `elems' is a list of `js2-object-prop-node', and `extends' is an
3570 optional `js2-expr-node'"
3571 form ; CLASS_{STATEMENT|EXPRESSION}
3572 name ; class name (a `js2-node-name', or nil if anonymous)
3573 extends ; class heritage (a `js2-expr-node', or nil if none)
3574 elems)
3575
3576 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3577 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3578
3579 (defun js2-visit-class-node (n v)
3580 (js2-visit-ast (js2-class-node-name n) v)
3581 (js2-visit-ast (js2-class-node-extends n) v)
3582 (dolist (e (js2-class-node-elems n))
3583 (js2-visit-ast e v)))
3584
3585 (defun js2-print-class-node (n i)
3586 (let* ((pad (js2-make-pad i))
3587 (name (js2-class-node-name n))
3588 (extends (js2-class-node-extends n))
3589 (elems (js2-class-node-elems n)))
3590 (insert pad "class")
3591 (when name
3592 (insert " ")
3593 (js2-print-ast name 0))
3594 (when extends
3595 (insert " extends ")
3596 (js2-print-ast extends))
3597 (insert " {")
3598 (dolist (elem elems)
3599 (insert "\n")
3600 (if (js2-node-get-prop elem 'STATIC)
3601 (progn (insert (js2-make-pad (1+ i)) "static ")
3602 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3603 (js2-print-ast elem (1+ i))))
3604 (insert "\n" pad "}")))
3605
3606 (defstruct (js2-object-node
3607 (:include js2-node)
3608 (:constructor nil)
3609 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3610 (pos js2-ts-cursor)
3611 len
3612 elems)))
3613 "AST node for an object literal expression.
3614 `elems' is a list of `js2-object-prop-node'."
3615 elems)
3616
3617 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3618 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3619
3620 (defun js2-visit-object-node (n v)
3621 (dolist (e (js2-object-node-elems n))
3622 (js2-visit-ast e v)))
3623
3624 (defun js2-print-object-node (n i)
3625 (insert (js2-make-pad i) "{")
3626 (js2-print-list (js2-object-node-elems n))
3627 (insert "}"))
3628
3629 (defstruct (js2-object-prop-node
3630 (:include js2-infix-node)
3631 (:constructor nil)
3632 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3633 (pos js2-ts-cursor)
3634 len left
3635 right op-pos)))
3636 "AST node for an object literal prop:value entry.
3637 The `left' field is the property: a name node, string node or number node.
3638 The `right' field is a `js2-node' representing the initializer value.
3639 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3640 and both fields have the same value.")
3641
3642 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3643 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3644
3645 (defun js2-print-object-prop-node (n i)
3646 (let* ((left (js2-object-prop-node-left n))
3647 (computed (not (or (js2-string-node-p left)
3648 (js2-number-node-p left)
3649 (js2-name-node-p left)))))
3650 (insert (js2-make-pad i))
3651 (if computed
3652 (insert "["))
3653 (js2-print-ast left 0)
3654 (if computed
3655 (insert "]"))
3656 (if (not (js2-node-get-prop n 'SHORTHAND))
3657 (progn
3658 (insert ": ")
3659 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3660
3661 (defstruct (js2-getter-setter-node
3662 (:include js2-infix-node)
3663 (:constructor nil)
3664 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3665 (pos js2-ts-cursor)
3666 len left right)))
3667 "AST node for a getter/setter property in an object literal.
3668 The `left' field is the `js2-name-node' naming the getter/setter prop.
3669 The `right' field is always an anonymous `js2-function-node' with a node
3670 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3671
3672 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3673 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3674
3675 (defun js2-print-getter-setter (n i)
3676 (let ((pad (js2-make-pad i))
3677 (left (js2-getter-setter-node-left n))
3678 (right (js2-getter-setter-node-right n)))
3679 (insert pad)
3680 (if (/= (js2-node-type n) js2-FUNCTION)
3681 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3682 (js2-print-ast left 0)
3683 (js2-print-ast right 0)))
3684
3685 (defstruct (js2-prop-get-node
3686 (:include js2-infix-node)
3687 (:constructor nil)
3688 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3689 (pos js2-ts-cursor)
3690 len left right)))
3691 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3692
3693 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3694 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3695
3696 (defun js2-visit-prop-get-node (n v)
3697 (js2-visit-ast (js2-prop-get-node-left n) v)
3698 (js2-visit-ast (js2-prop-get-node-right n) v))
3699
3700 (defun js2-print-prop-get-node (n i)
3701 (insert (js2-make-pad i))
3702 (js2-print-ast (js2-prop-get-node-left n) 0)
3703 (insert ".")
3704 (js2-print-ast (js2-prop-get-node-right n) 0))
3705
3706 (defstruct (js2-elem-get-node
3707 (:include js2-node)
3708 (:constructor nil)
3709 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3710 (pos js2-ts-cursor)
3711 len target element
3712 lb rb)))
3713 "AST node for an array index expression such as foo[bar]."
3714 target ; a `js2-node' - the expression preceding the "."
3715 element ; a `js2-node' - the expression in brackets
3716 lb ; position of left-bracket, nil if omitted
3717 rb) ; position of right-bracket, nil if omitted
3718
3719 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3720 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3721
3722 (defun js2-visit-elem-get-node (n v)
3723 (js2-visit-ast (js2-elem-get-node-target n) v)
3724 (js2-visit-ast (js2-elem-get-node-element n) v))
3725
3726 (defun js2-print-elem-get-node (n i)
3727 (insert (js2-make-pad i))
3728 (js2-print-ast (js2-elem-get-node-target n) 0)
3729 (insert "[")
3730 (js2-print-ast (js2-elem-get-node-element n) 0)
3731 (insert "]"))
3732
3733 (defstruct (js2-call-node
3734 (:include js2-node)
3735 (:constructor nil)
3736 (:constructor make-js2-call-node (&key (type js2-CALL)
3737 (pos js2-ts-cursor)
3738 len target args
3739 lp rp)))
3740 "AST node for a JavaScript function call."
3741 target ; a `js2-node' evaluating to the function to call
3742 args ; a Lisp list of `js2-node' arguments
3743 lp ; position of open-paren, or nil if missing
3744 rp) ; position of close-paren, or nil if missing
3745
3746 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3747 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3748
3749 (defun js2-visit-call-node (n v)
3750 (js2-visit-ast (js2-call-node-target n) v)
3751 (dolist (arg (js2-call-node-args n))
3752 (js2-visit-ast arg v)))
3753
3754 (defun js2-print-call-node (n i)
3755 (insert (js2-make-pad i))
3756 (js2-print-ast (js2-call-node-target n) 0)
3757 (insert "(")
3758 (js2-print-list (js2-call-node-args n))
3759 (insert ")"))
3760
3761 (defstruct (js2-yield-node
3762 (:include js2-node)
3763 (:constructor nil)
3764 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3765 (pos js2-ts-cursor)
3766 len value star-p)))
3767 "AST node for yield statement or expression."
3768 star-p ; whether it's yield*
3769 value) ; optional: value to be yielded
3770
3771 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3772 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3773
3774 (defun js2-visit-yield-node (n v)
3775 (js2-visit-ast (js2-yield-node-value n) v))
3776
3777 (defun js2-print-yield-node (n i)
3778 (insert (js2-make-pad i))
3779 (insert "yield")
3780 (when (js2-yield-node-star-p n)
3781 (insert "*"))
3782 (when (js2-yield-node-value n)
3783 (insert " ")
3784 (js2-print-ast (js2-yield-node-value n) 0)))
3785
3786 (defstruct (js2-paren-node
3787 (:include js2-node)
3788 (:constructor nil)
3789 (:constructor make-js2-paren-node (&key (type js2-LP)
3790 (pos js2-ts-cursor)
3791 len expr)))
3792 "AST node for a parenthesized expression.
3793 In particular, used when the parens are syntactically optional,
3794 as opposed to required parens such as those enclosing an if-conditional."
3795 expr) ; `js2-node'
3796
3797 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3798 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3799
3800 (defun js2-visit-paren-node (n v)
3801 (js2-visit-ast (js2-paren-node-expr n) v))
3802
3803 (defun js2-print-paren-node (n i)
3804 (insert (js2-make-pad i))
3805 (insert "(")
3806 (js2-print-ast (js2-paren-node-expr n) 0)
3807 (insert ")"))
3808
3809 (defstruct (js2-comp-node
3810 (:include js2-scope)
3811 (:constructor nil)
3812 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3813 (pos js2-ts-cursor)
3814 len result
3815 loops filters
3816 form)))
3817 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3818 result ; result expression (just after left-bracket)
3819 loops ; a Lisp list of `js2-comp-loop-node'
3820 filters ; a Lisp list of guard/filter expressions
3821 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3822 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3823 )
3824
3825 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3826 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3827
3828 (defun js2-visit-comp-node (n v)
3829 (js2-visit-ast (js2-comp-node-result n) v)
3830 (dolist (l (js2-comp-node-loops n))
3831 (js2-visit-ast l v))
3832 (dolist (f (js2-comp-node-filters n))
3833 (js2-visit-ast f v)))
3834
3835 (defun js2-print-comp-node (n i)
3836 (let ((pad (js2-make-pad i))
3837 (result (js2-comp-node-result n))
3838 (loops (js2-comp-node-loops n))
3839 (filters (js2-comp-node-filters n))
3840 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3841 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3842 (insert pad (if gen-p "(" "["))
3843 (when legacy-p
3844 (js2-print-ast result 0))
3845 (dolist (l loops)
3846 (when legacy-p
3847 (insert " "))
3848 (js2-print-ast l 0)
3849 (unless legacy-p
3850 (insert " ")))
3851 (dolist (f filters)
3852 (when legacy-p
3853 (insert " "))
3854 (insert "if (")
3855 (js2-print-ast f 0)
3856 (insert ")")
3857 (unless legacy-p
3858 (insert " ")))
3859 (unless legacy-p
3860 (js2-print-ast result 0))
3861 (insert (if gen-p ")" "]"))))
3862
3863 (defstruct (js2-comp-loop-node
3864 (:include js2-for-in-node)
3865 (:constructor nil)
3866 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3867 (pos js2-ts-cursor)
3868 len iterator
3869 object in-pos
3870 foreach-p
3871 each-pos
3872 forof-p
3873 lp rp)))
3874 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3875
3876 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3877 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3878
3879 (defun js2-visit-comp-loop (n v)
3880 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3881 (js2-visit-ast (js2-comp-loop-node-object n) v))
3882
3883 (defun js2-print-comp-loop (n _i)
3884 (insert "for ")
3885 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3886 (insert "(")
3887 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3888 (insert (if (js2-comp-loop-node-forof-p n)
3889 " of " " in "))
3890 (js2-print-ast (js2-comp-loop-node-object n) 0)
3891 (insert ")"))
3892
3893 (defstruct (js2-empty-expr-node
3894 (:include js2-node)
3895 (:constructor nil)
3896 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3897 (pos (js2-current-token-beg))
3898 len)))
3899 "AST node for an empty expression.")
3900
3901 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3902 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3903
3904 (defstruct (js2-xml-node
3905 (:include js2-block-node)
3906 (:constructor nil)
3907 (:constructor make-js2-xml-node (&key (type js2-XML)
3908 (pos (js2-current-token-beg))
3909 len kids)))
3910 "AST node for initial parse of E4X literals.
3911 The kids field is a list of XML fragments, each a `js2-string-node' or
3912 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3913
3914 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3915 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3916
3917 (defun js2-print-xml-node (n i)
3918 (dolist (kid (js2-xml-node-kids n))
3919 (js2-print-ast kid i)))
3920
3921 (defstruct (js2-xml-js-expr-node
3922 (:include js2-xml-node)
3923 (:constructor nil)
3924 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3925 (pos js2-ts-cursor)
3926 len expr)))
3927 "AST node for an embedded JavaScript {expression} in an E4X literal.
3928 The start and end fields correspond to the curly-braces."
3929 expr) ; a `js2-expr-node' of some sort
3930
3931 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3932 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3933
3934 (defun js2-visit-xml-js-expr (n v)
3935 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3936
3937 (defun js2-print-xml-js-expr (n i)
3938 (insert (js2-make-pad i))
3939 (insert "{")
3940 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3941 (insert "}"))
3942
3943 (defstruct (js2-xml-dot-query-node
3944 (:include js2-infix-node)
3945 (:constructor nil)
3946 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3947 (pos js2-ts-cursor)
3948 op-pos len left
3949 right rp)))
3950 "AST node for an E4X foo.(bar) filter expression.
3951 Note that the left-paren is automatically the character immediately
3952 following the dot (.) in the operator. No whitespace is permitted
3953 between the dot and the lp by the scanner."
3954 rp)
3955
3956 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3957 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3958
3959 (defun js2-print-xml-dot-query (n i)
3960 (insert (js2-make-pad i))
3961 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3962 (insert ".(")
3963 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3964 (insert ")"))
3965
3966 (defstruct (js2-xml-ref-node
3967 (:include js2-node)
3968 (:constructor nil)) ; abstract
3969 "Base type for E4X XML attribute-access or property-get expressions.
3970 Such expressions can take a variety of forms. The general syntax has
3971 three parts:
3972
3973 - (optional) an @ (specifying an attribute access)
3974 - (optional) a namespace (a `js2-name-node') and double-colon
3975 - (required) either a `js2-name-node' or a bracketed [expression]
3976
3977 The property-name expressions (examples: ns::name, @name) are
3978 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3979 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3980
3981 This node type (or more specifically, its subclasses) will sometimes
3982 be the right-hand child of a `js2-prop-get-node' or a
3983 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3984 The `js2-xml-ref-node' may also be a standalone primary expression with
3985 no explicit target, which is valid in certain expression contexts such as
3986
3987 company..employee.(@id < 100)
3988
3989 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3990 expression whose parent is a `js2-xml-dot-query-node'."
3991 namespace
3992 at-pos
3993 colon-pos)
3994
3995 (defsubst js2-xml-ref-node-attr-access-p (node)
3996 "Return non-nil if this expression began with an @-token."
3997 (and (numberp (js2-xml-ref-node-at-pos node))
3998 (plusp (js2-xml-ref-node-at-pos node))))
3999
4000 (defstruct (js2-xml-prop-ref-node
4001 (:include js2-xml-ref-node)
4002 (:constructor nil)
4003 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4004 (pos (js2-current-token-beg))
4005 len propname
4006 namespace at-pos
4007 colon-pos)))
4008 "AST node for an E4X XML [expr] property-ref expression.
4009 The JavaScript syntax is an optional @, an optional ns::, and a name.
4010
4011 [ '@' ] [ name '::' ] name
4012
4013 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4014 @ns::*, @*::attr, @*::*, and @*.
4015
4016 The node starts at the @ token, if present. Otherwise it starts at the
4017 namespace name. The node bounds extend through the closing right-bracket,
4018 or if it is missing due to a syntax error, through the end of the index
4019 expression."
4020 propname)
4021
4022 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4023 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4024
4025 (defun js2-visit-xml-prop-ref-node (n v)
4026 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4027 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4028
4029 (defun js2-print-xml-prop-ref-node (n i)
4030 (insert (js2-make-pad i))
4031 (if (js2-xml-ref-node-attr-access-p n)
4032 (insert "@"))
4033 (when (js2-xml-prop-ref-node-namespace n)
4034 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4035 (insert "::"))
4036 (if (js2-xml-prop-ref-node-propname n)
4037 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4038
4039 (defstruct (js2-xml-elem-ref-node
4040 (:include js2-xml-ref-node)
4041 (:constructor nil)
4042 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4043 (pos (js2-current-token-beg))
4044 len expr lb rb
4045 namespace at-pos
4046 colon-pos)))
4047 "AST node for an E4X XML [expr] member-ref expression.
4048 Syntax:
4049
4050 [ '@' ] [ name '::' ] '[' expr ']'
4051
4052 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4053
4054 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4055 is not a legal E4X XML element-ref expression, since it's already used
4056 for standard JavaScript element-get array indexing. Hence, a
4057 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4058 non-nil namespace node, or both.
4059
4060 The node starts at the @ token, if present. Otherwise it starts
4061 at the namespace name. The node bounds extend through the closing
4062 right-bracket, or if it is missing due to a syntax error, through the
4063 end of the index expression."
4064 expr ; the bracketed index expression
4065 lb
4066 rb)
4067
4068 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4069 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4070
4071 (defun js2-visit-xml-elem-ref-node (n v)
4072 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4073 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4074
4075 (defun js2-print-xml-elem-ref-node (n i)
4076 (insert (js2-make-pad i))
4077 (if (js2-xml-ref-node-attr-access-p n)
4078 (insert "@"))
4079 (when (js2-xml-elem-ref-node-namespace n)
4080 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4081 (insert "::"))
4082 (insert "[")
4083 (if (js2-xml-elem-ref-node-expr n)
4084 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4085 (insert "]"))
4086
4087 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4088
4089 (defstruct (js2-xml-start-tag-node
4090 (:include js2-xml-node)
4091 (:constructor nil)
4092 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4093 (pos js2-ts-cursor)
4094 len name attrs kids
4095 empty-p)))
4096 "AST node for an XML start-tag. Not currently used.
4097 The `kids' field is a Lisp list of child content nodes."
4098 name ; a `js2-xml-name-node'
4099 attrs ; a Lisp list of `js2-xml-attr-node'
4100 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4101
4102 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4103 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4104
4105 (defun js2-visit-xml-start-tag (n v)
4106 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4107 (dolist (attr (js2-xml-start-tag-node-attrs n))
4108 (js2-visit-ast attr v))
4109 (js2-visit-block n v))
4110
4111 (defun js2-print-xml-start-tag (n i)
4112 (insert (js2-make-pad i) "<")
4113 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4114 (when (js2-xml-start-tag-node-attrs n)
4115 (insert " ")
4116 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4117 (insert ">"))
4118
4119 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4120 ;; and add the end-tag to the kids list of the parent as well.
4121 (defstruct (js2-xml-end-tag-node
4122 (:include js2-xml-node)
4123 (:constructor nil)
4124 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4125 (pos js2-ts-cursor)
4126 len name)))
4127 "AST node for an XML end-tag. Not currently used."
4128 name) ; a `js2-xml-name-node'
4129
4130 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4131 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4132
4133 (defun js2-visit-xml-end-tag (n v)
4134 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4135
4136 (defun js2-print-xml-end-tag (n i)
4137 (insert (js2-make-pad i))
4138 (insert "</")
4139 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4140 (insert ">"))
4141
4142 (defstruct (js2-xml-name-node
4143 (:include js2-xml-node)
4144 (:constructor nil)
4145 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4146 (pos js2-ts-cursor)
4147 len namespace kids)))
4148 "AST node for an E4X XML name. Not currently used.
4149 Any XML name can be qualified with a namespace, hence the namespace field.
4150 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4151 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4152 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4153 namespace) ; a `js2-string-node'
4154
4155 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4156 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4157
4158 (defun js2-visit-xml-name-node (n v)
4159 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4160
4161 (defun js2-print-xml-name-node (n i)
4162 (insert (js2-make-pad i))
4163 (when (js2-xml-name-node-namespace n)
4164 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4165 (insert "::"))
4166 (dolist (kid (js2-xml-name-node-kids n))
4167 (js2-print-ast kid 0)))
4168
4169 (defstruct (js2-xml-pi-node
4170 (:include js2-xml-node)
4171 (:constructor nil)
4172 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4173 (pos js2-ts-cursor)
4174 len name attrs)))
4175 "AST node for an E4X XML processing instruction. Not currently used."
4176 name ; a `js2-xml-name-node'
4177 attrs) ; a list of `js2-xml-attr-node'
4178
4179 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4180 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4181
4182 (defun js2-visit-xml-pi-node (n v)
4183 (js2-visit-ast (js2-xml-pi-node-name n) v)
4184 (dolist (attr (js2-xml-pi-node-attrs n))
4185 (js2-visit-ast attr v)))
4186
4187 (defun js2-print-xml-pi-node (n i)
4188 (insert (js2-make-pad i) "<?")
4189 (js2-print-ast (js2-xml-pi-node-name n))
4190 (when (js2-xml-pi-node-attrs n)
4191 (insert " ")
4192 (js2-print-list (js2-xml-pi-node-attrs n)))
4193 (insert "?>"))
4194
4195 (defstruct (js2-xml-cdata-node
4196 (:include js2-xml-node)
4197 (:constructor nil)
4198 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4199 (pos js2-ts-cursor)
4200 len content)))
4201 "AST node for a CDATA escape section. Not currently used."
4202 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4203
4204 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4205 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4206
4207 (defun js2-visit-xml-cdata-node (n v)
4208 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4209
4210 (defun js2-print-xml-cdata-node (n i)
4211 (insert (js2-make-pad i))
4212 (js2-print-ast (js2-xml-cdata-node-content n)))
4213
4214 (defstruct (js2-xml-attr-node
4215 (:include js2-xml-node)
4216 (:constructor nil)
4217 (:constructor make-js2-attr-node (&key (type js2-XML)
4218 (pos js2-ts-cursor)
4219 len name value
4220 eq-pos quote-type)))
4221 "AST node representing a foo='bar' XML attribute value. Not yet used."
4222 name ; a `js2-xml-name-node'
4223 value ; a `js2-xml-name-node'
4224 eq-pos ; buffer position of "=" sign
4225 quote-type) ; 'single or 'double
4226
4227 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4228 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4229
4230 (defun js2-visit-xml-attr-node (n v)
4231 (js2-visit-ast (js2-xml-attr-node-name n) v)
4232 (js2-visit-ast (js2-xml-attr-node-value n) v))
4233
4234 (defun js2-print-xml-attr-node (n i)
4235 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4236 "'"
4237 "\"")))
4238 (insert (js2-make-pad i))
4239 (js2-print-ast (js2-xml-attr-node-name n) 0)
4240 (insert "=" quote)
4241 (js2-print-ast (js2-xml-attr-node-value n) 0)
4242 (insert quote)))
4243
4244 (defstruct (js2-xml-text-node
4245 (:include js2-xml-node)
4246 (:constructor nil)
4247 (:constructor make-js2-text-node (&key (type js2-XML)
4248 (pos js2-ts-cursor)
4249 len content)))
4250 "AST node for an E4X XML text node. Not currently used."
4251 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4252
4253 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4254 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4255
4256 (defun js2-visit-xml-text-node (n v)
4257 (js2-visit-ast (js2-xml-text-node-content n) v))
4258
4259 (defun js2-print-xml-text-node (n i)
4260 (insert (js2-make-pad i))
4261 (dolist (kid (js2-xml-text-node-content n))
4262 (js2-print-ast kid)))
4263
4264 (defstruct (js2-xml-comment-node
4265 (:include js2-xml-node)
4266 (:constructor nil)
4267 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4268 (pos js2-ts-cursor)
4269 len)))
4270 "AST node for E4X XML comment. Not currently used.")
4271
4272 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4273 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4274
4275 (defun js2-print-xml-comment (n i)
4276 (insert (js2-make-pad i)
4277 (js2-node-string n)))
4278
4279 ;;; Node utilities
4280
4281 (defsubst js2-node-line (n)
4282 "Fetch the source line number at the start of node N.
4283 This is O(n) in the length of the source buffer; use prudently."
4284 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4285
4286 (defsubst js2-block-node-kid (n i)
4287 "Return child I of node N, or nil if there aren't that many."
4288 (nth i (js2-block-node-kids n)))
4289
4290 (defsubst js2-block-node-first (n)
4291 "Return first child of block node N, or nil if there is none."
4292 (first (js2-block-node-kids n)))
4293
4294 (defun js2-node-root (n)
4295 "Return the root of the AST containing N.
4296 If N has no parent pointer, returns N."
4297 (let ((parent (js2-node-parent n)))
4298 (if parent
4299 (js2-node-root parent)
4300 n)))
4301
4302 (defsubst js2-node-short-name (n)
4303 "Return the short name of node N as a string, e.g. `js2-if-node'."
4304 (substring (symbol-name (aref n 0))
4305 (length "cl-struct-")))
4306
4307 (defun js2-node-child-list (node)
4308 "Return the child list for NODE, a Lisp list of nodes.
4309 Works for block nodes, array nodes, obj literals, funarg lists,
4310 var decls and try nodes (for catch clauses). Note that you should call
4311 `js2-block-node-kids' on the function body for the body statements.
4312 Returns nil for zero-length child lists or unsupported nodes."
4313 (cond
4314 ((js2-function-node-p node)
4315 (js2-function-node-params node))
4316 ((js2-block-node-p node)
4317 (js2-block-node-kids node))
4318 ((js2-try-node-p node)
4319 (js2-try-node-catch-clauses node))
4320 ((js2-array-node-p node)
4321 (js2-array-node-elems node))
4322 ((js2-object-node-p node)
4323 (js2-object-node-elems node))
4324 ((js2-call-node-p node)
4325 (js2-call-node-args node))
4326 ((js2-new-node-p node)
4327 (js2-new-node-args node))
4328 ((js2-var-decl-node-p node)
4329 (js2-var-decl-node-kids node))
4330 (t
4331 nil)))
4332
4333 (defun js2-node-set-child-list (node kids)
4334 "Set the child list for NODE to KIDS."
4335 (cond
4336 ((js2-function-node-p node)
4337 (setf (js2-function-node-params node) kids))
4338 ((js2-block-node-p node)
4339 (setf (js2-block-node-kids node) kids))
4340 ((js2-try-node-p node)
4341 (setf (js2-try-node-catch-clauses node) kids))
4342 ((js2-array-node-p node)
4343 (setf (js2-array-node-elems node) kids))
4344 ((js2-object-node-p node)
4345 (setf (js2-object-node-elems node) kids))
4346 ((js2-call-node-p node)
4347 (setf (js2-call-node-args node) kids))
4348 ((js2-new-node-p node)
4349 (setf (js2-new-node-args node) kids))
4350 ((js2-var-decl-node-p node)
4351 (setf (js2-var-decl-node-kids node) kids))
4352 (t
4353 (error "Unsupported node type: %s" (js2-node-short-name node))))
4354 kids)
4355
4356 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4357 (defconst js2-paren-expr-nodes
4358 '(cl-struct-js2-comp-loop-node
4359 cl-struct-js2-comp-node
4360 cl-struct-js2-call-node
4361 cl-struct-js2-catch-node
4362 cl-struct-js2-do-node
4363 cl-struct-js2-elem-get-node
4364 cl-struct-js2-for-in-node
4365 cl-struct-js2-for-node
4366 cl-struct-js2-function-node
4367 cl-struct-js2-if-node
4368 cl-struct-js2-let-node
4369 cl-struct-js2-new-node
4370 cl-struct-js2-paren-node
4371 cl-struct-js2-switch-node
4372 cl-struct-js2-while-node
4373 cl-struct-js2-with-node
4374 cl-struct-js2-xml-dot-query-node)
4375 "Node types that can have a parenthesized child expression.
4376 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4377
4378 (defsubst js2-paren-expr-node-p (node)
4379 "Return t for nodes that typically have a parenthesized child expression.
4380 Useful for computing the indentation anchors for arg-lists and conditions.
4381 Note that it may return a false positive, for instance when NODE is
4382 a `js2-new-node' and there are no arguments or parentheses."
4383 (memq (aref node 0) js2-paren-expr-nodes))
4384
4385 ;; Fake polymorphism... yech.
4386 (defun js2-node-lp (node)
4387 "Return relative left-paren position for NODE, if applicable.
4388 For `js2-elem-get-node' structs, returns left-bracket position.
4389 Note that the position may be nil in the case of a parse error."
4390 (cond
4391 ((js2-elem-get-node-p node)
4392 (js2-elem-get-node-lb node))
4393 ((js2-loop-node-p node)
4394 (js2-loop-node-lp node))
4395 ((js2-function-node-p node)
4396 (js2-function-node-lp node))
4397 ((js2-if-node-p node)
4398 (js2-if-node-lp node))
4399 ((js2-new-node-p node)
4400 (js2-new-node-lp node))
4401 ((js2-call-node-p node)
4402 (js2-call-node-lp node))
4403 ((js2-paren-node-p node)
4404 0)
4405 ((js2-switch-node-p node)
4406 (js2-switch-node-lp node))
4407 ((js2-catch-node-p node)
4408 (js2-catch-node-lp node))
4409 ((js2-let-node-p node)
4410 (js2-let-node-lp node))
4411 ((js2-comp-node-p node)
4412 0)
4413 ((js2-with-node-p node)
4414 (js2-with-node-lp node))
4415 ((js2-xml-dot-query-node-p node)
4416 (1+ (js2-infix-node-op-pos node)))
4417 (t
4418 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4419
4420 ;; Fake polymorphism... blech.
4421 (defun js2-node-rp (node)
4422 "Return relative right-paren position for NODE, if applicable.
4423 For `js2-elem-get-node' structs, returns right-bracket position.
4424 Note that the position may be nil in the case of a parse error."
4425 (cond
4426 ((js2-elem-get-node-p node)
4427 (js2-elem-get-node-rb node))
4428 ((js2-loop-node-p node)
4429 (js2-loop-node-rp node))
4430 ((js2-function-node-p node)
4431 (js2-function-node-rp node))
4432 ((js2-if-node-p node)
4433 (js2-if-node-rp node))
4434 ((js2-new-node-p node)
4435 (js2-new-node-rp node))
4436 ((js2-call-node-p node)
4437 (js2-call-node-rp node))
4438 ((js2-paren-node-p node)
4439 (1- (js2-node-len node)))
4440 ((js2-switch-node-p node)
4441 (js2-switch-node-rp node))
4442 ((js2-catch-node-p node)
4443 (js2-catch-node-rp node))
4444 ((js2-let-node-p node)
4445 (js2-let-node-rp node))
4446 ((js2-comp-node-p node)
4447 (1- (js2-node-len node)))
4448 ((js2-with-node-p node)
4449 (js2-with-node-rp node))
4450 ((js2-xml-dot-query-node-p node)
4451 (1+ (js2-xml-dot-query-node-rp node)))
4452 (t
4453 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4454
4455 (defsubst js2-node-first-child (node)
4456 "Return the first element of `js2-node-child-list' for NODE."
4457 (car (js2-node-child-list node)))
4458
4459 (defsubst js2-node-last-child (node)
4460 "Return the last element of `js2-node-last-child' for NODE."
4461 (car (last (js2-node-child-list node))))
4462
4463 (defun js2-node-prev-sibling (node)
4464 "Return the previous statement in parent.
4465 Works for parents supported by `js2-node-child-list'.
4466 Returns nil if NODE is not in the parent, or PARENT is
4467 not a supported node, or if NODE is the first child."
4468 (let* ((p (js2-node-parent node))
4469 (kids (js2-node-child-list p))
4470 (sib (car kids)))
4471 (while (and kids
4472 (not (eq node (cadr kids))))
4473 (setq kids (cdr kids)
4474 sib (car kids)))
4475 sib))
4476
4477 (defun js2-node-next-sibling (node)
4478 "Return the next statement in parent block.
4479 Returns nil if NODE is not in the block, or PARENT is not
4480 a block node, or if NODE is the last statement."
4481 (let* ((p (js2-node-parent node))
4482 (kids (js2-node-child-list p)))
4483 (while (and kids
4484 (not (eq node (car kids))))
4485 (setq kids (cdr kids)))
4486 (cadr kids)))
4487
4488 (defun js2-node-find-child-before (pos parent &optional after)
4489 "Find the last child that starts before POS in parent.
4490 If AFTER is non-nil, returns first child starting after POS.
4491 POS is an absolute buffer position. PARENT is any node
4492 supported by `js2-node-child-list'.
4493 Returns nil if no applicable child is found."
4494 (let ((kids (if (js2-function-node-p parent)
4495 (js2-block-node-kids (js2-function-node-body parent))
4496 (js2-node-child-list parent)))
4497 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4498 (js2-function-node-body parent)
4499 parent)))
4500 kid result fn
4501 (continue t))
4502 (setq fn (if after '>= '<))
4503 (while (and kids continue)
4504 (setq kid (car kids))
4505 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4506 (setq result kid
4507 continue (not after))
4508 (setq continue after))
4509 (setq kids (cdr kids)))
4510 result))
4511
4512 (defun js2-node-find-child-after (pos parent)
4513 "Find first child that starts after POS in parent.
4514 POS is an absolute buffer position. PARENT is any node
4515 supported by `js2-node-child-list'.
4516 Returns nil if no applicable child is found."
4517 (js2-node-find-child-before pos parent 'after))
4518
4519 (defun js2-node-replace-child (pos parent new-node)
4520 "Replace node at index POS in PARENT with NEW-NODE.
4521 Only works for parents supported by `js2-node-child-list'."
4522 (let ((kids (js2-node-child-list parent))
4523 (i 0))
4524 (while (< i pos)
4525 (setq kids (cdr kids)
4526 i (1+ i)))
4527 (setcar kids new-node)
4528 (js2-node-add-children parent new-node)))
4529
4530 (defun js2-node-buffer (n)
4531 "Return the buffer associated with AST N.
4532 Returns nil if the buffer is not set as a property on the root
4533 node, or if parent links were not recorded during parsing."
4534 (let ((root (js2-node-root n)))
4535 (and root
4536 (js2-ast-root-p root)
4537 (js2-ast-root-buffer root))))
4538
4539 (defun js2-block-node-push (n kid)
4540 "Push js2-node KID onto the end of js2-block-node N's child list.
4541 KID is always added to the -end- of the kids list.
4542 Function also calls `js2-node-add-children' to add the parent link."
4543 (let ((kids (js2-node-child-list n)))
4544 (if kids
4545 (setcdr kids (nconc (cdr kids) (list kid)))
4546 (js2-node-set-child-list n (list kid)))
4547 (js2-node-add-children n kid)))
4548
4549 (defun js2-node-string (node)
4550 (with-current-buffer (or (js2-node-buffer node)
4551 (error "No buffer available for node %s" node))
4552 (let ((pos (js2-node-abs-pos node)))
4553 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4554
4555 ;; Container for storing the node we're looking for in a traversal.
4556 (js2-deflocal js2-discovered-node nil)
4557
4558 ;; Keep track of absolute node position during traversals.
4559 (js2-deflocal js2-visitor-offset nil)
4560
4561 (js2-deflocal js2-node-search-point nil)
4562
4563 (when js2-mode-dev-mode-p
4564 (defun js2-find-node-at-point ()
4565 (interactive)
4566 (let ((node (js2-node-at-point)))
4567 (message "%s" (or node "No node found at point"))))
4568 (defun js2-node-name-at-point ()
4569 (interactive)
4570 (let ((node (js2-node-at-point)))
4571 (message "%s" (if node
4572 (js2-node-short-name node)
4573 "No node found at point.")))))
4574
4575 (defun js2-node-at-point (&optional pos skip-comments)
4576 "Return AST node at POS, a buffer position, defaulting to current point.
4577 The `js2-mode-ast' variable must be set to the current parse tree.
4578 Signals an error if the AST (`js2-mode-ast') is nil.
4579 Always returns a node - if it can't find one, it returns the root.
4580 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4581 (let ((ast js2-mode-ast)
4582 result)
4583 (unless ast
4584 (error "No JavaScript AST available"))
4585 ;; Look through comments first, since they may be inside nodes that
4586 ;; would otherwise report a match.
4587 (setq pos (or pos (point))
4588 result (if (> pos (js2-node-abs-end ast))
4589 ast
4590 (if (not skip-comments)
4591 (js2-comment-at-point pos))))
4592 (unless result
4593 (setq js2-discovered-node nil
4594 js2-visitor-offset 0
4595 js2-node-search-point pos)
4596 (unwind-protect
4597 (catch 'js2-visit-done
4598 (js2-visit-ast ast #'js2-node-at-point-visitor))
4599 (setq js2-visitor-offset nil
4600 js2-node-search-point nil))
4601 (setq result js2-discovered-node))
4602 ;; may have found a comment beyond end of last child node,
4603 ;; since visiting the ast-root looks at the comment-list last.
4604 (if (and skip-comments
4605 (js2-comment-node-p result))
4606 (setq result nil))
4607 (or result js2-mode-ast)))
4608
4609 (defun js2-node-at-point-visitor (node end-p)
4610 (let ((rel-pos (js2-node-pos node))
4611 abs-pos
4612 abs-end
4613 (point js2-node-search-point))
4614 (cond
4615 (end-p
4616 ;; this evaluates to a non-nil return value, even if it's zero
4617 (decf js2-visitor-offset rel-pos))
4618 ;; we already looked for comments before visiting, and don't want them now
4619 ((js2-comment-node-p node)
4620 nil)
4621 (t
4622 (setq abs-pos (incf js2-visitor-offset rel-pos)
4623 ;; we only want to use the node if the point is before
4624 ;; the last character position in the node, so we decrement
4625 ;; the absolute end by 1.
4626 abs-end (+ abs-pos (js2-node-len node) -1))
4627 (cond
4628 ;; If this node starts after search-point, stop the search.
4629 ((> abs-pos point)
4630 (throw 'js2-visit-done nil))
4631 ;; If this node ends before the search-point, don't check kids.
4632 ((> point abs-end)
4633 nil)
4634 (t
4635 ;; Otherwise point is within this node, possibly in a child.
4636 (setq js2-discovered-node node)
4637 t)))))) ; keep processing kids to look for more specific match
4638
4639 (defsubst js2-block-comment-p (node)
4640 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4641 (and (js2-comment-node-p node)
4642 (memq (js2-comment-node-format node) '(jsdoc block))))
4643
4644 ;; TODO: put the comments in a vector and binary-search them instead
4645 (defun js2-comment-at-point (&optional pos)
4646 "Look through scanned comment nodes for one containing POS.
4647 POS is a buffer position that defaults to current point.
4648 Function returns nil if POS was not in any comment node."
4649 (let ((ast js2-mode-ast)
4650 (x (or pos (point)))
4651 beg end)
4652 (unless ast
4653 (error "No JavaScript AST available"))
4654 (catch 'done
4655 ;; Comments are stored in lexical order.
4656 (dolist (comment (js2-ast-root-comments ast) nil)
4657 (setq beg (js2-node-abs-pos comment)
4658 end (+ beg (js2-node-len comment)))
4659 (if (and (>= x beg)
4660 (<= x end))
4661 (throw 'done comment))))))
4662
4663 (defun js2-mode-find-parent-fn (node)
4664 "Find function enclosing NODE.
4665 Returns nil if NODE is not inside a function."
4666 (setq node (js2-node-parent node))
4667 (while (and node (not (js2-function-node-p node)))
4668 (setq node (js2-node-parent node)))
4669 (and (js2-function-node-p node) node))
4670
4671 (defun js2-mode-find-enclosing-fn (node)
4672 "Find function or root enclosing NODE."
4673 (if (js2-ast-root-p node)
4674 node
4675 (setq node (js2-node-parent node))
4676 (while (not (or (js2-ast-root-p node)
4677 (js2-function-node-p node)))
4678 (setq node (js2-node-parent node)))
4679 node))
4680
4681 (defun js2-mode-find-enclosing-node (beg end)
4682 "Find node fully enclosing BEG and END."
4683 (let ((node (js2-node-at-point beg))
4684 pos
4685 (continue t))
4686 (while continue
4687 (if (or (js2-ast-root-p node)
4688 (and
4689 (<= (setq pos (js2-node-abs-pos node)) beg)
4690 (>= (+ pos (js2-node-len node)) end)))
4691 (setq continue nil)
4692 (setq node (js2-node-parent node))))
4693 node))
4694
4695 (defun js2-node-parent-script-or-fn (node)
4696 "Find script or function immediately enclosing NODE.
4697 If NODE is the ast-root, returns nil."
4698 (if (js2-ast-root-p node)
4699 nil
4700 (setq node (js2-node-parent node))
4701 (while (and node (not (or (js2-function-node-p node)
4702 (js2-script-node-p node))))
4703 (setq node (js2-node-parent node)))
4704 node))
4705
4706 (defun js2-node-is-descendant (node ancestor)
4707 "Return t if NODE is a descendant of ANCESTOR."
4708 (while (and node
4709 (not (eq node ancestor)))
4710 (setq node (js2-node-parent node)))
4711 node)
4712
4713 ;;; visitor infrastructure
4714
4715 (defun js2-visit-none (_node _callback)
4716 "Visitor for AST node that have no node children."
4717 nil)
4718
4719 (defun js2-print-none (_node _indent)
4720 "Visitor for AST node with no printed representation.")
4721
4722 (defun js2-print-body (node indent)
4723 "Print a statement, or a block without braces."
4724 (if (js2-block-node-p node)
4725 (dolist (kid (js2-block-node-kids node))
4726 (js2-print-ast kid indent))
4727 (js2-print-ast node indent)))
4728
4729 (defun js2-print-list (args &optional delimiter)
4730 (loop with len = (length args)
4731 for arg in args
4732 for count from 1
4733 do
4734 (when arg (js2-print-ast arg 0))
4735 (if (< count len)
4736 (insert (or delimiter ", ")))))
4737
4738 (defun js2-print-tree (ast)
4739 "Prints an AST to the current buffer.
4740 Makes `js2-ast-parent-nodes' available to the printer functions."
4741 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4742 (js2-print-ast ast)))
4743
4744 (defun js2-print-ast (node &optional indent)
4745 "Helper function for printing AST nodes.
4746 Requires `js2-ast-parent-nodes' to be non-nil.
4747 You should use `js2-print-tree' instead of this function."
4748 (let ((printer (get (aref node 0) 'js2-printer))
4749 (i (or indent 0)))
4750 ;; TODO: wedge comments in here somewhere
4751 (if printer
4752 (funcall printer node i))))
4753
4754 (defconst js2-side-effecting-tokens
4755 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4756 (dolist (tt (list js2-ASSIGN
4757 js2-ASSIGN_ADD
4758 js2-ASSIGN_BITAND
4759 js2-ASSIGN_BITOR
4760 js2-ASSIGN_BITXOR
4761 js2-ASSIGN_DIV
4762 js2-ASSIGN_LSH
4763 js2-ASSIGN_MOD
4764 js2-ASSIGN_MUL
4765 js2-ASSIGN_RSH
4766 js2-ASSIGN_SUB
4767 js2-ASSIGN_URSH
4768 js2-BLOCK
4769 js2-BREAK
4770 js2-CALL
4771 js2-CATCH
4772 js2-CATCH_SCOPE
4773 js2-CLASS
4774 js2-CONST
4775 js2-CONTINUE
4776 js2-DEBUGGER
4777 js2-DEC
4778 js2-DELPROP
4779 js2-DEL_REF
4780 js2-DO
4781 js2-ELSE
4782 js2-EMPTY
4783 js2-ENTERWITH
4784 js2-EXPORT
4785 js2-EXPR_RESULT
4786 js2-FINALLY
4787 js2-FOR
4788 js2-FUNCTION
4789 js2-GOTO
4790 js2-IF
4791 js2-IFEQ
4792 js2-IFNE
4793 js2-IMPORT
4794 js2-INC
4795 js2-JSR
4796 js2-LABEL
4797 js2-LEAVEWITH
4798 js2-LET
4799 js2-LETEXPR
4800 js2-LOCAL_BLOCK
4801 js2-LOOP
4802 js2-NEW
4803 js2-REF_CALL
4804 js2-RETHROW
4805 js2-RETURN
4806 js2-RETURN_RESULT
4807 js2-SEMI
4808 js2-SETELEM
4809 js2-SETELEM_OP
4810 js2-SETNAME
4811 js2-SETPROP
4812 js2-SETPROP_OP
4813 js2-SETVAR
4814 js2-SET_REF
4815 js2-SET_REF_OP
4816 js2-SWITCH
4817 js2-TARGET
4818 js2-THROW
4819 js2-TRY
4820 js2-VAR
4821 js2-WHILE
4822 js2-WITH
4823 js2-WITHEXPR
4824 js2-YIELD))
4825 (aset tokens tt t))
4826 (if js2-instanceof-has-side-effects
4827 (aset tokens js2-INSTANCEOF t))
4828 tokens))
4829
4830 (defun js2-node-has-side-effects (node)
4831 "Return t if NODE has side effects."
4832 (when node ; makes it easier to handle malformed expressions
4833 (let ((tt (js2-node-type node)))
4834 (cond
4835 ;; This doubtless needs some work, since EXPR_VOID is used
4836 ;; in several ways in Rhino and I may not have caught them all.
4837 ;; I'll wait for people to notice incorrect warnings.
4838 ((and (= tt js2-EXPR_VOID)
4839 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4840 (let ((expr (js2-expr-stmt-node-expr node)))
4841 (or (js2-node-has-side-effects expr)
4842 (when (js2-string-node-p expr)
4843 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4844 ((= tt js2-COMMA)
4845 (js2-node-has-side-effects (js2-infix-node-right node)))
4846 ((or (= tt js2-AND)
4847 (= tt js2-OR))
4848 (or (js2-node-has-side-effects (js2-infix-node-right node))
4849 (js2-node-has-side-effects (js2-infix-node-left node))))
4850 ((= tt js2-HOOK)
4851 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4852 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4853 ((js2-paren-node-p node)
4854 (js2-node-has-side-effects (js2-paren-node-expr node)))
4855 ((= tt js2-ERROR) ; avoid cascaded error messages
4856 nil)
4857 (t
4858 (aref js2-side-effecting-tokens tt))))))
4859
4860 (defconst js2-stmt-node-types
4861 (list js2-BLOCK
4862 js2-BREAK
4863 js2-CONTINUE
4864 js2-DEFAULT ; e4x "default xml namespace" statement
4865 js2-DO
4866 js2-EXPR_RESULT
4867 js2-EXPR_VOID
4868 js2-FOR
4869 js2-IF
4870 js2-RETURN
4871 js2-SWITCH
4872 js2-THROW
4873 js2-TRY
4874 js2-WHILE
4875 js2-WITH)
4876 "Node types that only appear in statement contexts.
4877 The list does not include nodes that always appear as the child
4878 of another specific statement type, such as switch-cases,
4879 catch and finally blocks, and else-clauses. The list also excludes
4880 nodes like yield, let and var, which may appear in either expression
4881 or statement context, and in the latter context always have a
4882 `js2-expr-stmt-node' parent. Finally, the list does not include
4883 functions or scripts, which are treated separately from statements
4884 by the JavaScript parser and runtime.")
4885
4886 (defun js2-stmt-node-p (node)
4887 "Heuristic for figuring out if NODE is a statement.
4888 Some node types can appear in either an expression context or a
4889 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4890 For these node types in a statement context, the parent will be a
4891 `js2-expr-stmt-node'.
4892 Functions aren't included in the check."
4893 (memq (js2-node-type node) js2-stmt-node-types))
4894
4895 (defun js2-mode-find-first-stmt (node)
4896 "Search upward starting from NODE looking for a statement.
4897 For purposes of this function, a `js2-function-node' counts."
4898 (while (not (or (js2-stmt-node-p node)
4899 (js2-function-node-p node)))
4900 (setq node (js2-node-parent node)))
4901 node)
4902
4903 (defun js2-node-parent-stmt (node)
4904 "Return the node's first ancestor that is a statement.
4905 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4906 appearing in a statement context will have a parent that is a
4907 `js2-expr-stmt-node' that will be returned by this function."
4908 (let ((parent (js2-node-parent node)))
4909 (if (or (null parent)
4910 (js2-stmt-node-p parent)
4911 (and (js2-function-node-p parent)
4912 (not (eq (js2-function-node-form parent)
4913 'FUNCTION_EXPRESSION))))
4914 parent
4915 (js2-node-parent-stmt parent))))
4916
4917 ;; In the Mozilla Rhino sources, Roshan James writes:
4918 ;; Does consistent-return analysis on the function body when strict mode is
4919 ;; enabled.
4920 ;;
4921 ;; function (x) { return (x+1) }
4922 ;;
4923 ;; is ok, but
4924 ;;
4925 ;; function (x) { if (x < 0) return (x+1); }
4926 ;;
4927 ;; is not because the function can potentially return a value when the
4928 ;; condition is satisfied and if not, the function does not explicitly
4929 ;; return a value.
4930 ;;
4931 ;; This extends to checking mismatches such as "return" and "return <value>"
4932 ;; used in the same function. Warnings are not emitted if inconsistent
4933 ;; returns exist in code that can be statically shown to be unreachable.
4934 ;; Ex.
4935 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4936 ;;
4937 ;; emits no warning. However if the loop had a break statement, then a
4938 ;; warning would be emitted.
4939 ;;
4940 ;; The consistency analysis looks at control structures such as loops, ifs,
4941 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4942 ;; warns the user about an inconsistent set of termination possibilities.
4943 ;;
4944 ;; These flags enumerate the possible ways a statement/function can
4945 ;; terminate. These flags are used by endCheck() and by the Parser to
4946 ;; detect inconsistent return usage.
4947 ;;
4948 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4949 ;; able to execute (example: throw, continue)
4950 ;;
4951 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4952 ;; next one. Statement such as return dont. A compound statement may have
4953 ;; some branch that drops off control to the next statement.
4954 ;;
4955 ;; END_RETURNS indicates that the statement can return with no value.
4956 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4957 ;;
4958 ;; A compound statement such as
4959 ;; if (condition) {
4960 ;; return value;
4961 ;; }
4962 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4963
4964 (defconst js2-END_UNREACHED 0)
4965 (defconst js2-END_DROPS_OFF 1)
4966 (defconst js2-END_RETURNS 2)
4967 (defconst js2-END_RETURNS_VALUE 4)
4968 (defconst js2-END_YIELDS 8)
4969
4970 (defun js2-has-consistent-return-usage (node)
4971 "Check that every return usage in a function body is consistent.
4972 Returns t if the function satisfies strict mode requirement."
4973 (let ((n (js2-end-check node)))
4974 ;; either it doesn't return a value in any branch...
4975 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4976 ;; or it returns a value (or is unreached) at every branch
4977 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4978 js2-END_RETURNS
4979 js2-END_YIELDS)))))
4980
4981 (defun js2-end-check-if (node)
4982 "Ensure that return usage in then/else blocks is consistent.
4983 If there is no else block, then the return statement can fall through.
4984 Returns logical OR of END_* flags"
4985 (let ((th (js2-if-node-then-part node))
4986 (el (js2-if-node-else-part node)))
4987 (if (null th)
4988 js2-END_UNREACHED
4989 (logior (js2-end-check th) (if el
4990 (js2-end-check el)
4991 js2-END_DROPS_OFF)))))
4992
4993 (defun js2-end-check-switch (node)
4994 "Consistency of return statements is checked between the case statements.
4995 If there is no default, then the switch can fall through. If there is a
4996 default, we check to see if all code paths in the default return or if
4997 there is a code path that can fall through.
4998 Returns logical OR of END_* flags."
4999 (let ((rv js2-END_UNREACHED)
5000 default-case)
5001 ;; examine the cases
5002 (catch 'break
5003 (dolist (c (js2-switch-node-cases node))
5004 (if (js2-case-node-expr c)
5005 (js2-set-flag rv (js2-end-check-block c))
5006 (setq default-case c)
5007 (throw 'break nil))))
5008 ;; we don't care how the cases drop into each other
5009 (js2-clear-flag rv js2-END_DROPS_OFF)
5010 ;; examine the default
5011 (js2-set-flag rv (if default-case
5012 (js2-end-check default-case)
5013 js2-END_DROPS_OFF))
5014 rv))
5015
5016 (defun js2-end-check-try (node)
5017 "If the block has a finally, return consistency is checked in the
5018 finally block. If all code paths in the finally return, then the
5019 returns in the try-catch blocks don't matter. If there is a code path
5020 that does not return or if there is no finally block, the returns
5021 of the try and catch blocks are checked for mismatch.
5022 Returns logical OR of END_* flags."
5023 (let ((finally (js2-try-node-finally-block node))
5024 rv)
5025 ;; check the finally if it exists
5026 (setq rv (if finally
5027 (js2-end-check (js2-finally-node-body finally))
5028 js2-END_DROPS_OFF))
5029 ;; If the finally block always returns, then none of the returns
5030 ;; in the try or catch blocks matter.
5031 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5032 (js2-clear-flag rv js2-END_DROPS_OFF)
5033 ;; examine the try block
5034 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5035 ;; check each catch block
5036 (dolist (cb (js2-try-node-catch-clauses node))
5037 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5038 rv))
5039
5040 (defun js2-end-check-loop (node)
5041 "Return statement in the loop body must be consistent.
5042 The default assumption for any kind of a loop is that it will eventually
5043 terminate. The only exception is a loop with a constant true condition.
5044 Code that follows such a loop is examined only if one can determine
5045 statically that there is a break out of the loop.
5046
5047 for(... ; ... ; ...) {}
5048 for(... in ... ) {}
5049 while(...) { }
5050 do { } while(...)
5051
5052 Returns logical OR of END_* flags."
5053 (let ((rv (js2-end-check (js2-loop-node-body node)))
5054 (condition (cond
5055 ((js2-while-node-p node)
5056 (js2-while-node-condition node))
5057 ((js2-do-node-p node)
5058 (js2-do-node-condition node))
5059 ((js2-for-node-p node)
5060 (js2-for-node-condition node)))))
5061
5062 ;; check to see if the loop condition is always true
5063 (if (and condition
5064 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5065 (js2-clear-flag rv js2-END_DROPS_OFF))
5066
5067 ;; look for effect of breaks
5068 (js2-set-flag rv (js2-node-get-prop node
5069 'CONTROL_BLOCK_PROP
5070 js2-END_UNREACHED))
5071 rv))
5072
5073 (defun js2-end-check-block (node)
5074 "A general block of code is examined statement by statement.
5075 If any statement (even a compound one) returns in all branches, then
5076 subsequent statements are not examined.
5077 Returns logical OR of END_* flags."
5078 (let* ((rv js2-END_DROPS_OFF)
5079 (kids (js2-block-node-kids node))
5080 (n (car kids)))
5081 ;; Check each statment. If the statement can continue onto the next
5082 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5083 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5084 (js2-clear-flag rv js2-END_DROPS_OFF)
5085 (js2-set-flag rv (js2-end-check n))
5086 (setq kids (cdr kids)
5087 n (car kids)))
5088 rv))
5089
5090 (defun js2-end-check-label (node)
5091 "A labeled statement implies that there may be a break to the label.
5092 The function processes the labeled statement and then checks the
5093 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5094 particular label.
5095 Returns logical OR of END_* flags."
5096 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5097 (logior rv (js2-node-get-prop node
5098 'CONTROL_BLOCK_PROP
5099 js2-END_UNREACHED))))
5100
5101 (defun js2-end-check-break (node)
5102 "When a break is encountered annotate the statement being broken
5103 out of by setting its CONTROL_BLOCK_PROP property.
5104 Returns logical OR of END_* flags."
5105 (and (js2-break-node-target node)
5106 (js2-node-set-prop (js2-break-node-target node)
5107 'CONTROL_BLOCK_PROP
5108 js2-END_DROPS_OFF))
5109 js2-END_UNREACHED)
5110
5111 (defun js2-end-check (node)
5112 "Examine the body of a function, doing a basic reachability analysis.
5113 Returns a combination of flags END_* flags that indicate
5114 how the function execution can terminate. These constitute only the
5115 pessimistic set of termination conditions. It is possible that at
5116 runtime certain code paths will never be actually taken. Hence this
5117 analysis will flag errors in cases where there may not be errors.
5118 Returns logical OR of END_* flags"
5119 (let (kid)
5120 (cond
5121 ((js2-break-node-p node)
5122 (js2-end-check-break node))
5123 ((js2-expr-stmt-node-p node)
5124 (if (setq kid (js2-expr-stmt-node-expr node))
5125 (js2-end-check kid)
5126 js2-END_DROPS_OFF))
5127 ((or (js2-continue-node-p node)
5128 (js2-throw-node-p node))
5129 js2-END_UNREACHED)
5130 ((js2-return-node-p node)
5131 (if (setq kid (js2-return-node-retval node))
5132 js2-END_RETURNS_VALUE
5133 js2-END_RETURNS))
5134 ((js2-loop-node-p node)
5135 (js2-end-check-loop node))
5136 ((js2-switch-node-p node)
5137 (js2-end-check-switch node))
5138 ((js2-labeled-stmt-node-p node)
5139 (js2-end-check-label node))
5140 ((js2-if-node-p node)
5141 (js2-end-check-if node))
5142 ((js2-try-node-p node)
5143 (js2-end-check-try node))
5144 ((js2-block-node-p node)
5145 (if (null (js2-block-node-kids node))
5146 js2-END_DROPS_OFF
5147 (js2-end-check-block node)))
5148 ((js2-yield-node-p node)
5149 js2-END_YIELDS)
5150 (t
5151 js2-END_DROPS_OFF))))
5152
5153 (defun js2-always-defined-boolean-p (node)
5154 "Check if NODE always evaluates to true or false in boolean context.
5155 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5156 nor always false."
5157 (let ((tt (js2-node-type node))
5158 num)
5159 (cond
5160 ((or (= tt js2-FALSE) (= tt js2-NULL))
5161 'ALWAYS_FALSE)
5162 ((= tt js2-TRUE)
5163 'ALWAYS_TRUE)
5164 ((= tt js2-NUMBER)
5165 (setq num (js2-number-node-num-value node))
5166 (if (and (not (eq num 0.0e+NaN))
5167 (not (zerop num)))
5168 'ALWAYS_TRUE
5169 'ALWAYS_FALSE))
5170 (t
5171 nil))))
5172
5173 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5174 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5175
5176 (defvar js2-tokens nil
5177 "List of all defined token names.") ; initialized in `js2-token-names'
5178
5179 (defconst js2-token-names
5180 (let* ((names (make-vector js2-num-tokens -1))
5181 (case-fold-search nil) ; only match js2-UPPER_CASE
5182 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5183 (loop for sym in syms
5184 for i from 0
5185 do
5186 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5187 (not (boundp sym)))
5188 (aset names (symbol-value sym) ; code, e.g. 152
5189 (downcase
5190 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5191 (push sym js2-tokens)))
5192 names)
5193 "Vector mapping int values to token string names, sans `js2-' prefix.")
5194
5195 (defun js2-tt-name (tok)
5196 "Return a string name for TOK, a token symbol or code.
5197 Signals an error if it's not a recognized token."
5198 (let ((code tok))
5199 (if (symbolp tok)
5200 (setq code (symbol-value tok)))
5201 (if (eq code -1)
5202 "ERROR"
5203 (if (and (numberp code)
5204 (not (minusp code))
5205 (< code js2-num-tokens))
5206 (aref js2-token-names code)
5207 (error "Invalid token: %s" code)))))
5208
5209 (defsubst js2-tt-sym (tok)
5210 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5211 (intern (js2-tt-name tok)))
5212
5213 (defconst js2-token-codes
5214 (let ((table (make-hash-table :test 'eq :size 256)))
5215 (loop for name across js2-token-names
5216 for sym = (intern (concat "js2-" (upcase name)))
5217 do
5218 (puthash sym (symbol-value sym) table))
5219 ;; clean up a few that are "wrong" in Rhino's token codes
5220 (puthash 'js2-DELETE js2-DELPROP table)
5221 table)
5222 "Hashtable mapping token type symbols to their bytecodes.")
5223
5224 (defsubst js2-tt-code (sym)
5225 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5226 (or (gethash sym js2-token-codes)
5227 (error "Invalid token symbol: %s " sym))) ; signal code bug
5228
5229 (defun js2-report-scan-error (msg &optional no-throw beg len)
5230 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5231 (js2-report-error msg nil
5232 (or beg (js2-current-token-beg))
5233 (or len (js2-current-token-len)))
5234 (unless no-throw
5235 (throw 'return js2-ERROR)))
5236
5237 (defun js2-set-string-from-buffer (token)
5238 "Set `string' and `end' slots for TOKEN, return the string."
5239 (setf (js2-token-end token) js2-ts-cursor
5240 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5241
5242 ;; TODO: could potentially avoid a lot of consing by allocating a
5243 ;; char buffer the way Rhino does.
5244 (defsubst js2-add-to-string (c)
5245 (push c js2-ts-string-buffer))
5246
5247 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5248 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5249 ;; any other character: when it's not part of the current token, we
5250 ;; unget it, allowing it to be read again by the following call.
5251 (defsubst js2-unget-char ()
5252 (decf js2-ts-cursor))
5253
5254 ;; Rhino distinguishes \r and \n line endings. We don't need to
5255 ;; because we only scan from Emacs buffers, which always use \n.
5256 (defun js2-get-char ()
5257 "Read and return the next character from the input buffer.
5258 Increments `js2-ts-lineno' if the return value is a newline char.
5259 Updates `js2-ts-cursor' to the point after the returned char.
5260 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5261 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5262 (let (c)
5263 ;; check for end of buffer
5264 (if (>= js2-ts-cursor (point-max))
5265 (setq js2-ts-hit-eof t
5266 js2-ts-cursor (1+ js2-ts-cursor)
5267 c js2-EOF_CHAR) ; return value
5268 ;; otherwise read next char
5269 (setq c (char-before (incf js2-ts-cursor)))
5270 ;; if we read a newline, update counters
5271 (if (= c ?\n)
5272 (setq js2-ts-line-start js2-ts-cursor
5273 js2-ts-lineno (1+ js2-ts-lineno)))
5274 ;; TODO: skip over format characters
5275 c)))
5276
5277 (defun js2-read-unicode-escape ()
5278 "Read a \\uNNNN sequence from the input.
5279 Assumes the ?\ and ?u have already been read.
5280 Returns the unicode character, or nil if it wasn't a valid character.
5281 Doesn't change the values of any scanner variables."
5282 ;; I really wish I knew a better way to do this, but I can't
5283 ;; find the Emacs function that takes a 16-bit int and converts
5284 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5285 ;; Have to first check that it's 4 hex characters or it may stop
5286 ;; the read early.
5287 (ignore-errors
5288 (let ((s (buffer-substring-no-properties js2-ts-cursor
5289 (+ 4 js2-ts-cursor))))
5290 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5291 (read (concat "?\\u" s))))))
5292
5293 (defun js2-match-char (test)
5294 "Consume and return next character if it matches TEST, a character.
5295 Returns nil and consumes nothing if TEST is not the next character."
5296 (let ((c (js2-get-char)))
5297 (if (eq c test)
5298 t
5299 (js2-unget-char)
5300 nil)))
5301
5302 (defun js2-peek-char ()
5303 (prog1
5304 (js2-get-char)
5305 (js2-unget-char)))
5306
5307 (defun js2-identifier-start-p (c)
5308 "Is C a valid start to an ES5 Identifier?
5309 See http://es5.github.io/#x7.6"
5310 (or
5311 (memq c '(?$ ?_))
5312 (memq (get-char-code-property c 'general-category)
5313 ;; Letters
5314 '(Lu Ll Lt Lm Lo Nl))))
5315
5316 (defun js2-identifier-part-p (c)
5317 "Is C a valid part of an ES5 Identifier?
5318 See http://es5.github.io/#x7.6"
5319 (or
5320 (memq c '(?$ ?_ ?\u200c ?\u200d))
5321 (memq (get-char-code-property c 'general-category)
5322 '(;; Letters
5323 Lu Ll Lt Lm Lo Nl
5324 ;; Combining Marks
5325 Mn Mc
5326 ;; Digits
5327 Nd
5328 ;; Connector Punctuation
5329 Pc))))
5330
5331 (defun js2-alpha-p (c)
5332 (cond ((and (<= ?A c) (<= c ?Z)) t)
5333 ((and (<= ?a c) (<= c ?z)) t)
5334 (t nil)))
5335
5336 (defsubst js2-digit-p (c)
5337 (and (<= ?0 c) (<= c ?9)))
5338
5339 (defun js2-js-space-p (c)
5340 (if (<= c 127)
5341 (memq c '(#x20 #x9 #xB #xC #xD))
5342 (or
5343 (eq c #xA0)
5344 ;; TODO: change this nil to check for Unicode space character
5345 nil)))
5346
5347 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5348
5349 (defun js2-skip-line ()
5350 "Skip to end of line."
5351 (while (not (memq (js2-get-char) js2-eol-chars)))
5352 (js2-unget-char)
5353 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5354 (setq js2-token-end js2-ts-cursor))
5355
5356 (defun js2-init-scanner (&optional buf line)
5357 "Create token stream for BUF starting on LINE.
5358 BUF defaults to `current-buffer' and LINE defaults to 1.
5359
5360 A buffer can only have one scanner active at a time, which yields
5361 dramatically simpler code than using a defstruct. If you need to
5362 have simultaneous scanners in a buffer, copy the regions to scan
5363 into temp buffers."
5364 (with-current-buffer (or buf (current-buffer))
5365 (setq js2-ts-dirty-line nil
5366 js2-ts-hit-eof nil
5367 js2-ts-line-start 0
5368 js2-ts-lineno (or line 1)
5369 js2-ts-line-end-char -1
5370 js2-ts-cursor (point-min)
5371 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5372 js2-ti-tokens-cursor 0
5373 js2-ti-lookahead 0
5374 js2-ts-is-xml-attribute nil
5375 js2-ts-xml-is-tag-content nil
5376 js2-ts-xml-open-tags-count 0
5377 js2-ts-string-buffer nil)))
5378
5379 ;; This function uses the cached op, string and number fields in
5380 ;; TokenStream; if getToken has been called since the passed token
5381 ;; was scanned, the op or string printed may be incorrect.
5382 (defun js2-token-to-string (token)
5383 ;; Not sure where this function is used in Rhino. Not tested.
5384 (if (not js2-debug-print-trees)
5385 ""
5386 (let ((name (js2-tt-name token)))
5387 (cond
5388 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5389 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5390 (concat name " `" (js2-current-token-string) "'"))
5391 ((eq token js2-NUMBER)
5392 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5393 (t
5394 name)))))
5395
5396 (defconst js2-keywords
5397 '(break
5398 case catch class const continue
5399 debugger default delete do
5400 else extends
5401 false finally for function
5402 if in instanceof import
5403 let
5404 new null
5405 return
5406 static super switch
5407 this throw true try typeof
5408 var void
5409 while with
5410 yield))
5411
5412 ;; Token names aren't exactly the same as the keywords, unfortunately.
5413 ;; E.g. delete is js2-DELPROP.
5414 (defconst js2-kwd-tokens
5415 (let ((table (make-vector js2-num-tokens nil))
5416 (tokens
5417 (list js2-BREAK
5418 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5419 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5420 js2-ELSE js2-EXTENDS
5421 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5422 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5423 js2-LET
5424 js2-NEW js2-NULL
5425 js2-RETURN
5426 js2-STATIC js2-SUPER js2-SWITCH
5427 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5428 js2-VAR
5429 js2-WHILE js2-WITH
5430 js2-YIELD)))
5431 (dolist (i tokens)
5432 (aset table i 'font-lock-keyword-face))
5433 (aset table js2-STRING 'font-lock-string-face)
5434 (aset table js2-REGEXP 'font-lock-string-face)
5435 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5436 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5437 (aset table js2-COMMENT 'font-lock-comment-face)
5438 (aset table js2-THIS 'font-lock-builtin-face)
5439 (aset table js2-SUPER 'font-lock-builtin-face)
5440 (aset table js2-VOID 'font-lock-constant-face)
5441 (aset table js2-NULL 'font-lock-constant-face)
5442 (aset table js2-TRUE 'font-lock-constant-face)
5443 (aset table js2-FALSE 'font-lock-constant-face)
5444 (aset table js2-NOT 'font-lock-negation-char-face)
5445 table)
5446 "Vector whose values are non-nil for tokens that are keywords.
5447 The values are default faces to use for highlighting the keywords.")
5448
5449 ;; FIXME: Support strict mode-only future reserved words, after we know
5450 ;; which parts scopes are in strict mode, and which are not.
5451 (defconst js2-reserved-words '(class enum export extends import super)
5452 "Future reserved keywords in ECMAScript 5.1.")
5453
5454 (defconst js2-keyword-names
5455 (let ((table (make-hash-table :test 'equal)))
5456 (loop for k in js2-keywords
5457 do (puthash
5458 (symbol-name k) ; instanceof
5459 (intern (concat "js2-"
5460 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5461 table))
5462 table)
5463 "JavaScript keywords by name, mapped to their symbols.")
5464
5465 (defconst js2-reserved-word-names
5466 (let ((table (make-hash-table :test 'equal)))
5467 (loop for k in js2-reserved-words
5468 do
5469 (puthash (symbol-name k) 'js2-RESERVED table))
5470 table)
5471 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5472
5473 (defun js2-collect-string (buf)
5474 "Convert BUF, a list of chars, to a string.
5475 Reverses BUF before converting."
5476 (if buf
5477 (apply #'string (nreverse buf))
5478 ""))
5479
5480 (defun js2-string-to-keyword (s)
5481 "Return token for S, a string, if S is a keyword or reserved word.
5482 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5483 (or (gethash s js2-keyword-names)
5484 (gethash s js2-reserved-word-names)))
5485
5486 (defsubst js2-ts-set-char-token-bounds (token)
5487 "Used when next token is one character."
5488 (setf (js2-token-beg token) (1- js2-ts-cursor)
5489 (js2-token-end token) js2-ts-cursor))
5490
5491 (defsubst js2-ts-return (token type)
5492 "Update the `end' and `type' slots of TOKEN,
5493 then throw `return' with value TYPE."
5494 (setf (js2-token-end token) js2-ts-cursor
5495 (js2-token-type token) type)
5496 (throw 'return type))
5497
5498 (defun js2-x-digit-to-int (c accumulator)
5499 "Build up a hex number.
5500 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5501 corresponding number. Otherwise return -1."
5502 (catch 'return
5503 (catch 'check
5504 ;; Use 0..9 < A..Z < a..z
5505 (cond
5506 ((<= c ?9)
5507 (decf c ?0)
5508 (if (<= 0 c)
5509 (throw 'check nil)))
5510 ((<= c ?F)
5511 (when (<= ?A c)
5512 (decf c (- ?A 10))
5513 (throw 'check nil)))
5514 ((<= c ?f)
5515 (when (<= ?a c)
5516 (decf c (- ?a 10))
5517 (throw 'check nil))))
5518 (throw 'return -1))
5519 (logior c (lsh accumulator 4))))
5520
5521 (defun js2-get-token (&optional modifier)
5522 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5523 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5524 next saved token.
5525
5526 This function will not return a newline (js2-EOL) - instead, it
5527 gobbles newlines until it finds a non-newline token. Call
5528 `js2-peek-token-or-eol' when you care about newlines.
5529
5530 This function will also not return a js2-COMMENT. Instead, it
5531 records comments found in `js2-scanned-comments'. If the token
5532 returned by this function immediately follows a jsdoc comment,
5533 the token is flagged as such."
5534 (if (zerop js2-ti-lookahead)
5535 (js2-get-token-internal modifier)
5536 (decf js2-ti-lookahead)
5537 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5538 (let ((tt (js2-current-token-type)))
5539 (assert (not (= tt js2-EOL)))
5540 tt)))
5541
5542 (defun js2-unget-token ()
5543 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5544 (incf js2-ti-lookahead)
5545 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5546
5547 (defun js2-get-token-internal (modifier)
5548 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5549 (tt (js2-token-type token))
5550 saw-eol
5551 face)
5552 ;; process comments
5553 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5554 (if (= tt js2-EOL)
5555 (setq saw-eol t)
5556 (setq saw-eol nil)
5557 (when js2-record-comments
5558 (js2-record-comment token)))
5559 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5560 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5561 tt (js2-token-type token)))
5562
5563 (when saw-eol
5564 (setf (js2-token-follows-eol-p token) t))
5565
5566 ;; perform lexical fontification as soon as token is scanned
5567 (when js2-parse-ide-mode
5568 (cond
5569 ((minusp tt)
5570 (js2-record-face 'js2-error token))
5571 ((setq face (aref js2-kwd-tokens tt))
5572 (js2-record-face face token))
5573 ((and (= tt js2-NAME)
5574 (equal (js2-token-string token) "undefined"))
5575 (js2-record-face 'font-lock-constant-face token))))
5576 tt))
5577
5578 (defun js2-get-token-internal-1 (modifier)
5579 "Return next JavaScript token type, an int such as js2-RETURN.
5580 During operation, creates an instance of `js2-token' struct, sets
5581 its relevant fields and puts it into `js2-ti-tokens'."
5582 (let (c c1 identifier-start is-unicode-escape-start
5583 contains-escape escape-val str result base
5584 quote-char val look-for-slash continue tt
5585 (token (js2-new-token 0)))
5586 (setq
5587 tt
5588 (catch 'return
5589 (when (eq modifier 'TEMPLATE_TAIL)
5590 (setf (js2-token-beg token) (1- js2-ts-cursor))
5591 (throw 'return (js2-get-string-or-template-token ?` token)))
5592 (while t
5593 ;; Eat whitespace, possibly sensitive to newlines.
5594 (setq continue t)
5595 (while continue
5596 (setq c (js2-get-char))
5597 (cond
5598 ((eq c js2-EOF_CHAR)
5599 (js2-unget-char)
5600 (js2-ts-set-char-token-bounds token)
5601 (throw 'return js2-EOF))
5602 ((eq c ?\n)
5603 (js2-ts-set-char-token-bounds token)
5604 (setq js2-ts-dirty-line nil)
5605 (throw 'return js2-EOL))
5606 ((not (js2-js-space-p c))
5607 (if (/= c ?-) ; in case end of HTML comment
5608 (setq js2-ts-dirty-line t))
5609 (setq continue nil))))
5610 ;; Assume the token will be 1 char - fixed up below.
5611 (js2-ts-set-char-token-bounds token)
5612 (when (eq c ?@)
5613 (throw 'return js2-XMLATTR))
5614 ;; identifier/keyword/instanceof?
5615 ;; watch out for starting with a <backslash>
5616 (cond
5617 ((eq c ?\\)
5618 (setq c (js2-get-char))
5619 (if (eq c ?u)
5620 (setq identifier-start t
5621 is-unicode-escape-start t
5622 js2-ts-string-buffer nil)
5623 (setq identifier-start nil)
5624 (js2-unget-char)
5625 (setq c ?\\)))
5626 (t
5627 (when (setq identifier-start (js2-identifier-start-p c))
5628 (setq js2-ts-string-buffer nil)
5629 (js2-add-to-string c))))
5630 (when identifier-start
5631 (setq contains-escape is-unicode-escape-start)
5632 (catch 'break
5633 (while t
5634 (if is-unicode-escape-start
5635 ;; strictly speaking we should probably push-back
5636 ;; all the bad characters if the <backslash>uXXXX
5637 ;; sequence is malformed. But since there isn't a
5638 ;; correct context(is there?) for a bad Unicode
5639 ;; escape sequence in an identifier, we can report
5640 ;; an error here.
5641 (progn
5642 (setq escape-val 0)
5643 (dotimes (_ 4)
5644 (setq c (js2-get-char)
5645 escape-val (js2-x-digit-to-int c escape-val))
5646 ;; Next check takes care of c < 0 and bad escape
5647 (if (minusp escape-val)
5648 (throw 'break nil)))
5649 (if (minusp escape-val)
5650 (js2-report-scan-error "msg.invalid.escape" t))
5651 (js2-add-to-string escape-val)
5652 (setq is-unicode-escape-start nil))
5653 (setq c (js2-get-char))
5654 (cond
5655 ((eq c ?\\)
5656 (setq c (js2-get-char))
5657 (if (eq c ?u)
5658 (setq is-unicode-escape-start t
5659 contains-escape t)
5660 (js2-report-scan-error "msg.illegal.character" t)))
5661 (t
5662 (if (or (eq c js2-EOF_CHAR)
5663 (not (js2-identifier-part-p c)))
5664 (throw 'break nil))
5665 (js2-add-to-string c))))))
5666 (js2-unget-char)
5667 (setf str (js2-collect-string js2-ts-string-buffer)
5668 (js2-token-end token) js2-ts-cursor)
5669 ;; FIXME: Invalid in ES5 and ES6, see
5670 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5671 ;; Probably should just drop this conditional.
5672 (unless contains-escape
5673 ;; OPT we shouldn't have to make a string (object!) to
5674 ;; check if it's a keyword.
5675 ;; Return the corresponding token if it's a keyword
5676 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5677 (setq result (js2-string-to-keyword str)))
5678 (if (and (< js2-language-version 170)
5679 (memq result '(js2-LET js2-YIELD)))
5680 ;; LET and YIELD are tokens only in 1.7 and later
5681 (setq result 'js2-NAME))
5682 (when (eq result 'js2-RESERVED)
5683 (setf (js2-token-string token) str))
5684 (throw 'return (js2-tt-code result))))
5685 ;; If we want to intern these as Rhino does, just use (intern str)
5686 (setf (js2-token-string token) str)
5687 (throw 'return js2-NAME)) ; end identifier/kwd check
5688 ;; is it a number?
5689 (when (or (js2-digit-p c)
5690 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5691 (setq js2-ts-string-buffer nil
5692 base 10)
5693 (when (eq c ?0)
5694 (setq c (js2-get-char))
5695 (cond
5696 ((or (eq c ?x) (eq c ?X))
5697 (setq base 16)
5698 (setq c (js2-get-char)))
5699 ((and (or (eq c ?b) (eq c ?B))
5700 (>= js2-language-version 200))
5701 (setq base 2)
5702 (setq c (js2-get-char)))
5703 ((and (or (eq c ?o) (eq c ?O))
5704 (>= js2-language-version 200))
5705 (setq base 8)
5706 (setq c (js2-get-char)))
5707 ((js2-digit-p c)
5708 (setq base 'maybe-8))
5709 (t
5710 (js2-add-to-string ?0))))
5711 (cond
5712 ((eq base 16)
5713 (if (> 0 (js2-x-digit-to-int c 0))
5714 (js2-report-scan-error "msg.missing.hex.digits")
5715 (while (<= 0 (js2-x-digit-to-int c 0))
5716 (js2-add-to-string c)
5717 (setq c (js2-get-char)))))
5718 ((eq base 2)
5719 (if (not (memq c '(?0 ?1)))
5720 (js2-report-scan-error "msg.missing.binary.digits")
5721 (while (memq c '(?0 ?1))
5722 (js2-add-to-string c)
5723 (setq c (js2-get-char)))))
5724 ((eq base 8)
5725 (if (or (> ?0 c) (< ?7 c))
5726 (js2-report-scan-error "msg.missing.octal.digits")
5727 (while (and (<= ?0 c) (>= ?7 c))
5728 (js2-add-to-string c)
5729 (setq c (js2-get-char)))))
5730 (t
5731 (while (and (<= ?0 c) (<= c ?9))
5732 ;; We permit 08 and 09 as decimal numbers, which
5733 ;; makes our behavior a superset of the ECMA
5734 ;; numeric grammar. We might not always be so
5735 ;; permissive, so we warn about it.
5736 (when (and (eq base 'maybe-8) (>= c ?8))
5737 (js2-report-warning "msg.bad.octal.literal"
5738 (if (eq c ?8) "8" "9"))
5739 (setq base 10))
5740 (js2-add-to-string c)
5741 (setq c (js2-get-char)))
5742 (when (eq base 'maybe-8)
5743 (setq base 8))))
5744 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5745 (when (eq c ?.)
5746 (loop do
5747 (js2-add-to-string c)
5748 (setq c (js2-get-char))
5749 while (js2-digit-p c)))
5750 (when (memq c '(?e ?E))
5751 (js2-add-to-string c)
5752 (setq c (js2-get-char))
5753 (when (memq c '(?+ ?-))
5754 (js2-add-to-string c)
5755 (setq c (js2-get-char)))
5756 (unless (js2-digit-p c)
5757 (js2-report-scan-error "msg.missing.exponent" t))
5758 (loop do
5759 (js2-add-to-string c)
5760 (setq c (js2-get-char))
5761 while (js2-digit-p c))))
5762 (js2-unget-char)
5763 (let ((str (js2-set-string-from-buffer token)))
5764 (setf (js2-token-number token)
5765 (js2-string-to-number str base)))
5766 (throw 'return js2-NUMBER))
5767 ;; is it a string?
5768 (when (or (memq c '(?\" ?\'))
5769 (and (>= js2-language-version 200)
5770 (= c ?`)))
5771 (throw 'return
5772 (js2-get-string-or-template-token c token)))
5773 (js2-ts-return token
5774 (case c
5775 (?\;
5776 (throw 'return js2-SEMI))
5777 (?\[
5778 (throw 'return js2-LB))
5779 (?\]
5780 (throw 'return js2-RB))
5781 (?{
5782 (throw 'return js2-LC))
5783 (?}
5784 (throw 'return js2-RC))
5785 (?\(
5786 (throw 'return js2-LP))
5787 (?\)
5788 (throw 'return js2-RP))
5789 (?,
5790 (throw 'return js2-COMMA))
5791 (??
5792 (throw 'return js2-HOOK))
5793 (?:
5794 (if (js2-match-char ?:)
5795 js2-COLONCOLON
5796 (throw 'return js2-COLON)))
5797 (?.
5798 (if (js2-match-char ?.)
5799 (if (js2-match-char ?.)
5800 js2-TRIPLEDOT js2-DOTDOT)
5801 (if (js2-match-char ?\()
5802 js2-DOTQUERY
5803 (throw 'return js2-DOT))))
5804 (?|
5805 (if (js2-match-char ?|)
5806 (throw 'return js2-OR)
5807 (if (js2-match-char ?=)
5808 js2-ASSIGN_BITOR
5809 (throw 'return js2-BITOR))))
5810 (?^
5811 (if (js2-match-char ?=)
5812 js2-ASSIGN_BITOR
5813 (throw 'return js2-BITXOR)))
5814 (?&
5815 (if (js2-match-char ?&)
5816 (throw 'return js2-AND)
5817 (if (js2-match-char ?=)
5818 js2-ASSIGN_BITAND
5819 (throw 'return js2-BITAND))))
5820 (?=
5821 (if (js2-match-char ?=)
5822 (if (js2-match-char ?=)
5823 js2-SHEQ
5824 (throw 'return js2-EQ))
5825 (if (js2-match-char ?>)
5826 (js2-ts-return token js2-ARROW)
5827 (throw 'return js2-ASSIGN))))
5828 (?!
5829 (if (js2-match-char ?=)
5830 (if (js2-match-char ?=)
5831 js2-SHNE
5832 js2-NE)
5833 (throw 'return js2-NOT)))
5834 (?<
5835 ;; NB:treat HTML begin-comment as comment-till-eol
5836 (when (js2-match-char ?!)
5837 (when (js2-match-char ?-)
5838 (when (js2-match-char ?-)
5839 (js2-skip-line)
5840 (setf (js2-token-comment-type (js2-current-token)) 'html)
5841 (throw 'return js2-COMMENT)))
5842 (js2-unget-char))
5843 (if (js2-match-char ?<)
5844 (if (js2-match-char ?=)
5845 js2-ASSIGN_LSH
5846 js2-LSH)
5847 (if (js2-match-char ?=)
5848 js2-LE
5849 (throw 'return js2-LT))))
5850 (?>
5851 (if (js2-match-char ?>)
5852 (if (js2-match-char ?>)
5853 (if (js2-match-char ?=)
5854 js2-ASSIGN_URSH
5855 js2-URSH)
5856 (if (js2-match-char ?=)
5857 js2-ASSIGN_RSH
5858 js2-RSH))
5859 (if (js2-match-char ?=)
5860 js2-GE
5861 (throw 'return js2-GT))))
5862 (?*
5863 (if (js2-match-char ?=)
5864 js2-ASSIGN_MUL
5865 (throw 'return js2-MUL)))
5866 (?/
5867 ;; is it a // comment?
5868 (when (js2-match-char ?/)
5869 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5870 (js2-skip-line)
5871 (setf (js2-token-comment-type token) 'line)
5872 ;; include newline so highlighting goes to end of window
5873 (incf (js2-token-end token))
5874 (throw 'return js2-COMMENT))
5875 ;; is it a /* comment?
5876 (when (js2-match-char ?*)
5877 (setf look-for-slash nil
5878 (js2-token-beg token) (- js2-ts-cursor 2)
5879 (js2-token-comment-type token)
5880 (if (js2-match-char ?*)
5881 (progn
5882 (setq look-for-slash t)
5883 'jsdoc)
5884 'block))
5885 (while t
5886 (setq c (js2-get-char))
5887 (cond
5888 ((eq c js2-EOF_CHAR)
5889 (setf (js2-token-end token) (1- js2-ts-cursor))
5890 (js2-report-error "msg.unterminated.comment")
5891 (throw 'return js2-COMMENT))
5892 ((eq c ?*)
5893 (setq look-for-slash t))
5894 ((eq c ?/)
5895 (if look-for-slash
5896 (js2-ts-return token js2-COMMENT)))
5897 (t
5898 (setf look-for-slash nil
5899 (js2-token-end token) js2-ts-cursor)))))
5900 (if (js2-match-char ?=)
5901 js2-ASSIGN_DIV
5902 (throw 'return js2-DIV)))
5903 (?#
5904 (when js2-skip-preprocessor-directives
5905 (js2-skip-line)
5906 (setf (js2-token-comment-type token) 'preprocessor
5907 (js2-token-end token) js2-ts-cursor)
5908 (throw 'return js2-COMMENT))
5909 (throw 'return js2-ERROR))
5910 (?%
5911 (if (js2-match-char ?=)
5912 js2-ASSIGN_MOD
5913 (throw 'return js2-MOD)))
5914 (?~
5915 (throw 'return js2-BITNOT))
5916 (?+
5917 (if (js2-match-char ?=)
5918 js2-ASSIGN_ADD
5919 (if (js2-match-char ?+)
5920 js2-INC
5921 (throw 'return js2-ADD))))
5922 (?-
5923 (cond
5924 ((js2-match-char ?=)
5925 (setq c js2-ASSIGN_SUB))
5926 ((js2-match-char ?-)
5927 (unless js2-ts-dirty-line
5928 ;; treat HTML end-comment after possible whitespace
5929 ;; after line start as comment-until-eol
5930 (when (js2-match-char ?>)
5931 (js2-skip-line)
5932 (setf (js2-token-comment-type (js2-current-token)) 'html)
5933 (throw 'return js2-COMMENT)))
5934 (setq c js2-DEC))
5935 (t
5936 (setq c js2-SUB)))
5937 (setq js2-ts-dirty-line t)
5938 c)
5939 (otherwise
5940 (js2-report-scan-error "msg.illegal.character")))))))
5941 (setf (js2-token-type token) tt)
5942 token))
5943
5944 (defun js2-get-string-or-template-token (quote-char token)
5945 ;; We attempt to accumulate a string the fast way, by
5946 ;; building it directly out of the reader. But if there
5947 ;; are any escaped characters in the string, we revert to
5948 ;; building it out of a string buffer.
5949 (let ((c (js2-get-char))
5950 js2-ts-string-buffer
5951 nc)
5952 (catch 'break
5953 (while (/= c quote-char)
5954 (catch 'continue
5955 (when (eq c js2-EOF_CHAR)
5956 (js2-unget-char)
5957 (js2-report-error "msg.unterminated.string.lit")
5958 (throw 'break nil))
5959 (when (and (eq c ?\n) (not (eq quote-char ?`)))
5960 (js2-unget-char)
5961 (js2-report-error "msg.unterminated.string.lit")
5962 (throw 'break nil))
5963 (when (eq c ?\\)
5964 ;; We've hit an escaped character
5965 (setq c (js2-get-char))
5966 (case c
5967 (?b (setq c ?\b))
5968 (?f (setq c ?\f))
5969 (?n (setq c ?\n))
5970 (?r (setq c ?\r))
5971 (?t (setq c ?\t))
5972 (?v (setq c ?\v))
5973 (?u
5974 (setq c1 (js2-read-unicode-escape))
5975 (if js2-parse-ide-mode
5976 (if c1
5977 (progn
5978 ;; just copy the string in IDE-mode
5979 (js2-add-to-string ?\\)
5980 (js2-add-to-string ?u)
5981 (dotimes (_ 3)
5982 (js2-add-to-string (js2-get-char)))
5983 (setq c (js2-get-char))) ; added at end of loop
5984 ;; flag it as an invalid escape
5985 (js2-report-warning "msg.invalid.escape"
5986 nil (- js2-ts-cursor 2) 6))
5987 ;; Get 4 hex digits; if the u escape is not
5988 ;; followed by 4 hex digits, use 'u' + the
5989 ;; literal character sequence that follows.
5990 (js2-add-to-string ?u)
5991 (setq escape-val 0)
5992 (dotimes (_ 4)
5993 (setq c (js2-get-char)
5994 escape-val (js2-x-digit-to-int c escape-val))
5995 (if (minusp escape-val)
5996 (throw 'continue nil))
5997 (js2-add-to-string c))
5998 ;; prepare for replace of stored 'u' sequence by escape value
5999 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6000 c escape-val)))
6001 (?x
6002 ;; Get 2 hex digits, defaulting to 'x'+literal
6003 ;; sequence, as above.
6004 (setq c (js2-get-char)
6005 escape-val (js2-x-digit-to-int c 0))
6006 (if (minusp escape-val)
6007 (progn
6008 (js2-add-to-string ?x)
6009 (throw 'continue nil))
6010 (setq c1 c
6011 c (js2-get-char)
6012 escape-val (js2-x-digit-to-int c escape-val))
6013 (if (minusp escape-val)
6014 (progn
6015 (js2-add-to-string ?x)
6016 (js2-add-to-string c1)
6017 (throw 'continue nil))
6018 ;; got 2 hex digits
6019 (setq c escape-val))))
6020 (?\n
6021 ;; Remove line terminator after escape to follow
6022 ;; SpiderMonkey and C/C++
6023 (setq c (js2-get-char))
6024 (throw 'continue nil))
6025 (t
6026 (when (and (<= ?0 c) (< c ?8))
6027 (setq val (- c ?0)
6028 c (js2-get-char))
6029 (when (and (<= ?0 c) (< c ?8))
6030 (setq val (- (+ (* 8 val) c) ?0)
6031 c (js2-get-char))
6032 (when (and (<= ?0 c)
6033 (< c ?8)
6034 (< val #o37))
6035 ;; c is 3rd char of octal sequence only
6036 ;; if the resulting val <= 0377
6037 (setq val (- (+ (* 8 val) c) ?0)
6038 c (js2-get-char))))
6039 (js2-unget-char)
6040 (setq c val)))))
6041 (when (and (eq quote-char ?`) (eq c ?$))
6042 (when (eq (setq nc (js2-get-char)) ?\{)
6043 (throw 'break nil))
6044 (js2-unget-char))
6045 (js2-add-to-string c)
6046 (setq c (js2-get-char)))))
6047 (js2-set-string-from-buffer token)
6048 (if (not (eq quote-char ?`))
6049 js2-STRING
6050 (if (and (eq c ?$) (eq nc ?\{))
6051 js2-TEMPLATE_HEAD
6052 js2-NO_SUBS_TEMPLATE))))
6053
6054 (defsubst js2-string-to-number (str base)
6055 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
6056 (condition-case nil
6057 (string-to-number str base)
6058 (overflow-error -1)))
6059
6060 (defun js2-read-regexp (start-tt)
6061 "Called by parser when it gets / or /= in literal context."
6062 (let (c err
6063 in-class ; inside a '[' .. ']' character-class
6064 flags
6065 (continue t)
6066 (token (js2-new-token 0)))
6067 (setq js2-ts-string-buffer nil)
6068 (if (eq start-tt js2-ASSIGN_DIV)
6069 ;; mis-scanned /=
6070 (js2-add-to-string ?=)
6071 (if (not (eq start-tt js2-DIV))
6072 (error "failed assertion")))
6073 (while (and (not err)
6074 (or (/= (setq c (js2-get-char)) ?/)
6075 in-class))
6076 (cond
6077 ((or (= c ?\n)
6078 (= c js2-EOF_CHAR))
6079 (setf (js2-token-end token) (1- js2-ts-cursor)
6080 err t
6081 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6082 (js2-report-error "msg.unterminated.re.lit"))
6083 (t (cond
6084 ((= c ?\\)
6085 (js2-add-to-string c)
6086 (setq c (js2-get-char)))
6087 ((= c ?\[)
6088 (setq in-class t))
6089 ((= c ?\])
6090 (setq in-class nil)))
6091 (js2-add-to-string c))))
6092 (unless err
6093 (while continue
6094 (cond
6095 ((js2-match-char ?g)
6096 (push ?g flags))
6097 ((js2-match-char ?i)
6098 (push ?i flags))
6099 ((js2-match-char ?m)
6100 (push ?m flags))
6101 ((and (js2-match-char ?u)
6102 (>= js2-language-version 200))
6103 (push ?u flags))
6104 ((and (js2-match-char ?y)
6105 (>= js2-language-version 200))
6106 (push ?y flags))
6107 (t
6108 (setq continue nil))))
6109 (if (js2-alpha-p (js2-peek-char))
6110 (js2-report-scan-error "msg.invalid.re.flag" t
6111 js2-ts-cursor 1))
6112 (js2-set-string-from-buffer token))
6113 (js2-collect-string flags)))
6114
6115 (defun js2-get-first-xml-token ()
6116 (setq js2-ts-xml-open-tags-count 0
6117 js2-ts-is-xml-attribute nil
6118 js2-ts-xml-is-tag-content nil)
6119 (js2-unget-char)
6120 (js2-get-next-xml-token))
6121
6122 (defun js2-xml-discard-string (token)
6123 "Throw away the string in progress and flag an XML parse error."
6124 (setf js2-ts-string-buffer nil
6125 (js2-token-string token) nil)
6126 (js2-report-scan-error "msg.XML.bad.form" t))
6127
6128 (defun js2-get-next-xml-token ()
6129 (setq js2-ts-string-buffer nil) ; for recording the XML
6130 (let ((token (js2-new-token 0))
6131 c result)
6132 (setq result
6133 (catch 'return
6134 (while t
6135 (setq c (js2-get-char))
6136 (cond
6137 ((= c js2-EOF_CHAR)
6138 (throw 'return js2-ERROR))
6139 (js2-ts-xml-is-tag-content
6140 (case c
6141 (?>
6142 (js2-add-to-string c)
6143 (setq js2-ts-xml-is-tag-content nil
6144 js2-ts-is-xml-attribute nil))
6145 (?/
6146 (js2-add-to-string c)
6147 (when (eq ?> (js2-peek-char))
6148 (setq c (js2-get-char))
6149 (js2-add-to-string c)
6150 (setq js2-ts-xml-is-tag-content nil)
6151 (decf js2-ts-xml-open-tags-count)))
6152 (?{
6153 (js2-unget-char)
6154 (js2-set-string-from-buffer token)
6155 (throw 'return js2-XML))
6156 ((?\' ?\")
6157 (js2-add-to-string c)
6158 (unless (js2-read-quoted-string c token)
6159 (throw 'return js2-ERROR)))
6160 (?=
6161 (js2-add-to-string c)
6162 (setq js2-ts-is-xml-attribute t))
6163 ((? ?\t ?\r ?\n)
6164 (js2-add-to-string c))
6165 (t
6166 (js2-add-to-string c)
6167 (setq js2-ts-is-xml-attribute nil)))
6168 (when (and (not js2-ts-xml-is-tag-content)
6169 (zerop js2-ts-xml-open-tags-count))
6170 (js2-set-string-from-buffer token)
6171 (throw 'return js2-XMLEND)))
6172 (t
6173 ;; else not tag content
6174 (case c
6175 (?<
6176 (js2-add-to-string c)
6177 (setq c (js2-peek-char))
6178 (case c
6179 (?!
6180 (setq c (js2-get-char)) ;; skip !
6181 (js2-add-to-string c)
6182 (setq c (js2-peek-char))
6183 (case c
6184 (?-
6185 (setq c (js2-get-char)) ;; skip -
6186 (js2-add-to-string c)
6187 (if (eq c ?-)
6188 (progn
6189 (js2-add-to-string c)
6190 (unless (js2-read-xml-comment token)
6191 (throw 'return js2-ERROR)))
6192 (js2-xml-discard-string token)
6193 (throw 'return js2-ERROR)))
6194 (?\[
6195 (setq c (js2-get-char)) ;; skip [
6196 (js2-add-to-string c)
6197 (if (and (= (js2-get-char) ?C)
6198 (= (js2-get-char) ?D)
6199 (= (js2-get-char) ?A)
6200 (= (js2-get-char) ?T)
6201 (= (js2-get-char) ?A)
6202 (= (js2-get-char) ?\[))
6203 (progn
6204 (js2-add-to-string ?C)
6205 (js2-add-to-string ?D)
6206 (js2-add-to-string ?A)
6207 (js2-add-to-string ?T)
6208 (js2-add-to-string ?A)
6209 (js2-add-to-string ?\[)
6210 (unless (js2-read-cdata token)
6211 (throw 'return js2-ERROR)))
6212 (js2-xml-discard-string token)
6213 (throw 'return js2-ERROR)))
6214 (t
6215 (unless (js2-read-entity token)
6216 (throw 'return js2-ERROR))))
6217 ;; Allow bare CDATA section, e.g.:
6218 ;; let xml = <![CDATA[ foo bar baz ]]>;
6219 (when (zerop js2-ts-xml-open-tags-count)
6220 (throw 'return js2-XMLEND)))
6221 (??
6222 (setq c (js2-get-char)) ;; skip ?
6223 (js2-add-to-string c)
6224 (unless (js2-read-PI token)
6225 (throw 'return js2-ERROR)))
6226 (?/
6227 ;; end tag
6228 (setq c (js2-get-char)) ;; skip /
6229 (js2-add-to-string c)
6230 (when (zerop js2-ts-xml-open-tags-count)
6231 (js2-xml-discard-string token)
6232 (throw 'return js2-ERROR))
6233 (setq js2-ts-xml-is-tag-content t)
6234 (decf js2-ts-xml-open-tags-count))
6235 (t
6236 ;; start tag
6237 (setq js2-ts-xml-is-tag-content t)
6238 (incf js2-ts-xml-open-tags-count))))
6239 (?{
6240 (js2-unget-char)
6241 (js2-set-string-from-buffer token)
6242 (throw 'return js2-XML))
6243 (t
6244 (js2-add-to-string c))))))))
6245 (setf (js2-token-end token) js2-ts-cursor)
6246 (setf (js2-token-type token) result)
6247 result))
6248
6249 (defun js2-read-quoted-string (quote token)
6250 (let (c)
6251 (catch 'return
6252 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6253 (js2-add-to-string c)
6254 (if (eq c quote)
6255 (throw 'return t)))
6256 (js2-xml-discard-string token) ;; throw away string in progress
6257 nil)))
6258
6259 (defun js2-read-xml-comment (token)
6260 (let ((c (js2-get-char)))
6261 (catch 'return
6262 (while (/= c js2-EOF_CHAR)
6263 (catch 'continue
6264 (js2-add-to-string c)
6265 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6266 (setq c (js2-get-char))
6267 (js2-add-to-string c)
6268 (if (eq (js2-peek-char) ?>)
6269 (progn
6270 (setq c (js2-get-char)) ;; skip >
6271 (js2-add-to-string c)
6272 (throw 'return t))
6273 (throw 'continue nil)))
6274 (setq c (js2-get-char))))
6275 (js2-xml-discard-string token)
6276 nil)))
6277
6278 (defun js2-read-cdata (token)
6279 (let ((c (js2-get-char)))
6280 (catch 'return
6281 (while (/= c js2-EOF_CHAR)
6282 (catch 'continue
6283 (js2-add-to-string c)
6284 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6285 (setq c (js2-get-char))
6286 (js2-add-to-string c)
6287 (if (eq (js2-peek-char) ?>)
6288 (progn
6289 (setq c (js2-get-char)) ;; Skip >
6290 (js2-add-to-string c)
6291 (throw 'return t))
6292 (throw 'continue nil)))
6293 (setq c (js2-get-char))))
6294 (js2-xml-discard-string token)
6295 nil)))
6296
6297 (defun js2-read-entity (token)
6298 (let ((decl-tags 1)
6299 c)
6300 (catch 'return
6301 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6302 (js2-add-to-string c)
6303 (case c
6304 (?<
6305 (incf decl-tags))
6306 (?>
6307 (decf decl-tags)
6308 (if (zerop decl-tags)
6309 (throw 'return t)))))
6310 (js2-xml-discard-string token)
6311 nil)))
6312
6313 (defun js2-read-PI (token)
6314 "Scan an XML processing instruction."
6315 (let (c)
6316 (catch 'return
6317 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6318 (js2-add-to-string c)
6319 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6320 (setq c (js2-get-char)) ;; Skip >
6321 (js2-add-to-string c)
6322 (throw 'return t)))
6323 (js2-xml-discard-string token)
6324 nil)))
6325
6326 ;;; Highlighting
6327
6328 (defun js2-set-face (beg end face &optional record)
6329 "Fontify a region. If RECORD is non-nil, record for later."
6330 (when (plusp js2-highlight-level)
6331 (setq beg (min (point-max) beg)
6332 beg (max (point-min) beg)
6333 end (min (point-max) end)
6334 end (max (point-min) end))
6335 (if record
6336 (push (list beg end face) js2-mode-fontifications)
6337 (put-text-property beg end 'font-lock-face face))))
6338
6339 (defsubst js2-clear-face (beg end)
6340 (remove-text-properties beg end '(font-lock-face nil
6341 help-echo nil
6342 point-entered nil
6343 c-in-sws nil)))
6344
6345 (defconst js2-ecma-global-props
6346 (concat "^"
6347 (regexp-opt
6348 '("Infinity" "NaN" "undefined" "arguments") t)
6349 "$")
6350 "Value properties of the Ecma-262 Global Object.
6351 Shown at or above `js2-highlight-level' 2.")
6352
6353 ;; might want to add the name "arguments" to this list?
6354 (defconst js2-ecma-object-props
6355 (concat "^"
6356 (regexp-opt
6357 '("prototype" "__proto__" "__parent__") t)
6358 "$")
6359 "Value properties of the Ecma-262 Object constructor.
6360 Shown at or above `js2-highlight-level' 2.")
6361
6362 (defconst js2-ecma-global-funcs
6363 (concat
6364 "^"
6365 (regexp-opt
6366 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6367 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6368 "$")
6369 "Function properties of the Ecma-262 Global object.
6370 Shown at or above `js2-highlight-level' 2.")
6371
6372 (defconst js2-ecma-number-props
6373 (concat "^"
6374 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6375 "NEGATIVE_INFINITY"
6376 "POSITIVE_INFINITY") t)
6377 "$")
6378 "Properties of the Ecma-262 Number constructor.
6379 Shown at or above `js2-highlight-level' 2.")
6380
6381 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6382 "Properties of the Ecma-262 Date constructor.
6383 Shown at or above `js2-highlight-level' 2.")
6384
6385 (defconst js2-ecma-math-props
6386 (concat "^"
6387 (regexp-opt
6388 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6389 t)
6390 "$")
6391 "Properties of the Ecma-262 Math object.
6392 Shown at or above `js2-highlight-level' 2.")
6393
6394 (defconst js2-ecma-math-funcs
6395 (concat "^"
6396 (regexp-opt
6397 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6398 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6399 "$")
6400 "Function properties of the Ecma-262 Math object.
6401 Shown at or above `js2-highlight-level' 2.")
6402
6403 (defconst js2-ecma-function-props
6404 (concat
6405 "^"
6406 (regexp-opt
6407 '(;; properties of the Object prototype object
6408 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6409 "toLocaleString" "toString" "valueOf"
6410 ;; properties of the Function prototype object
6411 "apply" "call"
6412 ;; properties of the Array prototype object
6413 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6414 "splice" "unshift"
6415 ;; properties of the String prototype object
6416 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6417 "localeCompare" "match" "replace" "search" "split" "substring"
6418 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6419 "toUpperCase"
6420 ;; properties of the Number prototype object
6421 "toExponential" "toFixed" "toPrecision"
6422 ;; properties of the Date prototype object
6423 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6424 "getMinutes" "getMonth" "getSeconds" "getTime"
6425 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6426 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6427 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6428 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6429 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6430 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6431 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6432 "toTimeString" "toUTCString"
6433 ;; properties of the RegExp prototype object
6434 "exec" "test"
6435 ;; properties of the JSON prototype object
6436 "parse" "stringify"
6437 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6438 "toSource" "__defineGetter__" "__defineSetter__"
6439 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6440 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6441 t)
6442 "$")
6443 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6444 Shown at or above `js2-highlight-level' 3.")
6445
6446 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6447 (let ((target-name (and target
6448 (js2-name-node-p target)
6449 (js2-name-node-name target)))
6450 (prop-name (if prop (js2-name-node-name prop)))
6451 (level2 (>= js2-highlight-level 2))
6452 (level3 (>= js2-highlight-level 3)))
6453 (when level2
6454 (let ((face
6455 (if call-p
6456 (cond
6457 ((and target prop)
6458 (cond
6459 ((and level3 (string-match js2-ecma-function-props prop-name))
6460 'font-lock-builtin-face)
6461 ((and target-name prop)
6462 (cond
6463 ((string= target-name "Date")
6464 (if (string-match js2-ecma-date-props prop-name)
6465 'font-lock-builtin-face))
6466 ((string= target-name "Math")
6467 (if (string-match js2-ecma-math-funcs prop-name)
6468 'font-lock-builtin-face))))))
6469 (prop
6470 (if (string-match js2-ecma-global-funcs prop-name)
6471 'font-lock-builtin-face)))
6472 (cond
6473 ((and target prop)
6474 (cond
6475 ((string= target-name "Number")
6476 (if (string-match js2-ecma-number-props prop-name)
6477 'font-lock-constant-face))
6478 ((string= target-name "Math")
6479 (if (string-match js2-ecma-math-props prop-name)
6480 'font-lock-constant-face))))
6481 (prop
6482 (if (string-match js2-ecma-object-props prop-name)
6483 'font-lock-constant-face))))))
6484 (when face
6485 (let ((pos (+ (js2-node-pos parent) ; absolute
6486 (js2-node-pos prop)))) ; relative
6487 (js2-set-face pos
6488 (+ pos (js2-node-len prop))
6489 face 'record)))))))
6490
6491 (defun js2-parse-highlight-member-expr-node (node)
6492 "Perform syntax highlighting of EcmaScript built-in properties.
6493 The variable `js2-highlight-level' governs this highighting."
6494 (let (face target prop name pos end parent call-p callee)
6495 (cond
6496 ;; case 1: simple name, e.g. foo
6497 ((js2-name-node-p node)
6498 (setq name (js2-name-node-name node))
6499 ;; possible for name to be nil in rare cases - saw it when
6500 ;; running js2-mode on an elisp buffer. Might as well try to
6501 ;; make it so js2-mode never barfs.
6502 (when name
6503 (setq face (if (string-match js2-ecma-global-props name)
6504 'font-lock-constant-face))
6505 (when face
6506 (setq pos (js2-node-pos node)
6507 end (+ pos (js2-node-len node)))
6508 (js2-set-face pos end face 'record))))
6509 ;; case 2: property access or function call
6510 ((or (js2-prop-get-node-p node)
6511 ;; highlight function call if expr is a prop-get node
6512 ;; or a plain name (i.e. unqualified function call)
6513 (and (setq call-p (js2-call-node-p node))
6514 (setq callee (js2-call-node-target node)) ; separate setq!
6515 (or (js2-prop-get-node-p callee)
6516 (js2-name-node-p callee))))
6517 (setq parent node
6518 node (if call-p callee node))
6519 (if (and call-p (js2-name-node-p callee))
6520 (setq prop callee)
6521 (setq target (js2-prop-get-node-left node)
6522 prop (js2-prop-get-node-right node)))
6523 (cond
6524 ((js2-name-node-p prop)
6525 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6526 (js2-parse-highlight-prop-get parent target prop call-p))
6527 ((js2-name-node-p target)
6528 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6529 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6530
6531 (defun js2-parse-highlight-member-expr-fn-name (expr)
6532 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6533 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6534 We currently only handle the case where the last component is a prop-get
6535 of a simple name. Called before EXPR has a parent node."
6536 (let (pos
6537 (name (and (js2-prop-get-node-p expr)
6538 (js2-prop-get-node-right expr))))
6539 (when (js2-name-node-p name)
6540 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6541 (js2-node-pos name)))
6542 (+ pos (js2-node-len name))
6543 'font-lock-function-name-face
6544 'record))))
6545
6546 ;; source: http://jsdoc.sourceforge.net/
6547 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6548 ;; allows type specifications, and needs work before entering the wild.
6549
6550 (defconst js2-jsdoc-param-tag-regexp
6551 (concat "^\\s-*\\*+\\s-*\\(@"
6552 "\\(?:param\\|argument\\)"
6553 "\\)"
6554 "\\s-*\\({[^}]+}\\)?" ; optional type
6555 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6556 "\\>")
6557 "Matches jsdoc tags with optional type and optional param name.")
6558
6559 (defconst js2-jsdoc-typed-tag-regexp
6560 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6561 (regexp-opt
6562 '("enum"
6563 "extends"
6564 "field"
6565 "id"
6566 "implements"
6567 "lends"
6568 "mods"
6569 "requires"
6570 "return"
6571 "returns"
6572 "throw"
6573 "throws"))
6574 "\\)\\)\\s-*\\({[^}]+}\\)?")
6575 "Matches jsdoc tags with optional type.")
6576
6577 (defconst js2-jsdoc-arg-tag-regexp
6578 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6579 (regexp-opt
6580 '("alias"
6581 "augments"
6582 "borrows"
6583 "bug"
6584 "base"
6585 "config"
6586 "default"
6587 "define"
6588 "exception"
6589 "function"
6590 "member"
6591 "memberOf"
6592 "name"
6593 "namespace"
6594 "property"
6595 "since"
6596 "suppress"
6597 "this"
6598 "throws"
6599 "type"
6600 "version"))
6601 "\\)\\)\\s-+\\([^ \t]+\\)")
6602 "Matches jsdoc tags with a single argument.")
6603
6604 (defconst js2-jsdoc-empty-tag-regexp
6605 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6606 (regexp-opt
6607 '("addon"
6608 "author"
6609 "class"
6610 "const"
6611 "constant"
6612 "constructor"
6613 "constructs"
6614 "deprecated"
6615 "desc"
6616 "description"
6617 "event"
6618 "example"
6619 "exec"
6620 "export"
6621 "fileoverview"
6622 "final"
6623 "function"
6624 "hidden"
6625 "ignore"
6626 "implicitCast"
6627 "inheritDoc"
6628 "inner"
6629 "interface"
6630 "license"
6631 "noalias"
6632 "noshadow"
6633 "notypecheck"
6634 "override"
6635 "owner"
6636 "preserve"
6637 "preserveTry"
6638 "private"
6639 "protected"
6640 "public"
6641 "static"
6642 "supported"
6643 ))
6644 "\\)\\)\\s-*")
6645 "Matches empty jsdoc tags.")
6646
6647 (defconst js2-jsdoc-link-tag-regexp
6648 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6649 "Matches a jsdoc link or code tag.")
6650
6651 (defconst js2-jsdoc-see-tag-regexp
6652 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6653 "Matches a jsdoc @see tag.")
6654
6655 (defconst js2-jsdoc-html-tag-regexp
6656 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6657 "Matches a simple (no attributes) html start- or end-tag.")
6658
6659 (defun js2-jsdoc-highlight-helper ()
6660 (js2-set-face (match-beginning 1)
6661 (match-end 1)
6662 'js2-jsdoc-tag)
6663 (if (match-beginning 2)
6664 (if (save-excursion
6665 (goto-char (match-beginning 2))
6666 (= (char-after) ?{))
6667 (js2-set-face (1+ (match-beginning 2))
6668 (1- (match-end 2))
6669 'js2-jsdoc-type)
6670 (js2-set-face (match-beginning 2)
6671 (match-end 2)
6672 'js2-jsdoc-value)))
6673 (if (match-beginning 3)
6674 (js2-set-face (match-beginning 3)
6675 (match-end 3)
6676 'js2-jsdoc-value)))
6677
6678 (defun js2-highlight-jsdoc (ast)
6679 "Highlight doc comment tags."
6680 (let ((comments (js2-ast-root-comments ast))
6681 beg end)
6682 (save-excursion
6683 (dolist (node comments)
6684 (when (eq (js2-comment-node-format node) 'jsdoc)
6685 (setq beg (js2-node-abs-pos node)
6686 end (+ beg (js2-node-len node)))
6687 (save-restriction
6688 (narrow-to-region beg end)
6689 (dolist (re (list js2-jsdoc-param-tag-regexp
6690 js2-jsdoc-typed-tag-regexp
6691 js2-jsdoc-arg-tag-regexp
6692 js2-jsdoc-link-tag-regexp
6693 js2-jsdoc-see-tag-regexp
6694 js2-jsdoc-empty-tag-regexp))
6695 (goto-char beg)
6696 (while (re-search-forward re nil t)
6697 (js2-jsdoc-highlight-helper)))
6698 ;; simple highlighting for html tags
6699 (goto-char beg)
6700 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6701 (js2-set-face (match-beginning 1)
6702 (match-end 1)
6703 'js2-jsdoc-html-tag-delimiter)
6704 (js2-set-face (match-beginning 2)
6705 (match-end 2)
6706 'js2-jsdoc-html-tag-name)
6707 (js2-set-face (match-beginning 3)
6708 (match-end 3)
6709 'js2-jsdoc-html-tag-delimiter))))))))
6710
6711 (defun js2-highlight-assign-targets (_node left right)
6712 "Highlight function properties and external variables."
6713 (let (leftpos name)
6714 ;; highlight vars and props assigned function values
6715 (when (or (js2-function-node-p right)
6716 (js2-class-node-p right))
6717 (cond
6718 ;; var foo = function() {...}
6719 ((js2-name-node-p left)
6720 (setq name left))
6721 ;; foo.bar.baz = function() {...}
6722 ((and (js2-prop-get-node-p left)
6723 (js2-name-node-p (js2-prop-get-node-right left)))
6724 (setq name (js2-prop-get-node-right left))))
6725 (when name
6726 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6727 (+ leftpos (js2-node-len name))
6728 'font-lock-function-name-face
6729 'record)))))
6730
6731 (defun js2-record-name-node (node)
6732 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6733 later. NODE must be a name node."
6734 (let ((leftpos (js2-node-abs-pos node)))
6735 (push (list node js2-current-scope
6736 leftpos
6737 (+ leftpos (js2-node-len node)))
6738 js2-recorded-identifiers)))
6739
6740 (defun js2-highlight-undeclared-vars ()
6741 "After entire parse is finished, look for undeclared variable references.
6742 We have to wait until entire buffer is parsed, since JavaScript permits var
6743 decls to occur after they're used.
6744
6745 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6746 it is considered declared."
6747 (let (name)
6748 (dolist (entry js2-recorded-identifiers)
6749 (destructuring-bind (name-node scope pos end) entry
6750 (setq name (js2-name-node-name name-node))
6751 (unless (or (member name js2-global-externs)
6752 (member name js2-default-externs)
6753 (member name js2-additional-externs)
6754 (js2-get-defining-scope scope name))
6755 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6756 'js2-external-variable))))
6757 (setq js2-recorded-identifiers nil)))
6758
6759 (defun js2-set-default-externs ()
6760 "Set the value of `js2-default-externs' based on the various
6761 `js2-include-?-externs' variables."
6762 (setq js2-default-externs
6763 (append js2-ecma-262-externs
6764 (if js2-include-browser-externs js2-browser-externs)
6765 (if (and js2-include-browser-externs
6766 (>= js2-language-version 200)) js2-harmony-externs)
6767 (if js2-include-rhino-externs js2-rhino-externs)
6768 (if js2-include-node-externs js2-node-externs)
6769 (if (or js2-include-browser-externs js2-include-node-externs)
6770 js2-typed-array-externs))))
6771
6772 (defun js2-apply-jslint-globals ()
6773 (setq js2-additional-externs
6774 (nconc (js2-get-jslint-globals)
6775 js2-additional-externs)))
6776
6777 (defun js2-get-jslint-globals ()
6778 (loop for node in (js2-ast-root-comments js2-mode-ast)
6779 when (and (eq 'block (js2-comment-node-format node))
6780 (save-excursion
6781 (goto-char (js2-node-abs-pos node))
6782 (looking-at "/\\*global ")))
6783 append (js2-get-jslint-globals-in
6784 (match-end 0)
6785 (js2-node-abs-end node))))
6786
6787 (defun js2-get-jslint-globals-in (beg end)
6788 (let (res)
6789 (save-excursion
6790 (goto-char beg)
6791 (while (re-search-forward js2-mode-identifier-re end t)
6792 (let ((match (match-string 0)))
6793 (unless (member match '("true" "false"))
6794 (push match res)))))
6795 (nreverse res)))
6796
6797 ;;; IMenu support
6798
6799 ;; We currently only support imenu, but eventually should support speedbar and
6800 ;; possibly other browsing mechanisms.
6801
6802 ;; The basic strategy is to identify function assignment targets of the form
6803 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6804 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6805 ;; for imenu after parsing is finished.
6806
6807 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6808 ;; JavaScript, and the general problem is undecidable. However, several forms
6809 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6810 ;; include:
6811
6812 ;; function foo() -- function declaration
6813 ;; foo = function() -- function expression assigned to variable
6814 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6815 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6816 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6817 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6818 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6819 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6820 ;; function foo() {function bar() {...}} -- nested function
6821 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6822
6823 ;; This list boils down to a few forms that can be combined recursively.
6824 ;; Top-level named function declarations include both the left-hand (name)
6825 ;; and the right-hand (function value) expressions needed to produce an imenu
6826 ;; entry. The other "right-hand" forms we need to look for are:
6827 ;; - functions declared as props/getters/setters in object literals
6828 ;; - nested named function declarations
6829 ;; The "left-hand" expressions that functions can be assigned to include:
6830 ;; - local/global variables
6831 ;; - nested property-get expressions like a.b.c.d
6832 ;; - element gets like foo[10] or foo['bar'] where the index
6833 ;; expression can be trivially converted to a property name. They
6834 ;; effectively then become property gets.
6835
6836 ;; All the different definition types are canonicalized into the form
6837 ;; foo.bar.baz = position-of-function-keyword
6838
6839 ;; We need to build a trie-like structure for imenu. As an example,
6840 ;; consider the following JavaScript code:
6841
6842 ;; a = function() {...} // function at position 5
6843 ;; b = function() {...} // function at position 25
6844 ;; foo = function() {...} // function at position 100
6845 ;; foo.bar = function() {...} // function at position 200
6846 ;; foo.bar.baz = function() {...} // function at position 300
6847 ;; foo.bar.zab = function() {...} // function at position 400
6848
6849 ;; During parsing we accumulate an entry for each definition in
6850 ;; the variable `js2-imenu-recorder', like so:
6851
6852 ;; '((fn a 5)
6853 ;; (fn b 25)
6854 ;; (fn foo 100)
6855 ;; (fn foo bar 200)
6856 ;; (fn foo bar baz 300)
6857 ;; (fn foo bar zab 400))
6858
6859 ;; Where 'fn' is the respective function node.
6860 ;; After parsing these entries are merged into this alist-trie:
6861
6862 ;; '((a . 1)
6863 ;; (b . 2)
6864 ;; (foo (<definition> . 3)
6865 ;; (bar (<definition> . 6)
6866 ;; (baz . 100)
6867 ;; (zab . 200))))
6868
6869 ;; Note the wacky need for a <definition> name. The token can be anything
6870 ;; that isn't a valid JavaScript identifier, because you might make foo
6871 ;; a function and then start setting properties on it that are also functions.
6872
6873 (defun js2-prop-node-name (node)
6874 "Return the name of a node that may be a property-get/property-name.
6875 If NODE is not a valid name-node, string-node or integral number-node,
6876 returns nil. Otherwise returns the string name/value of the node."
6877 (cond
6878 ((js2-name-node-p node)
6879 (js2-name-node-name node))
6880 ((js2-string-node-p node)
6881 (js2-string-node-value node))
6882 ((and (js2-number-node-p node)
6883 (string-match "^[0-9]+$" (js2-number-node-value node)))
6884 (js2-number-node-value node))
6885 ((eq (js2-node-type node) js2-THIS)
6886 "this")
6887 ((eq (js2-node-type node) js2-SUPER)
6888 "super")))
6889
6890 (defun js2-node-qname-component (node)
6891 "Return the name of this node, if it contributes to a qname.
6892 Returns nil if the node doesn't contribute."
6893 (copy-sequence
6894 (or (js2-prop-node-name node)
6895 (if (and (js2-function-node-p node)
6896 (js2-function-node-name node))
6897 (js2-name-node-name (js2-function-node-name node))))))
6898
6899 (defun js2-record-imenu-entry (fn-node qname pos)
6900 "Add an entry to `js2-imenu-recorder'.
6901 FN-NODE should be the current item's function node.
6902
6903 Associate FN-NODE with its QNAME for later lookup.
6904 This is used in postprocessing the chain list. For each chain, we find
6905 the parent function, look up its qname, then prepend a copy of it to the chain."
6906 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6907 (unless js2-imenu-function-map
6908 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6909 (puthash fn-node qname js2-imenu-function-map))
6910
6911 (defun js2-record-imenu-functions (node &optional var)
6912 "Record function definitions for imenu.
6913 NODE is a function node or an object literal.
6914 VAR, if non-nil, is the expression that NODE is being assigned to.
6915 When passed arguments of wrong type, does nothing."
6916 (when js2-parse-ide-mode
6917 (let ((fun-p (js2-function-node-p node))
6918 qname fname-node)
6919 (cond
6920 ;; non-anonymous function declaration?
6921 ((and fun-p
6922 (not var)
6923 (setq fname-node (js2-function-node-name node)))
6924 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6925 ;; for remaining forms, compute left-side tree branch first
6926 ((and var (setq qname (js2-compute-nested-prop-get var)))
6927 (cond
6928 ;; foo.bar.baz = function
6929 (fun-p
6930 (js2-record-imenu-entry node qname (js2-node-pos node)))
6931 ;; foo.bar.baz = object-literal
6932 ;; look for nested functions: {a: {b: function() {...} }}
6933 ((js2-object-node-p node)
6934 ;; Node position here is still absolute, since the parser
6935 ;; passes the assignment target and value expressions
6936 ;; to us before they are added as children of the assignment node.
6937 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6938
6939 (defun js2-compute-nested-prop-get (node)
6940 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6941 component nodes as a list. Otherwise return nil. Element-gets are treated
6942 as property-gets if the index expression is a string, or a positive integer."
6943 (let (left right head)
6944 (cond
6945 ((or (js2-name-node-p node)
6946 (js2-this-or-super-node-p node))
6947 (list node))
6948 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6949 ((js2-prop-get-node-p node) ; foo.bar
6950 (setq left (js2-prop-get-node-left node)
6951 right (js2-prop-get-node-right node))
6952 (if (setq head (js2-compute-nested-prop-get left))
6953 (nconc head (list right))))
6954 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6955 (setq left (js2-elem-get-node-target node)
6956 right (js2-elem-get-node-element node))
6957 (if (or (js2-string-node-p right) ; ['bar']
6958 (and (js2-number-node-p right) ; [10]
6959 (string-match "^[0-9]+$"
6960 (js2-number-node-value right))))
6961 (if (setq head (js2-compute-nested-prop-get left))
6962 (nconc head (list right))))))))
6963
6964 (defun js2-record-object-literal (node qname pos)
6965 "Recursively process an object literal looking for functions.
6966 NODE is an object literal that is the right-hand child of an assignment
6967 expression. QNAME is a list of nodes representing the assignment target,
6968 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6969 POS is the absolute position of the node.
6970 We do a depth-first traversal of NODE. For any functions we find,
6971 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6972 (let (right)
6973 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6974 (let ((left (js2-infix-node-left e))
6975 ;; Element positions are relative to the parent position.
6976 (pos (+ pos (js2-node-pos e))))
6977 (cond
6978 ;; foo: function() {...}
6979 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6980 (when (js2-prop-node-name left)
6981 ;; As a policy decision, we record the position of the property,
6982 ;; not the position of the `function' keyword, since the property
6983 ;; is effectively the name of the function.
6984 (js2-record-imenu-entry right (append qname (list left)) pos)))
6985 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6986 ((js2-object-node-p right)
6987 (js2-record-object-literal right
6988 (append qname (list (js2-infix-node-left e)))
6989 (+ pos (js2-node-pos right)))))))))
6990
6991 (defun js2-node-top-level-decl-p (node)
6992 "Return t if NODE's name is defined in the top-level scope.
6993 Also returns t if NODE's name is not defined in any scope, since it implies
6994 that it's an external variable, which must also be in the top-level scope."
6995 (let* ((name (js2-prop-node-name node))
6996 (this-scope (js2-node-get-enclosing-scope node))
6997 defining-scope)
6998 (cond
6999 ((js2-this-or-super-node-p node)
7000 nil)
7001 ((null this-scope)
7002 t)
7003 ((setq defining-scope (js2-get-defining-scope this-scope name))
7004 (js2-ast-root-p defining-scope))
7005 (t t))))
7006
7007 (defun js2-wrapper-function-p (node)
7008 "Return t if NODE is a function expression that's immediately invoked.
7009 NODE must be `js2-function-node'."
7010 (let ((parent (js2-node-parent node)))
7011 (or
7012 ;; function(){...}();
7013 (and (js2-call-node-p parent)
7014 (eq node (js2-call-node-target parent)))
7015 (and (js2-paren-node-p parent)
7016 ;; (function(){...})();
7017 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7018 ;; (function(){...}).call(this);
7019 (and (js2-prop-get-node-p parent)
7020 (member (js2-name-node-name (js2-prop-get-node-right parent))
7021 '("call" "apply"))
7022 (js2-call-node-p (js2-node-parent parent))))))))
7023
7024 (defun js2-browse-postprocess-chains ()
7025 "Modify function-declaration name chains after parsing finishes.
7026 Some of the information is only available after the parse tree is complete.
7027 For instance, processing a nested scope requires a parent function node."
7028 (let (result fn parent-qname p elem)
7029 (dolist (entry js2-imenu-recorder)
7030 ;; function node goes first
7031 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7032 ;; Examine head's defining scope:
7033 ;; Pre-processed chain, or top-level/external, keep as-is.
7034 (if (or (stringp head) (js2-node-top-level-decl-p head))
7035 (push chain result)
7036 (when (js2-this-or-super-node-p head)
7037 (setq chain (cdr chain))) ; discard this-node
7038 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7039 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7040 (when (eq parent-qname 'not-found)
7041 ;; anonymous function expressions are not recorded
7042 ;; during the parse, so we need to handle this case here
7043 (setq parent-qname
7044 (if (js2-wrapper-function-p fn)
7045 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7046 (if (js2-ast-root-p grandparent)
7047 nil
7048 (gethash grandparent js2-imenu-function-map 'skip)))
7049 'skip))
7050 (puthash fn parent-qname js2-imenu-function-map))
7051 (if (eq parent-qname 'skip)
7052 ;; We don't show it, let's record that fact.
7053 (remhash current-fn js2-imenu-function-map)
7054 ;; Prepend parent fn qname to this chain.
7055 (let ((qname (append parent-qname chain)))
7056 (puthash current-fn (butlast qname) js2-imenu-function-map)
7057 (push qname result)))))))
7058 ;; Collect chains obtained by third-party code.
7059 (let (js2-imenu-recorder)
7060 (run-hooks 'js2-build-imenu-callbacks)
7061 (dolist (entry js2-imenu-recorder)
7062 (push (cdr entry) result)))
7063 ;; Finally replace each node in each chain with its name.
7064 (dolist (chain result)
7065 (setq p chain)
7066 (while p
7067 (if (js2-node-p (setq elem (car p)))
7068 (setcar p (js2-node-qname-component elem)))
7069 (setq p (cdr p))))
7070 result))
7071
7072 ;; Merge name chains into a trie-like tree structure of nested lists.
7073 ;; To simplify construction of the trie, we first build it out using the rule
7074 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7075 ;; [key, num-or-list]. The second element can be a number; if so, this key
7076 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7077 ;; associated with the key at this level.) Otherwise the second element is
7078 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7079 ;; a simple recursive formulation.
7080 ;;
7081 ;; js2-mode is building the data structure for imenu. The imenu documentation
7082 ;; claims that it's the structure above, but in practice it wants the children
7083 ;; at the same list level as the key for that level, which is how I've drawn
7084 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7085 ;; list wrapper around the children at each level.
7086 ;;
7087 ;; A completed nested imenu-alist entry looks like this:
7088 ;; '(("foo"
7089 ;; ("<definition>" . 7)
7090 ;; ("bar"
7091 ;; ("a" . 40)
7092 ;; ("b" . 60))))
7093 ;;
7094 ;; In particular, the documentation for `imenu--index-alist' says that
7095 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7096 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7097
7098 (defun js2-treeify (lst)
7099 "Convert (a b c d) to (a ((b ((c d)))))."
7100 (if (null (cddr lst)) ; list length <= 2
7101 lst
7102 (list (car lst) (list (js2-treeify (cdr lst))))))
7103
7104 (defun js2-build-alist-trie (chains trie)
7105 "Merge declaration name chains into a trie-like alist structure for imenu.
7106 CHAINS is the qname chain list produced during parsing. TRIE is a
7107 list of elements built up so far."
7108 (let (head tail pos branch kids)
7109 (dolist (chain chains)
7110 (setq head (car chain)
7111 tail (cdr chain)
7112 pos (if (numberp (car tail)) (car tail))
7113 branch (js2-find-if (lambda (n)
7114 (string= (car n) head))
7115 trie)
7116 kids (second branch))
7117 (cond
7118 ;; case 1: this key isn't in the trie yet
7119 ((null branch)
7120 (if trie
7121 (setcdr (last trie) (list (js2-treeify chain)))
7122 (setq trie (list (js2-treeify chain)))))
7123 ;; case 2: key is present with a single number entry: replace w/ list
7124 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7125 ;; ("<definition>" 20)))
7126 ((numberp kids)
7127 (setcar (cdr branch)
7128 (list (list "<definition-1>" kids)
7129 (if pos
7130 (list "<definition-2>" pos)
7131 (js2-treeify tail)))))
7132 ;; case 3: key is there (with kids), and we're a number entry
7133 (pos
7134 (setcdr (last kids)
7135 (list
7136 (list (format "<definition-%d>"
7137 (1+ (loop for kid in kids
7138 count (eq ?< (aref (car kid) 0)))))
7139 pos))))
7140 ;; case 4: key is there with kids, need to merge in our chain
7141 (t
7142 (js2-build-alist-trie (list tail) kids))))
7143 trie))
7144
7145 (defun js2-flatten-trie (trie)
7146 "Convert TRIE to imenu-format.
7147 Recurses through nodes, and for each one whose second element is a list,
7148 appends the list's flattened elements to the current element. Also
7149 changes the tails into conses. For instance, this pre-flattened trie
7150
7151 '(a ((b 20)
7152 (c ((d 30)
7153 (e 40)))))
7154
7155 becomes
7156
7157 '(a (b . 20)
7158 (c (d . 30)
7159 (e . 40)))
7160
7161 Note that the root of the trie has no key, just a list of chains.
7162 This is also true for the value of any key with multiple children,
7163 e.g. key 'c' in the example above."
7164 (cond
7165 ((listp (car trie))
7166 (mapcar #'js2-flatten-trie trie))
7167 (t
7168 (if (numberp (second trie))
7169 (cons (car trie) (second trie))
7170 ;; else pop list and append its kids
7171 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7172
7173 (defun js2-build-imenu-index ()
7174 "Turn `js2-imenu-recorder' into an imenu data structure."
7175 (when (eq js2-imenu-recorder 'empty)
7176 (setq js2-imenu-recorder nil))
7177 (let* ((chains (js2-browse-postprocess-chains))
7178 (result (js2-build-alist-trie chains nil)))
7179 (js2-flatten-trie result)))
7180
7181 (defun js2-test-print-chains (chains)
7182 "Print a list of qname chains.
7183 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7184 i.e. one or more nodes, and an integer position as the list tail."
7185 (mapconcat (lambda (chain)
7186 (concat "("
7187 (mapconcat (lambda (elem)
7188 (if (js2-node-p elem)
7189 (or (js2-node-qname-component elem)
7190 "nil")
7191 (number-to-string elem)))
7192 chain
7193 " ")
7194 ")"))
7195 chains
7196 "\n"))
7197
7198 ;;; Parser
7199
7200 (defconst js2-version "1.8.5"
7201 "Version of JavaScript supported.")
7202
7203 (defun js2-record-face (face &optional token)
7204 "Record a style run of FACE for TOKEN or the current token."
7205 (unless token (setq token (js2-current-token)))
7206 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7207
7208 (defsubst js2-node-end (n)
7209 "Computes the absolute end of node N.
7210 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7211 is only true until the node is added to its parent; i.e., while parsing."
7212 (+ (js2-node-pos n)
7213 (js2-node-len n)))
7214
7215 (defun js2-record-comment (token)
7216 "Record a comment in `js2-scanned-comments'."
7217 (let ((ct (js2-token-comment-type token))
7218 (beg (js2-token-beg token))
7219 (end (js2-token-end token)))
7220 (push (make-js2-comment-node :len (- end beg)
7221 :format ct)
7222 js2-scanned-comments)
7223 (when js2-parse-ide-mode
7224 (js2-record-face (if (eq ct 'jsdoc)
7225 'font-lock-doc-face
7226 'font-lock-comment-face)
7227 token)
7228 (when (memq ct '(html preprocessor))
7229 ;; Tell cc-engine the bounds of the comment.
7230 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7231
7232 (defun js2-peek-token ()
7233 "Return the next token type without consuming it.
7234 If `js2-ti-lookahead' is positive, return the type of next token
7235 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7236 (if (not (zerop js2-ti-lookahead))
7237 (js2-token-type
7238 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7239 (let ((tt (js2-get-token-internal nil)))
7240 (js2-unget-token)
7241 tt)))
7242
7243 (defalias 'js2-next-token 'js2-get-token)
7244
7245 (defun js2-match-token (match &optional dont-unget)
7246 "Get next token and return t if it matches MATCH, a bytecode.
7247 Returns nil and consumes nothing if MATCH is not the next token."
7248 (if (/= (js2-get-token) match)
7249 (ignore (unless dont-unget (js2-unget-token)))
7250 t))
7251
7252 (defun js2-match-contextual-kwd (name)
7253 "Consume and return t if next token is `js2-NAME', and its
7254 string is NAME. Returns nil and keeps current token otherwise."
7255 (if (or (/= (js2-get-token) js2-NAME)
7256 (not (string= (js2-current-token-string) name)))
7257 (progn
7258 (js2-unget-token)
7259 nil)
7260 (js2-record-face 'font-lock-keyword-face)
7261 t))
7262
7263 (defun js2-get-prop-name-token ()
7264 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7265
7266 (defun js2-match-prop-name ()
7267 "Consume token and return t if next token is a valid property name.
7268 If `js2-language-version' is >= 180, a keyword or reserved word
7269 is considered valid name as well."
7270 (if (eq js2-NAME (js2-get-prop-name-token))
7271 t
7272 (js2-unget-token)
7273 nil))
7274
7275 (defun js2-must-match-prop-name (msg-id &optional pos len)
7276 (if (js2-match-prop-name)
7277 t
7278 (js2-report-error msg-id nil pos len)
7279 nil))
7280
7281 (defun js2-peek-token-or-eol ()
7282 "Return js2-EOL if the next token immediately follows a newline.
7283 Else returns the next token. Used in situations where we don't
7284 consider certain token types valid if they are preceded by a newline.
7285 One example is the postfix ++ or -- operator, which has to be on the
7286 same line as its operand."
7287 (let ((tt (js2-get-token))
7288 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7289 (js2-unget-token)
7290 (if follows-eol
7291 js2-EOL
7292 tt)))
7293
7294 (defun js2-must-match (token msg-id &optional pos len)
7295 "Match next token to token code TOKEN, or record a syntax error.
7296 MSG-ID is the error message to report if the match fails.
7297 Returns t on match, nil if no match."
7298 (if (js2-match-token token t)
7299 t
7300 (js2-report-error msg-id nil pos len)
7301 (js2-unget-token)
7302 nil))
7303
7304 (defun js2-must-match-name (msg-id)
7305 (if (js2-match-token js2-NAME t)
7306 t
7307 (if (eq (js2-current-token-type) js2-RESERVED)
7308 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7309 (js2-report-error msg-id)
7310 (js2-unget-token))
7311 nil))
7312
7313 (defsubst js2-inside-function ()
7314 (plusp js2-nesting-of-function))
7315
7316 (defun js2-set-requires-activation ()
7317 (if (js2-function-node-p js2-current-script-or-fn)
7318 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7319
7320 (defun js2-check-activation-name (name _token)
7321 (when (js2-inside-function)
7322 ;; skip language-version 1.2 check from Rhino
7323 (if (or (string= "arguments" name)
7324 (and js2-compiler-activation-names ; only used in codegen
7325 (gethash name js2-compiler-activation-names)))
7326 (js2-set-requires-activation))))
7327
7328 (defun js2-set-is-generator ()
7329 (let ((fn-node js2-current-script-or-fn))
7330 (when (and (js2-function-node-p fn-node)
7331 (not (js2-function-node-generator-type fn-node)))
7332 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7333
7334 (defun js2-must-have-xml ()
7335 (unless js2-compiler-xml-available
7336 (js2-report-error "msg.XML.not.available")))
7337
7338 (defun js2-push-scope (scope)
7339 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7340 (assert (js2-scope-p scope))
7341 (assert (null (js2-scope-parent-scope scope)))
7342 (assert (not (eq js2-current-scope scope)))
7343 (setf (js2-scope-parent-scope scope) js2-current-scope
7344 js2-current-scope scope))
7345
7346 (defsubst js2-pop-scope ()
7347 (setq js2-current-scope
7348 (js2-scope-parent-scope js2-current-scope)))
7349
7350 (defun js2-enter-loop (loop-node)
7351 (push loop-node js2-loop-set)
7352 (push loop-node js2-loop-and-switch-set)
7353 (js2-push-scope loop-node)
7354 ;; Tell the current labeled statement (if any) its statement,
7355 ;; and set the jump target of the first label to the loop.
7356 ;; These are used in `js2-parse-continue' to verify that the
7357 ;; continue target is an actual labeled loop. (And for codegen.)
7358 (when js2-labeled-stmt
7359 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7360 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7361 js2-labeled-stmt))) loop-node)))
7362
7363 (defun js2-exit-loop ()
7364 (pop js2-loop-set)
7365 (pop js2-loop-and-switch-set)
7366 (js2-pop-scope))
7367
7368 (defsubst js2-enter-switch (switch-node)
7369 (push switch-node js2-loop-and-switch-set))
7370
7371 (defsubst js2-exit-switch ()
7372 (pop js2-loop-and-switch-set))
7373
7374 (defun js2-parse (&optional buf cb)
7375 "Tell the js2 parser to parse a region of JavaScript.
7376
7377 BUF is a buffer or buffer name containing the code to parse.
7378 Call `narrow-to-region' first to parse only part of the buffer.
7379
7380 The returned AST root node is given some additional properties:
7381 `node-count' - total number of nodes in the AST
7382 `buffer' - BUF. The buffer it refers to may change or be killed,
7383 so the value is not necessarily reliable.
7384
7385 An optional callback CB can be specified to report parsing
7386 progress. If `(functionp CB)' returns t, it will be called with
7387 the current line number once before parsing begins, then again
7388 each time the lexer reaches a new line number.
7389
7390 CB can also be a list of the form `(symbol cb ...)' to specify
7391 multiple callbacks with different criteria. Each symbol is a
7392 criterion keyword, and the following element is the callback to
7393 call
7394
7395 :line - called whenever the line number changes
7396 :token - called for each new token consumed
7397
7398 The list of criteria could be extended to include entering or
7399 leaving a statement, an expression, or a function definition."
7400 (if (and cb (not (functionp cb)))
7401 (error "criteria callbacks not yet implemented"))
7402 (let ((inhibit-point-motion-hooks t)
7403 (js2-compiler-xml-available (>= js2-language-version 160))
7404 ;; This is a recursive-descent parser, so give it a big stack.
7405 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7406 (max-specpdl-size (max max-specpdl-size 3000))
7407 (case-fold-search nil)
7408 ast)
7409 (with-current-buffer (or buf (current-buffer))
7410 (setq js2-scanned-comments nil
7411 js2-parsed-errors nil
7412 js2-parsed-warnings nil
7413 js2-imenu-recorder nil
7414 js2-imenu-function-map nil
7415 js2-label-set nil)
7416 (js2-init-scanner)
7417 (setq ast (with-silent-modifications
7418 (js2-do-parse)))
7419 (unless js2-ts-hit-eof
7420 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7421 (setf (js2-ast-root-errors ast) js2-parsed-errors
7422 (js2-ast-root-warnings ast) js2-parsed-warnings)
7423 ;; if we didn't find any declarations, put a dummy in this list so we
7424 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7425 (unless js2-imenu-recorder
7426 (setq js2-imenu-recorder 'empty))
7427 (run-hooks 'js2-parse-finished-hook)
7428 ast)))
7429
7430 ;; Corresponds to Rhino's Parser.parse() method.
7431 (defun js2-do-parse ()
7432 "Parse current buffer starting from current point.
7433 Scanner should be initialized."
7434 (let ((pos js2-ts-cursor)
7435 (end js2-ts-cursor) ; in case file is empty
7436 root n tt)
7437 ;; initialize buffer-local parsing vars
7438 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7439 js2-current-script-or-fn root
7440 js2-current-scope root
7441 js2-nesting-of-function 0
7442 js2-labeled-stmt nil
7443 js2-recorded-identifiers nil) ; for js2-highlight
7444 (while (/= (setq tt (js2-get-token)) js2-EOF)
7445 (if (= tt js2-FUNCTION)
7446 (progn
7447 (setq n (if js2-called-by-compile-function
7448 (js2-parse-function-expr)
7449 (js2-parse-function-stmt))))
7450 ;; not a function - parse a statement
7451 (js2-unget-token)
7452 (setq n (js2-parse-statement)))
7453 ;; add function or statement to script
7454 (setq end (js2-node-end n))
7455 (js2-block-node-push root n))
7456 ;; add comments to root in lexical order
7457 (when js2-scanned-comments
7458 ;; if we find a comment beyond end of normal kids, use its end
7459 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7460 (dolist (comment js2-scanned-comments)
7461 (push comment (js2-ast-root-comments root))
7462 (js2-node-add-children root comment)))
7463 (setf (js2-node-len root) (- end pos))
7464 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7465 ;; Give extensions a chance to muck with things before highlighting starts.
7466 (let ((js2-additional-externs js2-additional-externs))
7467 (save-excursion
7468 (run-hooks 'js2-post-parse-callbacks))
7469 (js2-highlight-undeclared-vars))
7470 root))
7471
7472 (defun js2-parse-function-closure-body (fn-node)
7473 "Parse a JavaScript 1.8 function closure body."
7474 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7475 (if js2-ts-hit-eof
7476 (js2-report-error "msg.no.brace.body" nil
7477 (js2-node-pos fn-node)
7478 (- js2-ts-cursor (js2-node-pos fn-node)))
7479 (js2-node-add-children fn-node
7480 (setf (js2-function-node-body fn-node)
7481 (js2-parse-expr t))))))
7482
7483 (defun js2-parse-function-body (fn-node)
7484 (js2-must-match js2-LC "msg.no.brace.body"
7485 (js2-node-pos fn-node)
7486 (- js2-ts-cursor (js2-node-pos fn-node)))
7487 (let ((pos (js2-current-token-beg)) ; LC position
7488 (pn (make-js2-block-node)) ; starts at LC position
7489 tt
7490 end)
7491 (incf js2-nesting-of-function)
7492 (unwind-protect
7493 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7494 (= tt js2-EOF)
7495 (= tt js2-RC)))
7496 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7497 (js2-parse-statement)
7498 (js2-get-token)
7499 (js2-parse-function-stmt))))
7500 (decf js2-nesting-of-function))
7501 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7502 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7503 (setq end (js2-current-token-end)))
7504 (setf (js2-node-pos pn) pos
7505 (js2-node-len pn) (- end pos))
7506 (setf (js2-function-node-body fn-node) pn)
7507 (js2-node-add-children fn-node pn)
7508 pn))
7509
7510 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7511 "Declare and fontify destructuring parameters inside NODE.
7512 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7513 (cond
7514 ((js2-name-node-p node)
7515 (let (leftpos)
7516 (js2-define-symbol decl-type (js2-name-node-name node)
7517 node ignore-not-in-block)
7518 (when face
7519 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7520 (+ leftpos (js2-node-len node))
7521 face 'record))))
7522 ((js2-object-node-p node)
7523 (dolist (elem (js2-object-node-elems node))
7524 (js2-define-destruct-symbols
7525 ;; In abbreviated destructuring {a, b}, right == left.
7526 (js2-object-prop-node-right elem)
7527 decl-type face ignore-not-in-block)))
7528 ((js2-array-node-p node)
7529 (dolist (elem (js2-array-node-elems node))
7530 (when elem
7531 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7532 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7533 (js2-node-len node)))))
7534
7535 (defun js2-parse-function-params (function-type fn-node pos)
7536 (if (js2-match-token js2-RP)
7537 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7538 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7539 (eq (js2-current-token-type) js2-NAME)))
7540 params param default-found rest-param-at)
7541 (when paren-free-arrow
7542 (js2-unget-token))
7543 (loop for tt = (js2-peek-token)
7544 do
7545 (cond
7546 ;; destructuring param
7547 ((and (not paren-free-arrow)
7548 (or (= tt js2-LB) (= tt js2-LC)))
7549 (js2-get-token)
7550 (when default-found
7551 (js2-report-error "msg.no.default.after.default.param"))
7552 (setq param (js2-parse-destruct-primary-expr))
7553 (js2-define-destruct-symbols param
7554 js2-LP
7555 'js2-function-param)
7556 (push param params))
7557 ;; variable name
7558 (t
7559 (when (and (>= js2-language-version 200)
7560 (not paren-free-arrow)
7561 (js2-match-token js2-TRIPLEDOT)
7562 (not rest-param-at))
7563 ;; to report errors if there are more parameters
7564 (setq rest-param-at (length params)))
7565 (js2-must-match-name "msg.no.parm")
7566 (js2-record-face 'js2-function-param)
7567 (setq param (js2-create-name-node))
7568 (js2-define-symbol js2-LP (js2-current-token-string) param)
7569 ;; default parameter value
7570 (when (or (and default-found
7571 (not rest-param-at)
7572 (js2-must-match js2-ASSIGN
7573 "msg.no.default.after.default.param"
7574 (js2-node-pos param)
7575 (js2-node-len param)))
7576 (and (>= js2-language-version 200)
7577 (js2-match-token js2-ASSIGN)))
7578 (assert (not paren-free-arrow))
7579 (let* ((pos (js2-node-pos param))
7580 (tt (js2-current-token-type))
7581 (op-pos (- (js2-current-token-beg) pos))
7582 (left param)
7583 (right (js2-parse-assign-expr))
7584 (len (- (js2-node-end right) pos)))
7585 (setq param (make-js2-assign-node
7586 :type tt :pos pos :len len :op-pos op-pos
7587 :left left :right right)
7588 default-found t)
7589 (js2-node-add-children param left right)))
7590 (push param params)))
7591 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7592 (js2-report-error "msg.param.after.rest" nil
7593 (js2-node-pos param) (js2-node-len param)))
7594 while
7595 (js2-match-token js2-COMMA))
7596 (when (and (not paren-free-arrow)
7597 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7598 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7599 (when rest-param-at
7600 (setf (js2-function-node-rest-p fn-node) t))
7601 (dolist (p params)
7602 (js2-node-add-children fn-node p)
7603 (push p (js2-function-node-params fn-node))))))
7604
7605 (defun js2-check-inconsistent-return-warning (fn-node name)
7606 "Possibly show inconsistent-return warning.
7607 Last token scanned is the close-curly for the function body."
7608 (when (and js2-mode-show-strict-warnings
7609 js2-strict-inconsistent-return-warning
7610 (not (js2-has-consistent-return-usage
7611 (js2-function-node-body fn-node))))
7612 ;; Have it extend from close-curly to bol or beginning of block.
7613 (let ((pos (save-excursion
7614 (goto-char (js2-current-token-end))
7615 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7616 (point-at-bol))))
7617 (end (js2-current-token-end)))
7618 (if (plusp (js2-name-node-length name))
7619 (js2-add-strict-warning "msg.no.return.value"
7620 (js2-name-node-name name) pos end)
7621 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7622
7623 (defun js2-parse-function-stmt ()
7624 (let ((pos (js2-current-token-beg))
7625 (star-p (js2-match-token js2-MUL)))
7626 (js2-must-match-name "msg.unnamed.function.stmt")
7627 (let ((name (js2-create-name-node t))
7628 pn member-expr)
7629 (cond
7630 ((js2-match-token js2-LP)
7631 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7632 (js2-allow-member-expr-as-function-name
7633 (setq member-expr (js2-parse-member-expr-tail nil name))
7634 (js2-parse-highlight-member-expr-fn-name member-expr)
7635 (js2-must-match js2-LP "msg.no.paren.parms")
7636 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7637 (js2-function-node-member-expr pn) member-expr)
7638 pn)
7639 (t
7640 (js2-report-error "msg.no.paren.parms")
7641 (make-js2-error-node))))))
7642
7643 (defun js2-parse-function-expr ()
7644 (let ((pos (js2-current-token-beg))
7645 (star-p (js2-match-token js2-MUL))
7646 name)
7647 (when (js2-match-token js2-NAME)
7648 (setq name (js2-create-name-node t)))
7649 (js2-must-match js2-LP "msg.no.paren.parms")
7650 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7651
7652 (defun js2-parse-function (function-type pos star-p &optional name)
7653 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7654 beginning of the first token (function keyword, unless it's an
7655 arrow function), NAME is js2-name-node."
7656 (let (fn-node lp)
7657 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7658 (setq lp (js2-current-token-beg)))
7659 (setf fn-node (make-js2-function-node :pos pos
7660 :name name
7661 :form function-type
7662 :lp (if lp (- lp pos))
7663 :generator-type (and star-p 'STAR)))
7664 (when name
7665 (js2-set-face (js2-node-pos name) (js2-node-end name)
7666 'font-lock-function-name-face 'record)
7667 (when (plusp (js2-name-node-length name))
7668 ;; Function statements define a symbol in the enclosing scope
7669 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7670 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7671 ;; 1. Nested functions are not affected by the dynamic scope flag
7672 ;; as dynamic scope is already a parent of their scope.
7673 ;; 2. Functions defined under the with statement also immune to
7674 ;; this setup, in which case dynamic scope is ignored in favor
7675 ;; of the with object.
7676 (setf (js2-function-node-ignore-dynamic fn-node) t))
7677 ;; dynamically bind all the per-function variables
7678 (let ((js2-current-script-or-fn fn-node)
7679 (js2-current-scope fn-node)
7680 (js2-nesting-of-with 0)
7681 (js2-end-flags 0)
7682 js2-label-set
7683 js2-loop-set
7684 js2-loop-and-switch-set)
7685 (js2-parse-function-params function-type fn-node pos)
7686 (when (eq function-type 'FUNCTION_ARROW)
7687 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7688 (if (and (>= js2-language-version 180)
7689 (/= (js2-peek-token) js2-LC))
7690 (js2-parse-function-closure-body fn-node)
7691 (js2-parse-function-body fn-node))
7692 (js2-check-inconsistent-return-warning fn-node name)
7693
7694 (when name
7695 (js2-node-add-children fn-node name)
7696 ;; Function expressions define a name only in the body of the
7697 ;; function, and only if not hidden by a parameter name
7698 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7699 (null (js2-scope-get-symbol js2-current-scope
7700 (js2-name-node-name name))))
7701 (js2-define-symbol js2-FUNCTION
7702 (js2-name-node-name name)
7703 fn-node))
7704 (when (eq function-type 'FUNCTION_STATEMENT)
7705 (js2-record-imenu-functions fn-node))))
7706
7707 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7708 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7709 ;; We wait until after parsing the function to set its parent scope,
7710 ;; since `js2-define-symbol' needs the defining-scope check to stop
7711 ;; at the function boundary when checking for redeclarations.
7712 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7713 fn-node))
7714
7715 (defun js2-parse-statements (&optional parent)
7716 "Parse a statement list. Last token consumed must be js2-LC.
7717
7718 PARENT can be a `js2-block-node', in which case the statements are
7719 appended to PARENT. Otherwise a new `js2-block-node' is created
7720 and returned.
7721
7722 This function does not match the closing js2-RC: the caller
7723 matches the RC so it can provide a suitable error message if not
7724 matched. This means it's up to the caller to set the length of
7725 the node to include the closing RC. The node start pos is set to
7726 the absolute buffer start position, and the caller should fix it
7727 up to be relative to the parent node. All children of this block
7728 node are given relative start positions and correct lengths."
7729 (let ((pn (or parent (make-js2-block-node)))
7730 tt)
7731 (setf (js2-node-pos pn) (js2-current-token-beg))
7732 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7733 (/= tt js2-RC))
7734 (js2-block-node-push pn (js2-parse-statement)))
7735 pn))
7736
7737 (defun js2-parse-statement ()
7738 (let (pn beg end)
7739 ;; coarse-grained user-interrupt check - needs work
7740 (and js2-parse-interruptable-p
7741 (zerop (% (incf js2-parse-stmt-count)
7742 js2-statements-per-pause))
7743 (input-pending-p)
7744 (throw 'interrupted t))
7745 (setq pn (js2-statement-helper))
7746 ;; no-side-effects warning check
7747 (unless (js2-node-has-side-effects pn)
7748 (setq end (js2-node-end pn))
7749 (save-excursion
7750 (goto-char end)
7751 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7752 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7753 pn))
7754
7755 ;; These correspond to the switch cases in Parser.statementHelper
7756 (defconst js2-parsers
7757 (let ((parsers (make-vector js2-num-tokens
7758 #'js2-parse-expr-stmt)))
7759 (aset parsers js2-BREAK #'js2-parse-break)
7760 (aset parsers js2-CLASS #'js2-parse-class-stmt)
7761 (aset parsers js2-CONST #'js2-parse-const-var)
7762 (aset parsers js2-CONTINUE #'js2-parse-continue)
7763 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7764 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7765 (aset parsers js2-DO #'js2-parse-do)
7766 (aset parsers js2-FOR #'js2-parse-for)
7767 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7768 (aset parsers js2-IF #'js2-parse-if)
7769 (aset parsers js2-LC #'js2-parse-block)
7770 (aset parsers js2-LET #'js2-parse-let-stmt)
7771 (aset parsers js2-NAME #'js2-parse-name-or-label)
7772 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7773 (aset parsers js2-SEMI #'js2-parse-semi)
7774 (aset parsers js2-SWITCH #'js2-parse-switch)
7775 (aset parsers js2-THROW #'js2-parse-throw)
7776 (aset parsers js2-TRY #'js2-parse-try)
7777 (aset parsers js2-VAR #'js2-parse-const-var)
7778 (aset parsers js2-WHILE #'js2-parse-while)
7779 (aset parsers js2-WITH #'js2-parse-with)
7780 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7781 parsers)
7782 "A vector mapping token types to parser functions.")
7783
7784 (defun js2-parse-warn-missing-semi (beg end)
7785 (and js2-mode-show-strict-warnings
7786 js2-strict-missing-semi-warning
7787 (js2-add-strict-warning
7788 "msg.missing.semi" nil
7789 ;; back up to beginning of statement or line
7790 (max beg (save-excursion
7791 (goto-char end)
7792 (point-at-bol)))
7793 end)))
7794
7795 (defconst js2-no-semi-insertion
7796 (list js2-IF
7797 js2-SWITCH
7798 js2-WHILE
7799 js2-DO
7800 js2-FOR
7801 js2-TRY
7802 js2-WITH
7803 js2-LC
7804 js2-ERROR
7805 js2-SEMI
7806 js2-CLASS
7807 js2-FUNCTION)
7808 "List of tokens that don't do automatic semicolon insertion.")
7809
7810 (defconst js2-autoinsert-semi-and-warn
7811 (list js2-ERROR js2-EOF js2-RC))
7812
7813 (defun js2-statement-helper ()
7814 (let* ((tt (js2-get-token))
7815 (first-tt tt)
7816 (parser (if (= tt js2-ERROR)
7817 #'js2-parse-semi
7818 (aref js2-parsers tt)))
7819 pn)
7820 ;; If the statement is set, then it's been told its label by now.
7821 (and js2-labeled-stmt
7822 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7823 (setq js2-labeled-stmt nil))
7824 (setq pn (funcall parser))
7825 ;; Don't do auto semi insertion for certain statement types.
7826 (unless (or (memq first-tt js2-no-semi-insertion)
7827 (js2-labeled-stmt-node-p pn))
7828 (js2-auto-insert-semicolon pn))
7829 pn))
7830
7831 (defun js2-auto-insert-semicolon (pn)
7832 (let* ((tt (js2-get-token))
7833 (pos (js2-node-pos pn)))
7834 (cond
7835 ((= tt js2-SEMI)
7836 ;; extend the node bounds to include the semicolon.
7837 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7838 ((memq tt js2-autoinsert-semi-and-warn)
7839 (js2-unget-token) ; Not ';', do not consume.
7840 ;; Autoinsert ;
7841 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7842 (t
7843 (if (not (js2-token-follows-eol-p (js2-current-token)))
7844 ;; Report error if no EOL or autoinsert ';' otherwise
7845 (js2-report-error "msg.no.semi.stmt")
7846 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7847 (js2-unget-token) ; Not ';', do not consume.
7848 ))))
7849
7850 (defun js2-parse-condition ()
7851 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7852 The parens are discarded and the expression node is returned.
7853 The `pos' field of the return value is set to an absolute position
7854 that must be fixed up by the caller.
7855 Return value is a list (EXPR LP RP), with absolute paren positions."
7856 (let (pn lp rp)
7857 (if (js2-must-match js2-LP "msg.no.paren.cond")
7858 (setq lp (js2-current-token-beg)))
7859 (setq pn (js2-parse-expr))
7860 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7861 (setq rp (js2-current-token-beg)))
7862 ;; Report strict warning on code like "if (a = 7) ..."
7863 (if (and js2-strict-cond-assign-warning
7864 (js2-assign-node-p pn))
7865 (js2-add-strict-warning "msg.equal.as.assign" nil
7866 (js2-node-pos pn)
7867 (+ (js2-node-pos pn)
7868 (js2-node-len pn))))
7869 (list pn lp rp)))
7870
7871 (defun js2-parse-if ()
7872 "Parser for if-statement. Last matched token must be js2-IF."
7873 (let ((pos (js2-current-token-beg))
7874 cond if-true if-false else-pos end pn)
7875 (setq cond (js2-parse-condition)
7876 if-true (js2-parse-statement)
7877 if-false (if (js2-match-token js2-ELSE)
7878 (progn
7879 (setq else-pos (- (js2-current-token-beg) pos))
7880 (js2-parse-statement)))
7881 end (js2-node-end (or if-false if-true))
7882 pn (make-js2-if-node :pos pos
7883 :len (- end pos)
7884 :condition (car cond)
7885 :then-part if-true
7886 :else-part if-false
7887 :else-pos else-pos
7888 :lp (js2-relpos (second cond) pos)
7889 :rp (js2-relpos (third cond) pos)))
7890 (js2-node-add-children pn (car cond) if-true if-false)
7891 pn))
7892
7893 (defun js2-parse-switch ()
7894 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7895 (let ((pos (js2-current-token-beg))
7896 tt pn discriminant has-default case-expr case-node
7897 case-pos cases stmt lp)
7898 (if (js2-must-match js2-LP "msg.no.paren.switch")
7899 (setq lp (js2-current-token-beg)))
7900 (setq discriminant (js2-parse-expr)
7901 pn (make-js2-switch-node :discriminant discriminant
7902 :pos pos
7903 :lp (js2-relpos lp pos)))
7904 (js2-node-add-children pn discriminant)
7905 (js2-enter-switch pn)
7906 (unwind-protect
7907 (progn
7908 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7909 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7910 (js2-must-match js2-LC "msg.no.brace.switch")
7911 (catch 'break
7912 (while t
7913 (setq tt (js2-next-token)
7914 case-pos (js2-current-token-beg))
7915 (cond
7916 ((= tt js2-RC)
7917 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7918 (throw 'break nil)) ; done
7919 ((= tt js2-CASE)
7920 (setq case-expr (js2-parse-expr))
7921 (js2-must-match js2-COLON "msg.no.colon.case"))
7922 ((= tt js2-DEFAULT)
7923 (if has-default
7924 (js2-report-error "msg.double.switch.default"))
7925 (setq has-default t
7926 case-expr nil)
7927 (js2-must-match js2-COLON "msg.no.colon.case"))
7928 (t
7929 (js2-report-error "msg.bad.switch")
7930 (throw 'break nil)))
7931 (setq case-node (make-js2-case-node :pos case-pos
7932 :len (- (js2-current-token-end) case-pos)
7933 :expr case-expr))
7934 (js2-node-add-children case-node case-expr)
7935 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7936 (/= tt js2-CASE)
7937 (/= tt js2-DEFAULT)
7938 (/= tt js2-EOF))
7939 (setf stmt (js2-parse-statement)
7940 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7941 (js2-block-node-push case-node stmt))
7942 (push case-node cases)))
7943 ;; add cases last, as pushing reverses the order to be correct
7944 (dolist (kid cases)
7945 (js2-node-add-children pn kid)
7946 (push kid (js2-switch-node-cases pn)))
7947 pn) ; return value
7948 (js2-exit-switch))))
7949
7950 (defun js2-parse-while ()
7951 "Parser for while-statement. Last matched token must be js2-WHILE."
7952 (let ((pos (js2-current-token-beg))
7953 (pn (make-js2-while-node))
7954 cond body)
7955 (js2-enter-loop pn)
7956 (unwind-protect
7957 (progn
7958 (setf cond (js2-parse-condition)
7959 (js2-while-node-condition pn) (car cond)
7960 body (js2-parse-statement)
7961 (js2-while-node-body pn) body
7962 (js2-node-len pn) (- (js2-node-end body) pos)
7963 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7964 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7965 (js2-node-add-children pn body (car cond)))
7966 (js2-exit-loop))
7967 pn))
7968
7969 (defun js2-parse-do ()
7970 "Parser for do-statement. Last matched token must be js2-DO."
7971 (let ((pos (js2-current-token-beg))
7972 (pn (make-js2-do-node))
7973 cond body end)
7974 (js2-enter-loop pn)
7975 (unwind-protect
7976 (progn
7977 (setq body (js2-parse-statement))
7978 (js2-must-match js2-WHILE "msg.no.while.do")
7979 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7980 cond (js2-parse-condition)
7981 (js2-do-node-condition pn) (car cond)
7982 (js2-do-node-body pn) body
7983 end js2-ts-cursor
7984 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7985 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7986 (js2-node-add-children pn (car cond) body))
7987 (js2-exit-loop))
7988 ;; Always auto-insert semicolon to follow SpiderMonkey:
7989 ;; It is required by ECMAScript but is ignored by the rest of
7990 ;; world; see bug 238945
7991 (if (js2-match-token js2-SEMI)
7992 (setq end js2-ts-cursor))
7993 (setf (js2-node-len pn) (- end pos))
7994 pn))
7995
7996 (defun js2-parse-for ()
7997 "Parser for for-statement. Last matched token must be js2-FOR.
7998 Parses for, for-in, and for each-in statements."
7999 (let ((for-pos (js2-current-token-beg))
8000 pn is-for-each is-for-in-or-of is-for-of
8001 in-pos each-pos tmp-pos
8002 init ; Node init is also foo in 'foo in object'
8003 cond ; Node cond is also object in 'foo in object'
8004 incr ; 3rd section of for-loop initializer
8005 body tt lp rp)
8006 ;; See if this is a for each () instead of just a for ()
8007 (when (js2-match-token js2-NAME)
8008 (if (string= "each" (js2-current-token-string))
8009 (progn
8010 (setq is-for-each t
8011 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8012 (js2-record-face 'font-lock-keyword-face))
8013 (js2-report-error "msg.no.paren.for")))
8014 (if (js2-must-match js2-LP "msg.no.paren.for")
8015 (setq lp (- (js2-current-token-beg) for-pos)))
8016 (setq tt (js2-get-token))
8017 ;; 'for' makes local scope
8018 (js2-push-scope (make-js2-scope))
8019 (unwind-protect
8020 ;; parse init clause
8021 (let ((js2-in-for-init t)) ; set as dynamic variable
8022 (cond
8023 ((= tt js2-SEMI)
8024 (js2-unget-token)
8025 (setq init (make-js2-empty-expr-node)))
8026 ((or (= tt js2-VAR) (= tt js2-LET))
8027 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8028 (t
8029 (js2-unget-token)
8030 (setq init (js2-parse-expr)))))
8031 (if (or (js2-match-token js2-IN)
8032 (and (>= js2-language-version 200)
8033 (js2-match-contextual-kwd "of")
8034 (setq is-for-of t)))
8035 (setq is-for-in-or-of t
8036 in-pos (- (js2-current-token-beg) for-pos)
8037 ;; scope of iteration target object is not the scope we've created above.
8038 ;; stash current scope temporary.
8039 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8040 (js2-parse-expr))) ; object over which we're iterating
8041 ;; else ordinary for loop - parse cond and incr
8042 (js2-must-match js2-SEMI "msg.no.semi.for")
8043 (setq cond (if (= (js2-peek-token) js2-SEMI)
8044 (make-js2-empty-expr-node) ; no loop condition
8045 (js2-parse-expr)))
8046 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8047 (setq tmp-pos (js2-current-token-end)
8048 incr (if (= (js2-peek-token) js2-RP)
8049 (make-js2-empty-expr-node :pos tmp-pos)
8050 (js2-parse-expr))))
8051 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8052 (setq rp (- (js2-current-token-beg) for-pos)))
8053 (if (not is-for-in-or-of)
8054 (setq pn (make-js2-for-node :init init
8055 :condition cond
8056 :update incr
8057 :lp lp
8058 :rp rp))
8059 ;; cond could be null if 'in obj' got eaten by the init node.
8060 (if (js2-infix-node-p init)
8061 ;; it was (foo in bar) instead of (var foo in bar)
8062 (setq cond (js2-infix-node-right init)
8063 init (js2-infix-node-left init))
8064 (if (and (js2-var-decl-node-p init)
8065 (> (length (js2-var-decl-node-kids init)) 1))
8066 (js2-report-error "msg.mult.index")))
8067 (setq pn (make-js2-for-in-node :iterator init
8068 :object cond
8069 :in-pos in-pos
8070 :foreach-p is-for-each
8071 :each-pos each-pos
8072 :forof-p is-for-of
8073 :lp lp
8074 :rp rp)))
8075 (unwind-protect
8076 (progn
8077 (js2-enter-loop pn)
8078 ;; We have to parse the body -after- creating the loop node,
8079 ;; so that the loop node appears in the js2-loop-set, allowing
8080 ;; break/continue statements to find the enclosing loop.
8081 (setf body (js2-parse-statement)
8082 (js2-loop-node-body pn) body
8083 (js2-node-pos pn) for-pos
8084 (js2-node-len pn) (- (js2-node-end body) for-pos))
8085 (js2-node-add-children pn init cond incr body))
8086 ;; finally
8087 (js2-exit-loop))
8088 (js2-pop-scope))
8089 pn))
8090
8091 (defun js2-parse-try ()
8092 "Parser for try-statement. Last matched token must be js2-TRY."
8093 (let ((try-pos (js2-current-token-beg))
8094 try-end
8095 try-block
8096 catch-blocks
8097 finally-block
8098 saw-default-catch
8099 peek
8100 param
8101 catch-cond
8102 catch-node
8103 guard-kwd
8104 catch-pos
8105 finally-pos
8106 pn
8107 block
8108 lp
8109 rp)
8110 (if (/= (js2-peek-token) js2-LC)
8111 (js2-report-error "msg.no.brace.try"))
8112 (setq try-block (js2-parse-statement)
8113 try-end (js2-node-end try-block)
8114 peek (js2-peek-token))
8115 (cond
8116 ((= peek js2-CATCH)
8117 (while (js2-match-token js2-CATCH)
8118 (setq catch-pos (js2-current-token-beg)
8119 guard-kwd nil
8120 catch-cond nil
8121 lp nil
8122 rp nil)
8123 (if saw-default-catch
8124 (js2-report-error "msg.catch.unreachable"))
8125 (if (js2-must-match js2-LP "msg.no.paren.catch")
8126 (setq lp (- (js2-current-token-beg) catch-pos)))
8127 (js2-push-scope (make-js2-scope))
8128 (let ((tt (js2-peek-token)))
8129 (cond
8130 ;; destructuring pattern
8131 ;; catch ({ message, file }) { ... }
8132 ((or (= tt js2-LB) (= tt js2-LC))
8133 (js2-get-token)
8134 (setq param (js2-parse-destruct-primary-expr))
8135 (js2-define-destruct-symbols param js2-LET nil))
8136 ;; simple name
8137 (t
8138 (js2-must-match-name "msg.bad.catchcond")
8139 (setq param (js2-create-name-node))
8140 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8141 ;; pattern guard
8142 (if (js2-match-token js2-IF)
8143 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8144 catch-cond (js2-parse-expr))
8145 (setq saw-default-catch t))
8146 (if (js2-must-match js2-RP "msg.bad.catchcond")
8147 (setq rp (- (js2-current-token-beg) catch-pos)))
8148 (js2-must-match js2-LC "msg.no.brace.catchblock")
8149 (setq block (js2-parse-statements)
8150 try-end (js2-node-end block)
8151 catch-node (make-js2-catch-node :pos catch-pos
8152 :param param
8153 :guard-expr catch-cond
8154 :guard-kwd guard-kwd
8155 :block block
8156 :lp lp
8157 :rp rp))
8158 (js2-pop-scope)
8159 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8160 (setq try-end (js2-current-token-beg)))
8161 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8162 (js2-node-len catch-node) (- try-end catch-pos))
8163 (js2-node-add-children catch-node param catch-cond block)
8164 (push catch-node catch-blocks)))
8165 ((/= peek js2-FINALLY)
8166 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8167 (js2-node-pos try-block)
8168 (- (setq try-end (js2-node-end try-block))
8169 (js2-node-pos try-block)))))
8170 (when (js2-match-token js2-FINALLY)
8171 (setq finally-pos (js2-current-token-beg)
8172 block (js2-parse-statement)
8173 try-end (js2-node-end block)
8174 finally-block (make-js2-finally-node :pos finally-pos
8175 :len (- try-end finally-pos)
8176 :body block))
8177 (js2-node-add-children finally-block block))
8178 (setq pn (make-js2-try-node :pos try-pos
8179 :len (- try-end try-pos)
8180 :try-block try-block
8181 :finally-block finally-block))
8182 (js2-node-add-children pn try-block finally-block)
8183 ;; push them onto the try-node, which reverses and corrects their order
8184 (dolist (cb catch-blocks)
8185 (js2-node-add-children pn cb)
8186 (push cb (js2-try-node-catch-clauses pn)))
8187 pn))
8188
8189 (defun js2-parse-throw ()
8190 "Parser for throw-statement. Last matched token must be js2-THROW."
8191 (let ((pos (js2-current-token-beg))
8192 expr pn)
8193 (if (= (js2-peek-token-or-eol) js2-EOL)
8194 ;; ECMAScript does not allow new lines before throw expression,
8195 ;; see bug 256617
8196 (js2-report-error "msg.bad.throw.eol"))
8197 (setq expr (js2-parse-expr)
8198 pn (make-js2-throw-node :pos pos
8199 :len (- (js2-node-end expr) pos)
8200 :expr expr))
8201 (js2-node-add-children pn expr)
8202 pn))
8203
8204 (defun js2-match-jump-label-name (label-name)
8205 "If break/continue specified a label, return that label's labeled stmt.
8206 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8207 does not match an existing label, reports an error and returns nil."
8208 (let ((bundle (cdr (assoc label-name js2-label-set))))
8209 (if (null bundle)
8210 (js2-report-error "msg.undef.label"))
8211 bundle))
8212
8213 (defun js2-parse-break ()
8214 "Parser for break-statement. Last matched token must be js2-BREAK."
8215 (let ((pos (js2-current-token-beg))
8216 (end (js2-current-token-end))
8217 break-target ; statement to break from
8218 break-label ; in "break foo", name-node representing the foo
8219 labels ; matching labeled statement to break to
8220 pn)
8221 (when (eq (js2-peek-token-or-eol) js2-NAME)
8222 (js2-get-token)
8223 (setq break-label (js2-create-name-node)
8224 end (js2-node-end break-label)
8225 ;; matchJumpLabelName only matches if there is one
8226 labels (js2-match-jump-label-name (js2-current-token-string))
8227 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8228 (unless (or break-target break-label)
8229 ;; no break target specified - try for innermost enclosing loop/switch
8230 (if (null js2-loop-and-switch-set)
8231 (unless break-label
8232 (js2-report-error "msg.bad.break" nil pos (length "break")))
8233 (setq break-target (car js2-loop-and-switch-set))))
8234 (setq pn (make-js2-break-node :pos pos
8235 :len (- end pos)
8236 :label break-label
8237 :target break-target))
8238 (js2-node-add-children pn break-label) ; but not break-target
8239 pn))
8240
8241 (defun js2-parse-continue ()
8242 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8243 (let ((pos (js2-current-token-beg))
8244 (end (js2-current-token-end))
8245 label ; optional user-specified label, a `js2-name-node'
8246 labels ; current matching labeled stmt, if any
8247 target ; the `js2-loop-node' target of this continue stmt
8248 pn)
8249 (when (= (js2-peek-token-or-eol) js2-NAME)
8250 (js2-get-token)
8251 (setq label (js2-create-name-node)
8252 end (js2-node-end label)
8253 ;; matchJumpLabelName only matches if there is one
8254 labels (js2-match-jump-label-name (js2-current-token-string))))
8255 (cond
8256 ((null labels) ; no current label to go to
8257 (if (null js2-loop-set) ; no loop to continue to
8258 (js2-report-error "msg.continue.outside" nil pos
8259 (length "continue"))
8260 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8261 (t
8262 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8263 (setq target (js2-labeled-stmt-node-stmt labels))
8264 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8265 (setq pn (make-js2-continue-node :pos pos
8266 :len (- end pos)
8267 :label label
8268 :target target))
8269 (js2-node-add-children pn label) ; but not target - it's not our child
8270 pn))
8271
8272 (defun js2-parse-with ()
8273 "Parser for with-statement. Last matched token must be js2-WITH."
8274 (let ((pos (js2-current-token-beg))
8275 obj body pn lp rp)
8276 (if (js2-must-match js2-LP "msg.no.paren.with")
8277 (setq lp (js2-current-token-beg)))
8278 (setq obj (js2-parse-expr))
8279 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8280 (setq rp (js2-current-token-beg)))
8281 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8282 (setq body (js2-parse-statement)))
8283 (setq pn (make-js2-with-node :pos pos
8284 :len (- (js2-node-end body) pos)
8285 :object obj
8286 :body body
8287 :lp (js2-relpos lp pos)
8288 :rp (js2-relpos rp pos)))
8289 (js2-node-add-children pn obj body)
8290 pn))
8291
8292 (defun js2-parse-const-var ()
8293 "Parser for var- or const-statement.
8294 Last matched token must be js2-CONST or js2-VAR."
8295 (let ((tt (js2-current-token-type))
8296 (pos (js2-current-token-beg))
8297 expr pn)
8298 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8299 pn (make-js2-expr-stmt-node :pos pos
8300 :len (- (js2-node-end expr) pos)
8301 :expr expr))
8302 (js2-node-add-children pn expr)
8303 pn))
8304
8305 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8306 (let ((pn (make-js2-expr-stmt-node :pos pos
8307 :len (js2-node-len expr)
8308 :type (if (js2-inside-function)
8309 js2-EXPR_VOID
8310 js2-EXPR_RESULT)
8311 :expr expr)))
8312 (if add-child
8313 (js2-node-add-children pn expr))
8314 pn))
8315
8316 (defun js2-parse-let-stmt ()
8317 "Parser for let-statement. Last matched token must be js2-LET."
8318 (let ((pos (js2-current-token-beg))
8319 expr pn)
8320 (if (= (js2-peek-token) js2-LP)
8321 ;; let expression in statement context
8322 (setq expr (js2-parse-let pos 'statement)
8323 pn (js2-wrap-with-expr-stmt pos expr t))
8324 ;; else we're looking at a statement like let x=6, y=7;
8325 (setf expr (js2-parse-variables js2-LET pos)
8326 pn (js2-wrap-with-expr-stmt pos expr t)
8327 (js2-node-type pn) js2-EXPR_RESULT))
8328 pn))
8329
8330 (defun js2-parse-ret-yield ()
8331 (js2-parse-return-or-yield (js2-current-token-type) nil))
8332
8333 (defconst js2-parse-return-stmt-enders
8334 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8335
8336 (defsubst js2-now-all-set (before after mask)
8337 "Return whether or not the bits in the mask have changed to all set.
8338 BEFORE is bits before change, AFTER is bits after change, and MASK is
8339 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8340 but not BEFORE."
8341 (and (/= (logand before mask) mask)
8342 (= (logand after mask) mask)))
8343
8344 (defun js2-parse-return-or-yield (tt expr-context)
8345 (let* ((pos (js2-current-token-beg))
8346 (end (js2-current-token-end))
8347 (before js2-end-flags)
8348 (inside-function (js2-inside-function))
8349 (gen-type (and inside-function (js2-function-node-generator-type
8350 js2-current-script-or-fn)))
8351 e ret name yield-star-p)
8352 (unless inside-function
8353 (js2-report-error (if (eq tt js2-RETURN)
8354 "msg.bad.return"
8355 "msg.bad.yield")))
8356 (when (and inside-function
8357 (eq gen-type 'STAR)
8358 (js2-match-token js2-MUL))
8359 (setq yield-star-p t))
8360 ;; This is ugly, but we don't want to require a semicolon.
8361 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8362 (setq e (js2-parse-expr)
8363 end (js2-node-end e)))
8364 (cond
8365 ((eq tt js2-RETURN)
8366 (js2-set-flag js2-end-flags (if (null e)
8367 js2-end-returns
8368 js2-end-returns-value))
8369 (setq ret (make-js2-return-node :pos pos
8370 :len (- end pos)
8371 :retval e))
8372 (js2-node-add-children ret e)
8373 ;; See if we need a strict mode warning.
8374 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8375 ;; more thorough and accurate than this before/after flag check.
8376 ;; E.g. if there's a finally-block that always returns, we shouldn't
8377 ;; show a warning generated by inconsistent returns in the catch blocks.
8378 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8379 ;; so we know which returns/yields to highlight, and we should get rid of
8380 ;; all the checking in `js2-parse-return-or-yield'.
8381 (if (and js2-strict-inconsistent-return-warning
8382 (js2-now-all-set before js2-end-flags
8383 (logior js2-end-returns js2-end-returns-value)))
8384 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8385 ((eq gen-type 'COMPREHENSION)
8386 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8387 ;; like SpiderMonkey does.
8388 (js2-report-error "msg.syntax" nil pos 5))
8389 (t
8390 (setq ret (make-js2-yield-node :pos pos
8391 :len (- end pos)
8392 :value e
8393 :star-p yield-star-p))
8394 (js2-node-add-children ret e)
8395 (unless expr-context
8396 (setq e ret
8397 ret (js2-wrap-with-expr-stmt pos e t))
8398 (js2-set-requires-activation)
8399 (js2-set-is-generator))))
8400 ;; see if we are mixing yields and value returns.
8401 (when (and inside-function
8402 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8403 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8404 'LEGACY))
8405 (setq name (js2-function-name js2-current-script-or-fn))
8406 (if (zerop (length name))
8407 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8408 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8409 ret))
8410
8411 (defun js2-parse-debugger ()
8412 (make-js2-keyword-node :type js2-DEBUGGER))
8413
8414 (defun js2-parse-block ()
8415 "Parser for a curly-delimited statement block.
8416 Last token matched must be `js2-LC'."
8417 (let ((pos (js2-current-token-beg))
8418 (pn (make-js2-scope)))
8419 (js2-push-scope pn)
8420 (unwind-protect
8421 (progn
8422 (js2-parse-statements pn)
8423 (js2-must-match js2-RC "msg.no.brace.block")
8424 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8425 (js2-pop-scope))
8426 pn))
8427
8428 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8429 (defun js2-parse-semi ()
8430 "Parse a statement or handle an error.
8431 Current token type is `js2-SEMI' or `js2-ERROR'."
8432 (let ((tt (js2-current-token-type)) pos len)
8433 (if (eq tt js2-SEMI)
8434 (make-js2-empty-expr-node :len 1)
8435 (setq pos (js2-current-token-beg)
8436 len (- (js2-current-token-end) pos))
8437 (js2-report-error "msg.syntax" nil pos len)
8438 (make-js2-error-node :pos pos :len len))))
8439
8440 (defun js2-parse-default-xml-namespace ()
8441 "Parse a `default xml namespace = <expr>' e4x statement."
8442 (let ((pos (js2-current-token-beg))
8443 end len expr unary)
8444 (js2-must-have-xml)
8445 (js2-set-requires-activation)
8446 (setq len (- js2-ts-cursor pos))
8447 (unless (and (js2-match-token js2-NAME)
8448 (string= (js2-current-token-string) "xml"))
8449 (js2-report-error "msg.bad.namespace" nil pos len))
8450 (unless (and (js2-match-token js2-NAME)
8451 (string= (js2-current-token-string) "namespace"))
8452 (js2-report-error "msg.bad.namespace" nil pos len))
8453 (unless (js2-match-token js2-ASSIGN)
8454 (js2-report-error "msg.bad.namespace" nil pos len))
8455 (setq expr (js2-parse-expr)
8456 end (js2-node-end expr)
8457 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8458 :pos pos
8459 :len (- end pos)
8460 :operand expr))
8461 (js2-node-add-children unary expr)
8462 (make-js2-expr-stmt-node :pos pos
8463 :len (- end pos)
8464 :expr unary)))
8465
8466 (defun js2-record-label (label bundle)
8467 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8468 (js2-get-token)
8469 (let ((name (js2-label-node-name label))
8470 labeled-stmt
8471 dup)
8472 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8473 ;; flag both labels if possible when used in editing mode
8474 (if (and js2-parse-ide-mode
8475 (setq dup (js2-get-label-by-name labeled-stmt name)))
8476 (js2-report-error "msg.dup.label" nil
8477 (js2-node-abs-pos dup) (js2-node-len dup)))
8478 (js2-report-error "msg.dup.label" nil
8479 (js2-node-pos label) (js2-node-len label)))
8480 (js2-labeled-stmt-node-add-label bundle label)
8481 (js2-node-add-children bundle label)
8482 ;; Add one reference to the bundle per label in `js2-label-set'
8483 (push (cons name bundle) js2-label-set)))
8484
8485 (defun js2-parse-name-or-label ()
8486 "Parser for identifier or label. Last token matched must be js2-NAME.
8487 Called when we found a name in a statement context. If it's a label, we gather
8488 up any following labels and the next non-label statement into a
8489 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8490 expression and return it wrapped in a `js2-expr-stmt-node'."
8491 (let ((pos (js2-current-token-beg))
8492 expr stmt bundle
8493 (continue t))
8494 ;; set check for label and call down to `js2-parse-primary-expr'
8495 (setq expr (js2-maybe-parse-label))
8496 (if (null expr)
8497 ;; Parse the non-label expression and wrap with expression stmt.
8498 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8499 ;; else parsed a label
8500 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8501 (js2-record-label expr bundle)
8502 ;; look for more labels
8503 (while (and continue (= (js2-get-token) js2-NAME))
8504 (if (setq expr (js2-maybe-parse-label))
8505 (js2-record-label expr bundle)
8506 (setq expr (js2-parse-expr)
8507 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8508 continue nil)
8509 (js2-auto-insert-semicolon stmt)))
8510 ;; no more labels; now parse the labeled statement
8511 (unwind-protect
8512 (unless stmt
8513 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8514 (js2-unget-token)
8515 (setq stmt (js2-statement-helper))))
8516 ;; remove the labels for this statement from the global set
8517 (dolist (label (js2-labeled-stmt-node-labels bundle))
8518 (setq js2-label-set (remove label js2-label-set))))
8519 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8520 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8521 (js2-node-add-children bundle stmt)
8522 bundle)))
8523
8524 (defun js2-maybe-parse-label ()
8525 (assert (= (js2-current-token-type) js2-NAME))
8526 (let (label-pos
8527 (next-tt (js2-get-token))
8528 (label-end (js2-current-token-end)))
8529 ;; Do not consume colon, it is used as unwind indicator
8530 ;; to return to statementHelper.
8531 (js2-unget-token)
8532 (if (= next-tt js2-COLON)
8533 (prog2
8534 (setq label-pos (js2-current-token-beg))
8535 (make-js2-label-node :pos label-pos
8536 :len (- label-end label-pos)
8537 :name (js2-current-token-string))
8538 (js2-set-face label-pos
8539 label-end
8540 'font-lock-variable-name-face 'record))
8541 ;; Backtrack from the name token, too.
8542 (js2-unget-token)
8543 nil)))
8544
8545 (defun js2-parse-expr-stmt ()
8546 "Default parser in statement context, if no recognized statement found."
8547 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8548 (progn
8549 (js2-unget-token)
8550 (js2-parse-expr)) t))
8551
8552 (defun js2-parse-variables (decl-type pos)
8553 "Parse a comma-separated list of variable declarations.
8554 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8555
8556 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8557 For 'var' or 'const', the keyword should be the token last scanned.
8558
8559 POS is the position where the node should start. It's sometimes the
8560 var/const/let keyword, and other times the beginning of the first token
8561 in the first variable declaration.
8562
8563 Returns the parsed `js2-var-decl-node' expression node."
8564 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8565 :pos pos))
8566 destructuring kid-pos tt init name end nbeg nend vi
8567 (continue t))
8568 ;; Example:
8569 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8570 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8571 ;; var {a, b} = baz;
8572 (while continue
8573 (setq destructuring nil
8574 name nil
8575 tt (js2-get-token)
8576 kid-pos (js2-current-token-beg)
8577 end (js2-current-token-end)
8578 init nil)
8579 (if (or (= tt js2-LB) (= tt js2-LC))
8580 ;; Destructuring assignment, e.g., var [a, b] = ...
8581 (setq destructuring (js2-parse-destruct-primary-expr)
8582 end (js2-node-end destructuring))
8583 ;; Simple variable name
8584 (js2-unget-token)
8585 (when (js2-must-match-name "msg.bad.var")
8586 (setq name (js2-create-name-node)
8587 nbeg (js2-current-token-beg)
8588 nend (js2-current-token-end)
8589 end nend)
8590 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8591 (when (js2-match-token js2-ASSIGN)
8592 (setq init (js2-parse-assign-expr)
8593 end (js2-node-end init))
8594 (js2-record-imenu-functions init name))
8595 (when name
8596 (js2-set-face nbeg nend (if (js2-function-node-p init)
8597 'font-lock-function-name-face
8598 'font-lock-variable-name-face)
8599 'record))
8600 (setq vi (make-js2-var-init-node :pos kid-pos
8601 :len (- end kid-pos)
8602 :type decl-type))
8603 (if destructuring
8604 (progn
8605 (if (and (null init) (not js2-in-for-init))
8606 (js2-report-error "msg.destruct.assign.no.init"))
8607 (js2-define-destruct-symbols destructuring
8608 decl-type
8609 'font-lock-variable-name-face)
8610 (setf (js2-var-init-node-target vi) destructuring))
8611 (setf (js2-var-init-node-target vi) name))
8612 (setf (js2-var-init-node-initializer vi) init)
8613 (js2-node-add-children vi name destructuring init)
8614 (js2-block-node-push result vi)
8615 (unless (js2-match-token js2-COMMA)
8616 (setq continue nil)))
8617 (setf (js2-node-len result) (- end pos))
8618 result))
8619
8620 (defun js2-parse-let (pos &optional stmt-p)
8621 "Parse a let expression or statement.
8622 A let-expression is of the form `let (vars) expr'.
8623 A let-statment is of the form `let (vars) {statements}'.
8624 The third form of let is a variable declaration list, handled
8625 by `js2-parse-variables'."
8626 (let ((pn (make-js2-let-node :pos pos))
8627 beg vars body)
8628 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8629 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8630 (js2-push-scope pn)
8631 (unwind-protect
8632 (progn
8633 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8634 (if (js2-must-match js2-RP "msg.no.paren.let")
8635 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8636 (if (and stmt-p (js2-match-token js2-LC))
8637 ;; let statement
8638 (progn
8639 (setf beg (js2-current-token-beg) ; position stmt at LC
8640 body (js2-parse-statements))
8641 (js2-must-match js2-RC "msg.no.curly.let")
8642 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8643 (js2-node-len pn) (- (js2-current-token-end) pos)
8644 (js2-let-node-body pn) body
8645 (js2-node-type pn) js2-LET))
8646 ;; let expression
8647 (setf body (js2-parse-expr)
8648 (js2-node-len pn) (- (js2-node-end body) pos)
8649 (js2-let-node-body pn) body))
8650 (setf (js2-let-node-vars pn) vars)
8651 (js2-node-add-children pn vars body))
8652 (js2-pop-scope))
8653 pn))
8654
8655 (defun js2-define-new-symbol (decl-type name node &optional scope)
8656 (js2-scope-put-symbol (or scope js2-current-scope)
8657 name
8658 (make-js2-symbol decl-type name node)))
8659
8660 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8661 "Define a symbol in the current scope.
8662 If NODE is non-nil, it is the AST node associated with the symbol."
8663 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8664 (symbol (if defining-scope
8665 (js2-scope-get-symbol defining-scope name)))
8666 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8667 (cond
8668 ((and symbol ; already defined
8669 (or (= sdt js2-CONST) ; old version is const
8670 (= decl-type js2-CONST) ; new version is const
8671 ;; two let-bound vars in this block have same name
8672 (and (= sdt js2-LET)
8673 (eq defining-scope js2-current-scope))))
8674 (js2-report-error
8675 (cond
8676 ((= sdt js2-CONST) "msg.const.redecl")
8677 ((= sdt js2-LET) "msg.let.redecl")
8678 ((= sdt js2-VAR) "msg.var.redecl")
8679 ((= sdt js2-FUNCTION) "msg.function.redecl")
8680 (t "msg.parm.redecl"))
8681 name))
8682 ((= decl-type js2-LET)
8683 (if (and (not ignore-not-in-block)
8684 (or (= (js2-node-type js2-current-scope) js2-IF)
8685 (js2-loop-node-p js2-current-scope)))
8686 (js2-report-error "msg.let.decl.not.in.block")
8687 (js2-define-new-symbol decl-type name node)))
8688 ((or (= decl-type js2-VAR)
8689 (= decl-type js2-CONST)
8690 (= decl-type js2-FUNCTION))
8691 (if symbol
8692 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8693 (js2-add-strict-warning "msg.var.redecl" name)
8694 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8695 (js2-add-strict-warning "msg.var.hides.arg" name)))
8696 (js2-define-new-symbol decl-type name node
8697 js2-current-script-or-fn)))
8698 ((= decl-type js2-LP)
8699 (if symbol
8700 ;; must be duplicate parameter. Second parameter hides the
8701 ;; first, so go ahead and add the second pararameter
8702 (js2-report-warning "msg.dup.parms" name))
8703 (js2-define-new-symbol decl-type name node))
8704 (t (js2-code-bug)))))
8705
8706 (defun js2-parse-paren-expr-or-generator-comp ()
8707 (let ((px-pos (js2-current-token-beg)))
8708 (if (and (>= js2-language-version 200)
8709 (js2-match-token js2-FOR))
8710 (js2-parse-generator-comp px-pos)
8711 (let* ((js2-in-for-init nil)
8712 (expr (js2-parse-expr))
8713 (pn (make-js2-paren-node :pos px-pos
8714 :expr expr
8715 :len (- (js2-current-token-end)
8716 px-pos))))
8717 (js2-node-add-children pn (js2-paren-node-expr pn))
8718 (js2-must-match js2-RP "msg.no.paren")
8719 pn))))
8720
8721 (defun js2-parse-expr (&optional oneshot)
8722 (let* ((pn (js2-parse-assign-expr))
8723 (pos (js2-node-pos pn))
8724 left
8725 right
8726 op-pos)
8727 (while (and (not oneshot)
8728 (js2-match-token js2-COMMA))
8729 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8730 (if (= (js2-peek-token) js2-YIELD)
8731 (js2-report-error "msg.yield.parenthesized"))
8732 (setq right (js2-parse-assign-expr)
8733 left pn
8734 pn (make-js2-infix-node :type js2-COMMA
8735 :pos pos
8736 :len (- js2-ts-cursor pos)
8737 :op-pos op-pos
8738 :left left
8739 :right right))
8740 (js2-node-add-children pn left right))
8741 pn))
8742
8743 (defun js2-parse-assign-expr ()
8744 (let ((tt (js2-get-token))
8745 (pos (js2-current-token-beg))
8746 pn left right op-pos
8747 ts-state recorded-identifiers parsed-errors)
8748 (if (= tt js2-YIELD)
8749 (js2-parse-return-or-yield tt t)
8750 ;; Save the tokenizer state in case we find an arrow function
8751 ;; and have to rewind.
8752 (setq ts-state (make-js2-ts-state)
8753 recorded-identifiers js2-recorded-identifiers
8754 parsed-errors js2-parsed-errors)
8755 ;; not yield - parse assignment expression
8756 (setq pn (js2-parse-cond-expr)
8757 tt (js2-get-token))
8758 (cond
8759 ((and (<= js2-first-assign tt)
8760 (<= tt js2-last-assign))
8761 ;; tt express assignment (=, |=, ^=, ..., %=)
8762 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8763 left pn)
8764 (setq right (js2-parse-assign-expr)
8765 pn (make-js2-assign-node :type tt
8766 :pos pos
8767 :len (- (js2-node-end right) pos)
8768 :op-pos op-pos
8769 :left left
8770 :right right))
8771 (when js2-parse-ide-mode
8772 (js2-highlight-assign-targets pn left right)
8773 (js2-record-imenu-functions right left))
8774 ;; do this last so ide checks above can use absolute positions
8775 (js2-node-add-children pn left right))
8776 ((and (= tt js2-ARROW)
8777 (>= js2-language-version 200))
8778 (js2-ts-seek ts-state)
8779 (setq js2-recorded-identifiers recorded-identifiers
8780 js2-parsed-errors parsed-errors)
8781 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8782 (t
8783 (js2-unget-token)))
8784 pn)))
8785
8786 (defun js2-parse-cond-expr ()
8787 (let ((pos (js2-current-token-beg))
8788 (pn (js2-parse-or-expr))
8789 test-expr
8790 if-true
8791 if-false
8792 q-pos
8793 c-pos)
8794 (when (js2-match-token js2-HOOK)
8795 (setq q-pos (- (js2-current-token-beg) pos)
8796 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8797 (js2-must-match js2-COLON "msg.no.colon.cond")
8798 (setq c-pos (- (js2-current-token-beg) pos)
8799 if-false (js2-parse-assign-expr)
8800 test-expr pn
8801 pn (make-js2-cond-node :pos pos
8802 :len (- (js2-node-end if-false) pos)
8803 :test-expr test-expr
8804 :true-expr if-true
8805 :false-expr if-false
8806 :q-pos q-pos
8807 :c-pos c-pos))
8808 (js2-node-add-children pn test-expr if-true if-false))
8809 pn))
8810
8811 (defun js2-make-binary (type left parser)
8812 "Helper for constructing a binary-operator AST node.
8813 LEFT is the left-side-expression, already parsed, and the
8814 binary operator should have just been matched.
8815 PARSER is a function to call to parse the right operand,
8816 or a `js2-node' struct if it has already been parsed.
8817 FIXME: The latter option is unused?"
8818 (let* ((pos (js2-node-pos left))
8819 (op-pos (- (js2-current-token-beg) pos))
8820 (right (if (js2-node-p parser)
8821 parser
8822 (js2-get-token)
8823 (funcall parser)))
8824 (pn (make-js2-infix-node :type type
8825 :pos pos
8826 :len (- (js2-node-end right) pos)
8827 :op-pos op-pos
8828 :left left
8829 :right right)))
8830 (js2-node-add-children pn left right)
8831 pn))
8832
8833 (defun js2-parse-or-expr ()
8834 (let ((pn (js2-parse-and-expr)))
8835 (when (js2-match-token js2-OR)
8836 (setq pn (js2-make-binary js2-OR
8837 pn
8838 'js2-parse-or-expr)))
8839 pn))
8840
8841 (defun js2-parse-and-expr ()
8842 (let ((pn (js2-parse-bit-or-expr)))
8843 (when (js2-match-token js2-AND)
8844 (setq pn (js2-make-binary js2-AND
8845 pn
8846 'js2-parse-and-expr)))
8847 pn))
8848
8849 (defun js2-parse-bit-or-expr ()
8850 (let ((pn (js2-parse-bit-xor-expr)))
8851 (while (js2-match-token js2-BITOR)
8852 (setq pn (js2-make-binary js2-BITOR
8853 pn
8854 'js2-parse-bit-xor-expr)))
8855 pn))
8856
8857 (defun js2-parse-bit-xor-expr ()
8858 (let ((pn (js2-parse-bit-and-expr)))
8859 (while (js2-match-token js2-BITXOR)
8860 (setq pn (js2-make-binary js2-BITXOR
8861 pn
8862 'js2-parse-bit-and-expr)))
8863 pn))
8864
8865 (defun js2-parse-bit-and-expr ()
8866 (let ((pn (js2-parse-eq-expr)))
8867 (while (js2-match-token js2-BITAND)
8868 (setq pn (js2-make-binary js2-BITAND
8869 pn
8870 'js2-parse-eq-expr)))
8871 pn))
8872
8873 (defconst js2-parse-eq-ops
8874 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8875
8876 (defun js2-parse-eq-expr ()
8877 (let ((pn (js2-parse-rel-expr))
8878 tt)
8879 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8880 (setq pn (js2-make-binary tt
8881 pn
8882 'js2-parse-rel-expr)))
8883 (js2-unget-token)
8884 pn))
8885
8886 (defconst js2-parse-rel-ops
8887 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8888
8889 (defun js2-parse-rel-expr ()
8890 (let ((pn (js2-parse-shift-expr))
8891 (continue t)
8892 tt)
8893 (while continue
8894 (setq tt (js2-get-token))
8895 (cond
8896 ((and js2-in-for-init (= tt js2-IN))
8897 (js2-unget-token)
8898 (setq continue nil))
8899 ((memq tt js2-parse-rel-ops)
8900 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8901 (t
8902 (js2-unget-token)
8903 (setq continue nil))))
8904 pn))
8905
8906 (defconst js2-parse-shift-ops
8907 (list js2-LSH js2-URSH js2-RSH))
8908
8909 (defun js2-parse-shift-expr ()
8910 (let ((pn (js2-parse-add-expr))
8911 tt
8912 (continue t))
8913 (while continue
8914 (setq tt (js2-get-token))
8915 (if (memq tt js2-parse-shift-ops)
8916 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8917 (js2-unget-token)
8918 (setq continue nil)))
8919 pn))
8920
8921 (defun js2-parse-add-expr ()
8922 (let ((pn (js2-parse-mul-expr))
8923 tt
8924 (continue t))
8925 (while continue
8926 (setq tt (js2-get-token))
8927 (if (or (= tt js2-ADD) (= tt js2-SUB))
8928 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8929 (js2-unget-token)
8930 (setq continue nil)))
8931 pn))
8932
8933 (defconst js2-parse-mul-ops
8934 (list js2-MUL js2-DIV js2-MOD))
8935
8936 (defun js2-parse-mul-expr ()
8937 (let ((pn (js2-parse-unary-expr))
8938 tt
8939 (continue t))
8940 (while continue
8941 (setq tt (js2-get-token))
8942 (if (memq tt js2-parse-mul-ops)
8943 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8944 (js2-unget-token)
8945 (setq continue nil)))
8946 pn))
8947
8948 (defun js2-make-unary (type parser &rest args)
8949 "Make a unary node of type TYPE.
8950 PARSER is either a node (for postfix operators) or a function to call
8951 to parse the operand (for prefix operators)."
8952 (let* ((pos (js2-current-token-beg))
8953 (postfix (js2-node-p parser))
8954 (expr (if postfix
8955 parser
8956 (apply parser args)))
8957 end
8958 pn)
8959 (if postfix ; e.g. i++
8960 (setq pos (js2-node-pos expr)
8961 end (js2-current-token-end))
8962 (setq end (js2-node-end expr)))
8963 (setq pn (make-js2-unary-node :type type
8964 :pos pos
8965 :len (- end pos)
8966 :operand expr))
8967 (js2-node-add-children pn expr)
8968 pn))
8969
8970 (defconst js2-incrementable-node-types
8971 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8972 "Node types that can be the operand of a ++ or -- operator.")
8973
8974 (defun js2-check-bad-inc-dec (tt beg end unary)
8975 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8976 js2-incrementable-node-types)
8977 (js2-report-error (if (= tt js2-INC)
8978 "msg.bad.incr"
8979 "msg.bad.decr")
8980 nil beg (- end beg))))
8981
8982 (defun js2-parse-unary-expr ()
8983 (let ((tt (js2-current-token-type))
8984 pn expr beg end)
8985 (cond
8986 ((or (= tt js2-VOID)
8987 (= tt js2-NOT)
8988 (= tt js2-BITNOT)
8989 (= tt js2-TYPEOF))
8990 (js2-get-token)
8991 (js2-make-unary tt 'js2-parse-unary-expr))
8992 ((= tt js2-ADD)
8993 (js2-get-token)
8994 ;; Convert to special POS token in decompiler and parse tree
8995 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8996 ((= tt js2-SUB)
8997 (js2-get-token)
8998 ;; Convert to special NEG token in decompiler and parse tree
8999 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9000 ((or (= tt js2-INC)
9001 (= tt js2-DEC))
9002 (js2-get-token)
9003 (prog1
9004 (setq beg (js2-current-token-beg)
9005 end (js2-current-token-end)
9006 expr (js2-make-unary tt 'js2-parse-member-expr t))
9007 (js2-check-bad-inc-dec tt beg end expr)))
9008 ((= tt js2-DELPROP)
9009 (js2-get-token)
9010 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9011 ((= tt js2-ERROR)
9012 (js2-get-token)
9013 (make-js2-error-node)) ; try to continue
9014 ((and (= tt js2-LT)
9015 js2-compiler-xml-available)
9016 ;; XML stream encountered in expression.
9017 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9018 (t
9019 (setq pn (js2-parse-member-expr t)
9020 ;; Don't look across a newline boundary for a postfix incop.
9021 tt (js2-peek-token-or-eol))
9022 (when (or (= tt js2-INC) (= tt js2-DEC))
9023 (js2-get-token)
9024 (setf expr pn
9025 pn (js2-make-unary tt expr))
9026 (js2-node-set-prop pn 'postfix t)
9027 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9028 pn))))
9029
9030 (defun js2-parse-xml-initializer ()
9031 "Parse an E4X XML initializer.
9032 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9033 Then I'll postprocess the result, depending on whether we're in IDE
9034 mode or codegen mode, and generate the appropriate rewritten AST.
9035 IDE mode uses a rich AST that models the XML structure. Codegen mode
9036 just concatenates everything and makes a new XML or XMLList out of it."
9037 (let ((tt (js2-get-first-xml-token))
9038 pn-xml pn expr kids expr-pos
9039 (continue t)
9040 (first-token t))
9041 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9042 (js2-report-error "msg.syntax"))
9043 (setq pn-xml (make-js2-xml-node))
9044 (while continue
9045 (if first-token
9046 (setq first-token nil)
9047 (setq tt (js2-get-next-xml-token)))
9048 (cond
9049 ;; js2-XML means we found a {expr} in the XML stream.
9050 ;; The token string is the XML up to the left-curly.
9051 ((= tt js2-XML)
9052 (push (make-js2-string-node :pos (js2-current-token-beg)
9053 :len (- js2-ts-cursor (js2-current-token-beg)))
9054 kids)
9055 (js2-must-match js2-LC "msg.syntax")
9056 (setq expr-pos js2-ts-cursor
9057 expr (if (eq (js2-peek-token) js2-RC)
9058 (make-js2-empty-expr-node :pos expr-pos)
9059 (js2-parse-expr)))
9060 (js2-must-match js2-RC "msg.syntax")
9061 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9062 :len (js2-node-len expr)
9063 :expr expr))
9064 (js2-node-add-children pn expr)
9065 (push pn kids))
9066 ;; a js2-XMLEND token means we hit the final close-tag.
9067 ((= tt js2-XMLEND)
9068 (push (make-js2-string-node :pos (js2-current-token-beg)
9069 :len (- js2-ts-cursor (js2-current-token-beg)))
9070 kids)
9071 (dolist (kid (nreverse kids))
9072 (js2-block-node-push pn-xml kid))
9073 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9074 (js2-node-pos pn-xml))
9075 continue nil))
9076 (t
9077 (js2-report-error "msg.syntax")
9078 (setq continue nil))))
9079 pn-xml))
9080
9081
9082 (defun js2-parse-argument-list ()
9083 "Parse an argument list and return it as a Lisp list of nodes.
9084 Returns the list in reverse order. Consumes the right-paren token."
9085 (let (result)
9086 (unless (js2-match-token js2-RP)
9087 (loop do
9088 (let ((tt (js2-get-token)))
9089 (if (= tt js2-YIELD)
9090 (js2-report-error "msg.yield.parenthesized"))
9091 (if (and (= tt js2-TRIPLEDOT)
9092 (>= js2-language-version 200))
9093 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9094 (js2-unget-token)
9095 (push (js2-parse-assign-expr) result)))
9096 while
9097 (js2-match-token js2-COMMA))
9098 (js2-must-match js2-RP "msg.no.paren.arg")
9099 result)))
9100
9101 (defun js2-parse-member-expr (&optional allow-call-syntax)
9102 (let ((tt (js2-current-token-type))
9103 pn pos target args beg end init)
9104 (if (/= tt js2-NEW)
9105 (setq pn (js2-parse-primary-expr))
9106 ;; parse a 'new' expression
9107 (js2-get-token)
9108 (setq pos (js2-current-token-beg)
9109 beg pos
9110 target (js2-parse-member-expr)
9111 end (js2-node-end target)
9112 pn (make-js2-new-node :pos pos
9113 :target target
9114 :len (- end pos)))
9115 (js2-highlight-function-call (js2-current-token))
9116 (js2-node-add-children pn target)
9117 (when (js2-match-token js2-LP)
9118 ;; Add the arguments to pn, if any are supplied.
9119 (setf beg pos ; start of "new" keyword
9120 pos (js2-current-token-beg)
9121 args (nreverse (js2-parse-argument-list))
9122 (js2-new-node-args pn) args
9123 end (js2-current-token-end)
9124 (js2-new-node-lp pn) (- pos beg)
9125 (js2-new-node-rp pn) (- end 1 beg))
9126 (apply #'js2-node-add-children pn args))
9127 (when (and js2-allow-rhino-new-expr-initializer
9128 (js2-match-token js2-LC))
9129 (setf init (js2-parse-object-literal)
9130 end (js2-node-end init)
9131 (js2-new-node-initializer pn) init)
9132 (js2-node-add-children pn init))
9133 (setf (js2-node-len pn) (- end beg))) ; end outer if
9134 (js2-parse-member-expr-tail allow-call-syntax pn)))
9135
9136 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9137 "Parse a chain of property/array accesses or function calls.
9138 Includes parsing for E4X operators like `..' and `.@'.
9139 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9140 Returns an expression tree that includes PN, the parent node."
9141 (let (tt
9142 (continue t))
9143 (while continue
9144 (setq tt (js2-get-token))
9145 (cond
9146 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9147 (setq pn (js2-parse-property-access tt pn)))
9148 ((= tt js2-DOTQUERY)
9149 (setq pn (js2-parse-dot-query pn)))
9150 ((= tt js2-LB)
9151 (setq pn (js2-parse-element-get pn)))
9152 ((= tt js2-LP)
9153 (js2-unget-token)
9154 (if allow-call-syntax
9155 (setq pn (js2-parse-function-call pn))
9156 (setq continue nil)))
9157 ((= tt js2-TEMPLATE_HEAD)
9158 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9159 ((= tt js2-NO_SUBS_TEMPLATE)
9160 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9161 (t
9162 (js2-unget-token)
9163 (setq continue nil))))
9164 (if (>= js2-highlight-level 2)
9165 (js2-parse-highlight-member-expr-node pn))
9166 pn))
9167
9168 (defun js2-parse-tagged-template (tag-node tpl-node)
9169 "Parse tagged template expression."
9170 (let* ((beg (js2-node-pos tag-node))
9171 (pn (make-js2-tagged-template-node :beg beg
9172 :len (- (js2-current-token-end) beg)
9173 :tag tag-node
9174 :template tpl-node)))
9175 (js2-node-add-children pn tag-node tpl-node)
9176 pn))
9177
9178 (defun js2-parse-dot-query (pn)
9179 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9180 Last token parsed must be `js2-DOTQUERY'."
9181 (let ((pos (js2-node-pos pn))
9182 op-pos expr end)
9183 (js2-must-have-xml)
9184 (js2-set-requires-activation)
9185 (setq op-pos (js2-current-token-beg)
9186 expr (js2-parse-expr)
9187 end (js2-node-end expr)
9188 pn (make-js2-xml-dot-query-node :left pn
9189 :pos pos
9190 :op-pos op-pos
9191 :right expr))
9192 (js2-node-add-children pn
9193 (js2-xml-dot-query-node-left pn)
9194 (js2-xml-dot-query-node-right pn))
9195 (if (js2-must-match js2-RP "msg.no.paren")
9196 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9197 end (js2-current-token-end)))
9198 (setf (js2-node-len pn) (- end pos))
9199 pn))
9200
9201 (defun js2-parse-element-get (pn)
9202 "Parse an element-get expression, e.g. foo[bar].
9203 Last token parsed must be `js2-RB'."
9204 (let ((lb (js2-current-token-beg))
9205 (pos (js2-node-pos pn))
9206 rb expr)
9207 (setq expr (js2-parse-expr))
9208 (if (js2-must-match js2-RB "msg.no.bracket.index")
9209 (setq rb (js2-current-token-beg)))
9210 (setq pn (make-js2-elem-get-node :target pn
9211 :pos pos
9212 :element expr
9213 :lb (js2-relpos lb pos)
9214 :rb (js2-relpos rb pos)
9215 :len (- (js2-current-token-end) pos)))
9216 (js2-node-add-children pn
9217 (js2-elem-get-node-target pn)
9218 (js2-elem-get-node-element pn))
9219 pn))
9220
9221 (defun js2-highlight-function-call (token)
9222 (when (eq (js2-token-type token) js2-NAME)
9223 (js2-record-face 'js2-function-call token)))
9224
9225 (defun js2-parse-function-call (pn)
9226 (js2-highlight-function-call (js2-current-token))
9227 (js2-get-token)
9228 (let (args
9229 (pos (js2-node-pos pn)))
9230 (setq pn (make-js2-call-node :pos pos
9231 :target pn
9232 :lp (- (js2-current-token-beg) pos)))
9233 (js2-node-add-children pn (js2-call-node-target pn))
9234 ;; Add the arguments to pn, if any are supplied.
9235 (setf args (nreverse (js2-parse-argument-list))
9236 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9237 (js2-call-node-args pn) args)
9238 (apply #'js2-node-add-children pn args)
9239 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9240 pn))
9241
9242 (defun js2-parse-property-access (tt pn)
9243 "Parse a property access, XML descendants access, or XML attr access."
9244 (let ((member-type-flags 0)
9245 (dot-pos (js2-current-token-beg))
9246 (dot-len (if (= tt js2-DOTDOT) 2 1))
9247 name
9248 ref ; right side of . or .. operator
9249 result)
9250 (when (= tt js2-DOTDOT)
9251 (js2-must-have-xml)
9252 (setq member-type-flags js2-descendants-flag))
9253 (if (not js2-compiler-xml-available)
9254 (progn
9255 (js2-must-match-prop-name "msg.no.name.after.dot")
9256 (setq name (js2-create-name-node t js2-GETPROP)
9257 result (make-js2-prop-get-node :left pn
9258 :pos (js2-current-token-beg)
9259 :right name
9260 :len (js2-current-token-len)))
9261 (js2-node-add-children result pn name)
9262 result)
9263 ;; otherwise look for XML operators
9264 (setf result (if (= tt js2-DOT)
9265 (make-js2-prop-get-node)
9266 (make-js2-infix-node :type js2-DOTDOT))
9267 (js2-node-pos result) (js2-node-pos pn)
9268 (js2-infix-node-op-pos result) dot-pos
9269 (js2-infix-node-left result) pn ; do this after setting position
9270 tt (js2-get-prop-name-token))
9271 (cond
9272 ;; handles: name, ns::name, ns::*, ns::[expr]
9273 ((= tt js2-NAME)
9274 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9275 ;; handles: *, *::name, *::*, *::[expr]
9276 ((= tt js2-MUL)
9277 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9278 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9279 ((= tt js2-XMLATTR)
9280 (setq result (js2-parse-attribute-access)))
9281 (t
9282 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9283 (if ref
9284 (setf (js2-node-len result) (- (js2-node-end ref)
9285 (js2-node-pos result))
9286 (js2-infix-node-right result) ref))
9287 (if (js2-infix-node-p result)
9288 (js2-node-add-children result
9289 (js2-infix-node-left result)
9290 (js2-infix-node-right result)))
9291 result)))
9292
9293 (defun js2-parse-attribute-access ()
9294 "Parse an E4X XML attribute expression.
9295 This includes expressions of the forms:
9296
9297 @attr @ns::attr @ns::*
9298 @* @*::attr @*::*
9299 @[expr] @*::[expr] @ns::[expr]
9300
9301 Called if we peeked an '@' token."
9302 (let ((tt (js2-get-prop-name-token))
9303 (at-pos (js2-current-token-beg)))
9304 (cond
9305 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9306 ((= tt js2-NAME)
9307 (js2-parse-property-name at-pos nil 0))
9308 ;; handles: @*, @*::name, @*::*, @*::[expr]
9309 ((= tt js2-MUL)
9310 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9311 ;; handles @[expr]
9312 ((= tt js2-LB)
9313 (js2-parse-xml-elem-ref at-pos))
9314 (t
9315 (js2-report-error "msg.no.name.after.xmlAttr")
9316 ;; Avoid cascaded errors that happen if we make an error node here.
9317 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9318
9319 (defun js2-parse-property-name (at-pos s member-type-flags)
9320 "Check if :: follows name in which case it becomes qualified name.
9321
9322 AT-POS is a natural number if we just read an '@' token, else nil.
9323 S is the name or string that was matched: an identifier, 'throw' or '*'.
9324 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9325
9326 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9327 operator, or the name is followed by ::. For a plain name, returns a
9328 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9329 (let ((pos (or at-pos (js2-current-token-beg)))
9330 colon-pos
9331 (name (js2-create-name-node t (js2-current-token-type) s))
9332 ns tt pn)
9333 (catch 'return
9334 (when (js2-match-token js2-COLONCOLON)
9335 (setq ns name
9336 colon-pos (js2-current-token-beg)
9337 tt (js2-get-prop-name-token))
9338 (cond
9339 ;; handles name::name
9340 ((= tt js2-NAME)
9341 (setq name (js2-create-name-node)))
9342 ;; handles name::*
9343 ((= tt js2-MUL)
9344 (setq name (js2-create-name-node nil nil "*")))
9345 ;; handles name::[expr]
9346 ((= tt js2-LB)
9347 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9348 (t
9349 (js2-report-error "msg.no.name.after.coloncolon"))))
9350 (if (and (null ns) (zerop member-type-flags))
9351 name
9352 (prog1
9353 (setq pn
9354 (make-js2-xml-prop-ref-node :pos pos
9355 :len (- (js2-node-end name) pos)
9356 :at-pos at-pos
9357 :colon-pos colon-pos
9358 :propname name))
9359 (js2-node-add-children pn name))))))
9360
9361 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9362 "Parse the [expr] portion of an xml element reference.
9363 For instance, @[expr], @*::[expr], or ns::[expr]."
9364 (let* ((lb (js2-current-token-beg))
9365 (pos (or at-pos lb))
9366 rb
9367 (expr (js2-parse-expr))
9368 (end (js2-node-end expr))
9369 pn)
9370 (if (js2-must-match js2-RB "msg.no.bracket.index")
9371 (setq rb (js2-current-token-beg)
9372 end (js2-current-token-end)))
9373 (prog1
9374 (setq pn
9375 (make-js2-xml-elem-ref-node :pos pos
9376 :len (- end pos)
9377 :namespace namespace
9378 :colon-pos colon-pos
9379 :at-pos at-pos
9380 :expr expr
9381 :lb (js2-relpos lb pos)
9382 :rb (js2-relpos rb pos)))
9383 (js2-node-add-children pn namespace expr))))
9384
9385 (defun js2-parse-destruct-primary-expr ()
9386 (let ((js2-is-in-destructuring t))
9387 (js2-parse-primary-expr)))
9388
9389 (defun js2-parse-primary-expr ()
9390 "Parse a literal (leaf) expression of some sort.
9391 Includes complex literals such as functions, object-literals,
9392 array-literals, array comprehensions and regular expressions."
9393 (let (pn ; parent node (usually return value)
9394 tt)
9395 (setq tt (js2-current-token-type))
9396 (cond
9397 ((= tt js2-CLASS)
9398 (js2-parse-class-expr))
9399 ((= tt js2-FUNCTION)
9400 (js2-parse-function-expr))
9401 ((= tt js2-LB)
9402 (js2-parse-array-comp-or-literal))
9403 ((= tt js2-LC)
9404 (js2-parse-object-literal))
9405 ((= tt js2-LET)
9406 (js2-parse-let (js2-current-token-beg)))
9407 ((= tt js2-LP)
9408 (js2-parse-paren-expr-or-generator-comp))
9409 ((= tt js2-XMLATTR)
9410 (js2-must-have-xml)
9411 (js2-parse-attribute-access))
9412 ((= tt js2-NAME)
9413 (js2-parse-name tt))
9414 ((= tt js2-NUMBER)
9415 (make-js2-number-node))
9416 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9417 (make-js2-string-node :type tt))
9418 ((= tt js2-TEMPLATE_HEAD)
9419 (js2-parse-template-literal))
9420 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9421 ;; Got / or /= which in this context means a regexp literal
9422 (let ((px-pos (js2-current-token-beg))
9423 (flags (js2-read-regexp tt))
9424 (end (js2-current-token-end)))
9425 (prog1
9426 (make-js2-regexp-node :pos px-pos
9427 :len (- end px-pos)
9428 :value (js2-current-token-string)
9429 :flags flags)
9430 (js2-set-face px-pos end 'font-lock-string-face 'record)
9431 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9432 ((or (= tt js2-NULL)
9433 (= tt js2-THIS)
9434 (= tt js2-SUPER)
9435 (= tt js2-FALSE)
9436 (= tt js2-TRUE))
9437 (make-js2-keyword-node :type tt))
9438 ((= tt js2-RP)
9439 ;; Not valid expression syntax, but this is valid in an arrow
9440 ;; function with no params: () => body.
9441 (if (eq (js2-peek-token) js2-ARROW)
9442 (progn
9443 (js2-unget-token) ; Put back the right paren.
9444 ;; Return whatever, it will hopefully be rewinded and
9445 ;; reparsed when we reach the =>.
9446 (make-js2-keyword-node :type js2-NULL))
9447 (js2-report-error "msg.syntax")
9448 (make-js2-error-node)))
9449 ((= tt js2-TRIPLEDOT)
9450 ;; Likewise, only valid in an arrow function with a rest param.
9451 (if (and (js2-match-token js2-NAME)
9452 (js2-match-token js2-RP)
9453 (eq (js2-peek-token) js2-ARROW))
9454 (progn
9455 (js2-unget-token) ; Put back the right paren.
9456 ;; See the previous case.
9457 (make-js2-keyword-node :type js2-NULL))
9458 (js2-report-error "msg.syntax")
9459 (make-js2-error-node)))
9460 ((= tt js2-RESERVED)
9461 (js2-report-error "msg.reserved.id")
9462 (make-js2-name-node))
9463 ((= tt js2-ERROR)
9464 ;; the scanner or one of its subroutines reported the error.
9465 (make-js2-error-node))
9466 ((= tt js2-EOF)
9467 (let* ((px-pos (point-at-bol))
9468 (len (- js2-ts-cursor px-pos)))
9469 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9470 (make-js2-error-node :pos (1- js2-ts-cursor)))
9471 (t
9472 (js2-report-error "msg.syntax")
9473 (make-js2-error-node)))))
9474
9475 (defun js2-parse-template-literal ()
9476 (let ((beg (js2-current-token-beg))
9477 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
9478 (tt js2-TEMPLATE_HEAD))
9479 (while (eq tt js2-TEMPLATE_HEAD)
9480 (push (js2-parse-expr) kids)
9481 (js2-must-match js2-RC "msg.syntax")
9482 (setq tt (js2-get-token 'TEMPLATE_TAIL))
9483 (push (make-js2-string-node :type tt) kids))
9484 (setq kids (nreverse kids))
9485 (let ((tpl (make-js2-template-node :beg beg
9486 :len (- (js2-current-token-end) beg)
9487 :kids kids)))
9488 (apply #'js2-node-add-children tpl kids)
9489 tpl)))
9490
9491 (defun js2-parse-name (_tt)
9492 (let ((name (js2-current-token-string))
9493 node)
9494 (setq node (if js2-compiler-xml-available
9495 (js2-parse-property-name nil name 0)
9496 (js2-create-name-node 'check-activation nil name)))
9497 (if js2-highlight-external-variables
9498 (js2-record-name-node node))
9499 node))
9500
9501 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9502 (js2-add-strict-warning
9503 msg nil
9504 ;; back up from comma to beginning of line or array/objlit
9505 (max (if elems
9506 (js2-node-pos (car elems))
9507 pos)
9508 (save-excursion
9509 (goto-char comma-pos)
9510 (back-to-indentation)
9511 (point)))
9512 comma-pos))
9513
9514 (defun js2-parse-array-comp-or-literal ()
9515 (let ((pos (js2-current-token-beg)))
9516 (if (and (>= js2-language-version 200)
9517 (js2-match-token js2-FOR))
9518 (js2-parse-array-comp pos)
9519 (js2-parse-array-literal pos))))
9520
9521 (defun js2-parse-array-literal (pos)
9522 (let ((after-lb-or-comma t)
9523 after-comma tt elems pn
9524 (continue t))
9525 (unless js2-is-in-destructuring
9526 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9527 (while continue
9528 (setq tt (js2-get-token))
9529 (cond
9530 ;; comma
9531 ((= tt js2-COMMA)
9532 (setq after-comma (js2-current-token-end))
9533 (if (not after-lb-or-comma)
9534 (setq after-lb-or-comma t)
9535 (push nil elems)))
9536 ;; end of array
9537 ((or (= tt js2-RB)
9538 (= tt js2-EOF)) ; prevent infinite loop
9539 (if (= tt js2-EOF)
9540 (js2-report-error "msg.no.bracket.arg" nil pos))
9541 (when (and after-comma (< js2-language-version 170))
9542 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9543 pos (remove nil elems) after-comma))
9544 (setq continue nil
9545 pn (make-js2-array-node :pos pos
9546 :len (- js2-ts-cursor pos)
9547 :elems (nreverse elems)))
9548 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9549 ;; destructuring binding
9550 (js2-is-in-destructuring
9551 (push (if (or (= tt js2-LC)
9552 (= tt js2-LB)
9553 (= tt js2-NAME))
9554 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9555 (js2-parse-destruct-primary-expr)
9556 ;; invalid pattern
9557 (js2-report-error "msg.bad.var")
9558 (make-js2-error-node))
9559 elems)
9560 (setq after-lb-or-comma nil
9561 after-comma nil))
9562 ;; array comp
9563 ((and (>= js2-language-version 170)
9564 (= tt js2-FOR) ; check for array comprehension
9565 (not after-lb-or-comma) ; "for" can't follow a comma
9566 elems ; must have at least 1 element
9567 (not (cdr elems))) ; but no 2nd element
9568 (js2-unget-token)
9569 (setf continue nil
9570 pn (js2-parse-legacy-array-comp (car elems) pos)))
9571 ;; another element
9572 (t
9573 (unless after-lb-or-comma
9574 (js2-report-error "msg.no.bracket.arg"))
9575 (if (and (= tt js2-TRIPLEDOT)
9576 (>= js2-language-version 200))
9577 ;; spread operator
9578 (push (js2-make-unary tt 'js2-parse-assign-expr)
9579 elems)
9580 (js2-unget-token)
9581 (push (js2-parse-assign-expr) elems))
9582 (setq after-lb-or-comma nil
9583 after-comma nil))))
9584 (unless js2-is-in-destructuring
9585 (js2-pop-scope))
9586 pn))
9587
9588 (defun js2-parse-legacy-array-comp (expr pos)
9589 "Parse a legacy array comprehension (JavaScript 1.7).
9590 EXPR is the first expression after the opening left-bracket.
9591 POS is the beginning of the LB token preceding EXPR.
9592 We should have just parsed the 'for' keyword before calling this function."
9593 (let ((current-scope js2-current-scope)
9594 loops first filter result)
9595 (unwind-protect
9596 (progn
9597 (while (js2-match-token js2-FOR)
9598 (let ((loop (make-js2-comp-loop-node)))
9599 (js2-push-scope loop)
9600 (push loop loops)
9601 (js2-parse-comp-loop loop)))
9602 ;; First loop takes expr scope's parent.
9603 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9604 (js2-scope-parent-scope current-scope))
9605 ;; Set expr scope's parent to the last loop.
9606 (setf (js2-scope-parent-scope current-scope) (car loops))
9607 (if (/= (js2-get-token) js2-IF)
9608 (js2-unget-token)
9609 (setq filter (js2-parse-condition))))
9610 (dotimes (_ (1- (length loops)))
9611 (js2-pop-scope)))
9612 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9613 (setq result (make-js2-comp-node :pos pos
9614 :len (- js2-ts-cursor pos)
9615 :result expr
9616 :loops (nreverse loops)
9617 :filters (and filter (list (car filter)))
9618 :form 'LEGACY_ARRAY))
9619 (apply #'js2-node-add-children result expr (car filter)
9620 (js2-comp-node-loops result))
9621 result))
9622
9623 (defun js2-parse-array-comp (pos)
9624 "Parse an ES6 array comprehension.
9625 POS is the beginning of the LB token.
9626 We should have just parsed the 'for' keyword before calling this function."
9627 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9628 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9629 pn))
9630
9631 (defun js2-parse-generator-comp (pos)
9632 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9633 (js2-current-script-or-fn
9634 (make-js2-function-node :generator-type 'COMPREHENSION))
9635 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9636 (js2-must-match js2-RP "msg.no.paren" pos)
9637 pn))
9638
9639 (defun js2-parse-comprehension (pos form)
9640 (let (loops filters expr result)
9641 (unwind-protect
9642 (progn
9643 (js2-unget-token)
9644 (while (js2-match-token js2-FOR)
9645 (let ((loop (make-js2-comp-loop-node)))
9646 (js2-push-scope loop)
9647 (push loop loops)
9648 (js2-parse-comp-loop loop)))
9649 (while (js2-match-token js2-IF)
9650 (push (car (js2-parse-condition)) filters))
9651 (setq expr (js2-parse-assign-expr)))
9652 (dolist (_ loops)
9653 (js2-pop-scope)))
9654 (setq result (make-js2-comp-node :pos pos
9655 :len (- js2-ts-cursor pos)
9656 :result expr
9657 :loops (nreverse loops)
9658 :filters (nreverse filters)
9659 :form form))
9660 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9661 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9662 result))
9663
9664 (defun js2-parse-comp-loop (pn &optional only-of-p)
9665 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9666 The current token should be the initial FOR.
9667 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9668 (let ((pos (js2-comp-loop-node-pos pn))
9669 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9670 (when (and (not only-of-p) (js2-match-token js2-NAME))
9671 (if (string= (js2-current-token-string) "each")
9672 (progn
9673 (setq foreach-p t
9674 each-pos (- (js2-current-token-beg) pos)) ; relative
9675 (js2-record-face 'font-lock-keyword-face))
9676 (js2-report-error "msg.no.paren.for")))
9677 (if (js2-must-match js2-LP "msg.no.paren.for")
9678 (setq lp (- (js2-current-token-beg) pos)))
9679 (setq tt (js2-peek-token))
9680 (cond
9681 ((or (= tt js2-LB)
9682 (= tt js2-LC))
9683 (js2-get-token)
9684 (setq iter (js2-parse-destruct-primary-expr))
9685 (js2-define-destruct-symbols iter js2-LET
9686 'font-lock-variable-name-face t))
9687 ((js2-match-token js2-NAME)
9688 (setq iter (js2-create-name-node)))
9689 (t
9690 (js2-report-error "msg.bad.var")))
9691 ;; Define as a let since we want the scope of the variable to
9692 ;; be restricted to the array comprehension
9693 (if (js2-name-node-p iter)
9694 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9695 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9696 (and (>= js2-language-version 200)
9697 (js2-match-contextual-kwd "of")
9698 (setq forof-p t)))
9699 (setq in-pos (- (js2-current-token-beg) pos))
9700 (js2-report-error "msg.in.after.for.name"))
9701 (setq obj (js2-parse-expr))
9702 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9703 (setq rp (- (js2-current-token-beg) pos)))
9704 (setf (js2-node-pos pn) pos
9705 (js2-node-len pn) (- js2-ts-cursor pos)
9706 (js2-comp-loop-node-iterator pn) iter
9707 (js2-comp-loop-node-object pn) obj
9708 (js2-comp-loop-node-in-pos pn) in-pos
9709 (js2-comp-loop-node-each-pos pn) each-pos
9710 (js2-comp-loop-node-foreach-p pn) foreach-p
9711 (js2-comp-loop-node-forof-p pn) forof-p
9712 (js2-comp-loop-node-lp pn) lp
9713 (js2-comp-loop-node-rp pn) rp)
9714 (js2-node-add-children pn iter obj)
9715 pn))
9716
9717 (defun js2-parse-class-stmt ()
9718 (let ((pos (js2-current-token-beg)))
9719 (js2-must-match-name "msg.unnamed.class.stmt")
9720 (js2-parse-class pos 'CLASS_STATEMENT (js2-create-name-node t))))
9721
9722 (defun js2-parse-class-expr ()
9723 (let ((pos (js2-current-token-beg))
9724 name)
9725 (when (js2-match-token js2-NAME)
9726 (setq name (js2-create-name-node t)))
9727 (js2-parse-class pos 'CLASS_EXPRESSION name)))
9728
9729 (defun js2-parse-class (pos form name)
9730 ;; class X [extends ...] {
9731 (let (pn elems extends)
9732 (when name
9733 (js2-set-face (js2-node-pos name) (js2-node-end name)
9734 'font-lock-function-name-face 'record))
9735 (if (js2-match-token js2-EXTENDS)
9736 (if (= (js2-peek-token) js2-LC)
9737 (js2-report-error "msg.missing.extends")
9738 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
9739 (setq extends (js2-parse-assign-expr))
9740 (if (not extends)
9741 (js2-report-error "msg.bad.extends"))))
9742 (js2-must-match js2-LC "msg.no.brace.class")
9743 (setq elems (js2-parse-object-literal-elems t)
9744 pn (make-js2-class-node :pos pos
9745 :len (- js2-ts-cursor pos)
9746 :form form
9747 :name name
9748 :extends extends
9749 :elems elems))
9750 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
9751 pn))
9752
9753 (defun js2-parse-object-literal ()
9754 (let* ((pos (js2-current-token-beg))
9755 (elems (js2-parse-object-literal-elems))
9756 (result (make-js2-object-node :pos pos
9757 :len (- js2-ts-cursor pos)
9758 :elems elems)))
9759 (apply #'js2-node-add-children result (js2-object-node-elems result))
9760 result))
9761
9762 (defun js2-parse-object-literal-elems (&optional class-p)
9763 (let ((pos (js2-current-token-beg))
9764 (static nil)
9765 (continue t)
9766 tt elems elem after-comma)
9767 (while continue
9768 (setq static (and class-p (js2-match-token js2-STATIC))
9769 tt (js2-get-prop-name-token)
9770 elem nil)
9771 (cond
9772 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9773 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9774 ;; TODO(sdh): support *foo() {...}
9775 ((or (= js2-NAME tt)
9776 (= tt js2-STRING))
9777 (setq after-comma nil
9778 elem (js2-parse-named-prop tt))
9779 (if (and (null elem)
9780 (not js2-recover-from-parse-errors))
9781 (setq continue nil)))
9782 ;; {[Symbol.iterator]: ...}
9783 ((and (= tt js2-LB)
9784 (>= js2-language-version 200))
9785 (let ((expr (js2-parse-expr)))
9786 (js2-must-match js2-RB "msg.missing.computed.rb")
9787 (setq after-comma nil
9788 elem (js2-parse-plain-property expr))))
9789 ;; {12: x} or {10.7: x}
9790 ((= tt js2-NUMBER)
9791 (setq after-comma nil
9792 elem (js2-parse-plain-property (make-js2-number-node))))
9793 ;; Break out of loop, and handle trailing commas.
9794 ((or (= tt js2-RC)
9795 (= tt js2-EOF))
9796 (js2-unget-token)
9797 (setq continue nil)
9798 (if after-comma
9799 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9800 pos elems after-comma)))
9801 (t
9802 (js2-report-error "msg.bad.prop")
9803 (unless js2-recover-from-parse-errors
9804 (setq continue nil)))) ; end switch
9805 ;; Handle static for classes' codegen.
9806 (if static
9807 (if elem (js2-node-set-prop elem 'STATIC t)
9808 (js2-report-error "msg.unexpected.static")))
9809 ;; Handle commas, depending on class-p.
9810 (let ((comma (js2-match-token js2-COMMA)))
9811 (if class-p
9812 (if comma
9813 (js2-report-error "msg.class.unexpected.comma"))
9814 (if comma
9815 (setq after-comma (js2-current-token-end))
9816 (setq continue nil))))
9817 ;; Append any parsed element.
9818 (if elem (push elem elems))) ; end loop
9819 (js2-must-match js2-RC "msg.no.brace.prop")
9820 (nreverse elems)))
9821
9822 (defun js2-parse-named-prop (tt)
9823 "Parse a name, string, or getter/setter object property.
9824 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9825 (let ((string-prop (and (= tt js2-STRING)
9826 (make-js2-string-node)))
9827 expr
9828 (ppos (js2-current-token-beg))
9829 (pend (js2-current-token-end))
9830 (name (js2-create-name-node))
9831 (prop (js2-current-token-string)))
9832 (cond
9833 ;; getter/setter prop
9834 ((and (= tt js2-NAME)
9835 (= (js2-peek-token) js2-NAME)
9836 (or (string= prop "get")
9837 (string= prop "set")))
9838 (js2-get-token)
9839 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9840 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9841 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9842 (js2-parse-getter-setter-prop ppos name prop))
9843 ;; method definition: {f() {...}}
9844 ((and (= (js2-peek-token) js2-LP)
9845 (>= js2-language-version 200))
9846 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9847 (js2-parse-getter-setter-prop ppos name ""))
9848 ;; regular prop
9849 (t
9850 (prog1
9851 (setq expr (js2-parse-plain-property (or string-prop name)))
9852 (when (and (not string-prop)
9853 (not js2-is-in-destructuring)
9854 js2-highlight-external-variables
9855 (js2-node-get-prop expr 'SHORTHAND))
9856 (js2-record-name-node name))
9857 (js2-set-face ppos pend
9858 (if (js2-function-node-p
9859 (js2-object-prop-node-right expr))
9860 'font-lock-function-name-face
9861 'font-lock-variable-name-face)
9862 'record))))))
9863
9864 (defun js2-parse-plain-property (prop)
9865 "Parse a non-getter/setter property in an object literal.
9866 PROP is the node representing the property: a number, name or string."
9867 (let* ((tt (js2-get-token))
9868 (pos (js2-node-pos prop))
9869 colon expr result)
9870 (cond
9871 ;; Abbreviated property, as in {foo, bar}
9872 ((and (>= js2-language-version 200)
9873 (or (= tt js2-COMMA)
9874 (= tt js2-RC))
9875 (not (js2-number-node-p prop)))
9876 (js2-unget-token)
9877 (setq result (make-js2-object-prop-node
9878 :pos pos
9879 :left prop
9880 :right prop
9881 :op-pos (js2-current-token-len)))
9882 (js2-node-add-children result prop)
9883 (js2-node-set-prop result 'SHORTHAND t)
9884 result)
9885 ;; Normal property
9886 (t
9887 (if (= tt js2-COLON)
9888 (setq colon (- (js2-current-token-beg) pos)
9889 expr (js2-parse-assign-expr))
9890 (js2-report-error "msg.no.colon.prop")
9891 (setq expr (make-js2-error-node)))
9892 (setq result (make-js2-object-prop-node
9893 :pos pos
9894 ;; don't include last consumed token in length
9895 :len (- (+ (js2-node-pos expr)
9896 (js2-node-len expr))
9897 pos)
9898 :left prop
9899 :right expr
9900 :op-pos colon))
9901 (js2-node-add-children result prop expr)
9902 result))))
9903
9904 (defun js2-parse-getter-setter-prop (pos prop type-string)
9905 "Parse getter or setter property in an object literal.
9906 JavaScript syntax is:
9907
9908 { get foo() {...}, set foo(x) {...} }
9909
9910 and expression closure style is also supported
9911
9912 { get foo() x, set foo(x) _x = x }
9913
9914 POS is the start position of the `get' or `set' keyword.
9915 PROP is the `js2-name-node' representing the property name.
9916 GET-P is non-nil if the keyword was `get'."
9917 (let ((type (cond
9918 ((string= "get" type-string) js2-GET)
9919 ((string= "set" type-string) js2-SET)
9920 (t js2-FUNCTION)))
9921 result end
9922 (fn (js2-parse-function-expr)))
9923 ;; it has to be an anonymous function, as we already parsed the name
9924 (if (/= (js2-node-type fn) js2-FUNCTION)
9925 (js2-report-error "msg.bad.prop")
9926 (if (plusp (length (js2-function-name fn)))
9927 (js2-report-error "msg.bad.prop")))
9928 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9929 (setq end (js2-node-end fn)
9930 result (make-js2-getter-setter-node :type type
9931 :pos pos
9932 :len (- end pos)
9933 :left prop
9934 :right fn))
9935 (js2-node-add-children result prop fn)
9936 result))
9937
9938 (defun js2-create-name-node (&optional check-activation-p token string)
9939 "Create a name node using the current token and, optionally, STRING.
9940 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9941 (let* ((beg (js2-current-token-beg))
9942 (tt (js2-current-token-type))
9943 (s (or string
9944 (if (= js2-NAME tt)
9945 (js2-current-token-string)
9946 (js2-tt-name tt))))
9947 name)
9948 (setq name (make-js2-name-node :pos beg
9949 :name s
9950 :len (length s)))
9951 (if check-activation-p
9952 (js2-check-activation-name s (or token js2-NAME)))
9953 name))
9954
9955 ;;; Indentation support
9956
9957 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9958 ;; Karl cleverly deduces that the desired indentation level is often a
9959 ;; function of paren/bracket/brace nesting depth, which can be determined
9960 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9961 ;; then does some equally clever checks to see if we're in the context of a
9962 ;; substatement of a possibly braceless statement keyword such as if, while,
9963 ;; or finally. This approach yields pretty good results.
9964
9965 ;; The indenter is often "wrong", however, and needs to be overridden.
9966 ;; The right long-term solution is probably to emulate (or integrate
9967 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9968 ;; parse tree from `js2-parse' is present, which is not true at the
9969 ;; moment the user is typing, computing indentation is still thousands
9970 ;; of lines of code to handle every possible syntactic edge case.
9971
9972 ;; In the meantime, the compromise solution is that we offer a "bounce
9973 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9974 ;; current line indent among various likely guess points. This approach
9975 ;; is far from perfect, but should at least make it slightly easier to
9976 ;; move the line towards its desired indentation when manually
9977 ;; overriding Karl's heuristic nesting guesser.
9978
9979 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9980 ;; extensions such as `let' and Array comprehensions. Major kudos to
9981 ;; Karl for coming up with the initial approach, which packs a lot of
9982 ;; punch for so little code.
9983
9984 (defconst js2-possibly-braceless-keywords-re
9985 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9986 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9987 "try" "while" "with" "let")))
9988 "Regular expression matching keywords that are optionally
9989 followed by an opening brace.")
9990
9991 (defconst js2-indent-operator-re
9992 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9993 (regexp-opt '("in" "instanceof") 'words))
9994 "Regular expression matching operators that affect indentation
9995 of continued expressions.")
9996
9997 (defconst js2-declaration-keyword-re
9998 (regexp-opt '("var" "let" "const") 'words)
9999 "Regular expression matching variable declaration keywords.")
10000
10001 (defun js2-re-search-forward-inner (regexp &optional bound count)
10002 "Auxiliary function for `js2-re-search-forward'."
10003 (let (parse saved-point)
10004 (while (> count 0)
10005 (re-search-forward regexp bound)
10006 (setq parse (if saved-point
10007 (parse-partial-sexp saved-point (point))
10008 (syntax-ppss (point))))
10009 (cond ((nth 3 parse)
10010 (re-search-forward
10011 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10012 (save-excursion (end-of-line) (point)) t))
10013 ((nth 7 parse)
10014 (forward-line))
10015 ((or (nth 4 parse)
10016 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10017 (re-search-forward "\\*/"))
10018 (t
10019 (setq count (1- count))))
10020 (setq saved-point (point))))
10021 (point))
10022
10023 (defun js2-re-search-forward (regexp &optional bound noerror count)
10024 "Search forward but ignore strings and comments.
10025 Invokes `re-search-forward' but treats the buffer as if strings
10026 and comments have been removed."
10027 (let ((saved-point (point)))
10028 (condition-case err
10029 (cond ((null count)
10030 (js2-re-search-forward-inner regexp bound 1))
10031 ((< count 0)
10032 (js2-re-search-backward-inner regexp bound (- count)))
10033 ((> count 0)
10034 (js2-re-search-forward-inner regexp bound count)))
10035 (search-failed
10036 (goto-char saved-point)
10037 (unless noerror
10038 (error (error-message-string err)))))))
10039
10040 (defun js2-re-search-backward-inner (regexp &optional bound count)
10041 "Auxiliary function for `js2-re-search-backward'."
10042 (let (parse)
10043 (while (> count 0)
10044 (re-search-backward regexp bound)
10045 (setq parse (syntax-ppss (point)))
10046 (cond ((nth 3 parse)
10047 (re-search-backward
10048 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10049 (line-beginning-position) t))
10050 ((nth 7 parse)
10051 (goto-char (nth 8 parse)))
10052 ((or (nth 4 parse)
10053 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10054 (re-search-backward "/\\*"))
10055 (t
10056 (setq count (1- count))))))
10057 (point))
10058
10059 (defun js2-re-search-backward (regexp &optional bound noerror count)
10060 "Search backward but ignore strings and comments.
10061 Invokes `re-search-backward' but treats the buffer as if strings
10062 and comments have been removed."
10063 (let ((saved-point (point)))
10064 (condition-case err
10065 (cond ((null count)
10066 (js2-re-search-backward-inner regexp bound 1))
10067 ((< count 0)
10068 (js2-re-search-forward-inner regexp bound (- count)))
10069 ((> count 0)
10070 (js2-re-search-backward-inner regexp bound count)))
10071 (search-failed
10072 (goto-char saved-point)
10073 (unless noerror
10074 (error (error-message-string err)))))))
10075
10076 (defun js2-looking-at-operator-p ()
10077 "Return non-nil if text after point is a non-comma operator."
10078 (and (looking-at js2-indent-operator-re)
10079 (or (not (looking-at ":"))
10080 (save-excursion
10081 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10082 (looking-at "?"))))))
10083
10084 (defun js2-continued-expression-p ()
10085 "Return non-nil if the current line continues an expression."
10086 (save-excursion
10087 (back-to-indentation)
10088 (or (js2-looking-at-operator-p)
10089 (when (catch 'found
10090 (while (and (re-search-backward "\n" nil t)
10091 (let ((state (syntax-ppss)))
10092 (when (nth 4 state)
10093 (goto-char (nth 8 state))) ;; skip comments
10094 (skip-chars-backward " \t")
10095 (if (bolp)
10096 t
10097 (throw 'found t))))))
10098 (backward-char)
10099 (when (js2-looking-at-operator-p)
10100 (backward-char)
10101 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10102
10103 (defun js2-end-of-do-while-loop-p ()
10104 "Return non-nil if word after point is `while' of a do-while
10105 statement, else returns nil. A braceless do-while statement
10106 spanning several lines requires that the start of the loop is
10107 indented to the same column as the current line."
10108 (interactive)
10109 (save-excursion
10110 (when (looking-at "\\s-*\\<while\\>")
10111 (if (save-excursion
10112 (skip-chars-backward "[ \t\n]*}")
10113 (looking-at "[ \t\n]*}"))
10114 (save-excursion
10115 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10116 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10117 (or (looking-at "\\<do\\>")
10118 (let ((saved-indent (current-indentation)))
10119 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10120 (/= (current-indentation) saved-indent)))
10121 (and (looking-at "[ \t]*\\<do\\>")
10122 (not (js2-re-search-forward
10123 "\\<while\\>" (point-at-eol) t))
10124 (= (current-indentation) saved-indent))))))))
10125
10126 (defun js2-multiline-decl-indentation ()
10127 "Return the declaration indentation column if the current line belongs
10128 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10129 (let (forward-sexp-function ; use Lisp version
10130 at-opening-bracket)
10131 (save-excursion
10132 (back-to-indentation)
10133 (when (not (looking-at js2-declaration-keyword-re))
10134 (when (looking-at js2-indent-operator-re)
10135 (goto-char (match-end 0))) ; continued expressions are ok
10136 (while (and (not at-opening-bracket)
10137 (not (bobp))
10138 (let ((pos (point)))
10139 (save-excursion
10140 (js2-backward-sws)
10141 (or (eq (char-before) ?,)
10142 (and (not (eq (char-before) ?\;))
10143 (prog2 (skip-syntax-backward ".")
10144 (looking-at js2-indent-operator-re)
10145 (js2-backward-sws))
10146 (not (eq (char-before) ?\;)))
10147 (js2-same-line pos)))))
10148 (condition-case _
10149 (backward-sexp)
10150 (scan-error (setq at-opening-bracket t))))
10151 (when (looking-at js2-declaration-keyword-re)
10152 (goto-char (match-end 0))
10153 (1+ (current-column)))))))
10154
10155 (defun js2-ctrl-statement-indentation ()
10156 "Return the proper indentation of current line if it is a control statement.
10157 Returns an indentation if this line starts the body of a control
10158 statement without braces, else returns nil."
10159 (let (forward-sexp-function)
10160 (save-excursion
10161 (back-to-indentation)
10162 (when (and (not (js2-same-line (point-min)))
10163 (not (looking-at "{"))
10164 (js2-re-search-backward "[[:graph:]]" nil t)
10165 (not (looking-at "[{([]"))
10166 (progn
10167 (forward-char)
10168 (when (= (char-before) ?\))
10169 ;; scan-sexps sometimes throws an error
10170 (ignore-errors (backward-sexp))
10171 (skip-chars-backward " \t" (point-at-bol)))
10172 (let ((pt (point)))
10173 (back-to-indentation)
10174 (when (looking-at "}[ \t]*")
10175 (goto-char (match-end 0)))
10176 (and (looking-at js2-possibly-braceless-keywords-re)
10177 (= (match-end 0) pt)
10178 (not (js2-end-of-do-while-loop-p))))))
10179 (+ (current-indentation) js2-basic-offset)))))
10180
10181 (defun js2-indent-in-array-comp (parse-status)
10182 "Return non-nil if we think we're in an array comprehension.
10183 In particular, return the buffer position of the first `for' kwd."
10184 (let ((bracket (nth 1 parse-status))
10185 (end (point)))
10186 (when bracket
10187 (save-excursion
10188 (goto-char bracket)
10189 (when (looking-at "\\[")
10190 (forward-char 1)
10191 (js2-forward-sws)
10192 (if (looking-at "[[{]")
10193 (let (forward-sexp-function) ; use Lisp version
10194 (forward-sexp) ; skip destructuring form
10195 (js2-forward-sws)
10196 (if (and (/= (char-after) ?,) ; regular array
10197 (looking-at "for"))
10198 (match-beginning 0)))
10199 ;; to skip arbitrary expressions we need the parser,
10200 ;; so we'll just guess at it.
10201 (if (and (> end (point)) ; not empty literal
10202 (re-search-forward "[^,]]* \\(for\\) " end t)
10203 ;; not inside comment or string literal
10204 (let ((state (parse-partial-sexp bracket (point))))
10205 (not (or (nth 3 state) (nth 4 state)))))
10206 (match-beginning 1))))))))
10207
10208 (defun js2-array-comp-indentation (parse-status for-kwd)
10209 (if (js2-same-line for-kwd)
10210 ;; first continuation line
10211 (save-excursion
10212 (goto-char (nth 1 parse-status))
10213 (forward-char 1)
10214 (skip-chars-forward " \t")
10215 (current-column))
10216 (save-excursion
10217 (goto-char for-kwd)
10218 (current-column))))
10219
10220 (defun js2-proper-indentation (parse-status)
10221 "Return the proper indentation for the current line."
10222 (save-excursion
10223 (back-to-indentation)
10224 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10225 (at-closing-bracket (looking-at "[]})]"))
10226 (same-indent-p (or at-closing-bracket
10227 (looking-at "\\<case\\>[^:]")
10228 (and (looking-at "\\<default:")
10229 (save-excursion
10230 (js2-backward-sws)
10231 (not (memq (char-before) '(?, ?{)))))))
10232 (continued-expr-p (js2-continued-expression-p))
10233 (declaration-indent (and js2-pretty-multiline-declarations
10234 (js2-multiline-decl-indentation)))
10235 (bracket (nth 1 parse-status))
10236 beg indent)
10237 (cond
10238 ;; indent array comprehension continuation lines specially
10239 ((and bracket
10240 (>= js2-language-version 170)
10241 (not (js2-same-line bracket))
10242 (setq beg (js2-indent-in-array-comp parse-status))
10243 (>= (point) (save-excursion
10244 (goto-char beg)
10245 (point-at-bol)))) ; at or after first loop?
10246 (js2-array-comp-indentation parse-status beg))
10247
10248 (ctrl-stmt-indent)
10249
10250 ((and declaration-indent continued-expr-p)
10251 (+ declaration-indent js2-basic-offset))
10252
10253 (declaration-indent)
10254
10255 (bracket
10256 (goto-char bracket)
10257 (cond
10258 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10259 (when (save-excursion (skip-chars-backward " \t)")
10260 (looking-at ")"))
10261 (backward-list))
10262 (back-to-indentation)
10263 (and (eq js2-pretty-multiline-declarations 'all)
10264 (looking-at js2-declaration-keyword-re)
10265 (goto-char (1+ (match-end 0))))
10266 (setq indent
10267 (cond (same-indent-p
10268 (current-column))
10269 (continued-expr-p
10270 (+ (current-column) (* 2 js2-basic-offset)))
10271 (t
10272 (+ (current-column) js2-basic-offset))))
10273 (if (and js2-indent-switch-body
10274 (not at-closing-bracket)
10275 (looking-at "\\_<switch\\_>"))
10276 (+ indent js2-basic-offset)
10277 indent))
10278 (t
10279 (unless same-indent-p
10280 (forward-char)
10281 (skip-chars-forward " \t"))
10282 (current-column))))
10283
10284 (continued-expr-p js2-basic-offset)
10285
10286 (t 0)))))
10287
10288 (defun js2-lineup-comment (parse-status)
10289 "Indent a multi-line block comment continuation line."
10290 (let* ((beg (nth 8 parse-status))
10291 (first-line (js2-same-line beg))
10292 (offset (save-excursion
10293 (goto-char beg)
10294 (if (looking-at "/\\*")
10295 (+ 1 (current-column))
10296 0))))
10297 (unless first-line
10298 (indent-line-to offset))))
10299
10300 (defun js2-backward-sws ()
10301 "Move backward through whitespace and comments."
10302 (interactive)
10303 (while (forward-comment -1)))
10304
10305 (defun js2-forward-sws ()
10306 "Move forward through whitespace and comments."
10307 (interactive)
10308 (while (forward-comment 1)))
10309
10310 (defun js2-current-indent (&optional pos)
10311 "Return column of indentation on current line.
10312 If POS is non-nil, go to that point and return indentation for that line."
10313 (save-excursion
10314 (if pos
10315 (goto-char pos))
10316 (back-to-indentation)
10317 (current-column)))
10318
10319 (defun js2-arglist-close ()
10320 "Return non-nil if we're on a line beginning with a close-paren/brace."
10321 (save-excursion
10322 (goto-char (point-at-bol))
10323 (js2-forward-sws)
10324 (looking-at "[])}]")))
10325
10326 (defun js2-indent-looks-like-label-p ()
10327 (goto-char (point-at-bol))
10328 (js2-forward-sws)
10329 (looking-at (concat js2-mode-identifier-re ":")))
10330
10331 (defun js2-indent-in-objlit-p (parse-status)
10332 "Return non-nil if this looks like an object-literal entry."
10333 (let ((start (nth 1 parse-status)))
10334 (and
10335 start
10336 (save-excursion
10337 (and (zerop (forward-line -1))
10338 (not (< (point) start)) ; crossed a {} boundary
10339 (js2-indent-looks-like-label-p)))
10340 (save-excursion
10341 (js2-indent-looks-like-label-p)))))
10342
10343 ;; If prev line looks like foobar({ then we're passing an object
10344 ;; literal to a function call, and people pretty much always want to
10345 ;; de-dent back to the previous line, so move the 'basic-offset'
10346 ;; position to the front.
10347 (defun js2-indent-objlit-arg-p (parse-status)
10348 (save-excursion
10349 (back-to-indentation)
10350 (js2-backward-sws)
10351 (and (eq (1- (point)) (nth 1 parse-status))
10352 (eq (char-before) ?{)
10353 (progn
10354 (forward-char -1)
10355 (skip-chars-backward " \t")
10356 (eq (char-before) ?\()))))
10357
10358 (defun js2-indent-case-block-p ()
10359 (save-excursion
10360 (back-to-indentation)
10361 (js2-backward-sws)
10362 (goto-char (point-at-bol))
10363 (skip-chars-forward " \t")
10364 (looking-at "case\\s-.+:")))
10365
10366 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10367 "Cycle among alternate computed indentation positions.
10368 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10369 of the buffer to the current point. NORMAL-COL is the indentation
10370 column computed by the heuristic guesser based on current paren,
10371 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10372 in reverse."
10373 (let ((cur-indent (js2-current-indent))
10374 (old-buffer-undo-list buffer-undo-list)
10375 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10376 (current-line (save-excursion
10377 (forward-line 0) ; move to bol
10378 (1+ (count-lines (point-min) (point)))))
10379 positions pos main-pos anchor arglist-cont same-indent
10380 basic-offset computed-pos)
10381 ;; temporarily don't record undo info, if user requested this
10382 (when js2-mode-indent-inhibit-undo
10383 (setq buffer-undo-list t))
10384 (unwind-protect
10385 (progn
10386 ;; First likely point: indent from beginning of previous code line
10387 (push (setq basic-offset
10388 (+ (save-excursion
10389 (back-to-indentation)
10390 (js2-backward-sws)
10391 (back-to-indentation)
10392 (current-column))
10393 js2-basic-offset))
10394 positions)
10395
10396 ;; (First + epsilon) likely point: indent 2x from beginning of
10397 ;; previous code line. Google does it this way.
10398 (push (setq basic-offset
10399 (+ (save-excursion
10400 (back-to-indentation)
10401 (js2-backward-sws)
10402 (back-to-indentation)
10403 (current-column))
10404 (* 2 js2-basic-offset)))
10405 positions)
10406
10407 ;; Second likely point: indent from assign-expr RHS. This
10408 ;; is just a crude guess based on finding " = " on the previous
10409 ;; line containing actual code.
10410 (setq pos (save-excursion
10411 (forward-line -1)
10412 (goto-char (point-at-bol))
10413 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10414 (point-at-eol) t)
10415 (goto-char (match-end 1))
10416 (skip-chars-forward " \t\r\n")
10417 (current-column))))
10418 (when pos
10419 (incf pos js2-basic-offset)
10420 (push pos positions))
10421
10422 ;; Third likely point: same indent as previous line of code.
10423 ;; Make it the first likely point if we're not on an
10424 ;; arglist-close line and previous line ends in a comma, or
10425 ;; both this line and prev line look like object-literal
10426 ;; elements.
10427 (setq pos (save-excursion
10428 (goto-char (point-at-bol))
10429 (js2-backward-sws)
10430 (back-to-indentation)
10431 (prog1
10432 (current-column)
10433 ;; while we're here, look for trailing comma
10434 (if (save-excursion
10435 (goto-char (point-at-eol))
10436 (js2-backward-sws)
10437 (eq (char-before) ?,))
10438 (setq arglist-cont (1- (point)))))))
10439 (when pos
10440 (if (and (or arglist-cont
10441 (js2-indent-in-objlit-p parse-status))
10442 (not (js2-arglist-close)))
10443 (setq same-indent pos))
10444 (push pos positions))
10445
10446 ;; Fourth likely point: first preceding code with less indentation.
10447 ;; than the immediately preceding code line.
10448 (setq pos (save-excursion
10449 (back-to-indentation)
10450 (js2-backward-sws)
10451 (back-to-indentation)
10452 (setq anchor (current-column))
10453 (while (and (zerop (forward-line -1))
10454 (>= (progn
10455 (back-to-indentation)
10456 (current-column))
10457 anchor)))
10458 (setq pos (current-column))))
10459 (push pos positions)
10460
10461 ;; nesting-heuristic position, main by default
10462 (push (setq main-pos normal-col) positions)
10463
10464 ;; delete duplicates and sort positions list
10465 (setq positions (sort (delete-dups positions) '<))
10466
10467 ;; comma-list continuation lines: prev line indent takes precedence
10468 (if same-indent
10469 (setq main-pos same-indent))
10470
10471 ;; common special cases where we want to indent in from previous line
10472 (if (or (js2-indent-case-block-p)
10473 (js2-indent-objlit-arg-p parse-status))
10474 (setq main-pos basic-offset))
10475
10476 ;; if bouncing backwards, reverse positions list
10477 (if backwards
10478 (setq positions (reverse positions)))
10479
10480 ;; record whether we're already sitting on one of the alternatives
10481 (setq pos (member cur-indent positions))
10482
10483 (cond
10484 ;; case 0: we're one one of the alternatives and this is the
10485 ;; first time they've pressed TAB on this line (best-guess).
10486 ((and js2-mode-indent-ignore-first-tab
10487 pos
10488 ;; first time pressing TAB on this line?
10489 (not (eq js2-mode-last-indented-line current-line)))
10490 ;; do nothing
10491 (setq computed-pos nil))
10492 ;; case 1: only one computed position => use it
10493 ((null (cdr positions))
10494 (setq computed-pos 0))
10495 ;; case 2: not on any of the computed spots => use main spot
10496 ((not pos)
10497 (setq computed-pos (js2-position main-pos positions)))
10498 ;; case 3: on last position: cycle to first position
10499 ((null (cdr pos))
10500 (setq computed-pos 0))
10501 ;; case 4: on intermediate position: cycle to next position
10502 (t
10503 (setq computed-pos (js2-position (second pos) positions))))
10504
10505 ;; see if any hooks want to indent; otherwise we do it
10506 (loop with result = nil
10507 for hook in js2-indent-hook
10508 while (null result)
10509 do
10510 (setq result (funcall hook positions computed-pos))
10511 finally do
10512 (unless (or result (null computed-pos))
10513 (indent-line-to (nth computed-pos positions)))))
10514
10515 ;; finally
10516 (if js2-mode-indent-inhibit-undo
10517 (setq buffer-undo-list old-buffer-undo-list))
10518 ;; see commentary for `js2-mode-last-indented-line'
10519 (setq js2-mode-last-indented-line current-line))))
10520
10521 (defun js2-indent-bounce-backwards ()
10522 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10523 cycles between the computed indentation positions in reverse order."
10524 (interactive)
10525 (js2-indent-line t))
10526
10527 (defun js2-1-line-comment-continuation-p ()
10528 "Return t if we're in a 1-line comment continuation.
10529 If so, we don't ever want to use bounce-indent."
10530 (save-excursion
10531 (and (progn
10532 (forward-line 0)
10533 (looking-at "\\s-*//"))
10534 (progn
10535 (forward-line -1)
10536 (forward-line 0)
10537 (when (looking-at "\\s-*$")
10538 (js2-backward-sws)
10539 (forward-line 0))
10540 (looking-at "\\s-*//")))))
10541
10542 (defun js2-indent-line (&optional bounce-backwards)
10543 "Indent the current line as JavaScript source text."
10544 (interactive)
10545 (let (parse-status offset indent-col
10546 ;; Don't whine about errors/warnings when we're indenting.
10547 ;; This has to be set before calling parse-partial-sexp below.
10548 (inhibit-point-motion-hooks t))
10549 (setq parse-status (save-excursion
10550 (syntax-ppss (point-at-bol)))
10551 offset (- (point) (save-excursion
10552 (back-to-indentation)
10553 (point))))
10554 (js2-with-underscore-as-word-syntax
10555 (if (nth 4 parse-status)
10556 (js2-lineup-comment parse-status)
10557 (setq indent-col (js2-proper-indentation parse-status))
10558 ;; See comments below about `js2-mode-last-indented-line'.
10559 (cond
10560 ;; bounce-indenting is disabled during electric-key indent.
10561 ;; It doesn't work well on first line of buffer.
10562 ((and js2-bounce-indent-p
10563 (not (js2-same-line (point-min)))
10564 (not (js2-1-line-comment-continuation-p)))
10565 (js2-bounce-indent indent-col parse-status bounce-backwards))
10566 ;; just indent to the guesser's likely spot
10567 (t (indent-line-to indent-col))))
10568 (when (plusp offset)
10569 (forward-char offset)))))
10570
10571 (defun js2-indent-region (start end)
10572 "Indent the region, but don't use bounce indenting."
10573 (let ((js2-bounce-indent-p nil)
10574 (indent-region-function nil)
10575 (after-change-functions (remq 'js2-mode-edit
10576 after-change-functions)))
10577 (indent-region start end nil) ; nil for byte-compiler
10578 (js2-mode-edit start end (- end start))))
10579
10580 (defvar js2-minor-mode-map
10581 (let ((map (make-sparse-keymap)))
10582 (define-key map (kbd "C-c C-`") #'js2-next-error)
10583 (define-key map [mouse-1] #'js2-mode-show-node)
10584 map)
10585 "Keymap used when `js2-minor-mode' is active.")
10586
10587 ;;;###autoload
10588 (define-minor-mode js2-minor-mode
10589 "Minor mode for running js2 as a background linter.
10590 This allows you to use a different major mode for JavaScript editing,
10591 such as `js-mode', while retaining the asynchronous error/warning
10592 highlighting features of `js2-mode'."
10593 :group 'js2-mode
10594 :lighter " js-lint"
10595 (if js2-minor-mode
10596 (js2-minor-mode-enter)
10597 (js2-minor-mode-exit)))
10598
10599 (defun js2-minor-mode-enter ()
10600 "Initialization for `js2-minor-mode'."
10601 (set (make-local-variable 'max-lisp-eval-depth)
10602 (max max-lisp-eval-depth 3000))
10603 (setq next-error-function #'js2-next-error)
10604 (js2-set-default-externs)
10605 ;; Experiment: make reparse-delay longer for longer files.
10606 (if (plusp js2-dynamic-idle-timer-adjust)
10607 (setq js2-idle-timer-delay
10608 (* js2-idle-timer-delay
10609 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10610 (setq js2-mode-buffer-dirty-p t
10611 js2-mode-parsing nil)
10612 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10613 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10614 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10615 (when js2-include-jslint-globals
10616 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10617 (run-hooks 'js2-init-hook)
10618 (js2-reparse))
10619
10620 (defun js2-minor-mode-exit ()
10621 "Turn off `js2-minor-mode'."
10622 (setq next-error-function nil)
10623 (remove-hook 'after-change-functions #'js2-mode-edit t)
10624 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10625 (when js2-mode-node-overlay
10626 (delete-overlay js2-mode-node-overlay)
10627 (setq js2-mode-node-overlay nil))
10628 (js2-remove-overlays)
10629 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10630 (setq js2-mode-ast nil))
10631
10632 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10633 (make-variable-buffer-local 'js2-source-buffer)
10634
10635 (defun* js2-display-error-list ()
10636 "Display a navigable buffer listing parse errors/warnings."
10637 (interactive)
10638 (unless (js2-have-errors-p)
10639 (message "No errors")
10640 (return-from js2-display-error-list))
10641 (labels ((annotate-list
10642 (lst type)
10643 "Add diagnostic TYPE and line number to errs list"
10644 (mapcar (lambda (err)
10645 (list err type (line-number-at-pos (nth 1 err))))
10646 lst)))
10647 (let* ((srcbuf (current-buffer))
10648 (errbuf (get-buffer-create "*js-lint*"))
10649 (errors (annotate-list
10650 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10651 'js2-error)) ; must be a valid face name
10652 (warnings (annotate-list
10653 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10654 'js2-warning)) ; must be a valid face name
10655 (all-errs (sort (append errors warnings)
10656 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10657 (with-current-buffer errbuf
10658 (let ((inhibit-read-only t))
10659 (erase-buffer)
10660 (dolist (err all-errs)
10661 (destructuring-bind ((msg-key beg _end &rest) type line) err
10662 (insert-text-button
10663 (format "line %d: %s" line (js2-get-msg msg-key))
10664 'face type
10665 'follow-link "\C-m"
10666 'action 'js2-error-buffer-jump
10667 'js2-msg (js2-get-msg msg-key)
10668 'js2-pos beg)
10669 (insert "\n"))))
10670 (js2-error-buffer-mode)
10671 (setq js2-source-buffer srcbuf)
10672 (pop-to-buffer errbuf)
10673 (goto-char (point-min))
10674 (unless (eobp)
10675 (js2-error-buffer-view))))))
10676
10677 (defvar js2-error-buffer-mode-map
10678 (let ((map (make-sparse-keymap)))
10679 (define-key map "n" #'js2-error-buffer-next)
10680 (define-key map "p" #'js2-error-buffer-prev)
10681 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10682 (define-key map "o" #'js2-error-buffer-view)
10683 (define-key map "q" #'js2-error-buffer-quit)
10684 map)
10685 "Keymap used for js2 diagnostics buffers.")
10686
10687 (defun js2-error-buffer-mode ()
10688 "Major mode for js2 diagnostics buffers.
10689 Selecting an error will jump it to the corresponding source-buffer error.
10690 \\{js2-error-buffer-mode-map}"
10691 (interactive)
10692 (setq major-mode 'js2-error-buffer-mode
10693 mode-name "JS Lint Diagnostics")
10694 (use-local-map js2-error-buffer-mode-map)
10695 (setq truncate-lines t)
10696 (set-buffer-modified-p nil)
10697 (setq buffer-read-only t)
10698 (run-hooks 'js2-error-buffer-mode-hook))
10699
10700 (defun js2-error-buffer-next ()
10701 "Move to next error and view it."
10702 (interactive)
10703 (when (zerop (forward-line 1))
10704 (js2-error-buffer-view)))
10705
10706 (defun js2-error-buffer-prev ()
10707 "Move to previous error and view it."
10708 (interactive)
10709 (when (zerop (forward-line -1))
10710 (js2-error-buffer-view)))
10711
10712 (defun js2-error-buffer-quit ()
10713 "Kill the current buffer."
10714 (interactive)
10715 (kill-buffer))
10716
10717 (defun js2-error-buffer-jump (&rest ignored)
10718 "Jump cursor to current error in source buffer."
10719 (interactive)
10720 (when (js2-error-buffer-view)
10721 (pop-to-buffer js2-source-buffer)))
10722
10723 (defun js2-error-buffer-view ()
10724 "Scroll source buffer to show error at current line."
10725 (interactive)
10726 (cond
10727 ((not (eq major-mode 'js2-error-buffer-mode))
10728 (message "Not in a js2 errors buffer"))
10729 ((not (buffer-live-p js2-source-buffer))
10730 (message "Source buffer has been killed"))
10731 ((not (wholenump (get-text-property (point) 'js2-pos)))
10732 (message "There does not seem to be an error here"))
10733 (t
10734 (let ((pos (get-text-property (point) 'js2-pos))
10735 (msg (get-text-property (point) 'js2-msg)))
10736 (save-selected-window
10737 (pop-to-buffer js2-source-buffer)
10738 (goto-char pos)
10739 (message msg))))))
10740
10741 ;;;###autoload
10742 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10743 ;; FIXME: Should derive from js-mode.
10744 "Major mode for editing JavaScript code."
10745 ;; Used by comment-region; don't change it.
10746 (set (make-local-variable 'comment-start) "//")
10747 (set (make-local-variable 'comment-end) "")
10748 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10749 (set (make-local-variable 'max-lisp-eval-depth)
10750 (max max-lisp-eval-depth 3000))
10751 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10752 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10753 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10754 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10755 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10756 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10757 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10758 ;; for characters inside regexp literals.
10759 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10760 ;; this is necessary to make `show-paren-function' work properly
10761 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10762 ;; needed for M-x rgrep, among other things
10763 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10764
10765 (set (make-local-variable 'electric-indent-chars)
10766 (append "{}()[]:;,*." electric-indent-chars))
10767 (set (make-local-variable 'electric-layout-rules)
10768 '((?\; . after) (?\{ . after) (?\} . before)))
10769
10770 ;; some variables needed by cc-engine for paragraph-fill, etc.
10771 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10772 c-comment-start-regexp "/[*/]\\|\\s|"
10773 c-line-comment-starter "//"
10774 c-paragraph-start js2-paragraph-start
10775 c-paragraph-separate "$"
10776 c-syntactic-ws-start js2-syntactic-ws-start
10777 c-syntactic-ws-end js2-syntactic-ws-end
10778 c-syntactic-eol js2-syntactic-eol)
10779
10780 (let ((c-buffer-is-cc-mode t))
10781 ;; Copied from `js-mode'. Also see Bug#6071.
10782 (make-local-variable 'paragraph-start)
10783 (make-local-variable 'paragraph-separate)
10784 (make-local-variable 'paragraph-ignore-fill-prefix)
10785 (make-local-variable 'adaptive-fill-mode)
10786 (make-local-variable 'adaptive-fill-regexp)
10787 (c-setup-paragraph-variables))
10788
10789 (setq font-lock-defaults '(nil t))
10790
10791 ;; Experiment: make reparse-delay longer for longer files.
10792 (when (plusp js2-dynamic-idle-timer-adjust)
10793 (setq js2-idle-timer-delay
10794 (* js2-idle-timer-delay
10795 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10796
10797 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10798 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10799 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10800 (setq next-error-function #'js2-next-error)
10801 (imenu-add-to-menubar (concat "IM-" mode-name))
10802 (add-to-invisibility-spec '(js2-outline . t))
10803 (set (make-local-variable 'line-move-ignore-invisible) t)
10804 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10805
10806 (setq js2-mode-functions-hidden nil
10807 js2-mode-comments-hidden nil
10808 js2-mode-buffer-dirty-p t
10809 js2-mode-parsing nil)
10810
10811 (js2-set-default-externs)
10812
10813 (when js2-include-jslint-globals
10814 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10815
10816 (run-hooks 'js2-init-hook)
10817
10818 (js2-reparse))
10819
10820 (defun js2-mode-exit ()
10821 "Exit `js2-mode' and clean up."
10822 (interactive)
10823 (when js2-mode-node-overlay
10824 (delete-overlay js2-mode-node-overlay)
10825 (setq js2-mode-node-overlay nil))
10826 (js2-remove-overlays)
10827 (setq js2-mode-ast nil)
10828 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10829 (remove-from-invisibility-spec '(js2-outline . t))
10830 (js2-mode-show-all)
10831 (with-silent-modifications
10832 (js2-clear-face (point-min) (point-max))))
10833
10834 (defun js2-mode-reset-timer ()
10835 "Cancel any existing parse timer and schedule a new one."
10836 (if js2-mode-parse-timer
10837 (cancel-timer js2-mode-parse-timer))
10838 (setq js2-mode-parsing nil)
10839 (let ((timer (timer-create)))
10840 (setq js2-mode-parse-timer timer)
10841 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10842 (timer-set-idle-time timer js2-idle-timer-delay)
10843 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10844 (timer-activate-when-idle timer nil)))
10845
10846 (defun js2-mode-idle-reparse (buffer)
10847 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10848 it to be reparsed when the buffer is selected."
10849 (cond ((eq buffer (current-buffer))
10850 (js2-reparse))
10851 ((buffer-live-p buffer)
10852 ;; reparse when the buffer is selected again
10853 (with-current-buffer buffer
10854 (add-hook 'window-configuration-change-hook
10855 #'js2-mode-idle-reparse-inner
10856 nil t)))))
10857
10858 (defun js2-mode-idle-reparse-inner ()
10859 (remove-hook 'window-configuration-change-hook
10860 #'js2-mode-idle-reparse-inner
10861 t)
10862 (js2-reparse))
10863
10864 (defun js2-mode-edit (_beg _end _len)
10865 "Schedule a new parse after buffer is edited.
10866 Buffer edit spans from BEG to END and is of length LEN."
10867 (setq js2-mode-buffer-dirty-p t)
10868 (js2-mode-hide-overlay)
10869 (js2-mode-reset-timer))
10870
10871 (defun js2-minor-mode-edit (_beg _end _len)
10872 "Callback for buffer edits in `js2-mode'.
10873 Schedules a new parse after buffer is edited.
10874 Buffer edit spans from BEG to END and is of length LEN."
10875 (setq js2-mode-buffer-dirty-p t)
10876 (js2-mode-hide-overlay)
10877 (js2-mode-reset-timer))
10878
10879 (defun js2-reparse (&optional force)
10880 "Re-parse current buffer after user finishes some data entry.
10881 If we get any user input while parsing, including cursor motion,
10882 we discard the parse and reschedule it. If FORCE is nil, then the
10883 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10884 (let (time
10885 interrupted-p
10886 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10887 (unless js2-mode-parsing
10888 (setq js2-mode-parsing t)
10889 (unwind-protect
10890 (when (or js2-mode-buffer-dirty-p force)
10891 (js2-remove-overlays)
10892 (with-silent-modifications
10893 (setq js2-mode-buffer-dirty-p nil
10894 js2-mode-fontifications nil
10895 js2-mode-deferred-properties nil)
10896 (if js2-mode-verbose-parse-p
10897 (message "parsing..."))
10898 (setq time
10899 (js2-time
10900 (setq interrupted-p
10901 (catch 'interrupted
10902 (js2-parse)
10903 ;; if parsing is interrupted, comments and regex
10904 ;; literals stay ignored by `parse-partial-sexp'
10905 (remove-text-properties (point-min) (point-max)
10906 '(syntax-table))
10907 (js2-mode-apply-deferred-properties)
10908 (js2-mode-remove-suppressed-warnings)
10909 (js2-mode-show-warnings)
10910 (js2-mode-show-errors)
10911 (if (>= js2-highlight-level 1)
10912 (js2-highlight-jsdoc js2-mode-ast))
10913 nil))))
10914 (if interrupted-p
10915 (progn
10916 ;; unfinished parse => try again
10917 (setq js2-mode-buffer-dirty-p t)
10918 (js2-mode-reset-timer))
10919 (if js2-mode-verbose-parse-p
10920 (message "Parse time: %s" time)))))
10921 (setq js2-mode-parsing nil)
10922 (unless interrupted-p
10923 (setq js2-mode-parse-timer nil))))))
10924
10925 (defun js2-mode-show-node (event)
10926 "Debugging aid: highlight selected AST node on mouse click."
10927 (interactive "e")
10928 (mouse-set-point event)
10929 (setq deactivate-mark t)
10930 (when js2-mode-show-overlay
10931 (let ((node (js2-node-at-point))
10932 beg end)
10933 (if (null node)
10934 (message "No node found at location %s" (point))
10935 (setq beg (js2-node-abs-pos node)
10936 end (+ beg (js2-node-len node)))
10937 (if js2-mode-node-overlay
10938 (move-overlay js2-mode-node-overlay beg end)
10939 (setq js2-mode-node-overlay (make-overlay beg end))
10940 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10941 (with-silent-modifications
10942 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10943 (message "%s, parent: %s"
10944 (js2-node-short-name node)
10945 (if (js2-node-parent node)
10946 (js2-node-short-name (js2-node-parent node))
10947 "nil"))))))
10948
10949 (defun js2-mode-hide-overlay (&optional _p1 p2)
10950 "Remove the debugging overlay when the point moves.
10951 P1 and P2 are the old and new values of point, respectively."
10952 (when js2-mode-node-overlay
10953 (let ((beg (overlay-start js2-mode-node-overlay))
10954 (end (overlay-end js2-mode-node-overlay)))
10955 ;; Sometimes we're called spuriously.
10956 (unless (and p2
10957 (>= p2 beg)
10958 (<= p2 end))
10959 (with-silent-modifications
10960 (remove-text-properties beg end '(point-left nil)))
10961 (delete-overlay js2-mode-node-overlay)
10962 (setq js2-mode-node-overlay nil)))))
10963
10964 (defun js2-mode-reset ()
10965 "Debugging helper: reset everything."
10966 (interactive)
10967 (js2-mode-exit)
10968 (js2-mode))
10969
10970 (defun js2-mode-show-warn-or-err (e face)
10971 "Highlight a warning or error E with FACE.
10972 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10973 The last element is optional. When present, use instead of FACE."
10974 (let* ((key (first e))
10975 (beg (second e))
10976 (end (+ beg (third e)))
10977 ;; Don't inadvertently go out of bounds.
10978 (beg (max (point-min) (min beg (point-max))))
10979 (end (max (point-min) (min end (point-max))))
10980 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10981 (ovl (make-overlay beg end)))
10982 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10983 (overlay-put ovl 'js2-error t)
10984 (put-text-property beg end 'help-echo (js2-get-msg key))
10985 (put-text-property beg end 'point-entered #'js2-echo-error)))
10986
10987 (defun js2-remove-overlays ()
10988 "Remove overlays from buffer that have a `js2-error' property."
10989 (let ((beg (point-min))
10990 (end (point-max)))
10991 (save-excursion
10992 (dolist (o (overlays-in beg end))
10993 (when (overlay-get o 'js2-error)
10994 (delete-overlay o))))))
10995
10996 (defun js2-error-at-point (&optional pos)
10997 "Return non-nil if there's an error overlay at POS.
10998 Defaults to point."
10999 (loop with pos = (or pos (point))
11000 for o in (overlays-at pos)
11001 thereis (overlay-get o 'js2-error)))
11002
11003 (defun js2-mode-apply-deferred-properties ()
11004 "Apply fontifications and other text properties recorded during parsing."
11005 (when (plusp js2-highlight-level)
11006 ;; We defer clearing faces as long as possible to eliminate flashing.
11007 (js2-clear-face (point-min) (point-max))
11008 ;; Have to reverse the recorded fontifications list so that errors
11009 ;; and warnings overwrite the normal fontifications.
11010 (dolist (f (nreverse js2-mode-fontifications))
11011 (put-text-property (first f) (second f) 'font-lock-face (third f)))
11012 (setq js2-mode-fontifications nil))
11013 (dolist (p js2-mode-deferred-properties)
11014 (apply #'put-text-property p))
11015 (setq js2-mode-deferred-properties nil))
11016
11017 (defun js2-mode-show-errors ()
11018 "Highlight syntax errors."
11019 (when js2-mode-show-parse-errors
11020 (dolist (e (js2-ast-root-errors js2-mode-ast))
11021 (js2-mode-show-warn-or-err e 'js2-error))))
11022
11023 (defun js2-mode-remove-suppressed-warnings ()
11024 "Take suppressed warnings out of the AST warnings list.
11025 This ensures that the counts and `next-error' are correct."
11026 (setf (js2-ast-root-warnings js2-mode-ast)
11027 (js2-delete-if
11028 (lambda (e)
11029 (let ((key (caar e)))
11030 (or
11031 (and (not js2-strict-trailing-comma-warning)
11032 (string-match "trailing\\.comma" key))
11033 (and (not js2-strict-cond-assign-warning)
11034 (string= key "msg.equal.as.assign"))
11035 (and js2-missing-semi-one-line-override
11036 (string= key "msg.missing.semi")
11037 (let* ((beg (second e))
11038 (node (js2-node-at-point beg))
11039 (fn (js2-mode-find-parent-fn node))
11040 (body (and fn (js2-function-node-body fn)))
11041 (lc (and body (js2-node-abs-pos body)))
11042 (rc (and lc (+ lc (js2-node-len body)))))
11043 (and fn
11044 (or (null body)
11045 (save-excursion
11046 (goto-char beg)
11047 (and (js2-same-line lc)
11048 (js2-same-line rc))))))))))
11049 (js2-ast-root-warnings js2-mode-ast))))
11050
11051 (defun js2-mode-show-warnings ()
11052 "Highlight strict-mode warnings."
11053 (when js2-mode-show-strict-warnings
11054 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11055 (js2-mode-show-warn-or-err e 'js2-warning))))
11056
11057 (defun js2-echo-error (_old-point new-point)
11058 "Called by point-motion hooks."
11059 (let ((msg (get-text-property new-point 'help-echo)))
11060 (when (and (stringp msg)
11061 (not (active-minibuffer-window))
11062 (not (current-message)))
11063 (message msg))))
11064
11065 (defalias 'js2-echo-help #'js2-echo-error)
11066
11067 (defun js2-line-break (&optional _soft)
11068 "Break line at point and indent, continuing comment if within one.
11069 If inside a string, and `js2-concat-multiline-strings' is not
11070 nil, turn it into concatenation."
11071 (interactive)
11072 (let ((parse-status (syntax-ppss)))
11073 (cond
11074 ;; Check if we're inside a string.
11075 ((nth 3 parse-status)
11076 (if js2-concat-multiline-strings
11077 (js2-mode-split-string parse-status)
11078 (insert "\n")))
11079 ;; Check if inside a block comment.
11080 ((nth 4 parse-status)
11081 (js2-mode-extend-comment (nth 8 parse-status)))
11082 (t
11083 (newline-and-indent)))))
11084
11085 (defun js2-mode-split-string (parse-status)
11086 "Turn a newline in mid-string into a string concatenation.
11087 PARSE-STATUS is as documented in `parse-partial-sexp'."
11088 (let* ((quote-char (nth 3 parse-status))
11089 (at-eol (eq js2-concat-multiline-strings 'eol)))
11090 (insert quote-char)
11091 (insert (if at-eol " +\n" "\n"))
11092 (unless at-eol
11093 (insert "+ "))
11094 (js2-indent-line)
11095 (insert quote-char)
11096 (when (eolp)
11097 (insert quote-char)
11098 (backward-char 1))))
11099
11100 (defun js2-mode-extend-comment (start-pos)
11101 "Indent the line and, when inside a comment block, add comment prefix."
11102 (let (star single col first-line needs-close)
11103 (save-excursion
11104 (back-to-indentation)
11105 (when (< (point) start-pos)
11106 (goto-char start-pos))
11107 (cond
11108 ((looking-at "\\*[^/]")
11109 (setq star t
11110 col (current-column)))
11111 ((looking-at "/\\*")
11112 (setq star t
11113 first-line t
11114 col (1+ (current-column))))
11115 ((looking-at "//")
11116 (setq single t
11117 col (current-column)))))
11118 ;; Heuristic for whether we need to close the comment:
11119 ;; if we've got a parse error here, assume it's an unterminated
11120 ;; comment.
11121 (setq needs-close
11122 (or
11123 (eq (get-text-property (1- (point)) 'point-entered)
11124 'js2-echo-error)
11125 ;; The heuristic above doesn't work well when we're
11126 ;; creating a comment and there's another one downstream,
11127 ;; as our parser thinks this one ends at the end of the
11128 ;; next one. (You can have a /* inside a js block comment.)
11129 ;; So just close it if the next non-ws char isn't a *.
11130 (and first-line
11131 (eolp)
11132 (save-excursion
11133 (skip-chars-forward " \t\r\n")
11134 (not (eq (char-after) ?*))))))
11135 (delete-horizontal-space)
11136 (insert "\n")
11137 (cond
11138 (star
11139 (indent-to col)
11140 (insert "* ")
11141 (if (and first-line needs-close)
11142 (save-excursion
11143 (insert "\n")
11144 (indent-to col)
11145 (insert "*/"))))
11146 ((and single
11147 (save-excursion
11148 (and (zerop (forward-line 1))
11149 (looking-at "\\s-*//"))))
11150 (indent-to col)
11151 (insert "// ")))
11152 ;; Don't need to extend the comment after all.
11153 (js2-indent-line)))
11154
11155 (defun js2-beginning-of-line ()
11156 "Toggle point between bol and first non-whitespace char in line.
11157 Also moves past comment delimiters when inside comments."
11158 (interactive)
11159 (let (node)
11160 (cond
11161 ((bolp)
11162 (back-to-indentation))
11163 ((looking-at "//")
11164 (skip-chars-forward "/ \t"))
11165 ((and (eq (char-after) ?*)
11166 (setq node (js2-comment-at-point))
11167 (memq (js2-comment-node-format node) '(jsdoc block))
11168 (save-excursion
11169 (skip-chars-backward " \t")
11170 (bolp)))
11171 (skip-chars-forward "\* \t"))
11172 (t
11173 (goto-char (point-at-bol))))))
11174
11175 (defun js2-end-of-line ()
11176 "Toggle point between eol and last non-whitespace char in line."
11177 (interactive)
11178 (if (eolp)
11179 (skip-chars-backward " \t")
11180 (goto-char (point-at-eol))))
11181
11182 (defun js2-mode-wait-for-parse (callback)
11183 "Invoke CALLBACK when parsing is finished.
11184 If parsing is already finished, calls CALLBACK immediately."
11185 (if (not js2-mode-buffer-dirty-p)
11186 (funcall callback)
11187 (push callback js2-mode-pending-parse-callbacks)
11188 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11189
11190 (defun js2-mode-parse-finished ()
11191 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11192 ;; We can't let errors propagate up, since it prevents the
11193 ;; `js2-parse' method from completing normally and returning
11194 ;; the ast, which makes things mysteriously not work right.
11195 (unwind-protect
11196 (dolist (cb js2-mode-pending-parse-callbacks)
11197 (condition-case err
11198 (funcall cb)
11199 (error (message "%s" err))))
11200 (setq js2-mode-pending-parse-callbacks nil)))
11201
11202 (defun js2-mode-flag-region (from to flag)
11203 "Hide or show text from FROM to TO, according to FLAG.
11204 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11205 Returns the created overlay if FLAG is non-nil."
11206 (remove-overlays from to 'invisible 'js2-outline)
11207 (when flag
11208 (let ((o (make-overlay from to)))
11209 (overlay-put o 'invisible 'js2-outline)
11210 (overlay-put o 'isearch-open-invisible
11211 'js2-isearch-open-invisible)
11212 o)))
11213
11214 ;; Function to be set as an outline-isearch-open-invisible' property
11215 ;; to the overlay that makes the outline invisible (see
11216 ;; `js2-mode-flag-region').
11217 (defun js2-isearch-open-invisible (_overlay)
11218 ;; We rely on the fact that isearch places point on the matched text.
11219 (js2-mode-show-element))
11220
11221 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11222 "Return cons cell of bounds of folding overlay at POS.
11223 Returns nil if not found."
11224 (let ((overlays (overlays-at (or pos (point))))
11225 o)
11226 (while (and overlays
11227 (not o))
11228 (if (overlay-get (car overlays) 'invisible)
11229 (setq o (car overlays))
11230 (setq overlays (cdr overlays))))
11231 (if o
11232 (cons (overlay-start o) (overlay-end o)))))
11233
11234 (defun js2-mode-function-at-point (&optional pos)
11235 "Return the innermost function node enclosing current point.
11236 Returns nil if point is not in a function."
11237 (let ((node (js2-node-at-point pos)))
11238 (while (and node (not (js2-function-node-p node)))
11239 (setq node (js2-node-parent node)))
11240 (if (js2-function-node-p node)
11241 node)))
11242
11243 (defun js2-mode-toggle-element ()
11244 "Hide or show the foldable element at the point."
11245 (interactive)
11246 (let (comment fn pos)
11247 (save-excursion
11248 (cond
11249 ;; /* ... */ comment?
11250 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11251 (if (js2-mode-invisible-overlay-bounds
11252 (setq pos (+ 3 (js2-node-abs-pos comment))))
11253 (progn
11254 (goto-char pos)
11255 (js2-mode-show-element))
11256 (js2-mode-hide-element)))
11257 ;; //-comment?
11258 ((save-excursion
11259 (back-to-indentation)
11260 (looking-at js2-mode-//-comment-re))
11261 (js2-mode-toggle-//-comment))
11262 ;; function?
11263 ((setq fn (js2-mode-function-at-point))
11264 (setq pos (and (js2-function-node-body fn)
11265 (js2-node-abs-pos (js2-function-node-body fn))))
11266 (goto-char (1+ pos))
11267 (if (js2-mode-invisible-overlay-bounds)
11268 (js2-mode-show-element)
11269 (js2-mode-hide-element)))
11270 (t
11271 (message "Nothing at point to hide or show"))))))
11272
11273 (defun js2-mode-hide-element ()
11274 "Fold/hide contents of a block, showing ellipses.
11275 Show the hidden text with \\[js2-mode-show-element]."
11276 (interactive)
11277 (if js2-mode-buffer-dirty-p
11278 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11279 (let (node body beg end)
11280 (cond
11281 ((js2-mode-invisible-overlay-bounds)
11282 (message "already hidden"))
11283 (t
11284 (setq node (js2-node-at-point))
11285 (cond
11286 ((js2-block-comment-p node)
11287 (js2-mode-hide-comment node))
11288 (t
11289 (while (and node (not (js2-function-node-p node)))
11290 (setq node (js2-node-parent node)))
11291 (if (and node
11292 (setq body (js2-function-node-body node)))
11293 (progn
11294 (setq beg (js2-node-abs-pos body)
11295 end (+ beg (js2-node-len body)))
11296 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11297 (message "No collapsable element found at point"))))))))
11298
11299 (defun js2-mode-show-element ()
11300 "Show the hidden element at current point."
11301 (interactive)
11302 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11303 (if bounds
11304 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11305 (message "Nothing to un-hide"))))
11306
11307 (defun js2-mode-show-all ()
11308 "Show all of the text in the buffer."
11309 (interactive)
11310 (js2-mode-flag-region (point-min) (point-max) nil))
11311
11312 (defun js2-mode-toggle-hide-functions ()
11313 (interactive)
11314 (if js2-mode-functions-hidden
11315 (js2-mode-show-functions)
11316 (js2-mode-hide-functions)))
11317
11318 (defun js2-mode-hide-functions ()
11319 "Hides all non-nested function bodies in the buffer.
11320 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11321 to open an individual entry."
11322 (interactive)
11323 (if js2-mode-buffer-dirty-p
11324 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11325 (if (null js2-mode-ast)
11326 (message "Oops - parsing failed")
11327 (setq js2-mode-functions-hidden t)
11328 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11329
11330 (defun js2-mode-function-hider (n endp)
11331 (when (not endp)
11332 (let ((tt (js2-node-type n))
11333 body beg end)
11334 (cond
11335 ((and (= tt js2-FUNCTION)
11336 (setq body (js2-function-node-body n)))
11337 (setq beg (js2-node-abs-pos body)
11338 end (+ beg (js2-node-len body)))
11339 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11340 nil) ; don't process children of function
11341 (t
11342 t))))) ; keep processing other AST nodes
11343
11344 (defun js2-mode-show-functions ()
11345 "Un-hide any folded function bodies in the buffer."
11346 (interactive)
11347 (setq js2-mode-functions-hidden nil)
11348 (save-excursion
11349 (goto-char (point-min))
11350 (while (/= (goto-char (next-overlay-change (point)))
11351 (point-max))
11352 (dolist (o (overlays-at (point)))
11353 (when (and (overlay-get o 'invisible)
11354 (not (overlay-get o 'comment)))
11355 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11356
11357 (defun js2-mode-hide-comment (n)
11358 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11359 3 ; /**
11360 2)) ; /*
11361 (beg (+ (js2-node-abs-pos n) head))
11362 (end (- (+ beg (js2-node-len n)) head 2))
11363 (o (js2-mode-flag-region beg end 'hide)))
11364 (overlay-put o 'comment t)))
11365
11366 (defun js2-mode-toggle-hide-comments ()
11367 "Folds all block comments in the buffer.
11368 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11369 to open an individual entry."
11370 (interactive)
11371 (if js2-mode-comments-hidden
11372 (js2-mode-show-comments)
11373 (js2-mode-hide-comments)))
11374
11375 (defun js2-mode-hide-comments ()
11376 (interactive)
11377 (if js2-mode-buffer-dirty-p
11378 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11379 (if (null js2-mode-ast)
11380 (message "Oops - parsing failed")
11381 (setq js2-mode-comments-hidden t)
11382 (dolist (n (js2-ast-root-comments js2-mode-ast))
11383 (when (js2-block-comment-p n)
11384 (js2-mode-hide-comment n)))
11385 (js2-mode-hide-//-comments)))
11386
11387 (defun js2-mode-extend-//-comment (direction)
11388 "Find start or end of a block of similar //-comment lines.
11389 DIRECTION is -1 to look back, 1 to look forward.
11390 INDENT is the indentation level to match.
11391 Returns the end-of-line position of the furthest adjacent
11392 //-comment line with the same indentation as the current line.
11393 If there is no such matching line, returns current end of line."
11394 (let ((pos (point-at-eol))
11395 (indent (current-indentation)))
11396 (save-excursion
11397 (while (and (zerop (forward-line direction))
11398 (looking-at js2-mode-//-comment-re)
11399 (eq indent (length (match-string 1))))
11400 (setq pos (point-at-eol)))
11401 pos)))
11402
11403 (defun js2-mode-hide-//-comments ()
11404 "Fold adjacent 1-line comments, showing only snippet of first one."
11405 (let (beg end)
11406 (save-excursion
11407 (goto-char (point-min))
11408 (while (re-search-forward js2-mode-//-comment-re nil t)
11409 (setq beg (point)
11410 end (js2-mode-extend-//-comment 1))
11411 (unless (eq beg end)
11412 (overlay-put (js2-mode-flag-region beg end 'hide)
11413 'comment t))
11414 (goto-char end)
11415 (forward-char 1)))))
11416
11417 (defun js2-mode-toggle-//-comment ()
11418 "Fold or un-fold any multi-line //-comment at point.
11419 Caller should have determined that this line starts with a //-comment."
11420 (let* ((beg (point-at-eol))
11421 (end beg))
11422 (save-excursion
11423 (goto-char end)
11424 (if (js2-mode-invisible-overlay-bounds)
11425 (js2-mode-show-element)
11426 ;; else hide the comment
11427 (setq beg (js2-mode-extend-//-comment -1)
11428 end (js2-mode-extend-//-comment 1))
11429 (unless (eq beg end)
11430 (overlay-put (js2-mode-flag-region beg end 'hide)
11431 'comment t))))))
11432
11433 (defun js2-mode-show-comments ()
11434 "Un-hide any hidden comments, leaving other hidden elements alone."
11435 (interactive)
11436 (setq js2-mode-comments-hidden nil)
11437 (save-excursion
11438 (goto-char (point-min))
11439 (while (/= (goto-char (next-overlay-change (point)))
11440 (point-max))
11441 (dolist (o (overlays-at (point)))
11442 (when (overlay-get o 'comment)
11443 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11444
11445 (defun js2-mode-display-warnings-and-errors ()
11446 "Turn on display of warnings and errors."
11447 (interactive)
11448 (setq js2-mode-show-parse-errors t
11449 js2-mode-show-strict-warnings t)
11450 (js2-reparse 'force))
11451
11452 (defun js2-mode-hide-warnings-and-errors ()
11453 "Turn off display of warnings and errors."
11454 (interactive)
11455 (setq js2-mode-show-parse-errors nil
11456 js2-mode-show-strict-warnings nil)
11457 (js2-reparse 'force))
11458
11459 (defun js2-mode-toggle-warnings-and-errors ()
11460 "Toggle the display of warnings and errors.
11461 Some users don't like having warnings/errors reported while they type."
11462 (interactive)
11463 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11464 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11465 (if (called-interactively-p 'any)
11466 (message "warnings and errors %s"
11467 (if js2-mode-show-parse-errors
11468 "enabled"
11469 "disabled")))
11470 (js2-reparse 'force))
11471
11472 (defun js2-mode-customize ()
11473 (interactive)
11474 (customize-group 'js2-mode))
11475
11476 (defun js2-mode-forward-sexp (&optional arg)
11477 "Move forward across one statement or balanced expression.
11478 With ARG, do it that many times. Negative arg -N means
11479 move backward across N balanced expressions."
11480 (interactive "p")
11481 (setq arg (or arg 1))
11482 (save-restriction
11483 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11484 (js2-reparse)
11485 (let (forward-sexp-function
11486 node (start (point)) pos lp rp child)
11487 (cond
11488 ;; backward-sexp
11489 ;; could probably make this better for some cases:
11490 ;; - if in statement block (e.g. function body), go to parent
11491 ;; - infix exprs like (foo in bar) - maybe go to beginning
11492 ;; of infix expr if in the right-side expression?
11493 ((and arg (minusp arg))
11494 (dotimes (_ (- arg))
11495 (js2-backward-sws)
11496 (forward-char -1) ; Enter the node we backed up to.
11497 (when (setq node (js2-node-at-point (point) t))
11498 (setq pos (js2-node-abs-pos node))
11499 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11500 (setq lp (car parens)
11501 rp (cdr parens)))
11502 (when (and lp (> start lp))
11503 (if (and rp (<= start rp))
11504 ;; Between parens, check if there's a child node we can jump.
11505 (when (setq child (js2-node-closest-child node (point) lp t))
11506 (setq pos (js2-node-abs-pos child)))
11507 ;; Before both parens.
11508 (setq pos lp)))
11509 (let ((state (parse-partial-sexp start pos)))
11510 (goto-char (if (not (zerop (car state)))
11511 ;; Stumble at the unbalanced paren if < 0, or
11512 ;; jump a bit further if > 0.
11513 (scan-sexps start -1)
11514 pos))))
11515 (unless pos (goto-char (point-min)))))
11516 (t
11517 ;; forward-sexp
11518 (dotimes (_ arg)
11519 (js2-forward-sws)
11520 (when (setq node (js2-node-at-point (point) t))
11521 (setq pos (js2-node-abs-pos node))
11522 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11523 (setq lp (car parens)
11524 rp (cdr parens)))
11525 (or
11526 (when (and rp (<= start rp))
11527 (if (> start lp)
11528 (when (setq child (js2-node-closest-child node (point) rp))
11529 (setq pos (js2-node-abs-end child)))
11530 (setq pos (1+ rp))))
11531 ;; No parens or child nodes, looks for the end of the curren node.
11532 (incf pos (js2-node-len
11533 (if (js2-expr-stmt-node-p (js2-node-parent node))
11534 ;; Stop after the semicolon.
11535 (js2-node-parent node)
11536 node))))
11537 (let ((state (save-excursion (parse-partial-sexp start pos))))
11538 (goto-char (if (not (zerop (car state)))
11539 (scan-sexps start 1)
11540 pos))))
11541 (unless pos (goto-char (point-max)))))))))
11542
11543 (defun js2-mode-forward-sexp-parens (node abs-pos)
11544 "Return a cons cell with positions of main parens in NODE."
11545 (cond
11546 ((or (js2-array-node-p node)
11547 (js2-object-node-p node)
11548 (js2-comp-node-p node)
11549 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11550 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11551 ((js2-paren-expr-node-p node)
11552 (let ((lp (js2-node-lp node))
11553 (rp (js2-node-rp node)))
11554 (cons (when lp (+ abs-pos lp))
11555 (when rp (+ abs-pos rp)))))))
11556
11557 (defun js2-node-closest-child (parent point limit &optional before)
11558 (let* ((parent-pos (js2-node-abs-pos parent))
11559 (rpoint (- point parent-pos))
11560 (rlimit (- limit parent-pos))
11561 (min (min rpoint rlimit))
11562 (max (max rpoint rlimit))
11563 found)
11564 (catch 'done
11565 (js2-visit-ast
11566 parent
11567 (lambda (node _end-p)
11568 (if (eq node parent)
11569 t
11570 (let ((pos (js2-node-pos node)) ;; Both relative values.
11571 (end (+ (js2-node-pos node) (js2-node-len node))))
11572 (when (and (>= pos min) (<= end max)
11573 (if before (< pos rpoint) (> end rpoint)))
11574 (setq found node))
11575 (when (> end rpoint)
11576 (throw 'done nil)))
11577 nil))))
11578 found))
11579
11580 (defun js2-errors ()
11581 "Return a list of errors found."
11582 (and js2-mode-ast
11583 (js2-ast-root-errors js2-mode-ast)))
11584
11585 (defun js2-warnings ()
11586 "Return a list of warnings found."
11587 (and js2-mode-ast
11588 (js2-ast-root-warnings js2-mode-ast)))
11589
11590 (defun js2-have-errors-p ()
11591 "Return non-nil if any parse errors or warnings were found."
11592 (or (js2-errors) (js2-warnings)))
11593
11594 (defun js2-errors-and-warnings ()
11595 "Return a copy of the concatenated errors and warnings lists.
11596 They are appended: first the errors, then the warnings.
11597 Entries are of the form (MSG BEG END)."
11598 (when js2-mode-ast
11599 (append (js2-ast-root-errors js2-mode-ast)
11600 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11601
11602 (defun js2-next-error (&optional arg reset)
11603 "Move to next parse error.
11604 Typically invoked via \\[next-error].
11605 ARG is the number of errors, forward or backward, to move.
11606 RESET means start over from the beginning."
11607 (interactive "p")
11608 (if (not (or (js2-errors) (js2-warnings)))
11609 (message "No errors")
11610 (when reset
11611 (goto-char (point-min)))
11612 (let* ((errs (js2-errors-and-warnings))
11613 (continue t)
11614 (start (point))
11615 (count (or arg 1))
11616 (backward (minusp count))
11617 (sorter (if backward '> '<))
11618 (stopper (if backward '< '>))
11619 (count (abs count))
11620 all-errs err)
11621 ;; Sort by start position.
11622 (setq errs (sort errs (lambda (e1 e2)
11623 (funcall sorter (second e1) (second e2))))
11624 all-errs errs)
11625 ;; Find nth error with pos > start.
11626 (while (and errs continue)
11627 (when (funcall stopper (cadar errs) start)
11628 (setq err (car errs))
11629 (if (zerop (decf count))
11630 (setq continue nil)))
11631 (setq errs (cdr errs)))
11632 ;; Clear for `js2-echo-error'.
11633 (message nil)
11634 (if err
11635 (goto-char (second err))
11636 ;; Wrap around to first error.
11637 (goto-char (second (car all-errs)))
11638 ;; If we were already on it, echo msg again.
11639 (if (= (point) start)
11640 (js2-echo-error (point) (point)))))))
11641
11642 (defun js2-down-mouse-3 ()
11643 "Make right-click move the point to the click location.
11644 This makes right-click context menu operations a bit more intuitive.
11645 The point will not move if the region is active, however, to avoid
11646 destroying the region selection."
11647 (interactive)
11648 (when (and js2-move-point-on-right-click
11649 (not mark-active))
11650 (let ((e last-input-event))
11651 (ignore-errors
11652 (goto-char (cadadr e))))))
11653
11654 (defun js2-mode-create-imenu-index ()
11655 "Return an alist for `imenu--index-alist'."
11656 ;; This is built up in `js2-parse-record-imenu' during parsing.
11657 (when js2-mode-ast
11658 ;; if we have an ast but no recorder, they're requesting a rescan
11659 (unless js2-imenu-recorder
11660 (js2-reparse 'force))
11661 (prog1
11662 (js2-build-imenu-index)
11663 (setq js2-imenu-recorder nil
11664 js2-imenu-function-map nil))))
11665
11666 (defun js2-mode-find-tag ()
11667 "Replacement for `find-tag-default'.
11668 `find-tag-default' returns a ridiculous answer inside comments."
11669 (let (beg end)
11670 (js2-with-underscore-as-word-syntax
11671 (save-excursion
11672 (if (and (not (looking-at "[[:alnum:]_$]"))
11673 (looking-back "[[:alnum:]_$]"))
11674 (setq beg (progn (forward-word -1) (point))
11675 end (progn (forward-word 1) (point)))
11676 (setq beg (progn (forward-word 1) (point))
11677 end (progn (forward-word -1) (point))))
11678 (replace-regexp-in-string
11679 "[\"']" ""
11680 (buffer-substring-no-properties beg end))))))
11681
11682 (defun js2-mode-forward-sibling ()
11683 "Move to the end of the sibling following point in parent.
11684 Returns non-nil if successful, or nil if there was no following sibling."
11685 (let* ((node (js2-node-at-point))
11686 (parent (js2-mode-find-enclosing-fn node))
11687 sib)
11688 (when (setq sib (js2-node-find-child-after (point) parent))
11689 (goto-char (+ (js2-node-abs-pos sib)
11690 (js2-node-len sib))))))
11691
11692 (defun js2-mode-backward-sibling ()
11693 "Move to the beginning of the sibling node preceding point in parent.
11694 Parent is defined as the enclosing script or function."
11695 (let* ((node (js2-node-at-point))
11696 (parent (js2-mode-find-enclosing-fn node))
11697 sib)
11698 (when (setq sib (js2-node-find-child-before (point) parent))
11699 (goto-char (js2-node-abs-pos sib)))))
11700
11701 (defun js2-beginning-of-defun (&optional arg)
11702 "Go to line on which current function starts, and return t on success.
11703 If we're not in a function or already at the beginning of one, go
11704 to beginning of previous script-level element.
11705 With ARG N, do that N times. If N is negative, move forward."
11706 (setq arg (or arg 1))
11707 (if (plusp arg)
11708 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11709 (when (cond
11710 ((js2-function-node-p parent)
11711 (goto-char (js2-node-abs-pos parent)))
11712 (t
11713 (js2-mode-backward-sibling)))
11714 (if (> arg 1)
11715 (js2-beginning-of-defun (1- arg))
11716 t)))
11717 (when (js2-end-of-defun)
11718 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11719
11720 (defun js2-end-of-defun ()
11721 "Go to the char after the last position of the current function
11722 or script-level element."
11723 (let* ((node (js2-node-at-point))
11724 (parent (or (and (js2-function-node-p node) node)
11725 (js2-node-parent-script-or-fn node)))
11726 script)
11727 (unless (js2-function-node-p parent)
11728 ;; Use current script-level node, or, if none, the next one.
11729 (setq script (or parent node)
11730 parent (js2-node-find-child-before (point) script))
11731 (when (or (null parent)
11732 (>= (point) (+ (js2-node-abs-pos parent)
11733 (js2-node-len parent))))
11734 (setq parent (js2-node-find-child-after (point) script))))
11735 (when parent
11736 (goto-char (+ (js2-node-abs-pos parent)
11737 (js2-node-len parent))))))
11738
11739 (defun js2-mark-defun (&optional allow-extend)
11740 "Put mark at end of this function, point at beginning.
11741 The function marked is the one that contains point.
11742
11743 Interactively, if this command is repeated,
11744 or (in Transient Mark mode) if the mark is active,
11745 it marks the next defun after the ones already marked."
11746 (interactive "p")
11747 (let (extended)
11748 (when (and allow-extend
11749 (or (and (eq last-command this-command) (mark t))
11750 (and transient-mark-mode mark-active)))
11751 (let ((sib (save-excursion
11752 (goto-char (mark))
11753 (if (js2-mode-forward-sibling)
11754 (point)))))
11755 (if sib
11756 (progn
11757 (set-mark sib)
11758 (setq extended t))
11759 ;; no more siblings - try extending to enclosing node
11760 (goto-char (mark t)))))
11761 (when (not extended)
11762 (let ((node (js2-node-at-point (point) t)) ; skip comments
11763 ast fn stmt parent beg end)
11764 (when (js2-ast-root-p node)
11765 (setq ast node
11766 node (or (js2-node-find-child-after (point) node)
11767 (js2-node-find-child-before (point) node))))
11768 ;; only mark whole buffer if we can't find any children
11769 (if (null node)
11770 (setq node ast))
11771 (if (js2-function-node-p node)
11772 (setq parent node)
11773 (setq fn (js2-mode-find-enclosing-fn node)
11774 stmt (if (or (null fn)
11775 (js2-ast-root-p fn))
11776 (js2-mode-find-first-stmt node))
11777 parent (or stmt fn)))
11778 (setq beg (js2-node-abs-pos parent)
11779 end (+ beg (js2-node-len parent)))
11780 (push-mark beg)
11781 (goto-char end)
11782 (exchange-point-and-mark)))))
11783
11784 (defun js2-narrow-to-defun ()
11785 "Narrow to the function enclosing point."
11786 (interactive)
11787 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11788 (fn (if (js2-script-node-p node)
11789 node
11790 (js2-mode-find-enclosing-fn node)))
11791 (beg (js2-node-abs-pos fn)))
11792 (unless (js2-ast-root-p fn)
11793 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11794
11795 (provide 'js2-mode)
11796
11797 ;;; js2-mode.el ends here