]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
623c3fe380d6af9809da6a54fa92fa6a2b690877
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
10 ;; Version: 20141118
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28
29 ;;; Commentary:
30
31 ;; This JavaScript editing mode supports:
32
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
41 ;; - code folding:
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
47
48 ;; Installation:
49 ;;
50 ;; To install it as your major mode for JavaScript editing:
51
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
53
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
56
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
58
59 ;; You may also want to hook it in for shell scripts running via node.js:
60
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
62
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
65
66 ;; Notes:
67
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
71
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
76
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
81
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
84 ;; unmaintained.
85
86 ;;; Code:
87
88 (eval-when-compile
89 (require 'cl))
90
91 (require 'imenu)
92 (require 'cc-cmds) ; for `c-fill-paragraph'
93
94 (eval-and-compile
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
97
98 (defvar electric-layout-rules)
99
100 ;;; Externs (variables presumed to be defined by the host system)
101
102 (defvar js2-ecma-262-externs
103 (mapcar 'symbol-name
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
111
112 (defvar js2-browser-externs
113 (mapcar 'symbol-name
114 '(;; DOM level 1
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
120
121 ;; DOM level 2
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
143
144 ;; DOM level 3
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
148 UserDataHandler
149
150 ;; Window
151 window alert confirm document java navigator prompt screen
152 self top
153
154 ;; W3C CSS
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
163
164 ;; W3C Event
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
167
168 ;; W3C Range
169 DocumentRange Range RangeException
170
171 ;; W3C XML
172 XPathResult XMLHttpRequest
173
174 ;; console object. Provided by at least Chrome and Firefox.
175 console))
176 "Browser externs.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
179
180 (defvar js2-rhino-externs
181 (mapcar 'symbol-name
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
189
190 (defvar js2-node-externs
191 (mapcar 'symbol-name
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
194 "Node.js externs.
195 Set `js2-include-node-externs' to t to include them.")
196
197 (defvar js2-typed-array-externs
198 (mapcar 'symbol-name
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
205
206 (defvar js2-harmony-externs
207 (mapcar 'symbol-name
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
211
212 ;;; Variables
213
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
219
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
226 :group 'js2-mode
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
231
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
234
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
237 :group 'languages)
238
239 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
240 (numberp c-basic-offset))
241 c-basic-offset
242 4)
243 "Number of spaces to indent nested statements.
244 Similar to `c-basic-offset'."
245 :group 'js2-mode
246 :type 'integer)
247 (js2-mark-safe-local 'js2-basic-offset 'integerp)
248
249 (defcustom js2-bounce-indent-p nil
250 "Non-nil to have indent-line function choose among alternatives.
251 If nil, the indent-line function will indent to a predetermined column
252 based on heuristic guessing. If non-nil, then if the current line is
253 already indented to that predetermined column, indenting will choose
254 another likely column and indent to that spot. Repeated invocation of
255 the indent-line function will cycle among the computed alternatives.
256 See the function `js2-bounce-indent' for details. When it is non-nil,
257 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
258 :type 'boolean
259 :group 'js2-mode)
260
261 (defcustom js2-pretty-multiline-declarations t
262 "Non-nil to line up multiline declarations vertically:
263
264 var a = 10,
265 b = 20,
266 c = 30;
267
268 If the value is not `all', and the first assigned value in
269 declaration is a function/array/object literal spanning several
270 lines, it won't be indented additionally:
271
272 var o = { var bar = 2,
273 foo: 3 vs. o = {
274 }, foo: 3
275 bar = 2; };"
276 :group 'js2-mode
277 :type 'symbol)
278 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
279
280 (defcustom js2-indent-switch-body nil
281 "When nil, case labels are indented on the same level as the
282 containing switch statement. Otherwise, all lines inside
283 switch statement body are indented one additional level."
284 :type 'boolean
285 :group 'js2-mode)
286 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
287
288 (defcustom js2-idle-timer-delay 0.2
289 "Delay in secs before re-parsing after user makes changes.
290 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
291 :type 'number
292 :group 'js2-mode)
293 (make-variable-buffer-local 'js2-idle-timer-delay)
294
295 (defcustom js2-dynamic-idle-timer-adjust 0
296 "Positive to adjust `js2-idle-timer-delay' based on file size.
297 The idea is that for short files, parsing is faster so we can be
298 more responsive to user edits without interfering with editing.
299 The buffer length in characters (typically bytes) is divided by
300 this value and used to multiply `js2-idle-timer-delay' for the
301 buffer. For example, a 21k file and 10k adjust yields 21k/10k
302 == 2, so js2-idle-timer-delay is multiplied by 2.
303 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
304 `js2-idle-timer-delay' is not dependent on the file size."
305 :type 'number
306 :group 'js2-mode)
307
308 (defcustom js2-concat-multiline-strings t
309 "When non-nil, `js2-line-break' in mid-string will make it a
310 string concatenation. When `eol', the '+' will be inserted at the
311 end of the line, otherwise, at the beginning of the next line."
312 :type '(choice (const t) (const eol) (const nil))
313 :group 'js2-mode)
314
315 (defcustom js2-mode-show-parse-errors t
316 "True to highlight parse errors."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-mode-show-strict-warnings t
321 "Non-nil to emit Ecma strict-mode warnings.
322 Some of the warnings can be individually disabled by other flags,
323 even if this flag is non-nil."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-strict-trailing-comma-warning t
328 "Non-nil to warn about trailing commas in array literals.
329 Ecma-262-5.1 allows them, but older versions of IE raise an error."
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
336 depending on it."
337 :type 'boolean
338 :group 'js2-mode)
339
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
354 :type 'boolean
355 :group 'js2-mode)
356
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-var-redeclaration-warning t
366 "Non-nil to warn about redeclaring variables in a script or function."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-strict-var-hides-function-arg-warning t
371 "Non-nil to warn about a var decl hiding a function argument."
372 :type 'boolean
373 :group 'js2-mode)
374
375 (defcustom js2-skip-preprocessor-directives nil
376 "Non-nil to treat lines beginning with # as comments.
377 Useful for viewing Mozilla JavaScript source code."
378 :type 'boolean
379 :group 'js2-mode)
380
381 (defcustom js2-language-version 200
382 "Configures what JavaScript language version to recognize.
383 Currently versions 150, 160, 170, 180 and 200 are supported,
384 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
385 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
386 yield, and Array comprehensions, and 1.8 adds function closures."
387 :type 'integer
388 :group 'js2-mode)
389
390 (defcustom js2-allow-keywords-as-property-names t
391 "If non-nil, you can use JavaScript keywords as object property names.
392 Examples:
393
394 var foo = {int: 5, while: 6, continue: 7};
395 foo.return = 8;
396
397 Ecma-262 5.1 allows this syntax, but some engines still don't."
398 :type 'boolean
399 :group 'js2-mode)
400
401 (defcustom js2-instanceof-has-side-effects nil
402 "If non-nil, treats the instanceof operator as having side effects.
403 This is useful for xulrunner apps."
404 :type 'boolean
405 :group 'js2-mode)
406
407 (defcustom js2-move-point-on-right-click t
408 "Non-nil to move insertion point when you right-click.
409 This makes right-click context menu behavior a bit more intuitive,
410 since menu operations generally apply to the point. The exception
411 is if there is a region selection, in which case the point does -not-
412 move, so cut/copy/paste can work properly.
413
414 Note that IntelliJ moves the point, and Eclipse leaves it alone,
415 so this behavior is customizable."
416 :group 'js2-mode
417 :type 'boolean)
418
419 (defcustom js2-allow-rhino-new-expr-initializer t
420 "Non-nil to support a Rhino's experimental syntactic construct.
421
422 Rhino supports the ability to follow a `new' expression with an object
423 literal, which is used to set additional properties on the new object
424 after calling its constructor. Syntax:
425
426 new <expr> [ ( arglist ) ] [initializer]
427
428 Hence, this expression:
429
430 new Object {a: 1, b: 2}
431
432 results in an Object with properties a=1 and b=2. This syntax is
433 apparently not configurable in Rhino - it's currently always enabled,
434 as of Rhino version 1.7R2."
435 :type 'boolean
436 :group 'js2-mode)
437
438 (defcustom js2-allow-member-expr-as-function-name nil
439 "Non-nil to support experimental Rhino syntax for function names.
440
441 Rhino supports an experimental syntax configured via the Rhino Context
442 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
443
444 function <member-expr> ( [ arg-list ] ) { <body> }
445
446 Where member-expr is a non-parenthesized 'member expression', which
447 is anything at the grammar level of a new-expression or lower, meaning
448 any expression that does not involve infix or unary operators.
449
450 When <member-expr> is not a simple identifier, then it is syntactic
451 sugar for assigning the anonymous function to the <member-expr>. Hence,
452 this code:
453
454 function a.b().c[2] (x, y) { ... }
455
456 is rewritten as:
457
458 a.b().c[2] = function(x, y) {...}
459
460 which doesn't seem particularly useful, but Rhino permits it."
461 :type 'boolean
462 :group 'js2-mode)
463
464 ;; scanner variables
465
466 (defmacro js2-deflocal (name value &optional comment)
467 "Define a buffer-local variable NAME with VALUE and COMMENT."
468 `(progn
469 (defvar ,name ,value ,comment)
470 (make-variable-buffer-local ',name)))
471
472 (defvar js2-EOF_CHAR -1
473 "Represents end of stream. Distinct from js2-EOF token type.")
474
475 ;; I originally used symbols to represent tokens, but Rhino uses
476 ;; ints and then sets various flag bits in them, so ints it is.
477 ;; The upshot is that we need a `js2-' prefix in front of each name.
478 (defvar js2-ERROR -1)
479 (defvar js2-EOF 0)
480 (defvar js2-EOL 1)
481 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
482 (defvar js2-LEAVEWITH 3)
483 (defvar js2-RETURN 4)
484 (defvar js2-GOTO 5)
485 (defvar js2-IFEQ 6)
486 (defvar js2-IFNE 7)
487 (defvar js2-SETNAME 8)
488 (defvar js2-BITOR 9)
489 (defvar js2-BITXOR 10)
490 (defvar js2-BITAND 11)
491 (defvar js2-EQ 12)
492 (defvar js2-NE 13)
493 (defvar js2-LT 14)
494 (defvar js2-LE 15)
495 (defvar js2-GT 16)
496 (defvar js2-GE 17)
497 (defvar js2-LSH 18)
498 (defvar js2-RSH 19)
499 (defvar js2-URSH 20)
500 (defvar js2-ADD 21) ; infix plus
501 (defvar js2-SUB 22) ; infix minus
502 (defvar js2-MUL 23)
503 (defvar js2-DIV 24)
504 (defvar js2-MOD 25)
505 (defvar js2-NOT 26)
506 (defvar js2-BITNOT 27)
507 (defvar js2-POS 28) ; unary plus
508 (defvar js2-NEG 29) ; unary minus
509 (defvar js2-NEW 30)
510 (defvar js2-DELPROP 31)
511 (defvar js2-TYPEOF 32)
512 (defvar js2-GETPROP 33)
513 (defvar js2-GETPROPNOWARN 34)
514 (defvar js2-SETPROP 35)
515 (defvar js2-GETELEM 36)
516 (defvar js2-SETELEM 37)
517 (defvar js2-CALL 38)
518 (defvar js2-NAME 39) ; an identifier
519 (defvar js2-NUMBER 40)
520 (defvar js2-STRING 41)
521 (defvar js2-NULL 42)
522 (defvar js2-THIS 43)
523 (defvar js2-FALSE 44)
524 (defvar js2-TRUE 45)
525 (defvar js2-SHEQ 46) ; shallow equality (===)
526 (defvar js2-SHNE 47) ; shallow inequality (!==)
527 (defvar js2-REGEXP 48)
528 (defvar js2-BINDNAME 49)
529 (defvar js2-THROW 50)
530 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
531 (defvar js2-IN 52)
532 (defvar js2-INSTANCEOF 53)
533 (defvar js2-LOCAL_LOAD 54)
534 (defvar js2-GETVAR 55)
535 (defvar js2-SETVAR 56)
536 (defvar js2-CATCH_SCOPE 57)
537 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
538 (defvar js2-ENUM_INIT_VALUES 59)
539 (defvar js2-ENUM_INIT_ARRAY 60)
540 (defvar js2-ENUM_NEXT 61)
541 (defvar js2-ENUM_ID 62)
542 (defvar js2-THISFN 63)
543 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
544 (defvar js2-ARRAYLIT 65) ; array literal
545 (defvar js2-OBJECTLIT 66) ; object literal
546 (defvar js2-GET_REF 67) ; *reference
547 (defvar js2-SET_REF 68) ; *reference = something
548 (defvar js2-DEL_REF 69) ; delete reference
549 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
550 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
551 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
552
553 ;; XML support
554 (defvar js2-DEFAULTNAMESPACE 73)
555 (defvar js2-ESCXMLATTR 74)
556 (defvar js2-ESCXMLTEXT 75)
557 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
558 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
559 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
560 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
561
562 (defvar js2-first-bytecode js2-ENTERWITH)
563 (defvar js2-last-bytecode js2-REF_NS_NAME)
564
565 (defvar js2-TRY 80)
566 (defvar js2-SEMI 81) ; semicolon
567 (defvar js2-LB 82) ; left and right brackets
568 (defvar js2-RB 83)
569 (defvar js2-LC 84) ; left and right curly-braces
570 (defvar js2-RC 85)
571 (defvar js2-LP 86) ; left and right parens
572 (defvar js2-RP 87)
573 (defvar js2-COMMA 88) ; comma operator
574
575 (defvar js2-ASSIGN 89) ; simple assignment (=)
576 (defvar js2-ASSIGN_BITOR 90) ; |=
577 (defvar js2-ASSIGN_BITXOR 91) ; ^=
578 (defvar js2-ASSIGN_BITAND 92) ; &=
579 (defvar js2-ASSIGN_LSH 93) ; <<=
580 (defvar js2-ASSIGN_RSH 94) ; >>=
581 (defvar js2-ASSIGN_URSH 95) ; >>>=
582 (defvar js2-ASSIGN_ADD 96) ; +=
583 (defvar js2-ASSIGN_SUB 97) ; -=
584 (defvar js2-ASSIGN_MUL 98) ; *=
585 (defvar js2-ASSIGN_DIV 99) ; /=
586 (defvar js2-ASSIGN_MOD 100) ; %=
587
588 (defvar js2-first-assign js2-ASSIGN)
589 (defvar js2-last-assign js2-ASSIGN_MOD)
590
591 (defvar js2-HOOK 101) ; conditional (?:)
592 (defvar js2-COLON 102)
593 (defvar js2-OR 103) ; logical or (||)
594 (defvar js2-AND 104) ; logical and (&&)
595 (defvar js2-INC 105) ; increment/decrement (++ --)
596 (defvar js2-DEC 106)
597 (defvar js2-DOT 107) ; member operator (.)
598 (defvar js2-FUNCTION 108) ; function keyword
599 (defvar js2-EXPORT 109) ; export keyword
600 (defvar js2-IMPORT 110) ; import keyword
601 (defvar js2-IF 111) ; if keyword
602 (defvar js2-ELSE 112) ; else keyword
603 (defvar js2-SWITCH 113) ; switch keyword
604 (defvar js2-CASE 114) ; case keyword
605 (defvar js2-DEFAULT 115) ; default keyword
606 (defvar js2-WHILE 116) ; while keyword
607 (defvar js2-DO 117) ; do keyword
608 (defvar js2-FOR 118) ; for keyword
609 (defvar js2-BREAK 119) ; break keyword
610 (defvar js2-CONTINUE 120) ; continue keyword
611 (defvar js2-VAR 121) ; var keyword
612 (defvar js2-WITH 122) ; with keyword
613 (defvar js2-CATCH 123) ; catch keyword
614 (defvar js2-FINALLY 124) ; finally keyword
615 (defvar js2-VOID 125) ; void keyword
616 (defvar js2-RESERVED 126) ; reserved keywords
617
618 (defvar js2-EMPTY 127)
619
620 ;; Types used for the parse tree - never returned by scanner.
621
622 (defvar js2-BLOCK 128) ; statement block
623 (defvar js2-LABEL 129) ; label
624 (defvar js2-TARGET 130)
625 (defvar js2-LOOP 131)
626 (defvar js2-EXPR_VOID 132) ; expression statement in functions
627 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
628 (defvar js2-JSR 134)
629 (defvar js2-SCRIPT 135) ; top-level node for entire script
630 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
631 (defvar js2-USE_STACK 137)
632 (defvar js2-SETPROP_OP 138) ; x.y op= something
633 (defvar js2-SETELEM_OP 139) ; x[y] op= something
634 (defvar js2-LOCAL_BLOCK 140)
635 (defvar js2-SET_REF_OP 141) ; *reference op= something
636
637 ;; For XML support:
638 (defvar js2-DOTDOT 142) ; member operator (..)
639 (defvar js2-COLONCOLON 143) ; namespace::name
640 (defvar js2-XML 144) ; XML type
641 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
642 (defvar js2-XMLATTR 146) ; @
643 (defvar js2-XMLEND 147)
644
645 ;; Optimizer-only tokens
646 (defvar js2-TO_OBJECT 148)
647 (defvar js2-TO_DOUBLE 149)
648
649 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
650 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
651 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
652 (defvar js2-CONST 153)
653 (defvar js2-SETCONST 154)
654 (defvar js2-SETCONSTVAR 155)
655 (defvar js2-ARRAYCOMP 156)
656 (defvar js2-LETEXPR 157)
657 (defvar js2-WITHEXPR 158)
658 (defvar js2-DEBUGGER 159)
659
660 (defvar js2-COMMENT 160)
661 (defvar js2-TRIPLEDOT 161) ; for rest parameter
662 (defvar js2-ARROW 162) ; function arrow (=>)
663 (defvar js2-CLASS 163)
664 (defvar js2-EXTENDS 164)
665 (defvar js2-STATIC 165)
666 (defvar js2-SUPER 166)
667 (defvar js2-TEMPLATE_STRING 167)
668
669 (defconst js2-num-tokens (1+ js2-TEMPLATE_STRING))
670
671 (defconst js2-debug-print-trees nil)
672
673 ;; Rhino accepts any string or stream as input. Emacs character
674 ;; processing works best in buffers, so we'll assume the input is a
675 ;; buffer. JavaScript strings can be copied into temp buffers before
676 ;; scanning them.
677
678 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
679 ;; They're the Emacs equivalent of instance variables, more or less.
680
681 (js2-deflocal js2-ts-dirty-line nil
682 "Token stream buffer-local variable.
683 Indicates stuff other than whitespace since start of line.")
684
685 (js2-deflocal js2-ts-hit-eof nil
686 "Token stream buffer-local variable.")
687
688 ;; FIXME: Unused.
689 (js2-deflocal js2-ts-line-start 0
690 "Token stream buffer-local variable.")
691
692 (js2-deflocal js2-ts-lineno 1
693 "Token stream buffer-local variable.")
694
695 ;; FIXME: Unused.
696 (js2-deflocal js2-ts-line-end-char -1
697 "Token stream buffer-local variable.")
698
699 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
700 "Token stream buffer-local variable.
701 Current scan position.")
702
703 ;; FIXME: Unused.
704 (js2-deflocal js2-ts-is-xml-attribute nil
705 "Token stream buffer-local variable.")
706
707 (js2-deflocal js2-ts-xml-is-tag-content nil
708 "Token stream buffer-local variable.")
709
710 (js2-deflocal js2-ts-xml-open-tags-count 0
711 "Token stream buffer-local variable.")
712
713 (js2-deflocal js2-ts-string-buffer nil
714 "Token stream buffer-local variable.
715 List of chars built up while scanning various tokens.")
716
717 (defstruct (js2-token
718 (:constructor nil)
719 (:constructor make-js2-token (beg)))
720 "Value returned from the token stream."
721 (type js2-EOF)
722 (beg 1)
723 (end -1)
724 (string "")
725 number
726 regexp-flags
727 comment-type
728 follows-eol-p)
729
730 (defstruct (js2-ts-state
731 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
732 (cursor js2-ts-cursor)
733 (tokens (copy-sequence js2-ti-tokens))
734 (tokens-cursor js2-ti-tokens-cursor)
735 (lookahead js2-ti-lookahead))))
736 lineno
737 cursor
738 tokens
739 tokens-cursor
740 lookahead)
741
742 ;;; Parser variables
743
744 (js2-deflocal js2-parsed-errors nil
745 "List of errors produced during scanning/parsing.")
746
747 (js2-deflocal js2-parsed-warnings nil
748 "List of warnings produced during scanning/parsing.")
749
750 (js2-deflocal js2-recover-from-parse-errors t
751 "Non-nil to continue parsing after a syntax error.
752
753 In recovery mode, the AST will be built in full, and any error
754 nodes will be flagged with appropriate error information. If
755 this flag is nil, a syntax error will result in an error being
756 signaled.
757
758 The variable is automatically buffer-local, because different
759 modes that use the parser will need different settings.")
760
761 (js2-deflocal js2-parse-hook nil
762 "List of callbacks for receiving parsing progress.")
763
764 (defvar js2-parse-finished-hook nil
765 "List of callbacks to notify when parsing finishes.
766 Not called if parsing was interrupted.")
767
768 (js2-deflocal js2-is-eval-code nil
769 "True if we're evaluating code in a string.
770 If non-nil, the tokenizer will record the token text, and the AST nodes
771 will record their source text. Off by default for IDE modes, since the
772 text is available in the buffer.")
773
774 (defvar js2-parse-ide-mode t
775 "Non-nil if the parser is being used for `js2-mode'.
776 If non-nil, the parser will set text properties for fontification
777 and the syntax table. The value should be nil when using the
778 parser as a frontend to an interpreter or byte compiler.")
779
780 ;;; Parser instance variables (buffer-local vars for js2-parse)
781
782 (defconst js2-ti-after-eol (lsh 1 16)
783 "Flag: first token of the source line.")
784
785 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
786
787 (js2-deflocal js2-compiler-generate-debug-info t)
788 (js2-deflocal js2-compiler-use-dynamic-scope nil)
789 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
790 (js2-deflocal js2-compiler-xml-available t)
791 (js2-deflocal js2-compiler-optimization-level 0)
792 (js2-deflocal js2-compiler-generating-source t)
793 (js2-deflocal js2-compiler-strict-mode nil)
794 (js2-deflocal js2-compiler-report-warning-as-error nil)
795 (js2-deflocal js2-compiler-generate-observer-count nil)
796 (js2-deflocal js2-compiler-activation-names nil)
797
798 ;; SKIP: sourceURI
799
800 ;; There's a compileFunction method in Context.java - may need it.
801 (js2-deflocal js2-called-by-compile-function nil
802 "True if `js2-parse' was called by `js2-compile-function'.
803 Will only be used when we finish implementing the interpreter.")
804
805 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
806
807 ;; SKIP: node factory - we're going to just call functions directly,
808 ;; and eventually go to a unified AST format.
809
810 (js2-deflocal js2-nesting-of-function 0)
811
812 (js2-deflocal js2-recorded-identifiers nil
813 "Tracks identifiers found during parsing.")
814
815 (js2-deflocal js2-is-in-destructuring nil
816 "True while parsing destructuring expression.")
817
818 (defcustom js2-global-externs nil
819 "A list of any extern names you'd like to consider always declared.
820 This list is global and is used by all `js2-mode' files.
821 You can create buffer-local externs list using `js2-additional-externs'.
822
823 There is also a buffer-local variable `js2-default-externs',
824 which is initialized by default to include the Ecma-262 externs
825 and the standard browser externs. The three lists are all
826 checked during highlighting."
827 :type 'list
828 :group 'js2-mode)
829
830 (js2-deflocal js2-default-externs nil
831 "Default external declarations.
832
833 These are currently only used for highlighting undeclared variables,
834 which only worries about top-level (unqualified) references.
835 As js2-mode's processing improves, we will flesh out this list.
836
837 The initial value is set to `js2-ecma-262-externs', unless some
838 of the `js2-include-?-externs' variables are set to t, in which
839 case the browser, Rhino and/or Node.js externs are also included.
840
841 See `js2-additional-externs' for more information.")
842
843 (defcustom js2-include-browser-externs t
844 "Non-nil to include browser externs in the master externs list.
845 If you work on JavaScript files that are not intended for browsers,
846 such as Mozilla Rhino server-side JavaScript, set this to nil.
847 See `js2-additional-externs' for more information about externs."
848 :type 'boolean
849 :group 'js2-mode)
850
851 (defcustom js2-include-rhino-externs nil
852 "Non-nil to include Mozilla Rhino externs in the master externs list.
853 See `js2-additional-externs' for more information about externs."
854 :type 'boolean
855 :group 'js2-mode)
856
857 (defcustom js2-include-node-externs nil
858 "Non-nil to include Node.js externs in the master externs list.
859 See `js2-additional-externs' for more information about externs."
860 :type 'boolean
861 :group 'js2-mode)
862
863 (js2-deflocal js2-additional-externs nil
864 "A buffer-local list of additional external declarations.
865 It is used to decide whether variables are considered undeclared
866 for purposes of highlighting.
867
868 Each entry is a Lisp string. The string should be the fully qualified
869 name of an external entity. All externs should be added to this list,
870 so that as js2-mode's processing improves it can take advantage of them.
871
872 You may want to declare your externs in three ways.
873 First, you can add externs that are valid for all your JavaScript files.
874 You should probably do this by adding them to `js2-global-externs', which
875 is a global list used for all js2-mode files.
876
877 Next, you can add a function to `js2-init-hook' that adds additional
878 externs appropriate for the specific file, perhaps based on its path.
879 These should go in `js2-additional-externs', which is buffer-local.
880
881 Third, you can use JSLint's global declaration, as long as
882 `js2-include-jslint-globals' is non-nil, which see.
883
884 Finally, you can add a function to `js2-post-parse-callbacks',
885 which is called after parsing completes, and `js2-mode-ast' is bound to
886 the root of the parse tree. At this stage you can set up an AST
887 node visitor using `js2-visit-ast' and examine the parse tree
888 for specific import patterns that may imply the existence of
889 other externs, possibly tied to your build system. These should also
890 be added to `js2-additional-externs'.
891
892 Your post-parse callback may of course also use the simpler and
893 faster (but perhaps less robust) approach of simply scanning the
894 buffer text for your imports, using regular expressions.")
895
896 ;; SKIP: decompiler
897 ;; SKIP: encoded-source
898
899 ;;; The following variables are per-function and should be saved/restored
900 ;;; during function parsing...
901
902 (js2-deflocal js2-current-script-or-fn nil)
903 (js2-deflocal js2-current-scope nil)
904 (js2-deflocal js2-nesting-of-with 0)
905 (js2-deflocal js2-label-set nil
906 "An alist mapping label names to nodes.")
907
908 (js2-deflocal js2-loop-set nil)
909 (js2-deflocal js2-loop-and-switch-set nil)
910 (js2-deflocal js2-has-return-value nil)
911 (js2-deflocal js2-end-flags 0)
912
913 ;;; ...end of per function variables
914
915 ;; These flags enumerate the possible ways a statement/function can
916 ;; terminate. These flags are used by endCheck() and by the Parser to
917 ;; detect inconsistent return usage.
918 ;;
919 ;; END_UNREACHED is reserved for code paths that are assumed to always be
920 ;; able to execute (example: throw, continue)
921 ;;
922 ;; END_DROPS_OFF indicates if the statement can transfer control to the
923 ;; next one. Statement such as return dont. A compound statement may have
924 ;; some branch that drops off control to the next statement.
925 ;;
926 ;; END_RETURNS indicates that the statement can return (without arguments)
927 ;; END_RETURNS_VALUE indicates that the statement can return a value.
928 ;;
929 ;; A compound statement such as
930 ;; if (condition) {
931 ;; return value;
932 ;; }
933 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
934
935 (defconst js2-end-unreached #x0)
936 (defconst js2-end-drops-off #x1)
937 (defconst js2-end-returns #x2)
938 (defconst js2-end-returns-value #x4)
939
940 ;; Rhino awkwardly passes a statementLabel parameter to the
941 ;; statementHelper() function, the main statement parser, which
942 ;; is then used by quite a few of the sub-parsers. We just make
943 ;; it a buffer-local variable and make sure it's cleaned up properly.
944 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
945
946 ;; Similarly, Rhino passes an inForInit boolean through about half
947 ;; the expression parsers. We use a dynamically-scoped variable,
948 ;; which makes it easier to funcall the parsers individually without
949 ;; worrying about whether they take the parameter or not.
950 (js2-deflocal js2-in-for-init nil)
951 (js2-deflocal js2-temp-name-counter 0)
952 (js2-deflocal js2-parse-stmt-count 0)
953
954 (defsubst js2-get-next-temp-name ()
955 (format "$%d" (incf js2-temp-name-counter)))
956
957 (defvar js2-parse-interruptable-p t
958 "Set this to nil to force parse to continue until finished.
959 This will mostly be useful for interpreters.")
960
961 (defvar js2-statements-per-pause 50
962 "Pause after this many statements to check for user input.
963 If user input is pending, stop the parse and discard the tree.
964 This makes for a smoother user experience for large files.
965 You may have to wait a second or two before the highlighting
966 and error-reporting appear, but you can always type ahead if
967 you wish. This appears to be more or less how Eclipse, IntelliJ
968 and other editors work.")
969
970 (js2-deflocal js2-record-comments t
971 "Instructs the scanner to record comments in `js2-scanned-comments'.")
972
973 (js2-deflocal js2-scanned-comments nil
974 "List of all comments from the current parse.")
975
976 (defcustom js2-mode-indent-inhibit-undo nil
977 "Non-nil to disable collection of Undo information when indenting lines.
978 Some users have requested this behavior. It's nil by default because
979 other Emacs modes don't work this way."
980 :type 'boolean
981 :group 'js2-mode)
982
983 (defcustom js2-mode-indent-ignore-first-tab nil
984 "If non-nil, ignore first TAB keypress if we look indented properly.
985 It's fairly common for users to navigate to an already-indented line
986 and press TAB for reassurance that it's been indented. For this class
987 of users, we want the first TAB press on a line to be ignored if the
988 line is already indented to one of the precomputed alternatives.
989
990 This behavior is only partly implemented. If you TAB-indent a line,
991 navigate to another line, and then navigate back, it fails to clear
992 the last-indented variable, so it thinks you've already hit TAB once,
993 and performs the indent. A full solution would involve getting on the
994 point-motion hooks for the entire buffer. If we come across another
995 use cases that requires watching point motion, I'll consider doing it.
996
997 If you set this variable to nil, then the TAB key will always change
998 the indentation of the current line, if more than one alternative
999 indentation spot exists."
1000 :type 'boolean
1001 :group 'js2-mode)
1002
1003 (defvar js2-indent-hook nil
1004 "A hook for user-defined indentation rules.
1005
1006 Functions on this hook should expect two arguments: (LIST INDEX)
1007 The LIST argument is the list of computed indentation points for
1008 the current line. INDEX is the list index of the indentation point
1009 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1010 indent function is not going to change the current line indentation.
1011
1012 If a hook function on this list returns a non-nil value, then
1013 `js2-bounce-indent' assumes the hook function has performed its own
1014 indentation, and will do nothing. If all hook functions on the list
1015 return nil, then `js2-bounce-indent' will use its computed indentation
1016 and reindent the line.
1017
1018 When hook functions on this hook list are called, the variable
1019 `js2-mode-ast' may or may not be set, depending on whether the
1020 parse tree is available. If the variable is nil, you can pass a
1021 callback to `js2-mode-wait-for-parse', and your callback will be
1022 called after the new parse tree is built. This can take some time
1023 in large files.")
1024
1025 (defface js2-warning
1026 `((((class color) (background light))
1027 (:underline "orange"))
1028 (((class color) (background dark))
1029 (:underline "orange"))
1030 (t (:underline t)))
1031 "Face for JavaScript warnings."
1032 :group 'js2-mode)
1033
1034 (defface js2-error
1035 `((((class color) (background light))
1036 (:foreground "red"))
1037 (((class color) (background dark))
1038 (:foreground "red"))
1039 (t (:foreground "red")))
1040 "Face for JavaScript errors."
1041 :group 'js2-mode)
1042
1043 (defface js2-jsdoc-tag
1044 '((t :foreground "SlateGray"))
1045 "Face used to highlight @whatever tags in jsdoc comments."
1046 :group 'js2-mode)
1047
1048 (defface js2-jsdoc-type
1049 '((t :foreground "SteelBlue"))
1050 "Face used to highlight {FooBar} types in jsdoc comments."
1051 :group 'js2-mode)
1052
1053 (defface js2-jsdoc-value
1054 '((t :foreground "PeachPuff3"))
1055 "Face used to highlight tag values in jsdoc comments."
1056 :group 'js2-mode)
1057
1058 (defface js2-function-param
1059 '((t :foreground "SeaGreen"))
1060 "Face used to highlight function parameters in javascript."
1061 :group 'js2-mode)
1062
1063 (defface js2-function-call
1064 '((t :inherit default))
1065 "Face used to highlight function name in calls."
1066 :group 'js2-mode)
1067
1068 (defface js2-instance-member
1069 '((t :foreground "DarkOrchid"))
1070 "Face used to highlight instance variables in javascript.
1071 Not currently used."
1072 :group 'js2-mode)
1073
1074 (defface js2-private-member
1075 '((t :foreground "PeachPuff3"))
1076 "Face used to highlight calls to private methods in javascript.
1077 Not currently used."
1078 :group 'js2-mode)
1079
1080 (defface js2-private-function-call
1081 '((t :foreground "goldenrod"))
1082 "Face used to highlight calls to private functions in javascript.
1083 Not currently used."
1084 :group 'js2-mode)
1085
1086 (defface js2-jsdoc-html-tag-name
1087 '((((class color) (min-colors 88) (background light))
1088 (:foreground "rosybrown"))
1089 (((class color) (min-colors 8) (background dark))
1090 (:foreground "yellow"))
1091 (((class color) (min-colors 8) (background light))
1092 (:foreground "magenta")))
1093 "Face used to highlight jsdoc html tag names"
1094 :group 'js2-mode)
1095
1096 (defface js2-jsdoc-html-tag-delimiter
1097 '((((class color) (min-colors 88) (background light))
1098 (:foreground "dark khaki"))
1099 (((class color) (min-colors 8) (background dark))
1100 (:foreground "green"))
1101 (((class color) (min-colors 8) (background light))
1102 (:foreground "green")))
1103 "Face used to highlight brackets in jsdoc html tags."
1104 :group 'js2-mode)
1105
1106 (defface js2-external-variable
1107 '((t :foreground "orange"))
1108 "Face used to highlight undeclared variable identifiers.")
1109
1110 (defcustom js2-init-hook nil
1111 "List of functions to be called after `js2-mode' or
1112 `js2-minor-mode' has initialized all variables, before parsing
1113 the buffer for the first time."
1114 :type 'hook
1115 :group 'js2-mode
1116 :version "20130608")
1117
1118 (defcustom js2-post-parse-callbacks nil
1119 "List of callback functions invoked after parsing finishes.
1120 Currently, the main use for this function is to add synthetic
1121 declarations to `js2-recorded-identifiers', which see."
1122 :type 'hook
1123 :group 'js2-mode)
1124
1125 (defcustom js2-build-imenu-callbacks nil
1126 "List of functions called during Imenu index generation.
1127 It's a good place to add additional entries to it, using
1128 `js2-record-imenu-entry'."
1129 :type 'hook
1130 :group 'js2-mode)
1131
1132 (defcustom js2-highlight-external-variables t
1133 "Non-nil to highlight undeclared variable identifiers.
1134 An undeclared variable is any variable not declared with var or let
1135 in the current scope or any lexically enclosing scope. If you use
1136 such a variable, then you are either expecting it to originate from
1137 another file, or you've got a potential bug."
1138 :type 'boolean
1139 :group 'js2-mode)
1140
1141 (defcustom js2-include-jslint-globals t
1142 "Non-nil to include the identifiers from JSLint global
1143 declaration (see http://www.jslint.com/lint.html#global) in the
1144 buffer-local externs list. See `js2-additional-externs' for more
1145 information."
1146 :type 'boolean
1147 :group 'js2-mode)
1148
1149 (defvar js2-mode-map
1150 (let ((map (make-sparse-keymap)))
1151 (define-key map [mouse-1] #'js2-mode-show-node)
1152 (define-key map (kbd "M-j") #'js2-line-break)
1153 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1154 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1155 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1156 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1157 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1158 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1159 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1160 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1161 (when js2-bounce-indent-p
1162 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1163
1164 (define-key map [menu-bar javascript]
1165 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1166
1167 (define-key map [menu-bar javascript customize-js2-mode]
1168 '(menu-item "Customize js2-mode" js2-mode-customize
1169 :help "Customize the behavior of this mode"))
1170
1171 (define-key map [menu-bar javascript js2-force-refresh]
1172 '(menu-item "Force buffer refresh" js2-mode-reset
1173 :help "Re-parse the buffer from scratch"))
1174
1175 (define-key map [menu-bar javascript separator-2]
1176 '("--"))
1177
1178 (define-key map [menu-bar javascript next-error]
1179 '(menu-item "Next warning or error" next-error
1180 :enabled (and js2-mode-ast
1181 (or (js2-ast-root-errors js2-mode-ast)
1182 (js2-ast-root-warnings js2-mode-ast)))
1183 :help "Move to next warning or error"))
1184
1185 (define-key map [menu-bar javascript display-errors]
1186 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1187 :visible (not js2-mode-show-parse-errors)
1188 :help "Turn on display of warnings and errors"))
1189
1190 (define-key map [menu-bar javascript hide-errors]
1191 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1192 :visible js2-mode-show-parse-errors
1193 :help "Turn off display of warnings and errors"))
1194
1195 (define-key map [menu-bar javascript separator-1]
1196 '("--"))
1197
1198 (define-key map [menu-bar javascript js2-toggle-function]
1199 '(menu-item "Show/collapse element" js2-mode-toggle-element
1200 :help "Hide or show function body or comment"))
1201
1202 (define-key map [menu-bar javascript show-comments]
1203 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1204 :visible js2-mode-comments-hidden
1205 :help "Expand all hidden block comments"))
1206
1207 (define-key map [menu-bar javascript hide-comments]
1208 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1209 :visible (not js2-mode-comments-hidden)
1210 :help "Show block comments as /*...*/"))
1211
1212 (define-key map [menu-bar javascript show-all-functions]
1213 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1214 :visible js2-mode-functions-hidden
1215 :help "Expand all hidden function bodies"))
1216
1217 (define-key map [menu-bar javascript hide-all-functions]
1218 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1219 :visible (not js2-mode-functions-hidden)
1220 :help "Show {...} for all top-level function bodies"))
1221
1222 map)
1223 "Keymap used in `js2-mode' buffers.")
1224
1225 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1226
1227 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1228 "Matches a //-comment line. Must be first non-whitespace on line.
1229 First match-group is the leading whitespace.")
1230
1231 (defvar js2-mode-hook nil)
1232
1233 (js2-deflocal js2-mode-ast nil "Private variable.")
1234 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1235 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1236 (js2-deflocal js2-mode-parsing nil "Private variable.")
1237 (js2-deflocal js2-mode-node-overlay nil)
1238
1239 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1240 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1241
1242 (js2-deflocal js2-mode-fontifications nil "Private variable")
1243 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1244 (js2-deflocal js2-imenu-recorder nil "Private variable")
1245 (js2-deflocal js2-imenu-function-map nil "Private variable")
1246
1247 (defvar js2-paragraph-start
1248 "\\(@[[:alpha:]]+\\>\\|$\\)")
1249
1250 ;; Note that we also set a 'c-in-sws text property in html comments,
1251 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1252 (defvar js2-syntactic-ws-start
1253 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1254
1255 (defvar js2-syntactic-ws-end
1256 "\\s \\|[\n\r/]\\|\\s!")
1257
1258 (defvar js2-syntactic-eol
1259 (concat "\\s *\\(/\\*[^*\n\r]*"
1260 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1261 "\\*+/\\s *\\)*"
1262 "\\(//\\|/\\*[^*\n\r]*"
1263 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1264 "\\|\\\\$\\|$\\)")
1265 "Copied from `java-mode'. Needed for some cc-engine functions.")
1266
1267 (defvar js2-comment-prefix-regexp
1268 "//+\\|\\**")
1269
1270 (defvar js2-comment-start-skip
1271 "\\(//+\\|/\\*+\\)\\s *")
1272
1273 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1274 "Non-nil to emit status messages during parsing.")
1275
1276 (defvar js2-mode-functions-hidden nil "Private variable.")
1277 (defvar js2-mode-comments-hidden nil "Private variable.")
1278
1279 (defvar js2-mode-syntax-table
1280 (let ((table (make-syntax-table)))
1281 (c-populate-syntax-table table)
1282 table)
1283 "Syntax table used in `js2-mode' buffers.")
1284
1285 (defvar js2-mode-abbrev-table nil
1286 "Abbrev table in use in `js2-mode' buffers.")
1287 (define-abbrev-table 'js2-mode-abbrev-table ())
1288
1289 (defvar js2-mode-pending-parse-callbacks nil
1290 "List of functions waiting to be notified that parse is finished.")
1291
1292 (defvar js2-mode-last-indented-line -1)
1293
1294 ;;; Localizable error and warning messages
1295
1296 ;; Messages are copied from Rhino's Messages.properties.
1297 ;; Many of the Java-specific messages have been elided.
1298 ;; Add any js2-specific ones at the end, so we can keep
1299 ;; this file synced with changes to Rhino's.
1300
1301 (defvar js2-message-table
1302 (make-hash-table :test 'equal :size 250)
1303 "Contains localized messages for `js2-mode'.")
1304
1305 ;; TODO(stevey): construct this table at compile-time.
1306 (defmacro js2-msg (key &rest strings)
1307 `(puthash ,key (concat ,@strings)
1308 js2-message-table))
1309
1310 (defun js2-get-msg (msg-key)
1311 "Look up a localized message.
1312 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1313 the correct number of ARGS must be provided."
1314 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1315 (args (if (listp msg-key) (cdr msg-key)))
1316 (msg (gethash key js2-message-table)))
1317 (if msg
1318 (apply #'format msg args)
1319 key))) ; default to showing the key
1320
1321 (js2-msg "msg.dup.parms"
1322 "Duplicate parameter name '%s'.")
1323
1324 (js2-msg "msg.too.big.jump"
1325 "Program too complex: jump offset too big.")
1326
1327 (js2-msg "msg.too.big.index"
1328 "Program too complex: internal index exceeds 64K limit.")
1329
1330 (js2-msg "msg.while.compiling.fn"
1331 "Encountered code generation error while compiling function '%s': %s")
1332
1333 (js2-msg "msg.while.compiling.script"
1334 "Encountered code generation error while compiling script: %s")
1335
1336 ;; Context
1337 (js2-msg "msg.ctor.not.found"
1338 "Constructor for '%s' not found.")
1339
1340 (js2-msg "msg.not.ctor"
1341 "'%s' is not a constructor.")
1342
1343 ;; FunctionObject
1344 (js2-msg "msg.varargs.ctor"
1345 "Method or constructor '%s' must be static "
1346 "with the signature (Context cx, Object[] args, "
1347 "Function ctorObj, boolean inNewExpr) "
1348 "to define a variable arguments constructor.")
1349
1350 (js2-msg "msg.varargs.fun"
1351 "Method '%s' must be static with the signature "
1352 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1353 "to define a variable arguments function.")
1354
1355 (js2-msg "msg.incompat.call"
1356 "Method '%s' called on incompatible object.")
1357
1358 (js2-msg "msg.bad.parms"
1359 "Unsupported parameter type '%s' in method '%s'.")
1360
1361 (js2-msg "msg.bad.method.return"
1362 "Unsupported return type '%s' in method '%s'.")
1363
1364 (js2-msg "msg.bad.ctor.return"
1365 "Construction of objects of type '%s' is not supported.")
1366
1367 (js2-msg "msg.no.overload"
1368 "Method '%s' occurs multiple times in class '%s'.")
1369
1370 (js2-msg "msg.method.not.found"
1371 "Method '%s' not found in '%s'.")
1372
1373 ;; IRFactory
1374
1375 (js2-msg "msg.bad.for.in.lhs"
1376 "Invalid left-hand side of for..in loop.")
1377
1378 (js2-msg "msg.mult.index"
1379 "Only one variable allowed in for..in loop.")
1380
1381 (js2-msg "msg.bad.for.in.destruct"
1382 "Left hand side of for..in loop must be an array of "
1383 "length 2 to accept key/value pair.")
1384
1385 (js2-msg "msg.cant.convert"
1386 "Can't convert to type '%s'.")
1387
1388 (js2-msg "msg.bad.assign.left"
1389 "Invalid assignment left-hand side.")
1390
1391 (js2-msg "msg.bad.decr"
1392 "Invalid decerement operand.")
1393
1394 (js2-msg "msg.bad.incr"
1395 "Invalid increment operand.")
1396
1397 (js2-msg "msg.bad.yield"
1398 "yield must be in a function.")
1399
1400 (js2-msg "msg.yield.parenthesized"
1401 "yield expression must be parenthesized.")
1402
1403 ;; NativeGlobal
1404 (js2-msg "msg.cant.call.indirect"
1405 "Function '%s' must be called directly, and not by way of a "
1406 "function of another name.")
1407
1408 (js2-msg "msg.eval.nonstring"
1409 "Calling eval() with anything other than a primitive "
1410 "string value will simply return the value. "
1411 "Is this what you intended?")
1412
1413 (js2-msg "msg.eval.nonstring.strict"
1414 "Calling eval() with anything other than a primitive "
1415 "string value is not allowed in strict mode.")
1416
1417 (js2-msg "msg.bad.destruct.op"
1418 "Invalid destructuring assignment operator")
1419
1420 ;; NativeCall
1421 (js2-msg "msg.only.from.new"
1422 "'%s' may only be invoked from a `new' expression.")
1423
1424 (js2-msg "msg.deprec.ctor"
1425 "The '%s' constructor is deprecated.")
1426
1427 ;; NativeFunction
1428 (js2-msg "msg.no.function.ref.found"
1429 "no source found to decompile function reference %s")
1430
1431 (js2-msg "msg.arg.isnt.array"
1432 "second argument to Function.prototype.apply must be an array")
1433
1434 ;; NativeGlobal
1435 (js2-msg "msg.bad.esc.mask"
1436 "invalid string escape mask")
1437
1438 ;; NativeRegExp
1439 (js2-msg "msg.bad.quant"
1440 "Invalid quantifier %s")
1441
1442 (js2-msg "msg.overlarge.backref"
1443 "Overly large back reference %s")
1444
1445 (js2-msg "msg.overlarge.min"
1446 "Overly large minimum %s")
1447
1448 (js2-msg "msg.overlarge.max"
1449 "Overly large maximum %s")
1450
1451 (js2-msg "msg.zero.quant"
1452 "Zero quantifier %s")
1453
1454 (js2-msg "msg.max.lt.min"
1455 "Maximum %s less than minimum")
1456
1457 (js2-msg "msg.unterm.quant"
1458 "Unterminated quantifier %s")
1459
1460 (js2-msg "msg.unterm.paren"
1461 "Unterminated parenthetical %s")
1462
1463 (js2-msg "msg.unterm.class"
1464 "Unterminated character class %s")
1465
1466 (js2-msg "msg.bad.range"
1467 "Invalid range in character class.")
1468
1469 (js2-msg "msg.trail.backslash"
1470 "Trailing \\ in regular expression.")
1471
1472 (js2-msg "msg.re.unmatched.right.paren"
1473 "unmatched ) in regular expression.")
1474
1475 (js2-msg "msg.no.regexp"
1476 "Regular expressions are not available.")
1477
1478 (js2-msg "msg.bad.backref"
1479 "back-reference exceeds number of capturing parentheses.")
1480
1481 (js2-msg "msg.bad.regexp.compile"
1482 "Only one argument may be specified if the first "
1483 "argument to RegExp.prototype.compile is a RegExp object.")
1484
1485 ;; Parser
1486 (js2-msg "msg.got.syntax.errors"
1487 "Compilation produced %s syntax errors.")
1488
1489 (js2-msg "msg.var.redecl"
1490 "TypeError: redeclaration of var %s.")
1491
1492 (js2-msg "msg.const.redecl"
1493 "TypeError: redeclaration of const %s.")
1494
1495 (js2-msg "msg.let.redecl"
1496 "TypeError: redeclaration of variable %s.")
1497
1498 (js2-msg "msg.parm.redecl"
1499 "TypeError: redeclaration of formal parameter %s.")
1500
1501 (js2-msg "msg.fn.redecl"
1502 "TypeError: redeclaration of function %s.")
1503
1504 (js2-msg "msg.let.decl.not.in.block"
1505 "SyntaxError: let declaration not directly within block")
1506
1507 ;; NodeTransformer
1508 (js2-msg "msg.dup.label"
1509 "duplicated label")
1510
1511 (js2-msg "msg.undef.label"
1512 "undefined label")
1513
1514 (js2-msg "msg.bad.break"
1515 "unlabelled break must be inside loop or switch")
1516
1517 (js2-msg "msg.continue.outside"
1518 "continue must be inside loop")
1519
1520 (js2-msg "msg.continue.nonloop"
1521 "continue can only use labels of iteration statements")
1522
1523 (js2-msg "msg.bad.throw.eol"
1524 "Line terminator is not allowed between the throw "
1525 "keyword and throw expression.")
1526
1527 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1528 "function statement requires a name")
1529
1530 (js2-msg "msg.no.paren.parms"
1531 "missing ( before function parameters.")
1532
1533 (js2-msg "msg.no.parm"
1534 "missing formal parameter")
1535
1536 (js2-msg "msg.no.paren.after.parms"
1537 "missing ) after formal parameters")
1538
1539 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1540 "parameter without default follows parameter with default")
1541
1542 (js2-msg "msg.param.after.rest" ; added by js2-mode
1543 "parameter after rest parameter")
1544
1545 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1546 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1547
1548 (js2-msg "msg.no.brace.body"
1549 "missing '{' before function body")
1550
1551 (js2-msg "msg.no.brace.after.body"
1552 "missing } after function body")
1553
1554 (js2-msg "msg.no.paren.cond"
1555 "missing ( before condition")
1556
1557 (js2-msg "msg.no.paren.after.cond"
1558 "missing ) after condition")
1559
1560 (js2-msg "msg.no.semi.stmt"
1561 "missing ; before statement")
1562
1563 (js2-msg "msg.missing.semi"
1564 "missing ; after statement")
1565
1566 (js2-msg "msg.no.name.after.dot"
1567 "missing name after . operator")
1568
1569 (js2-msg "msg.no.name.after.coloncolon"
1570 "missing name after :: operator")
1571
1572 (js2-msg "msg.no.name.after.dotdot"
1573 "missing name after .. operator")
1574
1575 (js2-msg "msg.no.name.after.xmlAttr"
1576 "missing name after .@")
1577
1578 (js2-msg "msg.no.bracket.index"
1579 "missing ] in index expression")
1580
1581 (js2-msg "msg.no.paren.switch"
1582 "missing ( before switch expression")
1583
1584 (js2-msg "msg.no.paren.after.switch"
1585 "missing ) after switch expression")
1586
1587 (js2-msg "msg.no.brace.switch"
1588 "missing '{' before switch body")
1589
1590 (js2-msg "msg.bad.switch"
1591 "invalid switch statement")
1592
1593 (js2-msg "msg.no.colon.case"
1594 "missing : after case expression")
1595
1596 (js2-msg "msg.double.switch.default"
1597 "double default label in the switch statement")
1598
1599 (js2-msg "msg.no.while.do"
1600 "missing while after do-loop body")
1601
1602 (js2-msg "msg.no.paren.for"
1603 "missing ( after for")
1604
1605 (js2-msg "msg.no.semi.for"
1606 "missing ; after for-loop initializer")
1607
1608 (js2-msg "msg.no.semi.for.cond"
1609 "missing ; after for-loop condition")
1610
1611 (js2-msg "msg.in.after.for.name"
1612 "missing in or of after for")
1613
1614 (js2-msg "msg.no.paren.for.ctrl"
1615 "missing ) after for-loop control")
1616
1617 (js2-msg "msg.no.paren.with"
1618 "missing ( before with-statement object")
1619
1620 (js2-msg "msg.no.paren.after.with"
1621 "missing ) after with-statement object")
1622
1623 (js2-msg "msg.no.paren.after.let"
1624 "missing ( after let")
1625
1626 (js2-msg "msg.no.paren.let"
1627 "missing ) after variable list")
1628
1629 (js2-msg "msg.no.curly.let"
1630 "missing } after let statement")
1631
1632 (js2-msg "msg.bad.return"
1633 "invalid return")
1634
1635 (js2-msg "msg.no.brace.block"
1636 "missing } in compound statement")
1637
1638 (js2-msg "msg.bad.label"
1639 "invalid label")
1640
1641 (js2-msg "msg.bad.var"
1642 "missing variable name")
1643
1644 (js2-msg "msg.bad.var.init"
1645 "invalid variable initialization")
1646
1647 (js2-msg "msg.no.colon.cond"
1648 "missing : in conditional expression")
1649
1650 (js2-msg "msg.no.paren.arg"
1651 "missing ) after argument list")
1652
1653 (js2-msg "msg.no.bracket.arg"
1654 "missing ] after element list")
1655
1656 (js2-msg "msg.bad.prop"
1657 "invalid property id")
1658
1659 (js2-msg "msg.no.colon.prop"
1660 "missing : after property id")
1661
1662 (js2-msg "msg.no.brace.prop"
1663 "missing } after property list")
1664
1665 (js2-msg "msg.no.paren"
1666 "missing ) in parenthetical")
1667
1668 (js2-msg "msg.reserved.id"
1669 "'%s' is a reserved identifier")
1670
1671 (js2-msg "msg.no.paren.catch"
1672 "missing ( before catch-block condition")
1673
1674 (js2-msg "msg.bad.catchcond"
1675 "invalid catch block condition")
1676
1677 (js2-msg "msg.catch.unreachable"
1678 "any catch clauses following an unqualified catch are unreachable")
1679
1680 (js2-msg "msg.no.brace.try"
1681 "missing '{' before try block")
1682
1683 (js2-msg "msg.no.brace.catchblock"
1684 "missing '{' before catch-block body")
1685
1686 (js2-msg "msg.try.no.catchfinally"
1687 "'try' without 'catch' or 'finally'")
1688
1689 (js2-msg "msg.no.return.value"
1690 "function %s does not always return a value")
1691
1692 (js2-msg "msg.anon.no.return.value"
1693 "anonymous function does not always return a value")
1694
1695 (js2-msg "msg.return.inconsistent"
1696 "return statement is inconsistent with previous usage")
1697
1698 (js2-msg "msg.generator.returns"
1699 "TypeError: legacy generator function '%s' returns a value")
1700
1701 (js2-msg "msg.anon.generator.returns"
1702 "TypeError: anonymous legacy generator function returns a value")
1703
1704 (js2-msg "msg.syntax"
1705 "syntax error")
1706
1707 (js2-msg "msg.unexpected.eof"
1708 "Unexpected end of file")
1709
1710 (js2-msg "msg.XML.bad.form"
1711 "illegally formed XML syntax")
1712
1713 (js2-msg "msg.XML.not.available"
1714 "XML runtime not available")
1715
1716 (js2-msg "msg.too.deep.parser.recursion"
1717 "Too deep recursion while parsing")
1718
1719 (js2-msg "msg.no.side.effects"
1720 "Code has no side effects")
1721
1722 (js2-msg "msg.extra.trailing.comma"
1723 "Trailing comma is not supported in some browsers")
1724
1725 (js2-msg "msg.array.trailing.comma"
1726 "Trailing comma yields different behavior across browsers")
1727
1728 (js2-msg "msg.equal.as.assign"
1729 (concat "Test for equality (==) mistyped as assignment (=)?"
1730 " (parenthesize to suppress warning)"))
1731
1732 (js2-msg "msg.var.hides.arg"
1733 "Variable %s hides argument")
1734
1735 (js2-msg "msg.destruct.assign.no.init"
1736 "Missing = in destructuring declaration")
1737
1738 ;; ScriptRuntime
1739 (js2-msg "msg.no.properties"
1740 "%s has no properties.")
1741
1742 (js2-msg "msg.invalid.iterator"
1743 "Invalid iterator value")
1744
1745 (js2-msg "msg.iterator.primitive"
1746 "__iterator__ returned a primitive value")
1747
1748 (js2-msg "msg.assn.create.strict"
1749 "Assignment to undeclared variable %s")
1750
1751 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1752 "Undeclared variable or function '%s'")
1753
1754 (js2-msg "msg.ref.undefined.prop"
1755 "Reference to undefined property '%s'")
1756
1757 (js2-msg "msg.prop.not.found"
1758 "Property %s not found.")
1759
1760 (js2-msg "msg.invalid.type"
1761 "Invalid JavaScript value of type %s")
1762
1763 (js2-msg "msg.primitive.expected"
1764 "Primitive type expected (had %s instead)")
1765
1766 (js2-msg "msg.namespace.expected"
1767 "Namespace object expected to left of :: (found %s instead)")
1768
1769 (js2-msg "msg.null.to.object"
1770 "Cannot convert null to an object.")
1771
1772 (js2-msg "msg.undef.to.object"
1773 "Cannot convert undefined to an object.")
1774
1775 (js2-msg "msg.cyclic.value"
1776 "Cyclic %s value not allowed.")
1777
1778 (js2-msg "msg.is.not.defined"
1779 "'%s' is not defined.")
1780
1781 (js2-msg "msg.undef.prop.read"
1782 "Cannot read property '%s' from %s")
1783
1784 (js2-msg "msg.undef.prop.write"
1785 "Cannot set property '%s' of %s to '%s'")
1786
1787 (js2-msg "msg.undef.prop.delete"
1788 "Cannot delete property '%s' of %s")
1789
1790 (js2-msg "msg.undef.method.call"
1791 "Cannot call method '%s' of %s")
1792
1793 (js2-msg "msg.undef.with"
1794 "Cannot apply 'with' to %s")
1795
1796 (js2-msg "msg.isnt.function"
1797 "%s is not a function, it is %s.")
1798
1799 (js2-msg "msg.isnt.function.in"
1800 "Cannot call property %s in object %s. "
1801 "It is not a function, it is '%s'.")
1802
1803 (js2-msg "msg.function.not.found"
1804 "Cannot find function %s.")
1805
1806 (js2-msg "msg.function.not.found.in"
1807 "Cannot find function %s in object %s.")
1808
1809 (js2-msg "msg.isnt.xml.object"
1810 "%s is not an xml object.")
1811
1812 (js2-msg "msg.no.ref.to.get"
1813 "%s is not a reference to read reference value.")
1814
1815 (js2-msg "msg.no.ref.to.set"
1816 "%s is not a reference to set reference value to %s.")
1817
1818 (js2-msg "msg.no.ref.from.function"
1819 "Function %s can not be used as the left-hand "
1820 "side of assignment or as an operand of ++ or -- operator.")
1821
1822 (js2-msg "msg.bad.default.value"
1823 "Object's getDefaultValue() method returned an object.")
1824
1825 (js2-msg "msg.instanceof.not.object"
1826 "Can't use instanceof on a non-object.")
1827
1828 (js2-msg "msg.instanceof.bad.prototype"
1829 "'prototype' property of %s is not an object.")
1830
1831 (js2-msg "msg.bad.radix"
1832 "illegal radix %s.")
1833
1834 ;; ScriptableObject
1835 (js2-msg "msg.default.value"
1836 "Cannot find default value for object.")
1837
1838 (js2-msg "msg.zero.arg.ctor"
1839 "Cannot load class '%s' which has no zero-parameter constructor.")
1840
1841 (js2-msg "msg.ctor.multiple.parms"
1842 "Can't define constructor or class %s since more than "
1843 "one constructor has multiple parameters.")
1844
1845 (js2-msg "msg.extend.scriptable"
1846 "%s must extend ScriptableObject in order to define property %s.")
1847
1848 (js2-msg "msg.bad.getter.parms"
1849 "In order to define a property, getter %s must have zero "
1850 "parameters or a single ScriptableObject parameter.")
1851
1852 (js2-msg "msg.obj.getter.parms"
1853 "Expected static or delegated getter %s to take "
1854 "a ScriptableObject parameter.")
1855
1856 (js2-msg "msg.getter.static"
1857 "Getter and setter must both be static or neither be static.")
1858
1859 (js2-msg "msg.setter.return"
1860 "Setter must have void return type: %s")
1861
1862 (js2-msg "msg.setter2.parms"
1863 "Two-parameter setter must take a ScriptableObject as "
1864 "its first parameter.")
1865
1866 (js2-msg "msg.setter1.parms"
1867 "Expected single parameter setter for %s")
1868
1869 (js2-msg "msg.setter2.expected"
1870 "Expected static or delegated setter %s to take two parameters.")
1871
1872 (js2-msg "msg.setter.parms"
1873 "Expected either one or two parameters for setter.")
1874
1875 (js2-msg "msg.setter.bad.type"
1876 "Unsupported parameter type '%s' in setter '%s'.")
1877
1878 (js2-msg "msg.add.sealed"
1879 "Cannot add a property to a sealed object: %s.")
1880
1881 (js2-msg "msg.remove.sealed"
1882 "Cannot remove a property from a sealed object: %s.")
1883
1884 (js2-msg "msg.modify.sealed"
1885 "Cannot modify a property of a sealed object: %s.")
1886
1887 (js2-msg "msg.modify.readonly"
1888 "Cannot modify readonly property: %s.")
1889
1890 ;; TokenStream
1891 (js2-msg "msg.missing.exponent"
1892 "missing exponent")
1893
1894 (js2-msg "msg.caught.nfe"
1895 "number format error")
1896
1897 (js2-msg "msg.unterminated.string.lit"
1898 "unterminated string literal")
1899
1900 (js2-msg "msg.unterminated.comment"
1901 "unterminated comment")
1902
1903 (js2-msg "msg.unterminated.re.lit"
1904 "unterminated regular expression literal")
1905
1906 (js2-msg "msg.invalid.re.flag"
1907 "invalid flag after regular expression")
1908
1909 (js2-msg "msg.no.re.input.for"
1910 "no input for %s")
1911
1912 (js2-msg "msg.illegal.character"
1913 "illegal character")
1914
1915 (js2-msg "msg.invalid.escape"
1916 "invalid Unicode escape sequence")
1917
1918 (js2-msg "msg.bad.namespace"
1919 "not a valid default namespace statement. "
1920 "Syntax is: default xml namespace = EXPRESSION;")
1921
1922 ;; TokensStream warnings
1923 (js2-msg "msg.bad.octal.literal"
1924 "illegal octal literal digit %s; "
1925 "interpreting it as a decimal digit")
1926
1927 (js2-msg "msg.missing.hex.digits"
1928 "missing hexadecimal digits after '0x'")
1929
1930 (js2-msg "msg.missing.binary.digits"
1931 "missing binary digits after '0b'")
1932
1933 (js2-msg "msg.missing.octal.digits"
1934 "missing octal digits after '0o'")
1935
1936 (js2-msg "msg.script.is.not.constructor"
1937 "Script objects are not constructors.")
1938
1939 ;; Arrays
1940 (js2-msg "msg.arraylength.bad"
1941 "Inappropriate array length.")
1942
1943 ;; Arrays
1944 (js2-msg "msg.arraylength.too.big"
1945 "Array length %s exceeds supported capacity limit.")
1946
1947 ;; URI
1948 (js2-msg "msg.bad.uri"
1949 "Malformed URI sequence.")
1950
1951 ;; Number
1952 (js2-msg "msg.bad.precision"
1953 "Precision %s out of range.")
1954
1955 ;; NativeGenerator
1956 (js2-msg "msg.send.newborn"
1957 "Attempt to send value to newborn generator")
1958
1959 (js2-msg "msg.already.exec.gen"
1960 "Already executing generator")
1961
1962 (js2-msg "msg.StopIteration.invalid"
1963 "StopIteration may not be changed to an arbitrary object.")
1964
1965 ;; Interpreter
1966 (js2-msg "msg.yield.closing"
1967 "Yield from closing generator")
1968
1969 ;; Classes
1970 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1971 "class statement requires a name")
1972
1973 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1974 "unexpected ',' between class properties")
1975
1976 (js2-msg "msg.unexpected.static" ; added by js2-mode
1977 "unexpected 'static'")
1978
1979 (js2-msg "msg.missing.extends" ; added by js2-mode
1980 "name is required after extends")
1981
1982 (js2-msg "msg.no.brace.class" ; added by js2-mode
1983 "missing '{' before class body")
1984
1985 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1986 "missing ']' after computed property expression")
1987
1988 ;;; Tokens Buffer
1989
1990 (defconst js2-ti-max-lookahead 2)
1991 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1992
1993 ;; Have to call `js2-init-scanner' to initialize the values.
1994 (js2-deflocal js2-ti-tokens nil)
1995 (js2-deflocal js2-ti-tokens-cursor nil)
1996 (js2-deflocal js2-ti-lookahead nil)
1997
1998 (defun js2-new-token (offset)
1999 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2000 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2001 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2002 token))
2003
2004 (defsubst js2-current-token ()
2005 (aref js2-ti-tokens js2-ti-tokens-cursor))
2006
2007 (defsubst js2-current-token-string ()
2008 (js2-token-string (js2-current-token)))
2009
2010 (defsubst js2-current-token-type ()
2011 (js2-token-type (js2-current-token)))
2012
2013 (defsubst js2-current-token-beg ()
2014 (js2-token-beg (js2-current-token)))
2015
2016 (defsubst js2-current-token-end ()
2017 (js2-token-end (js2-current-token)))
2018
2019 (defun js2-current-token-len ()
2020 (let ((token (js2-current-token)))
2021 (- (js2-token-end token)
2022 (js2-token-beg token))))
2023
2024 (defun js2-ts-seek (state)
2025 (setq js2-ts-lineno (js2-ts-state-lineno state)
2026 js2-ts-cursor (js2-ts-state-cursor state)
2027 js2-ti-tokens (js2-ts-state-tokens state)
2028 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2029 js2-ti-lookahead (js2-ts-state-lookahead state)))
2030
2031 ;;; Utilities
2032
2033 (defun js2-delete-if (predicate list)
2034 "Remove all items satisfying PREDICATE in LIST."
2035 (loop for item in list
2036 if (not (funcall predicate item))
2037 collect item))
2038
2039 (defun js2-position (element list)
2040 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2041 Returns nil if element is not found in the list."
2042 (let ((count 0)
2043 found)
2044 (while (and list (not found))
2045 (if (eq element (car list))
2046 (setq found t)
2047 (setq count (1+ count)
2048 list (cdr list))))
2049 (if found count)))
2050
2051 (defun js2-find-if (predicate list)
2052 "Find first item satisfying PREDICATE in LIST."
2053 (let (result)
2054 (while (and list (not result))
2055 (if (funcall predicate (car list))
2056 (setq result (car list)))
2057 (setq list (cdr list)))
2058 result))
2059
2060 (defmacro js2-time (form)
2061 "Evaluate FORM, discard result, and return elapsed time in sec."
2062 (declare (debug t))
2063 (let ((beg (make-symbol "--js2-time-beg--"))
2064 (delta (make-symbol "--js2-time-end--")))
2065 `(let ((,beg (current-time))
2066 ,delta)
2067 ,form
2068 (/ (truncate (* (- (float-time (current-time))
2069 (float-time ,beg))
2070 10000))
2071 10000.0))))
2072
2073 (defsubst js2-same-line (pos)
2074 "Return t if POS is on the same line as current point."
2075 (and (>= pos (point-at-bol))
2076 (<= pos (point-at-eol))))
2077
2078 (defun js2-code-bug ()
2079 "Signal an error when we encounter an unexpected code path."
2080 (error "failed assertion"))
2081
2082 (defsubst js2-record-text-property (beg end prop value)
2083 "Record a text property to set when parsing finishes."
2084 (push (list beg end prop value) js2-mode-deferred-properties))
2085
2086 ;; I'd like to associate errors with nodes, but for now the
2087 ;; easiest thing to do is get the context info from the last token.
2088 (defun js2-record-parse-error (msg &optional arg pos len)
2089 (push (list (list msg arg)
2090 (or pos (js2-current-token-beg))
2091 (or len (js2-current-token-len)))
2092 js2-parsed-errors))
2093
2094 (defun js2-report-error (msg &optional msg-arg pos len)
2095 "Signal a syntax error or record a parse error."
2096 (if js2-recover-from-parse-errors
2097 (js2-record-parse-error msg msg-arg pos len)
2098 (signal 'js2-syntax-error
2099 (list msg
2100 js2-ts-lineno
2101 (save-excursion
2102 (goto-char js2-ts-cursor)
2103 (current-column))
2104 js2-ts-hit-eof))))
2105
2106 (defun js2-report-warning (msg &optional msg-arg pos len face)
2107 (if js2-compiler-report-warning-as-error
2108 (js2-report-error msg msg-arg pos len)
2109 (push (list (list msg msg-arg)
2110 (or pos (js2-current-token-beg))
2111 (or len (js2-current-token-len))
2112 face)
2113 js2-parsed-warnings)))
2114
2115 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2116 (if js2-compiler-strict-mode
2117 (js2-report-warning msg-id msg-arg beg
2118 (and beg end (- end beg)))))
2119
2120 (put 'js2-syntax-error 'error-conditions
2121 '(error syntax-error js2-syntax-error))
2122 (put 'js2-syntax-error 'error-message "Syntax error")
2123
2124 (put 'js2-parse-error 'error-conditions
2125 '(error parse-error js2-parse-error))
2126 (put 'js2-parse-error 'error-message "Parse error")
2127
2128 (defmacro js2-clear-flag (flags flag)
2129 `(setq ,flags (logand ,flags (lognot ,flag))))
2130
2131 (defmacro js2-set-flag (flags flag)
2132 "Logical-or FLAG into FLAGS."
2133 `(setq ,flags (logior ,flags ,flag)))
2134
2135 (defsubst js2-flag-set-p (flags flag)
2136 (/= 0 (logand flags flag)))
2137
2138 (defsubst js2-flag-not-set-p (flags flag)
2139 (zerop (logand flags flag)))
2140
2141 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2142 "Evaluate BODY with the _ character set to be word-syntax."
2143 (declare (indent 0) (debug t))
2144 (let ((old-syntax (make-symbol "old-syntax")))
2145 `(let ((,old-syntax (string (char-syntax ?_))))
2146 (unwind-protect
2147 (progn
2148 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2149 ,@body)
2150 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2151
2152 ;;; AST struct and function definitions
2153
2154 ;; flags for ast node property 'member-type (used for e4x operators)
2155 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2156 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2157 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2158
2159 (defsubst js2-relpos (pos anchor)
2160 "Convert POS to be relative to ANCHOR.
2161 If POS is nil, returns nil."
2162 (and pos (- pos anchor)))
2163
2164 (defun js2-make-pad (indent)
2165 (if (zerop indent)
2166 ""
2167 (make-string (* indent js2-basic-offset) ? )))
2168
2169 (defun js2-visit-ast (node callback)
2170 "Visit every node in ast NODE with visitor CALLBACK.
2171
2172 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2173 called twice: once to visit the node, and again after all the node's
2174 children have been processed. The END-P argument is nil on the first
2175 call and non-nil on the second call. The return value of the callback
2176 affects the traversal: if non-nil, the children of NODE are processed.
2177 If the callback returns nil, or if the node has no children, then the
2178 callback is called immediately with a non-nil END-P argument.
2179
2180 The node traversal is approximately lexical-order, although there
2181 are currently no guarantees around this."
2182 (when node
2183 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2184 ;; visit the node
2185 (when (funcall callback node nil)
2186 ;; visit the kids
2187 (cond
2188 ((eq vfunc 'js2-visit-none)
2189 nil) ; don't even bother calling it
2190 ;; Each AST node type has to define a `js2-visitor' function
2191 ;; that takes a node and a callback, and calls `js2-visit-ast'
2192 ;; on each child of the node.
2193 (vfunc
2194 (funcall vfunc node callback))
2195 (t
2196 (error "%s does not define a visitor-traversal function"
2197 (aref node 0)))))
2198 ;; call the end-visit
2199 (funcall callback node t))))
2200
2201 (defstruct (js2-node
2202 (:constructor nil)) ; abstract
2203 "Base AST node type."
2204 (type -1) ; token type
2205 (pos -1) ; start position of this AST node in parsed input
2206 (len 1) ; num characters spanned by the node
2207 props ; optional node property list (an alist)
2208 parent) ; link to parent node; null for root
2209
2210 (defsubst js2-node-get-prop (node prop &optional default)
2211 (or (cadr (assoc prop (js2-node-props node))) default))
2212
2213 (defsubst js2-node-set-prop (node prop value)
2214 (setf (js2-node-props node)
2215 (cons (list prop value) (js2-node-props node))))
2216
2217 (defun js2-fixup-starts (n nodes)
2218 "Adjust the start positions of NODES to be relative to N.
2219 Any node in the list may be nil, for convenience."
2220 (dolist (node nodes)
2221 (when node
2222 (setf (js2-node-pos node) (- (js2-node-pos node)
2223 (js2-node-pos n))))))
2224
2225 (defun js2-node-add-children (parent &rest nodes)
2226 "Set parent node of NODES to PARENT, and return PARENT.
2227 Does nothing if we're not recording parent links.
2228 If any given node in NODES is nil, doesn't record that link."
2229 (js2-fixup-starts parent nodes)
2230 (dolist (node nodes)
2231 (and node
2232 (setf (js2-node-parent node) parent))))
2233
2234 ;; Non-recursive since it's called a frightening number of times.
2235 (defun js2-node-abs-pos (n)
2236 (let ((pos (js2-node-pos n)))
2237 (while (setq n (js2-node-parent n))
2238 (setq pos (+ pos (js2-node-pos n))))
2239 pos))
2240
2241 (defsubst js2-node-abs-end (n)
2242 "Return absolute buffer position of end of N."
2243 (+ (js2-node-abs-pos n) (js2-node-len n)))
2244
2245 ;; It's important to make sure block nodes have a Lisp list for the
2246 ;; child nodes, to limit printing recursion depth in an AST that
2247 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2248 ;; a sufficiently large vector tree.
2249
2250 (defstruct (js2-block-node
2251 (:include js2-node)
2252 (:constructor nil)
2253 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2254 (pos (js2-current-token-beg))
2255 len
2256 props
2257 kids)))
2258 "A block of statements."
2259 kids) ; a Lisp list of the child statement nodes
2260
2261 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2262 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2263
2264 (defun js2-visit-block (ast callback)
2265 "Visit the `js2-block-node' children of AST."
2266 (dolist (kid (js2-block-node-kids ast))
2267 (js2-visit-ast kid callback)))
2268
2269 (defun js2-print-block (n i)
2270 (let ((pad (js2-make-pad i)))
2271 (insert pad "{\n")
2272 (dolist (kid (js2-block-node-kids n))
2273 (js2-print-ast kid (1+ i)))
2274 (insert pad "}")))
2275
2276 (defstruct (js2-scope
2277 (:include js2-block-node)
2278 (:constructor nil)
2279 (:constructor make-js2-scope (&key (type js2-BLOCK)
2280 (pos (js2-current-token-beg))
2281 len
2282 kids)))
2283 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2284 ;; I don't have one of those handy, so I'll use an alist for now.
2285 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2286 ;; and is much lighter-weight to construct (both CPU and mem).
2287 ;; The keys are interned strings (symbols) for faster lookup.
2288 ;; Should switch to hybrid alist/hashtable eventually.
2289 symbol-table ; an alist of (symbol . js2-symbol)
2290 parent-scope ; a `js2-scope'
2291 top) ; top-level `js2-scope' (script/function)
2292
2293 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2294 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2295
2296 (defun js2-node-get-enclosing-scope (node)
2297 "Return the innermost `js2-scope' node surrounding NODE.
2298 Returns nil if there is no enclosing scope node."
2299 (let ((parent (js2-node-parent node)))
2300 (while (not (js2-scope-p parent))
2301 (setq parent (js2-node-parent parent)))
2302 parent))
2303
2304 (defun js2-get-defining-scope (scope name)
2305 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2306 Returns `js2-scope' in which NAME is defined, or nil if not found."
2307 (let ((sym (if (symbolp name)
2308 name
2309 (intern name)))
2310 table
2311 result
2312 (continue t))
2313 (while (and scope continue)
2314 (if (and (setq table (js2-scope-symbol-table scope))
2315 (assq sym table))
2316 (setq continue nil
2317 result scope)
2318 (setq scope (js2-scope-parent-scope scope))))
2319 result))
2320
2321 (defun js2-scope-get-symbol (scope name)
2322 "Return symbol table entry for NAME in SCOPE.
2323 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2324 (and (js2-scope-symbol-table scope)
2325 (cdr (assq (if (symbolp name)
2326 name
2327 (intern name))
2328 (js2-scope-symbol-table scope)))))
2329
2330 (defun js2-scope-put-symbol (scope name symbol)
2331 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2332 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2333 (let* ((table (js2-scope-symbol-table scope))
2334 (sym (if (symbolp name) name (intern name)))
2335 (entry (assq sym table)))
2336 (if entry
2337 (setcdr entry symbol)
2338 (push (cons sym symbol)
2339 (js2-scope-symbol-table scope)))))
2340
2341 (defstruct (js2-symbol
2342 (:constructor nil)
2343 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2344 "A symbol table entry."
2345 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2346 ;; js2-LET, or js2-CONST
2347 decl-type
2348 name ; string
2349 ast-node) ; a `js2-node'
2350
2351 (defstruct (js2-error-node
2352 (:include js2-node)
2353 (:constructor nil) ; silence emacs21 byte-compiler
2354 (:constructor make-js2-error-node (&key (type js2-ERROR)
2355 (pos (js2-current-token-beg))
2356 len)))
2357 "AST node representing a parse error.")
2358
2359 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2360 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2361
2362 (defstruct (js2-script-node
2363 (:include js2-scope)
2364 (:constructor nil)
2365 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2366 (pos (js2-current-token-beg))
2367 len
2368 ;; FIXME: What are those?
2369 var-decls
2370 fun-decls)))
2371 functions ; Lisp list of nested functions
2372 regexps ; Lisp list of (string . flags)
2373 symbols ; alist (every symbol gets unique index)
2374 (param-count 0)
2375 var-names ; vector of string names
2376 consts ; bool-vector matching var-decls
2377 (temp-number 0)) ; for generating temp variables
2378
2379 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2380 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2381
2382 (defun js2-print-script (node indent)
2383 (dolist (kid (js2-block-node-kids node))
2384 (js2-print-ast kid indent)))
2385
2386 (defstruct (js2-ast-root
2387 (:include js2-script-node)
2388 (:constructor nil)
2389 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2390 (pos (js2-current-token-beg))
2391 len
2392 buffer)))
2393 "The root node of a js2 AST."
2394 buffer ; the source buffer from which the code was parsed
2395 comments ; a Lisp list of comments, ordered by start position
2396 errors ; a Lisp list of errors found during parsing
2397 warnings ; a Lisp list of warnings found during parsing
2398 node-count) ; number of nodes in the tree, including the root
2399
2400 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2401 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2402
2403 (defun js2-visit-ast-root (ast callback)
2404 (dolist (kid (js2-ast-root-kids ast))
2405 (js2-visit-ast kid callback))
2406 (dolist (comment (js2-ast-root-comments ast))
2407 (js2-visit-ast comment callback)))
2408
2409 (defstruct (js2-comment-node
2410 (:include js2-node)
2411 (:constructor nil)
2412 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2413 (pos (js2-current-token-beg))
2414 len
2415 format)))
2416 format) ; 'line, 'block, 'jsdoc or 'html
2417
2418 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2419 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2420
2421 (defun js2-print-comment (n i)
2422 ;; We really ought to link end-of-line comments to their nodes.
2423 ;; Or maybe we could add a new comment type, 'endline.
2424 (insert (js2-make-pad i)
2425 (js2-node-string n)))
2426
2427 (defstruct (js2-expr-stmt-node
2428 (:include js2-node)
2429 (:constructor nil)
2430 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2431 (pos js2-ts-cursor)
2432 len
2433 expr)))
2434 "An expression statement."
2435 expr)
2436
2437 (defsubst js2-expr-stmt-node-set-has-result (node)
2438 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2439 (setf (js2-node-type node) js2-EXPR_RESULT))
2440
2441 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2442 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2443
2444 (defun js2-visit-expr-stmt-node (n v)
2445 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2446
2447 (defun js2-print-expr-stmt-node (n indent)
2448 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2449 (insert ";\n"))
2450
2451 (defstruct (js2-loop-node
2452 (:include js2-scope)
2453 (:constructor nil))
2454 "Abstract supertype of loop nodes."
2455 body ; a `js2-block-node'
2456 lp ; position of left-paren, nil if omitted
2457 rp) ; position of right-paren, nil if omitted
2458
2459 (defstruct (js2-do-node
2460 (:include js2-loop-node)
2461 (:constructor nil)
2462 (:constructor make-js2-do-node (&key (type js2-DO)
2463 (pos (js2-current-token-beg))
2464 len
2465 body
2466 condition
2467 while-pos
2468 lp
2469 rp)))
2470 "AST node for do-loop."
2471 condition ; while (expression)
2472 while-pos) ; buffer position of 'while' keyword
2473
2474 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2475 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2476
2477 (defun js2-visit-do-node (n v)
2478 (js2-visit-ast (js2-do-node-body n) v)
2479 (js2-visit-ast (js2-do-node-condition n) v))
2480
2481 (defun js2-print-do-node (n i)
2482 (let ((pad (js2-make-pad i)))
2483 (insert pad "do {\n")
2484 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2485 (js2-print-ast kid (1+ i)))
2486 (insert pad "} while (")
2487 (js2-print-ast (js2-do-node-condition n) 0)
2488 (insert ");\n")))
2489
2490 (defstruct (js2-while-node
2491 (:include js2-loop-node)
2492 (:constructor nil)
2493 (:constructor make-js2-while-node (&key (type js2-WHILE)
2494 (pos (js2-current-token-beg))
2495 len body
2496 condition lp
2497 rp)))
2498 "AST node for while-loop."
2499 condition) ; while-condition
2500
2501 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2502 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2503
2504 (defun js2-visit-while-node (n v)
2505 (js2-visit-ast (js2-while-node-condition n) v)
2506 (js2-visit-ast (js2-while-node-body n) v))
2507
2508 (defun js2-print-while-node (n i)
2509 (let ((pad (js2-make-pad i)))
2510 (insert pad "while (")
2511 (js2-print-ast (js2-while-node-condition n) 0)
2512 (insert ") {\n")
2513 (js2-print-body (js2-while-node-body n) (1+ i))
2514 (insert pad "}\n")))
2515
2516 (defstruct (js2-for-node
2517 (:include js2-loop-node)
2518 (:constructor nil)
2519 (:constructor make-js2-for-node (&key (type js2-FOR)
2520 (pos js2-ts-cursor)
2521 len body init
2522 condition
2523 update lp rp)))
2524 "AST node for a C-style for-loop."
2525 init ; initialization expression
2526 condition ; loop condition
2527 update) ; update clause
2528
2529 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2530 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2531
2532 (defun js2-visit-for-node (n v)
2533 (js2-visit-ast (js2-for-node-init n) v)
2534 (js2-visit-ast (js2-for-node-condition n) v)
2535 (js2-visit-ast (js2-for-node-update n) v)
2536 (js2-visit-ast (js2-for-node-body n) v))
2537
2538 (defun js2-print-for-node (n i)
2539 (let ((pad (js2-make-pad i)))
2540 (insert pad "for (")
2541 (js2-print-ast (js2-for-node-init n) 0)
2542 (insert "; ")
2543 (js2-print-ast (js2-for-node-condition n) 0)
2544 (insert "; ")
2545 (js2-print-ast (js2-for-node-update n) 0)
2546 (insert ") {\n")
2547 (js2-print-body (js2-for-node-body n) (1+ i))
2548 (insert pad "}\n")))
2549
2550 (defstruct (js2-for-in-node
2551 (:include js2-loop-node)
2552 (:constructor nil)
2553 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2554 (pos js2-ts-cursor)
2555 len body
2556 iterator
2557 object
2558 in-pos
2559 each-pos
2560 foreach-p forof-p
2561 lp rp)))
2562 "AST node for a for..in loop."
2563 iterator ; [var] foo in ...
2564 object ; object over which we're iterating
2565 in-pos ; buffer position of 'in' keyword
2566 each-pos ; buffer position of 'each' keyword, if foreach-p
2567 foreach-p ; t if it's a for-each loop
2568 forof-p) ; t if it's a for-of loop
2569
2570 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2571 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2572
2573 (defun js2-visit-for-in-node (n v)
2574 (js2-visit-ast (js2-for-in-node-iterator n) v)
2575 (js2-visit-ast (js2-for-in-node-object n) v)
2576 (js2-visit-ast (js2-for-in-node-body n) v))
2577
2578 (defun js2-print-for-in-node (n i)
2579 (let ((pad (js2-make-pad i))
2580 (foreach (js2-for-in-node-foreach-p n))
2581 (forof (js2-for-in-node-forof-p n)))
2582 (insert pad "for ")
2583 (if foreach
2584 (insert "each "))
2585 (insert "(")
2586 (js2-print-ast (js2-for-in-node-iterator n) 0)
2587 (insert (if forof " of " " in "))
2588 (js2-print-ast (js2-for-in-node-object n) 0)
2589 (insert ") {\n")
2590 (js2-print-body (js2-for-in-node-body n) (1+ i))
2591 (insert pad "}\n")))
2592
2593 (defstruct (js2-return-node
2594 (:include js2-node)
2595 (:constructor nil)
2596 (:constructor make-js2-return-node (&key (type js2-RETURN)
2597 (pos js2-ts-cursor)
2598 len
2599 retval)))
2600 "AST node for a return statement."
2601 retval) ; expression to return, or 'undefined
2602
2603 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2604 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2605
2606 (defun js2-visit-return-node (n v)
2607 (js2-visit-ast (js2-return-node-retval n) v))
2608
2609 (defun js2-print-return-node (n i)
2610 (insert (js2-make-pad i) "return")
2611 (when (js2-return-node-retval n)
2612 (insert " ")
2613 (js2-print-ast (js2-return-node-retval n) 0))
2614 (insert ";\n"))
2615
2616 (defstruct (js2-if-node
2617 (:include js2-node)
2618 (:constructor nil)
2619 (:constructor make-js2-if-node (&key (type js2-IF)
2620 (pos js2-ts-cursor)
2621 len condition
2622 then-part
2623 else-pos
2624 else-part lp
2625 rp)))
2626 "AST node for an if-statement."
2627 condition ; expression
2628 then-part ; statement or block
2629 else-pos ; optional buffer position of 'else' keyword
2630 else-part ; optional statement or block
2631 lp ; position of left-paren, nil if omitted
2632 rp) ; position of right-paren, nil if omitted
2633
2634 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2635 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2636
2637 (defun js2-visit-if-node (n v)
2638 (js2-visit-ast (js2-if-node-condition n) v)
2639 (js2-visit-ast (js2-if-node-then-part n) v)
2640 (js2-visit-ast (js2-if-node-else-part n) v))
2641
2642 (defun js2-print-if-node (n i)
2643 (let ((pad (js2-make-pad i))
2644 (then-part (js2-if-node-then-part n))
2645 (else-part (js2-if-node-else-part n)))
2646 (insert pad "if (")
2647 (js2-print-ast (js2-if-node-condition n) 0)
2648 (insert ") {\n")
2649 (js2-print-body then-part (1+ i))
2650 (insert pad "}")
2651 (cond
2652 ((not else-part)
2653 (insert "\n"))
2654 ((js2-if-node-p else-part)
2655 (insert " else ")
2656 (js2-print-body else-part i))
2657 (t
2658 (insert " else {\n")
2659 (js2-print-body else-part (1+ i))
2660 (insert pad "}\n")))))
2661
2662 (defstruct (js2-try-node
2663 (:include js2-node)
2664 (:constructor nil)
2665 (:constructor make-js2-try-node (&key (type js2-TRY)
2666 (pos js2-ts-cursor)
2667 len
2668 try-block
2669 catch-clauses
2670 finally-block)))
2671 "AST node for a try-statement."
2672 try-block
2673 catch-clauses ; a Lisp list of `js2-catch-node'
2674 finally-block) ; a `js2-finally-node'
2675
2676 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2677 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2678
2679 (defun js2-visit-try-node (n v)
2680 (js2-visit-ast (js2-try-node-try-block n) v)
2681 (dolist (clause (js2-try-node-catch-clauses n))
2682 (js2-visit-ast clause v))
2683 (js2-visit-ast (js2-try-node-finally-block n) v))
2684
2685 (defun js2-print-try-node (n i)
2686 (let ((pad (js2-make-pad i))
2687 (catches (js2-try-node-catch-clauses n))
2688 (finally (js2-try-node-finally-block n)))
2689 (insert pad "try {\n")
2690 (js2-print-body (js2-try-node-try-block n) (1+ i))
2691 (insert pad "}")
2692 (when catches
2693 (dolist (catch catches)
2694 (js2-print-ast catch i)))
2695 (if finally
2696 (js2-print-ast finally i)
2697 (insert "\n"))))
2698
2699 (defstruct (js2-catch-node
2700 (:include js2-node)
2701 (:constructor nil)
2702 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2703 (pos js2-ts-cursor)
2704 len
2705 param
2706 guard-kwd
2707 guard-expr
2708 block lp
2709 rp)))
2710 "AST node for a catch clause."
2711 param ; destructuring form or simple name node
2712 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2713 guard-expr ; catch condition, a `js2-node'
2714 block ; statements, a `js2-block-node'
2715 lp ; buffer position of left-paren, nil if omitted
2716 rp) ; buffer position of right-paren, nil if omitted
2717
2718 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2719 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2720
2721 (defun js2-visit-catch-node (n v)
2722 (js2-visit-ast (js2-catch-node-param n) v)
2723 (when (js2-catch-node-guard-kwd n)
2724 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2725 (js2-visit-ast (js2-catch-node-block n) v))
2726
2727 (defun js2-print-catch-node (n i)
2728 (let ((pad (js2-make-pad i))
2729 (guard-kwd (js2-catch-node-guard-kwd n))
2730 (guard-expr (js2-catch-node-guard-expr n)))
2731 (insert " catch (")
2732 (js2-print-ast (js2-catch-node-param n) 0)
2733 (when guard-kwd
2734 (insert " if ")
2735 (js2-print-ast guard-expr 0))
2736 (insert ") {\n")
2737 (js2-print-body (js2-catch-node-block n) (1+ i))
2738 (insert pad "}")))
2739
2740 (defstruct (js2-finally-node
2741 (:include js2-node)
2742 (:constructor nil)
2743 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2744 (pos js2-ts-cursor)
2745 len body)))
2746 "AST node for a finally clause."
2747 body) ; a `js2-node', often but not always a block node
2748
2749 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2750 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2751
2752 (defun js2-visit-finally-node (n v)
2753 (js2-visit-ast (js2-finally-node-body n) v))
2754
2755 (defun js2-print-finally-node (n i)
2756 (let ((pad (js2-make-pad i)))
2757 (insert " finally {\n")
2758 (js2-print-body (js2-finally-node-body n) (1+ i))
2759 (insert pad "}\n")))
2760
2761 (defstruct (js2-switch-node
2762 (:include js2-node)
2763 (:constructor nil)
2764 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2765 (pos js2-ts-cursor)
2766 len
2767 discriminant
2768 cases lp
2769 rp)))
2770 "AST node for a switch statement."
2771 discriminant ; a `js2-node' (switch expression)
2772 cases ; a Lisp list of `js2-case-node'
2773 lp ; position of open-paren for discriminant, nil if omitted
2774 rp) ; position of close-paren for discriminant, nil if omitted
2775
2776 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2777 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2778
2779 (defun js2-visit-switch-node (n v)
2780 (js2-visit-ast (js2-switch-node-discriminant n) v)
2781 (dolist (c (js2-switch-node-cases n))
2782 (js2-visit-ast c v)))
2783
2784 (defun js2-print-switch-node (n i)
2785 (let ((pad (js2-make-pad i))
2786 (cases (js2-switch-node-cases n)))
2787 (insert pad "switch (")
2788 (js2-print-ast (js2-switch-node-discriminant n) 0)
2789 (insert ") {\n")
2790 (dolist (case cases)
2791 (js2-print-ast case i))
2792 (insert pad "}\n")))
2793
2794 (defstruct (js2-case-node
2795 (:include js2-block-node)
2796 (:constructor nil)
2797 (:constructor make-js2-case-node (&key (type js2-CASE)
2798 (pos js2-ts-cursor)
2799 len kids expr)))
2800 "AST node for a case clause of a switch statement."
2801 expr) ; the case expression (nil for default)
2802
2803 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2804 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2805
2806 (defun js2-visit-case-node (n v)
2807 (js2-visit-ast (js2-case-node-expr n) v)
2808 (js2-visit-block n v))
2809
2810 (defun js2-print-case-node (n i)
2811 (let ((pad (js2-make-pad i))
2812 (expr (js2-case-node-expr n)))
2813 (insert pad)
2814 (if (null expr)
2815 (insert "default:\n")
2816 (insert "case ")
2817 (js2-print-ast expr 0)
2818 (insert ":\n"))
2819 (dolist (kid (js2-case-node-kids n))
2820 (js2-print-ast kid (1+ i)))))
2821
2822 (defstruct (js2-throw-node
2823 (:include js2-node)
2824 (:constructor nil)
2825 (:constructor make-js2-throw-node (&key (type js2-THROW)
2826 (pos js2-ts-cursor)
2827 len expr)))
2828 "AST node for a throw statement."
2829 expr) ; the expression to throw
2830
2831 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2832 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2833
2834 (defun js2-visit-throw-node (n v)
2835 (js2-visit-ast (js2-throw-node-expr n) v))
2836
2837 (defun js2-print-throw-node (n i)
2838 (insert (js2-make-pad i) "throw ")
2839 (js2-print-ast (js2-throw-node-expr n) 0)
2840 (insert ";\n"))
2841
2842 (defstruct (js2-with-node
2843 (:include js2-node)
2844 (:constructor nil)
2845 (:constructor make-js2-with-node (&key (type js2-WITH)
2846 (pos js2-ts-cursor)
2847 len object
2848 body lp rp)))
2849 "AST node for a with-statement."
2850 object
2851 body
2852 lp ; buffer position of left-paren around object, nil if omitted
2853 rp) ; buffer position of right-paren around object, nil if omitted
2854
2855 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2856 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2857
2858 (defun js2-visit-with-node (n v)
2859 (js2-visit-ast (js2-with-node-object n) v)
2860 (js2-visit-ast (js2-with-node-body n) v))
2861
2862 (defun js2-print-with-node (n i)
2863 (let ((pad (js2-make-pad i)))
2864 (insert pad "with (")
2865 (js2-print-ast (js2-with-node-object n) 0)
2866 (insert ") {\n")
2867 (js2-print-body (js2-with-node-body n) (1+ i))
2868 (insert pad "}\n")))
2869
2870 (defstruct (js2-label-node
2871 (:include js2-node)
2872 (:constructor nil)
2873 (:constructor make-js2-label-node (&key (type js2-LABEL)
2874 (pos js2-ts-cursor)
2875 len name)))
2876 "AST node for a statement label or case label."
2877 name ; a string
2878 loop) ; for validating and code-generating continue-to-label
2879
2880 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2881 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2882
2883 (defun js2-print-label (n i)
2884 (insert (js2-make-pad i)
2885 (js2-label-node-name n)
2886 ":\n"))
2887
2888 (defstruct (js2-labeled-stmt-node
2889 (:include js2-node)
2890 (:constructor nil)
2891 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2892 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2893 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2894 (pos js2-ts-cursor)
2895 len labels stmt)))
2896 "AST node for a statement with one or more labels.
2897 Multiple labels for a statement are collapsed into the labels field."
2898 labels ; Lisp list of `js2-label-node'
2899 stmt) ; the statement these labels are for
2900
2901 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2902 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2903
2904 (defun js2-get-label-by-name (lbl-stmt name)
2905 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2906 Returns nil if no such label is in the list."
2907 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2908 result)
2909 (while (and label-list (not result))
2910 (if (string= (js2-label-node-name (car label-list)) name)
2911 (setq result (car label-list))
2912 (setq label-list (cdr label-list))))
2913 result))
2914
2915 (defun js2-visit-labeled-stmt (n v)
2916 (dolist (label (js2-labeled-stmt-node-labels n))
2917 (js2-visit-ast label v))
2918 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2919
2920 (defun js2-print-labeled-stmt (n i)
2921 (dolist (label (js2-labeled-stmt-node-labels n))
2922 (js2-print-ast label i))
2923 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2924
2925 (defun js2-labeled-stmt-node-contains (node label)
2926 "Return t if NODE contains LABEL in its label set.
2927 NODE is a `js2-labels-node'. LABEL is an identifier."
2928 (loop for nl in (js2-labeled-stmt-node-labels node)
2929 if (string= label (js2-label-node-name nl))
2930 return t
2931 finally return nil))
2932
2933 (defsubst js2-labeled-stmt-node-add-label (node label)
2934 "Add a `js2-label-node' to the label set for this statement."
2935 (setf (js2-labeled-stmt-node-labels node)
2936 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2937
2938 (defstruct (js2-jump-node
2939 (:include js2-node)
2940 (:constructor nil))
2941 "Abstract supertype of break and continue nodes."
2942 label ; `js2-name-node' for location of label identifier, if present
2943 target) ; target js2-labels-node or loop/switch statement
2944
2945 (defun js2-visit-jump-node (n v)
2946 ;; We don't visit the target, since it's a back-link.
2947 (js2-visit-ast (js2-jump-node-label n) v))
2948
2949 (defstruct (js2-break-node
2950 (:include js2-jump-node)
2951 (:constructor nil)
2952 (:constructor make-js2-break-node (&key (type js2-BREAK)
2953 (pos js2-ts-cursor)
2954 len label target)))
2955 "AST node for a break statement.
2956 The label field is a `js2-name-node', possibly nil, for the named label
2957 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2958 is the target of the break - a label node or enclosing loop/switch statement.")
2959
2960 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2961 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2962
2963 (defun js2-print-break-node (n i)
2964 (insert (js2-make-pad i) "break")
2965 (when (js2-break-node-label n)
2966 (insert " ")
2967 (js2-print-ast (js2-break-node-label n) 0))
2968 (insert ";\n"))
2969
2970 (defstruct (js2-continue-node
2971 (:include js2-jump-node)
2972 (:constructor nil)
2973 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2974 (pos js2-ts-cursor)
2975 len label target)))
2976 "AST node for a continue statement.
2977 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2978 It is nil if continue specifies no label. The target field is the jump target:
2979 a `js2-label-node' or the innermost enclosing loop.")
2980
2981 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2982 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2983
2984 (defun js2-print-continue-node (n i)
2985 (insert (js2-make-pad i) "continue")
2986 (when (js2-continue-node-label n)
2987 (insert " ")
2988 (js2-print-ast (js2-continue-node-label n) 0))
2989 (insert ";\n"))
2990
2991 (defstruct (js2-function-node
2992 (:include js2-script-node)
2993 (:constructor nil)
2994 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2995 (pos js2-ts-cursor)
2996 len
2997 (ftype 'FUNCTION)
2998 (form 'FUNCTION_STATEMENT)
2999 (name "")
3000 params rest-p
3001 body
3002 generator-type
3003 lp rp)))
3004 "AST node for a function declaration.
3005 The `params' field is a Lisp list of nodes. Each node is either a simple
3006 `js2-name-node', or if it's a destructuring-assignment parameter, a
3007 `js2-array-node' or `js2-object-node'."
3008 ftype ; FUNCTION, GETTER or SETTER
3009 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3010 name ; function name (a `js2-name-node', or nil if anonymous)
3011 params ; a Lisp list of destructuring forms or simple name nodes
3012 rest-p ; if t, the last parameter is rest parameter
3013 body ; a `js2-block-node' or expression node (1.8 only)
3014 lp ; position of arg-list open-paren, or nil if omitted
3015 rp ; position of arg-list close-paren, or nil if omitted
3016 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3017 needs-activation ; t if we need an activation object for this frame
3018 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3019 member-expr) ; nonstandard Ecma extension from Rhino
3020
3021 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3022 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3023
3024 (defun js2-visit-function-node (n v)
3025 (js2-visit-ast (js2-function-node-name n) v)
3026 (dolist (p (js2-function-node-params n))
3027 (js2-visit-ast p v))
3028 (js2-visit-ast (js2-function-node-body n) v))
3029
3030 (defun js2-print-function-node (n i)
3031 (let* ((pad (js2-make-pad i))
3032 (getter (js2-node-get-prop n 'GETTER_SETTER))
3033 (name (or (js2-function-node-name n)
3034 (js2-function-node-member-expr n)))
3035 (params (js2-function-node-params n))
3036 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3037 (rest-p (js2-function-node-rest-p n))
3038 (body (js2-function-node-body n))
3039 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3040 (unless (or getter arrow)
3041 (insert pad "function")
3042 (when (eq (js2-function-node-generator-type n) 'STAR)
3043 (insert "*")))
3044 (when name
3045 (insert " ")
3046 (js2-print-ast name 0))
3047 (insert "(")
3048 (loop with len = (length params)
3049 for param in params
3050 for count from 1
3051 do
3052 (when (and rest-p (= count len))
3053 (insert "..."))
3054 (js2-print-ast param 0)
3055 (when (< count len)
3056 (insert ", ")))
3057 (insert ") ")
3058 (when arrow
3059 (insert "=> "))
3060 (insert "{")
3061 ;; TODO: fix this to be smarter about indenting, etc.
3062 (unless expr
3063 (insert "\n"))
3064 (if (js2-block-node-p body)
3065 (js2-print-body body (1+ i))
3066 (js2-print-ast body 0))
3067 (insert pad "}")
3068 (unless expr
3069 (insert "\n"))))
3070
3071 (defun js2-function-name (node)
3072 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3073 (and (js2-function-node-name node)
3074 (js2-name-node-name (js2-function-node-name node))))
3075
3076 ;; Having this be an expression node makes it more flexible.
3077 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3078 ;; that work better if you assume it's an expression. Whenever we have
3079 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3080 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3081 (defstruct (js2-var-decl-node
3082 (:include js2-node)
3083 (:constructor nil)
3084 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3085 (pos (js2-current-token-beg))
3086 len kids
3087 decl-type)))
3088 "AST node for a variable declaration list (VAR, CONST or LET).
3089 The node bounds differ depending on the declaration type. For VAR or
3090 CONST declarations, the bounds include the var/const keyword. For LET
3091 declarations, the node begins at the position of the first child."
3092 kids ; a Lisp list of `js2-var-init-node' structs.
3093 decl-type) ; js2-VAR, js2-CONST or js2-LET
3094
3095 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3096 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3097
3098 (defun js2-visit-var-decl (n v)
3099 (dolist (kid (js2-var-decl-node-kids n))
3100 (js2-visit-ast kid v)))
3101
3102 (defun js2-print-var-decl (n i)
3103 (let ((pad (js2-make-pad i))
3104 (tt (js2-var-decl-node-decl-type n)))
3105 (insert pad)
3106 (insert (cond
3107 ((= tt js2-VAR) "var ")
3108 ((= tt js2-LET) "let ")
3109 ((= tt js2-CONST) "const ")
3110 (t
3111 (error "malformed var-decl node"))))
3112 (loop with kids = (js2-var-decl-node-kids n)
3113 with len = (length kids)
3114 for kid in kids
3115 for count from 1
3116 do
3117 (js2-print-ast kid 0)
3118 (if (< count len)
3119 (insert ", ")))))
3120
3121 (defstruct (js2-var-init-node
3122 (:include js2-node)
3123 (:constructor nil)
3124 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3125 (pos js2-ts-cursor)
3126 len target
3127 initializer)))
3128 "AST node for a variable declaration.
3129 The type field will be js2-CONST for a const decl."
3130 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3131 initializer) ; initializer expression, a `js2-node'
3132
3133 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3134 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3135
3136 (defun js2-visit-var-init-node (n v)
3137 (js2-visit-ast (js2-var-init-node-target n) v)
3138 (js2-visit-ast (js2-var-init-node-initializer n) v))
3139
3140 (defun js2-print-var-init-node (n i)
3141 (let ((pad (js2-make-pad i))
3142 (name (js2-var-init-node-target n))
3143 (init (js2-var-init-node-initializer n)))
3144 (insert pad)
3145 (js2-print-ast name 0)
3146 (when init
3147 (insert " = ")
3148 (js2-print-ast init 0))))
3149
3150 (defstruct (js2-cond-node
3151 (:include js2-node)
3152 (:constructor nil)
3153 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3154 (pos js2-ts-cursor)
3155 len
3156 test-expr
3157 true-expr
3158 false-expr
3159 q-pos c-pos)))
3160 "AST node for the ternary operator"
3161 test-expr
3162 true-expr
3163 false-expr
3164 q-pos ; buffer position of ?
3165 c-pos) ; buffer position of :
3166
3167 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3168 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3169
3170 (defun js2-visit-cond-node (n v)
3171 (js2-visit-ast (js2-cond-node-test-expr n) v)
3172 (js2-visit-ast (js2-cond-node-true-expr n) v)
3173 (js2-visit-ast (js2-cond-node-false-expr n) v))
3174
3175 (defun js2-print-cond-node (n i)
3176 (let ((pad (js2-make-pad i)))
3177 (insert pad)
3178 (js2-print-ast (js2-cond-node-test-expr n) 0)
3179 (insert " ? ")
3180 (js2-print-ast (js2-cond-node-true-expr n) 0)
3181 (insert " : ")
3182 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3183
3184 (defstruct (js2-infix-node
3185 (:include js2-node)
3186 (:constructor nil)
3187 (:constructor make-js2-infix-node (&key type
3188 (pos js2-ts-cursor)
3189 len op-pos
3190 left right)))
3191 "Represents infix expressions.
3192 Includes assignment ops like `|=', and the comma operator.
3193 The type field inherited from `js2-node' holds the operator."
3194 op-pos ; buffer position where operator begins
3195 left ; any `js2-node'
3196 right) ; any `js2-node'
3197
3198 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3199 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3200
3201 (defun js2-visit-infix-node (n v)
3202 (js2-visit-ast (js2-infix-node-left n) v)
3203 (js2-visit-ast (js2-infix-node-right n) v))
3204
3205 (defconst js2-operator-tokens
3206 (let ((table (make-hash-table :test 'eq))
3207 (tokens
3208 (list (cons js2-IN "in")
3209 (cons js2-TYPEOF "typeof")
3210 (cons js2-INSTANCEOF "instanceof")
3211 (cons js2-DELPROP "delete")
3212 (cons js2-COMMA ",")
3213 (cons js2-COLON ":")
3214 (cons js2-OR "||")
3215 (cons js2-AND "&&")
3216 (cons js2-INC "++")
3217 (cons js2-DEC "--")
3218 (cons js2-BITOR "|")
3219 (cons js2-BITXOR "^")
3220 (cons js2-BITAND "&")
3221 (cons js2-EQ "==")
3222 (cons js2-NE "!=")
3223 (cons js2-LT "<")
3224 (cons js2-LE "<=")
3225 (cons js2-GT ">")
3226 (cons js2-GE ">=")
3227 (cons js2-LSH "<<")
3228 (cons js2-RSH ">>")
3229 (cons js2-URSH ">>>")
3230 (cons js2-ADD "+") ; infix plus
3231 (cons js2-SUB "-") ; infix minus
3232 (cons js2-MUL "*")
3233 (cons js2-DIV "/")
3234 (cons js2-MOD "%")
3235 (cons js2-NOT "!")
3236 (cons js2-BITNOT "~")
3237 (cons js2-POS "+") ; unary plus
3238 (cons js2-NEG "-") ; unary minus
3239 (cons js2-TRIPLEDOT "...")
3240 (cons js2-SHEQ "===") ; shallow equality
3241 (cons js2-SHNE "!==") ; shallow inequality
3242 (cons js2-ASSIGN "=")
3243 (cons js2-ASSIGN_BITOR "|=")
3244 (cons js2-ASSIGN_BITXOR "^=")
3245 (cons js2-ASSIGN_BITAND "&=")
3246 (cons js2-ASSIGN_LSH "<<=")
3247 (cons js2-ASSIGN_RSH ">>=")
3248 (cons js2-ASSIGN_URSH ">>>=")
3249 (cons js2-ASSIGN_ADD "+=")
3250 (cons js2-ASSIGN_SUB "-=")
3251 (cons js2-ASSIGN_MUL "*=")
3252 (cons js2-ASSIGN_DIV "/=")
3253 (cons js2-ASSIGN_MOD "%="))))
3254 (loop for (k . v) in tokens do
3255 (puthash k v table))
3256 table))
3257
3258 (defun js2-print-infix-node (n i)
3259 (let* ((tt (js2-node-type n))
3260 (op (gethash tt js2-operator-tokens)))
3261 (unless op
3262 (error "unrecognized infix operator %s" (js2-node-type n)))
3263 (insert (js2-make-pad i))
3264 (js2-print-ast (js2-infix-node-left n) 0)
3265 (unless (= tt js2-COMMA)
3266 (insert " "))
3267 (insert op)
3268 (insert " ")
3269 (js2-print-ast (js2-infix-node-right n) 0)))
3270
3271 (defstruct (js2-assign-node
3272 (:include js2-infix-node)
3273 (:constructor nil)
3274 (:constructor make-js2-assign-node (&key type
3275 (pos js2-ts-cursor)
3276 len op-pos
3277 left right)))
3278 "Represents any assignment.
3279 The type field holds the actual assignment operator.")
3280
3281 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3282 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3283
3284 (defstruct (js2-unary-node
3285 (:include js2-node)
3286 (:constructor nil)
3287 (:constructor make-js2-unary-node (&key type ; required
3288 (pos js2-ts-cursor)
3289 len operand)))
3290 "AST node type for unary operator nodes.
3291 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3292 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3293 property is added if the operator follows the operand."
3294 operand) ; a `js2-node' expression
3295
3296 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3297 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3298
3299 (defun js2-visit-unary-node (n v)
3300 (js2-visit-ast (js2-unary-node-operand n) v))
3301
3302 (defun js2-print-unary-node (n i)
3303 (let* ((tt (js2-node-type n))
3304 (op (gethash tt js2-operator-tokens))
3305 (postfix (js2-node-get-prop n 'postfix)))
3306 (unless op
3307 (error "unrecognized unary operator %s" tt))
3308 (insert (js2-make-pad i))
3309 (unless postfix
3310 (insert op))
3311 (if (or (= tt js2-TYPEOF)
3312 (= tt js2-DELPROP))
3313 (insert " "))
3314 (js2-print-ast (js2-unary-node-operand n) 0)
3315 (when postfix
3316 (insert op))))
3317
3318 (defstruct (js2-let-node
3319 (:include js2-scope)
3320 (:constructor nil)
3321 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3322 (pos (js2-current-token-beg))
3323 len vars body
3324 lp rp)))
3325 "AST node for a let expression or a let statement.
3326 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3327 vars ; a `js2-var-decl-node'
3328 body ; a `js2-node' representing the expression or body block
3329 lp
3330 rp)
3331
3332 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3333 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3334
3335 (defun js2-visit-let-node (n v)
3336 (js2-visit-ast (js2-let-node-vars n) v)
3337 (js2-visit-ast (js2-let-node-body n) v))
3338
3339 (defun js2-print-let-node (n i)
3340 (insert (js2-make-pad i) "let (")
3341 (let ((p (point)))
3342 (js2-print-ast (js2-let-node-vars n) 0)
3343 (delete-region p (+ p 4)))
3344 (insert ") ")
3345 (js2-print-ast (js2-let-node-body n) i))
3346
3347 (defstruct (js2-keyword-node
3348 (:include js2-node)
3349 (:constructor nil)
3350 (:constructor make-js2-keyword-node (&key type
3351 (pos (js2-current-token-beg))
3352 (len (- js2-ts-cursor pos)))))
3353 "AST node representing a literal keyword such as `null'.
3354 Used for `null', `this', `true', `false' and `debugger'.
3355 The node type is set to js2-NULL, js2-THIS, etc.")
3356
3357 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3358 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3359
3360 (defun js2-print-keyword-node (n i)
3361 (insert (js2-make-pad i)
3362 (let ((tt (js2-node-type n)))
3363 (cond
3364 ((= tt js2-THIS) "this")
3365 ((= tt js2-SUPER) "super")
3366 ((= tt js2-NULL) "null")
3367 ((= tt js2-TRUE) "true")
3368 ((= tt js2-FALSE) "false")
3369 ((= tt js2-DEBUGGER) "debugger")
3370 (t (error "Invalid keyword literal type: %d" tt))))))
3371
3372 (defsubst js2-this-or-super-node-p (node)
3373 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3374 (let ((type (js2-node-type node)))
3375 (or (eq type js2-THIS) (eq type js2-SUPER))))
3376
3377 (defstruct (js2-new-node
3378 (:include js2-node)
3379 (:constructor nil)
3380 (:constructor make-js2-new-node (&key (type js2-NEW)
3381 (pos (js2-current-token-beg))
3382 len target
3383 args initializer
3384 lp rp)))
3385 "AST node for new-expression such as new Foo()."
3386 target ; an identifier or reference
3387 args ; a Lisp list of argument nodes
3388 lp ; position of left-paren, nil if omitted
3389 rp ; position of right-paren, nil if omitted
3390 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3391
3392 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3393 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3394
3395 (defun js2-visit-new-node (n v)
3396 (js2-visit-ast (js2-new-node-target n) v)
3397 (dolist (arg (js2-new-node-args n))
3398 (js2-visit-ast arg v))
3399 (js2-visit-ast (js2-new-node-initializer n) v))
3400
3401 (defun js2-print-new-node (n i)
3402 (insert (js2-make-pad i) "new ")
3403 (js2-print-ast (js2-new-node-target n))
3404 (insert "(")
3405 (js2-print-list (js2-new-node-args n))
3406 (insert ")")
3407 (when (js2-new-node-initializer n)
3408 (insert " ")
3409 (js2-print-ast (js2-new-node-initializer n))))
3410
3411 (defstruct (js2-name-node
3412 (:include js2-node)
3413 (:constructor nil)
3414 (:constructor make-js2-name-node (&key (type js2-NAME)
3415 (pos (js2-current-token-beg))
3416 (len (- js2-ts-cursor
3417 (js2-current-token-beg)))
3418 (name (js2-current-token-string)))))
3419 "AST node for a JavaScript identifier"
3420 name ; a string
3421 scope) ; a `js2-scope' (optional, used for codegen)
3422
3423 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3424 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3425
3426 (defun js2-print-name-node (n i)
3427 (insert (js2-make-pad i)
3428 (js2-name-node-name n)))
3429
3430 (defsubst js2-name-node-length (node)
3431 "Return identifier length of NODE, a `js2-name-node'.
3432 Returns 0 if NODE is nil or its identifier field is nil."
3433 (if node
3434 (length (js2-name-node-name node))
3435 0))
3436
3437 (defstruct (js2-number-node
3438 (:include js2-node)
3439 (:constructor nil)
3440 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3441 (pos (js2-current-token-beg))
3442 (len (- js2-ts-cursor
3443 (js2-current-token-beg)))
3444 (value (js2-current-token-string))
3445 (num-value (js2-token-number
3446 (js2-current-token))))))
3447 "AST node for a number literal."
3448 value ; the original string, e.g. "6.02e23"
3449 num-value) ; the parsed number value
3450
3451 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3452 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3453
3454 (defun js2-print-number-node (n i)
3455 (insert (js2-make-pad i)
3456 (number-to-string (js2-number-node-num-value n))))
3457
3458 (defstruct (js2-regexp-node
3459 (:include js2-node)
3460 (:constructor nil)
3461 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3462 (pos (js2-current-token-beg))
3463 (len (- js2-ts-cursor
3464 (js2-current-token-beg)))
3465 value flags)))
3466 "AST node for a regular expression literal."
3467 value ; the regexp string, without // delimiters
3468 flags) ; a string of flags, e.g. `mi'.
3469
3470 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3471 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3472
3473 (defun js2-print-regexp (n i)
3474 (insert (js2-make-pad i)
3475 "/"
3476 (js2-regexp-node-value n)
3477 "/")
3478 (if (js2-regexp-node-flags n)
3479 (insert (js2-regexp-node-flags n))))
3480
3481 (defstruct (js2-string-node
3482 (:include js2-node)
3483 (:constructor nil)
3484 (:constructor make-js2-string-node (&key (type js2-STRING)
3485 (pos (js2-current-token-beg))
3486 (len (- js2-ts-cursor
3487 (js2-current-token-beg)))
3488 (value (js2-current-token-string)))))
3489 "String literal.
3490 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3491 You can tell the quote type by looking at the first character."
3492 value) ; the characters of the string, including the quotes
3493
3494 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3495 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3496
3497 (defun js2-print-string-node (n i)
3498 (insert (js2-make-pad i)
3499 (js2-node-string n)))
3500
3501 (defstruct (js2-array-node
3502 (:include js2-node)
3503 (:constructor nil)
3504 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3505 (pos js2-ts-cursor)
3506 len elems)))
3507 "AST node for an array literal."
3508 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3509
3510 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3511 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3512
3513 (defun js2-visit-array-node (n v)
3514 (dolist (e (js2-array-node-elems n))
3515 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3516
3517 (defun js2-print-array-node (n i)
3518 (insert (js2-make-pad i) "[")
3519 (let ((elems (js2-array-node-elems n)))
3520 (js2-print-list elems)
3521 (when (and elems (null (car (last elems))))
3522 (insert ",")))
3523 (insert "]"))
3524
3525 (defstruct (js2-class-node
3526 (:include js2-node)
3527 (:constructor nil)
3528 (:constructor make-js2-class-node (&key (type js2-CLASS)
3529 (pos js2-ts-cursor)
3530 (form 'CLASS_STATEMENT)
3531 (name "")
3532 extends len elems)))
3533 "AST node for an class expression.
3534 `elems' is a list of `js2-object-prop-node', and `extends' is an
3535 optional `js2-expr-node'"
3536 form ; CLASS_{STATEMENT|EXPRESSION}
3537 name ; class name (a `js2-node-name', or nil if anonymous)
3538 extends ; class heritage (a `js2-expr-node', or nil if none)
3539 elems)
3540
3541 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3542 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3543
3544 (defun js2-visit-class-node (n v)
3545 (js2-visit-ast (js2-class-node-name n) v)
3546 (js2-visit-ast (js2-class-node-extends n) v)
3547 (dolist (e (js2-class-node-elems n))
3548 (js2-visit-ast e v)))
3549
3550 (defun js2-print-class-node (n i)
3551 (let* ((pad (js2-make-pad i))
3552 (name (js2-class-node-name n))
3553 (extends (js2-class-node-extends n))
3554 (elems (js2-class-node-elems n)))
3555 (insert pad "class")
3556 (when name
3557 (insert " ")
3558 (js2-print-ast name 0))
3559 (when extends
3560 (insert " extends ")
3561 (js2-print-ast extends))
3562 (insert " {")
3563 (dolist (elem elems)
3564 (insert "\n")
3565 (if (js2-node-get-prop elem 'STATIC)
3566 (progn (insert (js2-make-pad (1+ i)) "static ")
3567 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3568 (js2-print-ast elem (1+ i))))
3569 (insert "\n" pad "}")))
3570
3571 (defstruct (js2-object-node
3572 (:include js2-node)
3573 (:constructor nil)
3574 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3575 (pos js2-ts-cursor)
3576 len
3577 elems)))
3578 "AST node for an object literal expression.
3579 `elems' is a list of `js2-object-prop-node'."
3580 elems)
3581
3582 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3583 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3584
3585 (defun js2-visit-object-node (n v)
3586 (dolist (e (js2-object-node-elems n))
3587 (js2-visit-ast e v)))
3588
3589 (defun js2-print-object-node (n i)
3590 (insert (js2-make-pad i) "{")
3591 (js2-print-list (js2-object-node-elems n))
3592 (insert "}"))
3593
3594 (defstruct (js2-object-prop-node
3595 (:include js2-infix-node)
3596 (:constructor nil)
3597 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3598 (pos js2-ts-cursor)
3599 len left
3600 right op-pos)))
3601 "AST node for an object literal prop:value entry.
3602 The `left' field is the property: a name node, string node or number node.
3603 The `right' field is a `js2-node' representing the initializer value.
3604 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3605 and both fields have the same value.")
3606
3607 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3608 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3609
3610 (defun js2-print-object-prop-node (n i)
3611 (let* ((left (js2-object-prop-node-left n))
3612 (computed (not (or (js2-string-node-p left)
3613 (js2-number-node-p left)
3614 (js2-name-node-p left)))))
3615 (insert (js2-make-pad i))
3616 (if computed
3617 (insert "["))
3618 (js2-print-ast left 0)
3619 (if computed
3620 (insert "]"))
3621 (if (not (js2-node-get-prop n 'SHORTHAND))
3622 (progn
3623 (insert ": ")
3624 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3625
3626 (defstruct (js2-getter-setter-node
3627 (:include js2-infix-node)
3628 (:constructor nil)
3629 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3630 (pos js2-ts-cursor)
3631 len left right)))
3632 "AST node for a getter/setter property in an object literal.
3633 The `left' field is the `js2-name-node' naming the getter/setter prop.
3634 The `right' field is always an anonymous `js2-function-node' with a node
3635 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3636
3637 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3638 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3639
3640 (defun js2-print-getter-setter (n i)
3641 (let ((pad (js2-make-pad i))
3642 (left (js2-getter-setter-node-left n))
3643 (right (js2-getter-setter-node-right n)))
3644 (insert pad)
3645 (if (/= (js2-node-type n) js2-FUNCTION)
3646 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3647 (js2-print-ast left 0)
3648 (js2-print-ast right 0)))
3649
3650 (defstruct (js2-prop-get-node
3651 (:include js2-infix-node)
3652 (:constructor nil)
3653 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3654 (pos js2-ts-cursor)
3655 len left right)))
3656 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3657
3658 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3659 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3660
3661 (defun js2-visit-prop-get-node (n v)
3662 (js2-visit-ast (js2-prop-get-node-left n) v)
3663 (js2-visit-ast (js2-prop-get-node-right n) v))
3664
3665 (defun js2-print-prop-get-node (n i)
3666 (insert (js2-make-pad i))
3667 (js2-print-ast (js2-prop-get-node-left n) 0)
3668 (insert ".")
3669 (js2-print-ast (js2-prop-get-node-right n) 0))
3670
3671 (defstruct (js2-elem-get-node
3672 (:include js2-node)
3673 (:constructor nil)
3674 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3675 (pos js2-ts-cursor)
3676 len target element
3677 lb rb)))
3678 "AST node for an array index expression such as foo[bar]."
3679 target ; a `js2-node' - the expression preceding the "."
3680 element ; a `js2-node' - the expression in brackets
3681 lb ; position of left-bracket, nil if omitted
3682 rb) ; position of right-bracket, nil if omitted
3683
3684 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3685 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3686
3687 (defun js2-visit-elem-get-node (n v)
3688 (js2-visit-ast (js2-elem-get-node-target n) v)
3689 (js2-visit-ast (js2-elem-get-node-element n) v))
3690
3691 (defun js2-print-elem-get-node (n i)
3692 (insert (js2-make-pad i))
3693 (js2-print-ast (js2-elem-get-node-target n) 0)
3694 (insert "[")
3695 (js2-print-ast (js2-elem-get-node-element n) 0)
3696 (insert "]"))
3697
3698 (defstruct (js2-call-node
3699 (:include js2-node)
3700 (:constructor nil)
3701 (:constructor make-js2-call-node (&key (type js2-CALL)
3702 (pos js2-ts-cursor)
3703 len target args
3704 lp rp)))
3705 "AST node for a JavaScript function call."
3706 target ; a `js2-node' evaluating to the function to call
3707 args ; a Lisp list of `js2-node' arguments
3708 lp ; position of open-paren, or nil if missing
3709 rp) ; position of close-paren, or nil if missing
3710
3711 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3712 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3713
3714 (defun js2-visit-call-node (n v)
3715 (js2-visit-ast (js2-call-node-target n) v)
3716 (dolist (arg (js2-call-node-args n))
3717 (js2-visit-ast arg v)))
3718
3719 (defun js2-print-call-node (n i)
3720 (insert (js2-make-pad i))
3721 (js2-print-ast (js2-call-node-target n) 0)
3722 (insert "(")
3723 (js2-print-list (js2-call-node-args n))
3724 (insert ")"))
3725
3726 (defstruct (js2-yield-node
3727 (:include js2-node)
3728 (:constructor nil)
3729 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3730 (pos js2-ts-cursor)
3731 len value star-p)))
3732 "AST node for yield statement or expression."
3733 star-p ; whether it's yield*
3734 value) ; optional: value to be yielded
3735
3736 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3737 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3738
3739 (defun js2-visit-yield-node (n v)
3740 (js2-visit-ast (js2-yield-node-value n) v))
3741
3742 (defun js2-print-yield-node (n i)
3743 (insert (js2-make-pad i))
3744 (insert "yield")
3745 (when (js2-yield-node-star-p n)
3746 (insert "*"))
3747 (when (js2-yield-node-value n)
3748 (insert " ")
3749 (js2-print-ast (js2-yield-node-value n) 0)))
3750
3751 (defstruct (js2-paren-node
3752 (:include js2-node)
3753 (:constructor nil)
3754 (:constructor make-js2-paren-node (&key (type js2-LP)
3755 (pos js2-ts-cursor)
3756 len expr)))
3757 "AST node for a parenthesized expression.
3758 In particular, used when the parens are syntactically optional,
3759 as opposed to required parens such as those enclosing an if-conditional."
3760 expr) ; `js2-node'
3761
3762 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3763 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3764
3765 (defun js2-visit-paren-node (n v)
3766 (js2-visit-ast (js2-paren-node-expr n) v))
3767
3768 (defun js2-print-paren-node (n i)
3769 (insert (js2-make-pad i))
3770 (insert "(")
3771 (js2-print-ast (js2-paren-node-expr n) 0)
3772 (insert ")"))
3773
3774 (defstruct (js2-comp-node
3775 (:include js2-scope)
3776 (:constructor nil)
3777 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3778 (pos js2-ts-cursor)
3779 len result
3780 loops filters
3781 form)))
3782 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3783 result ; result expression (just after left-bracket)
3784 loops ; a Lisp list of `js2-comp-loop-node'
3785 filters ; a Lisp list of guard/filter expressions
3786 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3787 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3788 )
3789
3790 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3791 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3792
3793 (defun js2-visit-comp-node (n v)
3794 (js2-visit-ast (js2-comp-node-result n) v)
3795 (dolist (l (js2-comp-node-loops n))
3796 (js2-visit-ast l v))
3797 (dolist (f (js2-comp-node-filters n))
3798 (js2-visit-ast f v)))
3799
3800 (defun js2-print-comp-node (n i)
3801 (let ((pad (js2-make-pad i))
3802 (result (js2-comp-node-result n))
3803 (loops (js2-comp-node-loops n))
3804 (filters (js2-comp-node-filters n))
3805 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3806 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3807 (insert pad (if gen-p "(" "["))
3808 (when legacy-p
3809 (js2-print-ast result 0))
3810 (dolist (l loops)
3811 (when legacy-p
3812 (insert " "))
3813 (js2-print-ast l 0)
3814 (unless legacy-p
3815 (insert " ")))
3816 (dolist (f filters)
3817 (when legacy-p
3818 (insert " "))
3819 (insert "if (")
3820 (js2-print-ast f 0)
3821 (insert ")")
3822 (unless legacy-p
3823 (insert " ")))
3824 (unless legacy-p
3825 (js2-print-ast result 0))
3826 (insert (if gen-p ")" "]"))))
3827
3828 (defstruct (js2-comp-loop-node
3829 (:include js2-for-in-node)
3830 (:constructor nil)
3831 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3832 (pos js2-ts-cursor)
3833 len iterator
3834 object in-pos
3835 foreach-p
3836 each-pos
3837 forof-p
3838 lp rp)))
3839 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3840
3841 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3842 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3843
3844 (defun js2-visit-comp-loop (n v)
3845 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3846 (js2-visit-ast (js2-comp-loop-node-object n) v))
3847
3848 (defun js2-print-comp-loop (n _i)
3849 (insert "for ")
3850 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3851 (insert "(")
3852 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3853 (insert (if (js2-comp-loop-node-forof-p n)
3854 " of " " in "))
3855 (js2-print-ast (js2-comp-loop-node-object n) 0)
3856 (insert ")"))
3857
3858 (defstruct (js2-empty-expr-node
3859 (:include js2-node)
3860 (:constructor nil)
3861 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3862 (pos (js2-current-token-beg))
3863 len)))
3864 "AST node for an empty expression.")
3865
3866 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3867 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3868
3869 (defstruct (js2-xml-node
3870 (:include js2-block-node)
3871 (:constructor nil)
3872 (:constructor make-js2-xml-node (&key (type js2-XML)
3873 (pos (js2-current-token-beg))
3874 len kids)))
3875 "AST node for initial parse of E4X literals.
3876 The kids field is a list of XML fragments, each a `js2-string-node' or
3877 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3878
3879 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3880 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3881
3882 (defun js2-print-xml-node (n i)
3883 (dolist (kid (js2-xml-node-kids n))
3884 (js2-print-ast kid i)))
3885
3886 (defstruct (js2-xml-js-expr-node
3887 (:include js2-xml-node)
3888 (:constructor nil)
3889 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3890 (pos js2-ts-cursor)
3891 len expr)))
3892 "AST node for an embedded JavaScript {expression} in an E4X literal.
3893 The start and end fields correspond to the curly-braces."
3894 expr) ; a `js2-expr-node' of some sort
3895
3896 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3897 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3898
3899 (defun js2-visit-xml-js-expr (n v)
3900 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3901
3902 (defun js2-print-xml-js-expr (n i)
3903 (insert (js2-make-pad i))
3904 (insert "{")
3905 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3906 (insert "}"))
3907
3908 (defstruct (js2-xml-dot-query-node
3909 (:include js2-infix-node)
3910 (:constructor nil)
3911 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3912 (pos js2-ts-cursor)
3913 op-pos len left
3914 right rp)))
3915 "AST node for an E4X foo.(bar) filter expression.
3916 Note that the left-paren is automatically the character immediately
3917 following the dot (.) in the operator. No whitespace is permitted
3918 between the dot and the lp by the scanner."
3919 rp)
3920
3921 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3922 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3923
3924 (defun js2-print-xml-dot-query (n i)
3925 (insert (js2-make-pad i))
3926 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3927 (insert ".(")
3928 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3929 (insert ")"))
3930
3931 (defstruct (js2-xml-ref-node
3932 (:include js2-node)
3933 (:constructor nil)) ; abstract
3934 "Base type for E4X XML attribute-access or property-get expressions.
3935 Such expressions can take a variety of forms. The general syntax has
3936 three parts:
3937
3938 - (optional) an @ (specifying an attribute access)
3939 - (optional) a namespace (a `js2-name-node') and double-colon
3940 - (required) either a `js2-name-node' or a bracketed [expression]
3941
3942 The property-name expressions (examples: ns::name, @name) are
3943 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3944 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3945
3946 This node type (or more specifically, its subclasses) will sometimes
3947 be the right-hand child of a `js2-prop-get-node' or a
3948 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3949 The `js2-xml-ref-node' may also be a standalone primary expression with
3950 no explicit target, which is valid in certain expression contexts such as
3951
3952 company..employee.(@id < 100)
3953
3954 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3955 expression whose parent is a `js2-xml-dot-query-node'."
3956 namespace
3957 at-pos
3958 colon-pos)
3959
3960 (defsubst js2-xml-ref-node-attr-access-p (node)
3961 "Return non-nil if this expression began with an @-token."
3962 (and (numberp (js2-xml-ref-node-at-pos node))
3963 (plusp (js2-xml-ref-node-at-pos node))))
3964
3965 (defstruct (js2-xml-prop-ref-node
3966 (:include js2-xml-ref-node)
3967 (:constructor nil)
3968 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3969 (pos (js2-current-token-beg))
3970 len propname
3971 namespace at-pos
3972 colon-pos)))
3973 "AST node for an E4X XML [expr] property-ref expression.
3974 The JavaScript syntax is an optional @, an optional ns::, and a name.
3975
3976 [ '@' ] [ name '::' ] name
3977
3978 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3979 @ns::*, @*::attr, @*::*, and @*.
3980
3981 The node starts at the @ token, if present. Otherwise it starts at the
3982 namespace name. The node bounds extend through the closing right-bracket,
3983 or if it is missing due to a syntax error, through the end of the index
3984 expression."
3985 propname)
3986
3987 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3988 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3989
3990 (defun js2-visit-xml-prop-ref-node (n v)
3991 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3992 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3993
3994 (defun js2-print-xml-prop-ref-node (n i)
3995 (insert (js2-make-pad i))
3996 (if (js2-xml-ref-node-attr-access-p n)
3997 (insert "@"))
3998 (when (js2-xml-prop-ref-node-namespace n)
3999 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4000 (insert "::"))
4001 (if (js2-xml-prop-ref-node-propname n)
4002 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4003
4004 (defstruct (js2-xml-elem-ref-node
4005 (:include js2-xml-ref-node)
4006 (:constructor nil)
4007 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4008 (pos (js2-current-token-beg))
4009 len expr lb rb
4010 namespace at-pos
4011 colon-pos)))
4012 "AST node for an E4X XML [expr] member-ref expression.
4013 Syntax:
4014
4015 [ '@' ] [ name '::' ] '[' expr ']'
4016
4017 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4018
4019 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4020 is not a legal E4X XML element-ref expression, since it's already used
4021 for standard JavaScript element-get array indexing. Hence, a
4022 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4023 non-nil namespace node, or both.
4024
4025 The node starts at the @ token, if present. Otherwise it starts
4026 at the namespace name. The node bounds extend through the closing
4027 right-bracket, or if it is missing due to a syntax error, through the
4028 end of the index expression."
4029 expr ; the bracketed index expression
4030 lb
4031 rb)
4032
4033 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4034 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4035
4036 (defun js2-visit-xml-elem-ref-node (n v)
4037 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4038 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4039
4040 (defun js2-print-xml-elem-ref-node (n i)
4041 (insert (js2-make-pad i))
4042 (if (js2-xml-ref-node-attr-access-p n)
4043 (insert "@"))
4044 (when (js2-xml-elem-ref-node-namespace n)
4045 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4046 (insert "::"))
4047 (insert "[")
4048 (if (js2-xml-elem-ref-node-expr n)
4049 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4050 (insert "]"))
4051
4052 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4053
4054 (defstruct (js2-xml-start-tag-node
4055 (:include js2-xml-node)
4056 (:constructor nil)
4057 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4058 (pos js2-ts-cursor)
4059 len name attrs kids
4060 empty-p)))
4061 "AST node for an XML start-tag. Not currently used.
4062 The `kids' field is a Lisp list of child content nodes."
4063 name ; a `js2-xml-name-node'
4064 attrs ; a Lisp list of `js2-xml-attr-node'
4065 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4066
4067 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4068 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4069
4070 (defun js2-visit-xml-start-tag (n v)
4071 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4072 (dolist (attr (js2-xml-start-tag-node-attrs n))
4073 (js2-visit-ast attr v))
4074 (js2-visit-block n v))
4075
4076 (defun js2-print-xml-start-tag (n i)
4077 (insert (js2-make-pad i) "<")
4078 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4079 (when (js2-xml-start-tag-node-attrs n)
4080 (insert " ")
4081 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4082 (insert ">"))
4083
4084 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4085 ;; and add the end-tag to the kids list of the parent as well.
4086 (defstruct (js2-xml-end-tag-node
4087 (:include js2-xml-node)
4088 (:constructor nil)
4089 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4090 (pos js2-ts-cursor)
4091 len name)))
4092 "AST node for an XML end-tag. Not currently used."
4093 name) ; a `js2-xml-name-node'
4094
4095 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4096 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4097
4098 (defun js2-visit-xml-end-tag (n v)
4099 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4100
4101 (defun js2-print-xml-end-tag (n i)
4102 (insert (js2-make-pad i))
4103 (insert "</")
4104 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4105 (insert ">"))
4106
4107 (defstruct (js2-xml-name-node
4108 (:include js2-xml-node)
4109 (:constructor nil)
4110 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4111 (pos js2-ts-cursor)
4112 len namespace kids)))
4113 "AST node for an E4X XML name. Not currently used.
4114 Any XML name can be qualified with a namespace, hence the namespace field.
4115 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4116 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4117 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4118 namespace) ; a `js2-string-node'
4119
4120 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4121 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4122
4123 (defun js2-visit-xml-name-node (n v)
4124 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4125
4126 (defun js2-print-xml-name-node (n i)
4127 (insert (js2-make-pad i))
4128 (when (js2-xml-name-node-namespace n)
4129 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4130 (insert "::"))
4131 (dolist (kid (js2-xml-name-node-kids n))
4132 (js2-print-ast kid 0)))
4133
4134 (defstruct (js2-xml-pi-node
4135 (:include js2-xml-node)
4136 (:constructor nil)
4137 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4138 (pos js2-ts-cursor)
4139 len name attrs)))
4140 "AST node for an E4X XML processing instruction. Not currently used."
4141 name ; a `js2-xml-name-node'
4142 attrs) ; a list of `js2-xml-attr-node'
4143
4144 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4145 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4146
4147 (defun js2-visit-xml-pi-node (n v)
4148 (js2-visit-ast (js2-xml-pi-node-name n) v)
4149 (dolist (attr (js2-xml-pi-node-attrs n))
4150 (js2-visit-ast attr v)))
4151
4152 (defun js2-print-xml-pi-node (n i)
4153 (insert (js2-make-pad i) "<?")
4154 (js2-print-ast (js2-xml-pi-node-name n))
4155 (when (js2-xml-pi-node-attrs n)
4156 (insert " ")
4157 (js2-print-list (js2-xml-pi-node-attrs n)))
4158 (insert "?>"))
4159
4160 (defstruct (js2-xml-cdata-node
4161 (:include js2-xml-node)
4162 (:constructor nil)
4163 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4164 (pos js2-ts-cursor)
4165 len content)))
4166 "AST node for a CDATA escape section. Not currently used."
4167 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4168
4169 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4170 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4171
4172 (defun js2-visit-xml-cdata-node (n v)
4173 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4174
4175 (defun js2-print-xml-cdata-node (n i)
4176 (insert (js2-make-pad i))
4177 (js2-print-ast (js2-xml-cdata-node-content n)))
4178
4179 (defstruct (js2-xml-attr-node
4180 (:include js2-xml-node)
4181 (:constructor nil)
4182 (:constructor make-js2-attr-node (&key (type js2-XML)
4183 (pos js2-ts-cursor)
4184 len name value
4185 eq-pos quote-type)))
4186 "AST node representing a foo='bar' XML attribute value. Not yet used."
4187 name ; a `js2-xml-name-node'
4188 value ; a `js2-xml-name-node'
4189 eq-pos ; buffer position of "=" sign
4190 quote-type) ; 'single or 'double
4191
4192 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4193 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4194
4195 (defun js2-visit-xml-attr-node (n v)
4196 (js2-visit-ast (js2-xml-attr-node-name n) v)
4197 (js2-visit-ast (js2-xml-attr-node-value n) v))
4198
4199 (defun js2-print-xml-attr-node (n i)
4200 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4201 "'"
4202 "\"")))
4203 (insert (js2-make-pad i))
4204 (js2-print-ast (js2-xml-attr-node-name n) 0)
4205 (insert "=" quote)
4206 (js2-print-ast (js2-xml-attr-node-value n) 0)
4207 (insert quote)))
4208
4209 (defstruct (js2-xml-text-node
4210 (:include js2-xml-node)
4211 (:constructor nil)
4212 (:constructor make-js2-text-node (&key (type js2-XML)
4213 (pos js2-ts-cursor)
4214 len content)))
4215 "AST node for an E4X XML text node. Not currently used."
4216 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4217
4218 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4219 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4220
4221 (defun js2-visit-xml-text-node (n v)
4222 (js2-visit-ast (js2-xml-text-node-content n) v))
4223
4224 (defun js2-print-xml-text-node (n i)
4225 (insert (js2-make-pad i))
4226 (dolist (kid (js2-xml-text-node-content n))
4227 (js2-print-ast kid)))
4228
4229 (defstruct (js2-xml-comment-node
4230 (:include js2-xml-node)
4231 (:constructor nil)
4232 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4233 (pos js2-ts-cursor)
4234 len)))
4235 "AST node for E4X XML comment. Not currently used.")
4236
4237 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4238 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4239
4240 (defun js2-print-xml-comment (n i)
4241 (insert (js2-make-pad i)
4242 (js2-node-string n)))
4243
4244 ;;; Node utilities
4245
4246 (defsubst js2-node-line (n)
4247 "Fetch the source line number at the start of node N.
4248 This is O(n) in the length of the source buffer; use prudently."
4249 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4250
4251 (defsubst js2-block-node-kid (n i)
4252 "Return child I of node N, or nil if there aren't that many."
4253 (nth i (js2-block-node-kids n)))
4254
4255 (defsubst js2-block-node-first (n)
4256 "Return first child of block node N, or nil if there is none."
4257 (first (js2-block-node-kids n)))
4258
4259 (defun js2-node-root (n)
4260 "Return the root of the AST containing N.
4261 If N has no parent pointer, returns N."
4262 (let ((parent (js2-node-parent n)))
4263 (if parent
4264 (js2-node-root parent)
4265 n)))
4266
4267 (defsubst js2-node-short-name (n)
4268 "Return the short name of node N as a string, e.g. `js2-if-node'."
4269 (substring (symbol-name (aref n 0))
4270 (length "cl-struct-")))
4271
4272 (defun js2-node-child-list (node)
4273 "Return the child list for NODE, a Lisp list of nodes.
4274 Works for block nodes, array nodes, obj literals, funarg lists,
4275 var decls and try nodes (for catch clauses). Note that you should call
4276 `js2-block-node-kids' on the function body for the body statements.
4277 Returns nil for zero-length child lists or unsupported nodes."
4278 (cond
4279 ((js2-function-node-p node)
4280 (js2-function-node-params node))
4281 ((js2-block-node-p node)
4282 (js2-block-node-kids node))
4283 ((js2-try-node-p node)
4284 (js2-try-node-catch-clauses node))
4285 ((js2-array-node-p node)
4286 (js2-array-node-elems node))
4287 ((js2-object-node-p node)
4288 (js2-object-node-elems node))
4289 ((js2-call-node-p node)
4290 (js2-call-node-args node))
4291 ((js2-new-node-p node)
4292 (js2-new-node-args node))
4293 ((js2-var-decl-node-p node)
4294 (js2-var-decl-node-kids node))
4295 (t
4296 nil)))
4297
4298 (defun js2-node-set-child-list (node kids)
4299 "Set the child list for NODE to KIDS."
4300 (cond
4301 ((js2-function-node-p node)
4302 (setf (js2-function-node-params node) kids))
4303 ((js2-block-node-p node)
4304 (setf (js2-block-node-kids node) kids))
4305 ((js2-try-node-p node)
4306 (setf (js2-try-node-catch-clauses node) kids))
4307 ((js2-array-node-p node)
4308 (setf (js2-array-node-elems node) kids))
4309 ((js2-object-node-p node)
4310 (setf (js2-object-node-elems node) kids))
4311 ((js2-call-node-p node)
4312 (setf (js2-call-node-args node) kids))
4313 ((js2-new-node-p node)
4314 (setf (js2-new-node-args node) kids))
4315 ((js2-var-decl-node-p node)
4316 (setf (js2-var-decl-node-kids node) kids))
4317 (t
4318 (error "Unsupported node type: %s" (js2-node-short-name node))))
4319 kids)
4320
4321 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4322 (defconst js2-paren-expr-nodes
4323 '(cl-struct-js2-comp-loop-node
4324 cl-struct-js2-comp-node
4325 cl-struct-js2-call-node
4326 cl-struct-js2-catch-node
4327 cl-struct-js2-do-node
4328 cl-struct-js2-elem-get-node
4329 cl-struct-js2-for-in-node
4330 cl-struct-js2-for-node
4331 cl-struct-js2-function-node
4332 cl-struct-js2-if-node
4333 cl-struct-js2-let-node
4334 cl-struct-js2-new-node
4335 cl-struct-js2-paren-node
4336 cl-struct-js2-switch-node
4337 cl-struct-js2-while-node
4338 cl-struct-js2-with-node
4339 cl-struct-js2-xml-dot-query-node)
4340 "Node types that can have a parenthesized child expression.
4341 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4342
4343 (defsubst js2-paren-expr-node-p (node)
4344 "Return t for nodes that typically have a parenthesized child expression.
4345 Useful for computing the indentation anchors for arg-lists and conditions.
4346 Note that it may return a false positive, for instance when NODE is
4347 a `js2-new-node' and there are no arguments or parentheses."
4348 (memq (aref node 0) js2-paren-expr-nodes))
4349
4350 ;; Fake polymorphism... yech.
4351 (defun js2-node-lp (node)
4352 "Return relative left-paren position for NODE, if applicable.
4353 For `js2-elem-get-node' structs, returns left-bracket position.
4354 Note that the position may be nil in the case of a parse error."
4355 (cond
4356 ((js2-elem-get-node-p node)
4357 (js2-elem-get-node-lb node))
4358 ((js2-loop-node-p node)
4359 (js2-loop-node-lp node))
4360 ((js2-function-node-p node)
4361 (js2-function-node-lp node))
4362 ((js2-if-node-p node)
4363 (js2-if-node-lp node))
4364 ((js2-new-node-p node)
4365 (js2-new-node-lp node))
4366 ((js2-call-node-p node)
4367 (js2-call-node-lp node))
4368 ((js2-paren-node-p node)
4369 0)
4370 ((js2-switch-node-p node)
4371 (js2-switch-node-lp node))
4372 ((js2-catch-node-p node)
4373 (js2-catch-node-lp node))
4374 ((js2-let-node-p node)
4375 (js2-let-node-lp node))
4376 ((js2-comp-node-p node)
4377 0)
4378 ((js2-with-node-p node)
4379 (js2-with-node-lp node))
4380 ((js2-xml-dot-query-node-p node)
4381 (1+ (js2-infix-node-op-pos node)))
4382 (t
4383 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4384
4385 ;; Fake polymorphism... blech.
4386 (defun js2-node-rp (node)
4387 "Return relative right-paren position for NODE, if applicable.
4388 For `js2-elem-get-node' structs, returns right-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-rb node))
4393 ((js2-loop-node-p node)
4394 (js2-loop-node-rp node))
4395 ((js2-function-node-p node)
4396 (js2-function-node-rp node))
4397 ((js2-if-node-p node)
4398 (js2-if-node-rp node))
4399 ((js2-new-node-p node)
4400 (js2-new-node-rp node))
4401 ((js2-call-node-p node)
4402 (js2-call-node-rp node))
4403 ((js2-paren-node-p node)
4404 (1- (js2-node-len node)))
4405 ((js2-switch-node-p node)
4406 (js2-switch-node-rp node))
4407 ((js2-catch-node-p node)
4408 (js2-catch-node-rp node))
4409 ((js2-let-node-p node)
4410 (js2-let-node-rp node))
4411 ((js2-comp-node-p node)
4412 (1- (js2-node-len node)))
4413 ((js2-with-node-p node)
4414 (js2-with-node-rp node))
4415 ((js2-xml-dot-query-node-p node)
4416 (1+ (js2-xml-dot-query-node-rp node)))
4417 (t
4418 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4419
4420 (defsubst js2-node-first-child (node)
4421 "Return the first element of `js2-node-child-list' for NODE."
4422 (car (js2-node-child-list node)))
4423
4424 (defsubst js2-node-last-child (node)
4425 "Return the last element of `js2-node-last-child' for NODE."
4426 (car (last (js2-node-child-list node))))
4427
4428 (defun js2-node-prev-sibling (node)
4429 "Return the previous statement in parent.
4430 Works for parents supported by `js2-node-child-list'.
4431 Returns nil if NODE is not in the parent, or PARENT is
4432 not a supported node, or if NODE is the first child."
4433 (let* ((p (js2-node-parent node))
4434 (kids (js2-node-child-list p))
4435 (sib (car kids)))
4436 (while (and kids
4437 (not (eq node (cadr kids))))
4438 (setq kids (cdr kids)
4439 sib (car kids)))
4440 sib))
4441
4442 (defun js2-node-next-sibling (node)
4443 "Return the next statement in parent block.
4444 Returns nil if NODE is not in the block, or PARENT is not
4445 a block node, or if NODE is the last statement."
4446 (let* ((p (js2-node-parent node))
4447 (kids (js2-node-child-list p)))
4448 (while (and kids
4449 (not (eq node (car kids))))
4450 (setq kids (cdr kids)))
4451 (cadr kids)))
4452
4453 (defun js2-node-find-child-before (pos parent &optional after)
4454 "Find the last child that starts before POS in parent.
4455 If AFTER is non-nil, returns first child starting after POS.
4456 POS is an absolute buffer position. PARENT is any node
4457 supported by `js2-node-child-list'.
4458 Returns nil if no applicable child is found."
4459 (let ((kids (if (js2-function-node-p parent)
4460 (js2-block-node-kids (js2-function-node-body parent))
4461 (js2-node-child-list parent)))
4462 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4463 (js2-function-node-body parent)
4464 parent)))
4465 kid result fn
4466 (continue t))
4467 (setq fn (if after '>= '<))
4468 (while (and kids continue)
4469 (setq kid (car kids))
4470 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4471 (setq result kid
4472 continue (not after))
4473 (setq continue after))
4474 (setq kids (cdr kids)))
4475 result))
4476
4477 (defun js2-node-find-child-after (pos parent)
4478 "Find first child that starts after POS in parent.
4479 POS is an absolute buffer position. PARENT is any node
4480 supported by `js2-node-child-list'.
4481 Returns nil if no applicable child is found."
4482 (js2-node-find-child-before pos parent 'after))
4483
4484 (defun js2-node-replace-child (pos parent new-node)
4485 "Replace node at index POS in PARENT with NEW-NODE.
4486 Only works for parents supported by `js2-node-child-list'."
4487 (let ((kids (js2-node-child-list parent))
4488 (i 0))
4489 (while (< i pos)
4490 (setq kids (cdr kids)
4491 i (1+ i)))
4492 (setcar kids new-node)
4493 (js2-node-add-children parent new-node)))
4494
4495 (defun js2-node-buffer (n)
4496 "Return the buffer associated with AST N.
4497 Returns nil if the buffer is not set as a property on the root
4498 node, or if parent links were not recorded during parsing."
4499 (let ((root (js2-node-root n)))
4500 (and root
4501 (js2-ast-root-p root)
4502 (js2-ast-root-buffer root))))
4503
4504 (defun js2-block-node-push (n kid)
4505 "Push js2-node KID onto the end of js2-block-node N's child list.
4506 KID is always added to the -end- of the kids list.
4507 Function also calls `js2-node-add-children' to add the parent link."
4508 (let ((kids (js2-node-child-list n)))
4509 (if kids
4510 (setcdr kids (nconc (cdr kids) (list kid)))
4511 (js2-node-set-child-list n (list kid)))
4512 (js2-node-add-children n kid)))
4513
4514 (defun js2-node-string (node)
4515 (with-current-buffer (or (js2-node-buffer node)
4516 (error "No buffer available for node %s" node))
4517 (let ((pos (js2-node-abs-pos node)))
4518 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4519
4520 ;; Container for storing the node we're looking for in a traversal.
4521 (js2-deflocal js2-discovered-node nil)
4522
4523 ;; Keep track of absolute node position during traversals.
4524 (js2-deflocal js2-visitor-offset nil)
4525
4526 (js2-deflocal js2-node-search-point nil)
4527
4528 (when js2-mode-dev-mode-p
4529 (defun js2-find-node-at-point ()
4530 (interactive)
4531 (let ((node (js2-node-at-point)))
4532 (message "%s" (or node "No node found at point"))))
4533 (defun js2-node-name-at-point ()
4534 (interactive)
4535 (let ((node (js2-node-at-point)))
4536 (message "%s" (if node
4537 (js2-node-short-name node)
4538 "No node found at point.")))))
4539
4540 (defun js2-node-at-point (&optional pos skip-comments)
4541 "Return AST node at POS, a buffer position, defaulting to current point.
4542 The `js2-mode-ast' variable must be set to the current parse tree.
4543 Signals an error if the AST (`js2-mode-ast') is nil.
4544 Always returns a node - if it can't find one, it returns the root.
4545 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4546 (let ((ast js2-mode-ast)
4547 result)
4548 (unless ast
4549 (error "No JavaScript AST available"))
4550 ;; Look through comments first, since they may be inside nodes that
4551 ;; would otherwise report a match.
4552 (setq pos (or pos (point))
4553 result (if (> pos (js2-node-abs-end ast))
4554 ast
4555 (if (not skip-comments)
4556 (js2-comment-at-point pos))))
4557 (unless result
4558 (setq js2-discovered-node nil
4559 js2-visitor-offset 0
4560 js2-node-search-point pos)
4561 (unwind-protect
4562 (catch 'js2-visit-done
4563 (js2-visit-ast ast #'js2-node-at-point-visitor))
4564 (setq js2-visitor-offset nil
4565 js2-node-search-point nil))
4566 (setq result js2-discovered-node))
4567 ;; may have found a comment beyond end of last child node,
4568 ;; since visiting the ast-root looks at the comment-list last.
4569 (if (and skip-comments
4570 (js2-comment-node-p result))
4571 (setq result nil))
4572 (or result js2-mode-ast)))
4573
4574 (defun js2-node-at-point-visitor (node end-p)
4575 (let ((rel-pos (js2-node-pos node))
4576 abs-pos
4577 abs-end
4578 (point js2-node-search-point))
4579 (cond
4580 (end-p
4581 ;; this evaluates to a non-nil return value, even if it's zero
4582 (decf js2-visitor-offset rel-pos))
4583 ;; we already looked for comments before visiting, and don't want them now
4584 ((js2-comment-node-p node)
4585 nil)
4586 (t
4587 (setq abs-pos (incf js2-visitor-offset rel-pos)
4588 ;; we only want to use the node if the point is before
4589 ;; the last character position in the node, so we decrement
4590 ;; the absolute end by 1.
4591 abs-end (+ abs-pos (js2-node-len node) -1))
4592 (cond
4593 ;; If this node starts after search-point, stop the search.
4594 ((> abs-pos point)
4595 (throw 'js2-visit-done nil))
4596 ;; If this node ends before the search-point, don't check kids.
4597 ((> point abs-end)
4598 nil)
4599 (t
4600 ;; Otherwise point is within this node, possibly in a child.
4601 (setq js2-discovered-node node)
4602 t)))))) ; keep processing kids to look for more specific match
4603
4604 (defsubst js2-block-comment-p (node)
4605 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4606 (and (js2-comment-node-p node)
4607 (memq (js2-comment-node-format node) '(jsdoc block))))
4608
4609 ;; TODO: put the comments in a vector and binary-search them instead
4610 (defun js2-comment-at-point (&optional pos)
4611 "Look through scanned comment nodes for one containing POS.
4612 POS is a buffer position that defaults to current point.
4613 Function returns nil if POS was not in any comment node."
4614 (let ((ast js2-mode-ast)
4615 (x (or pos (point)))
4616 beg end)
4617 (unless ast
4618 (error "No JavaScript AST available"))
4619 (catch 'done
4620 ;; Comments are stored in lexical order.
4621 (dolist (comment (js2-ast-root-comments ast) nil)
4622 (setq beg (js2-node-abs-pos comment)
4623 end (+ beg (js2-node-len comment)))
4624 (if (and (>= x beg)
4625 (<= x end))
4626 (throw 'done comment))))))
4627
4628 (defun js2-mode-find-parent-fn (node)
4629 "Find function enclosing NODE.
4630 Returns nil if NODE is not inside a function."
4631 (setq node (js2-node-parent node))
4632 (while (and node (not (js2-function-node-p node)))
4633 (setq node (js2-node-parent node)))
4634 (and (js2-function-node-p node) node))
4635
4636 (defun js2-mode-find-enclosing-fn (node)
4637 "Find function or root enclosing NODE."
4638 (if (js2-ast-root-p node)
4639 node
4640 (setq node (js2-node-parent node))
4641 (while (not (or (js2-ast-root-p node)
4642 (js2-function-node-p node)))
4643 (setq node (js2-node-parent node)))
4644 node))
4645
4646 (defun js2-mode-find-enclosing-node (beg end)
4647 "Find node fully enclosing BEG and END."
4648 (let ((node (js2-node-at-point beg))
4649 pos
4650 (continue t))
4651 (while continue
4652 (if (or (js2-ast-root-p node)
4653 (and
4654 (<= (setq pos (js2-node-abs-pos node)) beg)
4655 (>= (+ pos (js2-node-len node)) end)))
4656 (setq continue nil)
4657 (setq node (js2-node-parent node))))
4658 node))
4659
4660 (defun js2-node-parent-script-or-fn (node)
4661 "Find script or function immediately enclosing NODE.
4662 If NODE is the ast-root, returns nil."
4663 (if (js2-ast-root-p node)
4664 nil
4665 (setq node (js2-node-parent node))
4666 (while (and node (not (or (js2-function-node-p node)
4667 (js2-script-node-p node))))
4668 (setq node (js2-node-parent node)))
4669 node))
4670
4671 (defun js2-node-is-descendant (node ancestor)
4672 "Return t if NODE is a descendant of ANCESTOR."
4673 (while (and node
4674 (not (eq node ancestor)))
4675 (setq node (js2-node-parent node)))
4676 node)
4677
4678 ;;; visitor infrastructure
4679
4680 (defun js2-visit-none (_node _callback)
4681 "Visitor for AST node that have no node children."
4682 nil)
4683
4684 (defun js2-print-none (_node _indent)
4685 "Visitor for AST node with no printed representation.")
4686
4687 (defun js2-print-body (node indent)
4688 "Print a statement, or a block without braces."
4689 (if (js2-block-node-p node)
4690 (dolist (kid (js2-block-node-kids node))
4691 (js2-print-ast kid indent))
4692 (js2-print-ast node indent)))
4693
4694 (defun js2-print-list (args &optional delimiter)
4695 (loop with len = (length args)
4696 for arg in args
4697 for count from 1
4698 do
4699 (when arg (js2-print-ast arg 0))
4700 (if (< count len)
4701 (insert (or delimiter ", ")))))
4702
4703 (defun js2-print-tree (ast)
4704 "Prints an AST to the current buffer.
4705 Makes `js2-ast-parent-nodes' available to the printer functions."
4706 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4707 (js2-print-ast ast)))
4708
4709 (defun js2-print-ast (node &optional indent)
4710 "Helper function for printing AST nodes.
4711 Requires `js2-ast-parent-nodes' to be non-nil.
4712 You should use `js2-print-tree' instead of this function."
4713 (let ((printer (get (aref node 0) 'js2-printer))
4714 (i (or indent 0)))
4715 ;; TODO: wedge comments in here somewhere
4716 (if printer
4717 (funcall printer node i))))
4718
4719 (defconst js2-side-effecting-tokens
4720 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4721 (dolist (tt (list js2-ASSIGN
4722 js2-ASSIGN_ADD
4723 js2-ASSIGN_BITAND
4724 js2-ASSIGN_BITOR
4725 js2-ASSIGN_BITXOR
4726 js2-ASSIGN_DIV
4727 js2-ASSIGN_LSH
4728 js2-ASSIGN_MOD
4729 js2-ASSIGN_MUL
4730 js2-ASSIGN_RSH
4731 js2-ASSIGN_SUB
4732 js2-ASSIGN_URSH
4733 js2-BLOCK
4734 js2-BREAK
4735 js2-CALL
4736 js2-CATCH
4737 js2-CATCH_SCOPE
4738 js2-CLASS
4739 js2-CONST
4740 js2-CONTINUE
4741 js2-DEBUGGER
4742 js2-DEC
4743 js2-DELPROP
4744 js2-DEL_REF
4745 js2-DO
4746 js2-ELSE
4747 js2-EMPTY
4748 js2-ENTERWITH
4749 js2-EXPORT
4750 js2-EXPR_RESULT
4751 js2-FINALLY
4752 js2-FOR
4753 js2-FUNCTION
4754 js2-GOTO
4755 js2-IF
4756 js2-IFEQ
4757 js2-IFNE
4758 js2-IMPORT
4759 js2-INC
4760 js2-JSR
4761 js2-LABEL
4762 js2-LEAVEWITH
4763 js2-LET
4764 js2-LETEXPR
4765 js2-LOCAL_BLOCK
4766 js2-LOOP
4767 js2-NEW
4768 js2-REF_CALL
4769 js2-RETHROW
4770 js2-RETURN
4771 js2-RETURN_RESULT
4772 js2-SEMI
4773 js2-SETELEM
4774 js2-SETELEM_OP
4775 js2-SETNAME
4776 js2-SETPROP
4777 js2-SETPROP_OP
4778 js2-SETVAR
4779 js2-SET_REF
4780 js2-SET_REF_OP
4781 js2-SWITCH
4782 js2-TARGET
4783 js2-THROW
4784 js2-TRY
4785 js2-VAR
4786 js2-WHILE
4787 js2-WITH
4788 js2-WITHEXPR
4789 js2-YIELD))
4790 (aset tokens tt t))
4791 (if js2-instanceof-has-side-effects
4792 (aset tokens js2-INSTANCEOF t))
4793 tokens))
4794
4795 (defun js2-node-has-side-effects (node)
4796 "Return t if NODE has side effects."
4797 (when node ; makes it easier to handle malformed expressions
4798 (let ((tt (js2-node-type node)))
4799 (cond
4800 ;; This doubtless needs some work, since EXPR_VOID is used
4801 ;; in several ways in Rhino and I may not have caught them all.
4802 ;; I'll wait for people to notice incorrect warnings.
4803 ((and (= tt js2-EXPR_VOID)
4804 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4805 (let ((expr (js2-expr-stmt-node-expr node)))
4806 (or (js2-node-has-side-effects expr)
4807 (when (js2-string-node-p expr)
4808 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4809 ((= tt js2-COMMA)
4810 (js2-node-has-side-effects (js2-infix-node-right node)))
4811 ((or (= tt js2-AND)
4812 (= tt js2-OR))
4813 (or (js2-node-has-side-effects (js2-infix-node-right node))
4814 (js2-node-has-side-effects (js2-infix-node-left node))))
4815 ((= tt js2-HOOK)
4816 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4817 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4818 ((js2-paren-node-p node)
4819 (js2-node-has-side-effects (js2-paren-node-expr node)))
4820 ((= tt js2-ERROR) ; avoid cascaded error messages
4821 nil)
4822 (t
4823 (aref js2-side-effecting-tokens tt))))))
4824
4825 (defconst js2-stmt-node-types
4826 (list js2-BLOCK
4827 js2-BREAK
4828 js2-CONTINUE
4829 js2-DEFAULT ; e4x "default xml namespace" statement
4830 js2-DO
4831 js2-EXPR_RESULT
4832 js2-EXPR_VOID
4833 js2-FOR
4834 js2-IF
4835 js2-RETURN
4836 js2-SWITCH
4837 js2-THROW
4838 js2-TRY
4839 js2-WHILE
4840 js2-WITH)
4841 "Node types that only appear in statement contexts.
4842 The list does not include nodes that always appear as the child
4843 of another specific statement type, such as switch-cases,
4844 catch and finally blocks, and else-clauses. The list also excludes
4845 nodes like yield, let and var, which may appear in either expression
4846 or statement context, and in the latter context always have a
4847 `js2-expr-stmt-node' parent. Finally, the list does not include
4848 functions or scripts, which are treated separately from statements
4849 by the JavaScript parser and runtime.")
4850
4851 (defun js2-stmt-node-p (node)
4852 "Heuristic for figuring out if NODE is a statement.
4853 Some node types can appear in either an expression context or a
4854 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4855 For these node types in a statement context, the parent will be a
4856 `js2-expr-stmt-node'.
4857 Functions aren't included in the check."
4858 (memq (js2-node-type node) js2-stmt-node-types))
4859
4860 (defun js2-mode-find-first-stmt (node)
4861 "Search upward starting from NODE looking for a statement.
4862 For purposes of this function, a `js2-function-node' counts."
4863 (while (not (or (js2-stmt-node-p node)
4864 (js2-function-node-p node)))
4865 (setq node (js2-node-parent node)))
4866 node)
4867
4868 (defun js2-node-parent-stmt (node)
4869 "Return the node's first ancestor that is a statement.
4870 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4871 appearing in a statement context will have a parent that is a
4872 `js2-expr-stmt-node' that will be returned by this function."
4873 (let ((parent (js2-node-parent node)))
4874 (if (or (null parent)
4875 (js2-stmt-node-p parent)
4876 (and (js2-function-node-p parent)
4877 (not (eq (js2-function-node-form parent)
4878 'FUNCTION_EXPRESSION))))
4879 parent
4880 (js2-node-parent-stmt parent))))
4881
4882 ;; In the Mozilla Rhino sources, Roshan James writes:
4883 ;; Does consistent-return analysis on the function body when strict mode is
4884 ;; enabled.
4885 ;;
4886 ;; function (x) { return (x+1) }
4887 ;;
4888 ;; is ok, but
4889 ;;
4890 ;; function (x) { if (x < 0) return (x+1); }
4891 ;;
4892 ;; is not because the function can potentially return a value when the
4893 ;; condition is satisfied and if not, the function does not explicitly
4894 ;; return a value.
4895 ;;
4896 ;; This extends to checking mismatches such as "return" and "return <value>"
4897 ;; used in the same function. Warnings are not emitted if inconsistent
4898 ;; returns exist in code that can be statically shown to be unreachable.
4899 ;; Ex.
4900 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4901 ;;
4902 ;; emits no warning. However if the loop had a break statement, then a
4903 ;; warning would be emitted.
4904 ;;
4905 ;; The consistency analysis looks at control structures such as loops, ifs,
4906 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4907 ;; warns the user about an inconsistent set of termination possibilities.
4908 ;;
4909 ;; These flags enumerate the possible ways a statement/function can
4910 ;; terminate. These flags are used by endCheck() and by the Parser to
4911 ;; detect inconsistent return usage.
4912 ;;
4913 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4914 ;; able to execute (example: throw, continue)
4915 ;;
4916 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4917 ;; next one. Statement such as return dont. A compound statement may have
4918 ;; some branch that drops off control to the next statement.
4919 ;;
4920 ;; END_RETURNS indicates that the statement can return with no value.
4921 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4922 ;;
4923 ;; A compound statement such as
4924 ;; if (condition) {
4925 ;; return value;
4926 ;; }
4927 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4928
4929 (defconst js2-END_UNREACHED 0)
4930 (defconst js2-END_DROPS_OFF 1)
4931 (defconst js2-END_RETURNS 2)
4932 (defconst js2-END_RETURNS_VALUE 4)
4933 (defconst js2-END_YIELDS 8)
4934
4935 (defun js2-has-consistent-return-usage (node)
4936 "Check that every return usage in a function body is consistent.
4937 Returns t if the function satisfies strict mode requirement."
4938 (let ((n (js2-end-check node)))
4939 ;; either it doesn't return a value in any branch...
4940 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4941 ;; or it returns a value (or is unreached) at every branch
4942 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4943 js2-END_RETURNS
4944 js2-END_YIELDS)))))
4945
4946 (defun js2-end-check-if (node)
4947 "Ensure that return usage in then/else blocks is consistent.
4948 If there is no else block, then the return statement can fall through.
4949 Returns logical OR of END_* flags"
4950 (let ((th (js2-if-node-then-part node))
4951 (el (js2-if-node-else-part node)))
4952 (if (null th)
4953 js2-END_UNREACHED
4954 (logior (js2-end-check th) (if el
4955 (js2-end-check el)
4956 js2-END_DROPS_OFF)))))
4957
4958 (defun js2-end-check-switch (node)
4959 "Consistency of return statements is checked between the case statements.
4960 If there is no default, then the switch can fall through. If there is a
4961 default, we check to see if all code paths in the default return or if
4962 there is a code path that can fall through.
4963 Returns logical OR of END_* flags."
4964 (let ((rv js2-END_UNREACHED)
4965 default-case)
4966 ;; examine the cases
4967 (catch 'break
4968 (dolist (c (js2-switch-node-cases node))
4969 (if (js2-case-node-expr c)
4970 (js2-set-flag rv (js2-end-check-block c))
4971 (setq default-case c)
4972 (throw 'break nil))))
4973 ;; we don't care how the cases drop into each other
4974 (js2-clear-flag rv js2-END_DROPS_OFF)
4975 ;; examine the default
4976 (js2-set-flag rv (if default-case
4977 (js2-end-check default-case)
4978 js2-END_DROPS_OFF))
4979 rv))
4980
4981 (defun js2-end-check-try (node)
4982 "If the block has a finally, return consistency is checked in the
4983 finally block. If all code paths in the finally return, then the
4984 returns in the try-catch blocks don't matter. If there is a code path
4985 that does not return or if there is no finally block, the returns
4986 of the try and catch blocks are checked for mismatch.
4987 Returns logical OR of END_* flags."
4988 (let ((finally (js2-try-node-finally-block node))
4989 rv)
4990 ;; check the finally if it exists
4991 (setq rv (if finally
4992 (js2-end-check (js2-finally-node-body finally))
4993 js2-END_DROPS_OFF))
4994 ;; If the finally block always returns, then none of the returns
4995 ;; in the try or catch blocks matter.
4996 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4997 (js2-clear-flag rv js2-END_DROPS_OFF)
4998 ;; examine the try block
4999 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5000 ;; check each catch block
5001 (dolist (cb (js2-try-node-catch-clauses node))
5002 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5003 rv))
5004
5005 (defun js2-end-check-loop (node)
5006 "Return statement in the loop body must be consistent.
5007 The default assumption for any kind of a loop is that it will eventually
5008 terminate. The only exception is a loop with a constant true condition.
5009 Code that follows such a loop is examined only if one can determine
5010 statically that there is a break out of the loop.
5011
5012 for(... ; ... ; ...) {}
5013 for(... in ... ) {}
5014 while(...) { }
5015 do { } while(...)
5016
5017 Returns logical OR of END_* flags."
5018 (let ((rv (js2-end-check (js2-loop-node-body node)))
5019 (condition (cond
5020 ((js2-while-node-p node)
5021 (js2-while-node-condition node))
5022 ((js2-do-node-p node)
5023 (js2-do-node-condition node))
5024 ((js2-for-node-p node)
5025 (js2-for-node-condition node)))))
5026
5027 ;; check to see if the loop condition is always true
5028 (if (and condition
5029 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5030 (js2-clear-flag rv js2-END_DROPS_OFF))
5031
5032 ;; look for effect of breaks
5033 (js2-set-flag rv (js2-node-get-prop node
5034 'CONTROL_BLOCK_PROP
5035 js2-END_UNREACHED))
5036 rv))
5037
5038 (defun js2-end-check-block (node)
5039 "A general block of code is examined statement by statement.
5040 If any statement (even a compound one) returns in all branches, then
5041 subsequent statements are not examined.
5042 Returns logical OR of END_* flags."
5043 (let* ((rv js2-END_DROPS_OFF)
5044 (kids (js2-block-node-kids node))
5045 (n (car kids)))
5046 ;; Check each statment. If the statement can continue onto the next
5047 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5048 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5049 (js2-clear-flag rv js2-END_DROPS_OFF)
5050 (js2-set-flag rv (js2-end-check n))
5051 (setq kids (cdr kids)
5052 n (car kids)))
5053 rv))
5054
5055 (defun js2-end-check-label (node)
5056 "A labeled statement implies that there may be a break to the label.
5057 The function processes the labeled statement and then checks the
5058 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5059 particular label.
5060 Returns logical OR of END_* flags."
5061 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5062 (logior rv (js2-node-get-prop node
5063 'CONTROL_BLOCK_PROP
5064 js2-END_UNREACHED))))
5065
5066 (defun js2-end-check-break (node)
5067 "When a break is encountered annotate the statement being broken
5068 out of by setting its CONTROL_BLOCK_PROP property.
5069 Returns logical OR of END_* flags."
5070 (and (js2-break-node-target node)
5071 (js2-node-set-prop (js2-break-node-target node)
5072 'CONTROL_BLOCK_PROP
5073 js2-END_DROPS_OFF))
5074 js2-END_UNREACHED)
5075
5076 (defun js2-end-check (node)
5077 "Examine the body of a function, doing a basic reachability analysis.
5078 Returns a combination of flags END_* flags that indicate
5079 how the function execution can terminate. These constitute only the
5080 pessimistic set of termination conditions. It is possible that at
5081 runtime certain code paths will never be actually taken. Hence this
5082 analysis will flag errors in cases where there may not be errors.
5083 Returns logical OR of END_* flags"
5084 (let (kid)
5085 (cond
5086 ((js2-break-node-p node)
5087 (js2-end-check-break node))
5088 ((js2-expr-stmt-node-p node)
5089 (if (setq kid (js2-expr-stmt-node-expr node))
5090 (js2-end-check kid)
5091 js2-END_DROPS_OFF))
5092 ((or (js2-continue-node-p node)
5093 (js2-throw-node-p node))
5094 js2-END_UNREACHED)
5095 ((js2-return-node-p node)
5096 (if (setq kid (js2-return-node-retval node))
5097 js2-END_RETURNS_VALUE
5098 js2-END_RETURNS))
5099 ((js2-loop-node-p node)
5100 (js2-end-check-loop node))
5101 ((js2-switch-node-p node)
5102 (js2-end-check-switch node))
5103 ((js2-labeled-stmt-node-p node)
5104 (js2-end-check-label node))
5105 ((js2-if-node-p node)
5106 (js2-end-check-if node))
5107 ((js2-try-node-p node)
5108 (js2-end-check-try node))
5109 ((js2-block-node-p node)
5110 (if (null (js2-block-node-kids node))
5111 js2-END_DROPS_OFF
5112 (js2-end-check-block node)))
5113 ((js2-yield-node-p node)
5114 js2-END_YIELDS)
5115 (t
5116 js2-END_DROPS_OFF))))
5117
5118 (defun js2-always-defined-boolean-p (node)
5119 "Check if NODE always evaluates to true or false in boolean context.
5120 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5121 nor always false."
5122 (let ((tt (js2-node-type node))
5123 num)
5124 (cond
5125 ((or (= tt js2-FALSE) (= tt js2-NULL))
5126 'ALWAYS_FALSE)
5127 ((= tt js2-TRUE)
5128 'ALWAYS_TRUE)
5129 ((= tt js2-NUMBER)
5130 (setq num (js2-number-node-num-value node))
5131 (if (and (not (eq num 0.0e+NaN))
5132 (not (zerop num)))
5133 'ALWAYS_TRUE
5134 'ALWAYS_FALSE))
5135 (t
5136 nil))))
5137
5138 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5139 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5140
5141 (defvar js2-tokens nil
5142 "List of all defined token names.") ; initialized in `js2-token-names'
5143
5144 (defconst js2-token-names
5145 (let* ((names (make-vector js2-num-tokens -1))
5146 (case-fold-search nil) ; only match js2-UPPER_CASE
5147 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5148 (loop for sym in syms
5149 for i from 0
5150 do
5151 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5152 (not (boundp sym)))
5153 (aset names (symbol-value sym) ; code, e.g. 152
5154 (downcase
5155 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5156 (push sym js2-tokens)))
5157 names)
5158 "Vector mapping int values to token string names, sans `js2-' prefix.")
5159
5160 (defun js2-tt-name (tok)
5161 "Return a string name for TOK, a token symbol or code.
5162 Signals an error if it's not a recognized token."
5163 (let ((code tok))
5164 (if (symbolp tok)
5165 (setq code (symbol-value tok)))
5166 (if (eq code -1)
5167 "ERROR"
5168 (if (and (numberp code)
5169 (not (minusp code))
5170 (< code js2-num-tokens))
5171 (aref js2-token-names code)
5172 (error "Invalid token: %s" code)))))
5173
5174 (defsubst js2-tt-sym (tok)
5175 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5176 (intern (js2-tt-name tok)))
5177
5178 (defconst js2-token-codes
5179 (let ((table (make-hash-table :test 'eq :size 256)))
5180 (loop for name across js2-token-names
5181 for sym = (intern (concat "js2-" (upcase name)))
5182 do
5183 (puthash sym (symbol-value sym) table))
5184 ;; clean up a few that are "wrong" in Rhino's token codes
5185 (puthash 'js2-DELETE js2-DELPROP table)
5186 table)
5187 "Hashtable mapping token type symbols to their bytecodes.")
5188
5189 (defsubst js2-tt-code (sym)
5190 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5191 (or (gethash sym js2-token-codes)
5192 (error "Invalid token symbol: %s " sym))) ; signal code bug
5193
5194 (defun js2-report-scan-error (msg &optional no-throw beg len)
5195 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5196 (js2-report-error msg nil
5197 (or beg (js2-current-token-beg))
5198 (or len (js2-current-token-len)))
5199 (unless no-throw
5200 (throw 'return js2-ERROR)))
5201
5202 (defun js2-set-string-from-buffer (token)
5203 "Set `string' and `end' slots for TOKEN, return the string."
5204 (setf (js2-token-end token) js2-ts-cursor
5205 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5206
5207 ;; TODO: could potentially avoid a lot of consing by allocating a
5208 ;; char buffer the way Rhino does.
5209 (defsubst js2-add-to-string (c)
5210 (push c js2-ts-string-buffer))
5211
5212 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5213 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5214 ;; any other character: when it's not part of the current token, we
5215 ;; unget it, allowing it to be read again by the following call.
5216 (defsubst js2-unget-char ()
5217 (decf js2-ts-cursor))
5218
5219 ;; Rhino distinguishes \r and \n line endings. We don't need to
5220 ;; because we only scan from Emacs buffers, which always use \n.
5221 (defun js2-get-char ()
5222 "Read and return the next character from the input buffer.
5223 Increments `js2-ts-lineno' if the return value is a newline char.
5224 Updates `js2-ts-cursor' to the point after the returned char.
5225 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5226 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5227 (let (c)
5228 ;; check for end of buffer
5229 (if (>= js2-ts-cursor (point-max))
5230 (setq js2-ts-hit-eof t
5231 js2-ts-cursor (1+ js2-ts-cursor)
5232 c js2-EOF_CHAR) ; return value
5233 ;; otherwise read next char
5234 (setq c (char-before (incf js2-ts-cursor)))
5235 ;; if we read a newline, update counters
5236 (if (= c ?\n)
5237 (setq js2-ts-line-start js2-ts-cursor
5238 js2-ts-lineno (1+ js2-ts-lineno)))
5239 ;; TODO: skip over format characters
5240 c)))
5241
5242 (defun js2-read-unicode-escape ()
5243 "Read a \\uNNNN sequence from the input.
5244 Assumes the ?\ and ?u have already been read.
5245 Returns the unicode character, or nil if it wasn't a valid character.
5246 Doesn't change the values of any scanner variables."
5247 ;; I really wish I knew a better way to do this, but I can't
5248 ;; find the Emacs function that takes a 16-bit int and converts
5249 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5250 ;; Have to first check that it's 4 hex characters or it may stop
5251 ;; the read early.
5252 (ignore-errors
5253 (let ((s (buffer-substring-no-properties js2-ts-cursor
5254 (+ 4 js2-ts-cursor))))
5255 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5256 (read (concat "?\\u" s))))))
5257
5258 (defun js2-match-char (test)
5259 "Consume and return next character if it matches TEST, a character.
5260 Returns nil and consumes nothing if TEST is not the next character."
5261 (let ((c (js2-get-char)))
5262 (if (eq c test)
5263 t
5264 (js2-unget-char)
5265 nil)))
5266
5267 (defun js2-peek-char ()
5268 (prog1
5269 (js2-get-char)
5270 (js2-unget-char)))
5271
5272 (defun js2-identifier-start-p (c)
5273 "Is C a valid start to an ES5 Identifier?
5274 See http://es5.github.io/#x7.6"
5275 (or
5276 (memq c '(?$ ?_))
5277 (memq (get-char-code-property c 'general-category)
5278 ;; Letters
5279 '(Lu Ll Lt Lm Lo Nl))))
5280
5281 (defun js2-identifier-part-p (c)
5282 "Is C a valid part of an ES5 Identifier?
5283 See http://es5.github.io/#x7.6"
5284 (or
5285 (memq c '(?$ ?_ ?\u200c ?\u200d))
5286 (memq (get-char-code-property c 'general-category)
5287 '(;; Letters
5288 Lu Ll Lt Lm Lo Nl
5289 ;; Combining Marks
5290 Mn Mc
5291 ;; Digits
5292 Nd
5293 ;; Connector Punctuation
5294 Pc))))
5295
5296 (defun js2-alpha-p (c)
5297 (cond ((and (<= ?A c) (<= c ?Z)) t)
5298 ((and (<= ?a c) (<= c ?z)) t)
5299 (t nil)))
5300
5301 (defsubst js2-digit-p (c)
5302 (and (<= ?0 c) (<= c ?9)))
5303
5304 (defun js2-js-space-p (c)
5305 (if (<= c 127)
5306 (memq c '(#x20 #x9 #xB #xC #xD))
5307 (or
5308 (eq c #xA0)
5309 ;; TODO: change this nil to check for Unicode space character
5310 nil)))
5311
5312 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5313
5314 (defun js2-skip-line ()
5315 "Skip to end of line."
5316 (while (not (memq (js2-get-char) js2-eol-chars)))
5317 (js2-unget-char)
5318 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5319 (setq js2-token-end js2-ts-cursor))
5320
5321 (defun js2-init-scanner (&optional buf line)
5322 "Create token stream for BUF starting on LINE.
5323 BUF defaults to `current-buffer' and LINE defaults to 1.
5324
5325 A buffer can only have one scanner active at a time, which yields
5326 dramatically simpler code than using a defstruct. If you need to
5327 have simultaneous scanners in a buffer, copy the regions to scan
5328 into temp buffers."
5329 (with-current-buffer (or buf (current-buffer))
5330 (setq js2-ts-dirty-line nil
5331 js2-ts-hit-eof nil
5332 js2-ts-line-start 0
5333 js2-ts-lineno (or line 1)
5334 js2-ts-line-end-char -1
5335 js2-ts-cursor (point-min)
5336 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5337 js2-ti-tokens-cursor 0
5338 js2-ti-lookahead 0
5339 js2-ts-is-xml-attribute nil
5340 js2-ts-xml-is-tag-content nil
5341 js2-ts-xml-open-tags-count 0
5342 js2-ts-string-buffer nil)))
5343
5344 ;; This function uses the cached op, string and number fields in
5345 ;; TokenStream; if getToken has been called since the passed token
5346 ;; was scanned, the op or string printed may be incorrect.
5347 (defun js2-token-to-string (token)
5348 ;; Not sure where this function is used in Rhino. Not tested.
5349 (if (not js2-debug-print-trees)
5350 ""
5351 (let ((name (js2-tt-name token)))
5352 (cond
5353 ((memq token (list js2-STRING js2-REGEXP js2-NAME js2-TEMPLATE_STRING))
5354 (concat name " `" (js2-current-token-string) "'"))
5355 ((eq token js2-NUMBER)
5356 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5357 (t
5358 name)))))
5359
5360 (defconst js2-keywords
5361 '(break
5362 case catch class const continue
5363 debugger default delete do
5364 else extends
5365 false finally for function
5366 if in instanceof import
5367 let
5368 new null
5369 return
5370 static super switch
5371 this throw true try typeof
5372 var void
5373 while with
5374 yield))
5375
5376 ;; Token names aren't exactly the same as the keywords, unfortunately.
5377 ;; E.g. delete is js2-DELPROP.
5378 (defconst js2-kwd-tokens
5379 (let ((table (make-vector js2-num-tokens nil))
5380 (tokens
5381 (list js2-BREAK
5382 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5383 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5384 js2-ELSE js2-EXTENDS
5385 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5386 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5387 js2-LET
5388 js2-NEW js2-NULL
5389 js2-RETURN
5390 js2-STATIC js2-SUPER js2-SWITCH
5391 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5392 js2-VAR
5393 js2-WHILE js2-WITH
5394 js2-YIELD)))
5395 (dolist (i tokens)
5396 (aset table i 'font-lock-keyword-face))
5397 (aset table js2-STRING 'font-lock-string-face)
5398 (aset table js2-REGEXP 'font-lock-string-face)
5399 (aset table js2-TEMPLATE_STRING 'font-lock-string-face)
5400 (aset table js2-COMMENT 'font-lock-comment-face)
5401 (aset table js2-THIS 'font-lock-builtin-face)
5402 (aset table js2-SUPER 'font-lock-builtin-face)
5403 (aset table js2-VOID 'font-lock-constant-face)
5404 (aset table js2-NULL 'font-lock-constant-face)
5405 (aset table js2-TRUE 'font-lock-constant-face)
5406 (aset table js2-FALSE 'font-lock-constant-face)
5407 (aset table js2-NOT 'font-lock-negation-char-face)
5408 table)
5409 "Vector whose values are non-nil for tokens that are keywords.
5410 The values are default faces to use for highlighting the keywords.")
5411
5412 ;; FIXME: Support strict mode-only future reserved words, after we know
5413 ;; which parts scopes are in strict mode, and which are not.
5414 (defconst js2-reserved-words '(class enum export extends import super)
5415 "Future reserved keywords in ECMAScript 5.1.")
5416
5417 (defconst js2-keyword-names
5418 (let ((table (make-hash-table :test 'equal)))
5419 (loop for k in js2-keywords
5420 do (puthash
5421 (symbol-name k) ; instanceof
5422 (intern (concat "js2-"
5423 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5424 table))
5425 table)
5426 "JavaScript keywords by name, mapped to their symbols.")
5427
5428 (defconst js2-reserved-word-names
5429 (let ((table (make-hash-table :test 'equal)))
5430 (loop for k in js2-reserved-words
5431 do
5432 (puthash (symbol-name k) 'js2-RESERVED table))
5433 table)
5434 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5435
5436 (defun js2-collect-string (buf)
5437 "Convert BUF, a list of chars, to a string.
5438 Reverses BUF before converting."
5439 (if buf
5440 (apply #'string (nreverse buf))
5441 ""))
5442
5443 (defun js2-string-to-keyword (s)
5444 "Return token for S, a string, if S is a keyword or reserved word.
5445 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5446 (or (gethash s js2-keyword-names)
5447 (gethash s js2-reserved-word-names)))
5448
5449 (defsubst js2-ts-set-char-token-bounds (token)
5450 "Used when next token is one character."
5451 (setf (js2-token-beg token) (1- js2-ts-cursor)
5452 (js2-token-end token) js2-ts-cursor))
5453
5454 (defsubst js2-ts-return (token type)
5455 "Update the `end' and `type' slots of TOKEN,
5456 then throw `return' with value TYPE."
5457 (setf (js2-token-end token) js2-ts-cursor
5458 (js2-token-type token) type)
5459 (throw 'return type))
5460
5461 (defun js2-x-digit-to-int (c accumulator)
5462 "Build up a hex number.
5463 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5464 corresponding number. Otherwise return -1."
5465 (catch 'return
5466 (catch 'check
5467 ;; Use 0..9 < A..Z < a..z
5468 (cond
5469 ((<= c ?9)
5470 (decf c ?0)
5471 (if (<= 0 c)
5472 (throw 'check nil)))
5473 ((<= c ?F)
5474 (when (<= ?A c)
5475 (decf c (- ?A 10))
5476 (throw 'check nil)))
5477 ((<= c ?f)
5478 (when (<= ?a c)
5479 (decf c (- ?a 10))
5480 (throw 'check nil))))
5481 (throw 'return -1))
5482 (logior c (lsh accumulator 4))))
5483
5484 (defun js2-get-token ()
5485 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5486 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5487 next saved token.
5488
5489 This function will not return a newline (js2-EOL) - instead, it
5490 gobbles newlines until it finds a non-newline token. Call
5491 `js2-peek-token-or-eol' when you care about newlines.
5492
5493 This function will also not return a js2-COMMENT. Instead, it
5494 records comments found in `js2-scanned-comments'. If the token
5495 returned by this function immediately follows a jsdoc comment,
5496 the token is flagged as such."
5497 (if (zerop js2-ti-lookahead)
5498 (js2-get-token-internal)
5499 (decf js2-ti-lookahead)
5500 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5501 (let ((tt (js2-current-token-type)))
5502 (assert (not (= tt js2-EOL)))
5503 tt)))
5504
5505 (defun js2-unget-token ()
5506 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5507 (incf js2-ti-lookahead)
5508 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5509
5510 (defun js2-get-token-internal ()
5511 (let* ((token (js2-get-token-internal-1)) ; call scanner
5512 (tt (js2-token-type token))
5513 saw-eol
5514 face)
5515 ;; process comments
5516 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5517 (if (= tt js2-EOL)
5518 (setq saw-eol t)
5519 (setq saw-eol nil)
5520 (when js2-record-comments
5521 (js2-record-comment token)))
5522 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5523 (setq token (js2-get-token-internal-1) ; call scanner again
5524 tt (js2-token-type token)))
5525
5526 (when saw-eol
5527 (setf (js2-token-follows-eol-p token) t))
5528
5529 ;; perform lexical fontification as soon as token is scanned
5530 (when js2-parse-ide-mode
5531 (cond
5532 ((minusp tt)
5533 (js2-record-face 'js2-error token))
5534 ((setq face (aref js2-kwd-tokens tt))
5535 (js2-record-face face token))
5536 ((and (= tt js2-NAME)
5537 (equal (js2-token-string token) "undefined"))
5538 (js2-record-face 'font-lock-constant-face token))))
5539 tt))
5540
5541 (defun js2-get-token-internal-1 ()
5542 "Return next JavaScript token type, an int such as js2-RETURN.
5543 During operation, creates an instance of `js2-token' struct, sets
5544 its relevant fields and puts it into `js2-ti-tokens'."
5545 (let (c c1 identifier-start is-unicode-escape-start
5546 contains-escape escape-val str result base
5547 quote-char val look-for-slash continue tt
5548 (token (js2-new-token 0)))
5549 (setq
5550 tt
5551 (catch 'return
5552 (while t
5553 ;; Eat whitespace, possibly sensitive to newlines.
5554 (setq continue t)
5555 (while continue
5556 (setq c (js2-get-char))
5557 (cond
5558 ((eq c js2-EOF_CHAR)
5559 (js2-unget-char)
5560 (js2-ts-set-char-token-bounds token)
5561 (throw 'return js2-EOF))
5562 ((eq c ?\n)
5563 (js2-ts-set-char-token-bounds token)
5564 (setq js2-ts-dirty-line nil)
5565 (throw 'return js2-EOL))
5566 ((not (js2-js-space-p c))
5567 (if (/= c ?-) ; in case end of HTML comment
5568 (setq js2-ts-dirty-line t))
5569 (setq continue nil))))
5570 ;; Assume the token will be 1 char - fixed up below.
5571 (js2-ts-set-char-token-bounds token)
5572 (when (eq c ?@)
5573 (throw 'return js2-XMLATTR))
5574 ;; identifier/keyword/instanceof?
5575 ;; watch out for starting with a <backslash>
5576 (cond
5577 ((eq c ?\\)
5578 (setq c (js2-get-char))
5579 (if (eq c ?u)
5580 (setq identifier-start t
5581 is-unicode-escape-start t
5582 js2-ts-string-buffer nil)
5583 (setq identifier-start nil)
5584 (js2-unget-char)
5585 (setq c ?\\)))
5586 (t
5587 (when (setq identifier-start (js2-identifier-start-p c))
5588 (setq js2-ts-string-buffer nil)
5589 (js2-add-to-string c))))
5590 (when identifier-start
5591 (setq contains-escape is-unicode-escape-start)
5592 (catch 'break
5593 (while t
5594 (if is-unicode-escape-start
5595 ;; strictly speaking we should probably push-back
5596 ;; all the bad characters if the <backslash>uXXXX
5597 ;; sequence is malformed. But since there isn't a
5598 ;; correct context(is there?) for a bad Unicode
5599 ;; escape sequence in an identifier, we can report
5600 ;; an error here.
5601 (progn
5602 (setq escape-val 0)
5603 (dotimes (_ 4)
5604 (setq c (js2-get-char)
5605 escape-val (js2-x-digit-to-int c escape-val))
5606 ;; Next check takes care of c < 0 and bad escape
5607 (if (minusp escape-val)
5608 (throw 'break nil)))
5609 (if (minusp escape-val)
5610 (js2-report-scan-error "msg.invalid.escape" t))
5611 (js2-add-to-string escape-val)
5612 (setq is-unicode-escape-start nil))
5613 (setq c (js2-get-char))
5614 (cond
5615 ((eq c ?\\)
5616 (setq c (js2-get-char))
5617 (if (eq c ?u)
5618 (setq is-unicode-escape-start t
5619 contains-escape t)
5620 (js2-report-scan-error "msg.illegal.character" t)))
5621 (t
5622 (if (or (eq c js2-EOF_CHAR)
5623 (not (js2-identifier-part-p c)))
5624 (throw 'break nil))
5625 (js2-add-to-string c))))))
5626 (js2-unget-char)
5627 (setf str (js2-collect-string js2-ts-string-buffer)
5628 (js2-token-end token) js2-ts-cursor)
5629 ;; FIXME: Invalid in ES5 and ES6, see
5630 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5631 ;; Probably should just drop this conditional.
5632 (unless contains-escape
5633 ;; OPT we shouldn't have to make a string (object!) to
5634 ;; check if it's a keyword.
5635 ;; Return the corresponding token if it's a keyword
5636 (when (setq result (js2-string-to-keyword str))
5637 (if (and (< js2-language-version 170)
5638 (memq result '(js2-LET js2-YIELD)))
5639 ;; LET and YIELD are tokens only in 1.7 and later
5640 (setq result 'js2-NAME))
5641 (when (eq result 'js2-RESERVED)
5642 (setf (js2-token-string token) str))
5643 (throw 'return (js2-tt-code result))))
5644 ;; If we want to intern these as Rhino does, just use (intern str)
5645 (setf (js2-token-string token) str)
5646 (throw 'return js2-NAME)) ; end identifier/kwd check
5647 ;; is it a number?
5648 (when (or (js2-digit-p c)
5649 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5650 (setq js2-ts-string-buffer nil
5651 base 10)
5652 (when (eq c ?0)
5653 (setq c (js2-get-char))
5654 (cond
5655 ((or (eq c ?x) (eq c ?X))
5656 (setq base 16)
5657 (setq c (js2-get-char)))
5658 ((and (or (eq c ?b) (eq c ?B))
5659 (>= js2-language-version 200))
5660 (setq base 2)
5661 (setq c (js2-get-char)))
5662 ((and (or (eq c ?o) (eq c ?O))
5663 (>= js2-language-version 200))
5664 (setq base 8)
5665 (setq c (js2-get-char)))
5666 ((js2-digit-p c)
5667 (setq base 'maybe-8))
5668 (t
5669 (js2-add-to-string ?0))))
5670 (cond
5671 ((eq base 16)
5672 (if (> 0 (js2-x-digit-to-int c 0))
5673 (js2-report-scan-error "msg.missing.hex.digits")
5674 (while (<= 0 (js2-x-digit-to-int c 0))
5675 (js2-add-to-string c)
5676 (setq c (js2-get-char)))))
5677 ((eq base 2)
5678 (if (not (memq c '(?0 ?1)))
5679 (js2-report-scan-error "msg.missing.binary.digits")
5680 (while (memq c '(?0 ?1))
5681 (js2-add-to-string c)
5682 (setq c (js2-get-char)))))
5683 ((eq base 8)
5684 (if (or (> ?0 c) (< ?7 c))
5685 (js2-report-scan-error "msg.missing.octal.digits")
5686 (while (and (<= ?0 c) (>= ?7 c))
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char)))))
5689 (t
5690 (while (and (<= ?0 c) (<= c ?9))
5691 ;; We permit 08 and 09 as decimal numbers, which
5692 ;; makes our behavior a superset of the ECMA
5693 ;; numeric grammar. We might not always be so
5694 ;; permissive, so we warn about it.
5695 (when (and (eq base 'maybe-8) (>= c ?8))
5696 (js2-report-warning "msg.bad.octal.literal"
5697 (if (eq c ?8) "8" "9"))
5698 (setq base 10))
5699 (js2-add-to-string c)
5700 (setq c (js2-get-char)))
5701 (when (eq base 'maybe-8)
5702 (setq base 8))))
5703 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5704 (when (eq c ?.)
5705 (loop do
5706 (js2-add-to-string c)
5707 (setq c (js2-get-char))
5708 while (js2-digit-p c)))
5709 (when (memq c '(?e ?E))
5710 (js2-add-to-string c)
5711 (setq c (js2-get-char))
5712 (when (memq c '(?+ ?-))
5713 (js2-add-to-string c)
5714 (setq c (js2-get-char)))
5715 (unless (js2-digit-p c)
5716 (js2-report-scan-error "msg.missing.exponent" t))
5717 (loop do
5718 (js2-add-to-string c)
5719 (setq c (js2-get-char))
5720 while (js2-digit-p c))))
5721 (js2-unget-char)
5722 (let ((str (js2-set-string-from-buffer token)))
5723 (setf (js2-token-number token)
5724 (js2-string-to-number str base)))
5725 (throw 'return js2-NUMBER))
5726 ;; is it a string?
5727 (when (memq c '(?\" ?\' ?`))
5728 ;; We attempt to accumulate a string the fast way, by
5729 ;; building it directly out of the reader. But if there
5730 ;; are any escaped characters in the string, we revert to
5731 ;; building it out of a string buffer.
5732 (setq quote-char c
5733 js2-ts-string-buffer nil
5734 c (js2-get-char))
5735 (catch 'break
5736 (while (/= c quote-char)
5737 (catch 'continue
5738 (when (eq c js2-EOF_CHAR)
5739 (js2-unget-char)
5740 (js2-report-error "msg.unterminated.string.lit")
5741 (throw 'break nil))
5742 (when (and (eq c ?\n) (not (eq quote-char ?`)))
5743 (js2-unget-char)
5744 (js2-report-error "msg.unterminated.string.lit")
5745 (throw 'break nil))
5746 (when (eq c ?\\)
5747 ;; We've hit an escaped character
5748 (setq c (js2-get-char))
5749 (case c
5750 (?b (setq c ?\b))
5751 (?f (setq c ?\f))
5752 (?n (setq c ?\n))
5753 (?r (setq c ?\r))
5754 (?t (setq c ?\t))
5755 (?v (setq c ?\v))
5756 (?u
5757 (setq c1 (js2-read-unicode-escape))
5758 (if js2-parse-ide-mode
5759 (if c1
5760 (progn
5761 ;; just copy the string in IDE-mode
5762 (js2-add-to-string ?\\)
5763 (js2-add-to-string ?u)
5764 (dotimes (_ 3)
5765 (js2-add-to-string (js2-get-char)))
5766 (setq c (js2-get-char))) ; added at end of loop
5767 ;; flag it as an invalid escape
5768 (js2-report-warning "msg.invalid.escape"
5769 nil (- js2-ts-cursor 2) 6))
5770 ;; Get 4 hex digits; if the u escape is not
5771 ;; followed by 4 hex digits, use 'u' + the
5772 ;; literal character sequence that follows.
5773 (js2-add-to-string ?u)
5774 (setq escape-val 0)
5775 (dotimes (_ 4)
5776 (setq c (js2-get-char)
5777 escape-val (js2-x-digit-to-int c escape-val))
5778 (if (minusp escape-val)
5779 (throw 'continue nil))
5780 (js2-add-to-string c))
5781 ;; prepare for replace of stored 'u' sequence by escape value
5782 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5783 c escape-val)))
5784 (?x
5785 ;; Get 2 hex digits, defaulting to 'x'+literal
5786 ;; sequence, as above.
5787 (setq c (js2-get-char)
5788 escape-val (js2-x-digit-to-int c 0))
5789 (if (minusp escape-val)
5790 (progn
5791 (js2-add-to-string ?x)
5792 (throw 'continue nil))
5793 (setq c1 c
5794 c (js2-get-char)
5795 escape-val (js2-x-digit-to-int c escape-val))
5796 (if (minusp escape-val)
5797 (progn
5798 (js2-add-to-string ?x)
5799 (js2-add-to-string c1)
5800 (throw 'continue nil))
5801 ;; got 2 hex digits
5802 (setq c escape-val))))
5803 (?\n
5804 ;; Remove line terminator after escape to follow
5805 ;; SpiderMonkey and C/C++
5806 (setq c (js2-get-char))
5807 (throw 'continue nil))
5808 (t
5809 (when (and (<= ?0 c) (< c ?8))
5810 (setq val (- c ?0)
5811 c (js2-get-char))
5812 (when (and (<= ?0 c) (< c ?8))
5813 (setq val (- (+ (* 8 val) c) ?0)
5814 c (js2-get-char))
5815 (when (and (<= ?0 c)
5816 (< c ?8)
5817 (< val #o37))
5818 ;; c is 3rd char of octal sequence only
5819 ;; if the resulting val <= 0377
5820 (setq val (- (+ (* 8 val) c) ?0)
5821 c (js2-get-char))))
5822 (js2-unget-char)
5823 (setq c val)))))
5824 (js2-add-to-string c)
5825 (setq c (js2-get-char)))))
5826 (js2-set-string-from-buffer token)
5827 (throw 'return (if (eq quote-char ?`)
5828 js2-TEMPLATE_STRING
5829 js2-STRING)))
5830 (js2-ts-return token
5831 (case c
5832 (?\;
5833 (throw 'return js2-SEMI))
5834 (?\[
5835 (throw 'return js2-LB))
5836 (?\]
5837 (throw 'return js2-RB))
5838 (?{
5839 (throw 'return js2-LC))
5840 (?}
5841 (throw 'return js2-RC))
5842 (?\(
5843 (throw 'return js2-LP))
5844 (?\)
5845 (throw 'return js2-RP))
5846 (?,
5847 (throw 'return js2-COMMA))
5848 (??
5849 (throw 'return js2-HOOK))
5850 (?:
5851 (if (js2-match-char ?:)
5852 js2-COLONCOLON
5853 (throw 'return js2-COLON)))
5854 (?.
5855 (if (js2-match-char ?.)
5856 (if (js2-match-char ?.)
5857 js2-TRIPLEDOT js2-DOTDOT)
5858 (if (js2-match-char ?\()
5859 js2-DOTQUERY
5860 (throw 'return js2-DOT))))
5861 (?|
5862 (if (js2-match-char ?|)
5863 (throw 'return js2-OR)
5864 (if (js2-match-char ?=)
5865 js2-ASSIGN_BITOR
5866 (throw 'return js2-BITOR))))
5867 (?^
5868 (if (js2-match-char ?=)
5869 js2-ASSIGN_BITOR
5870 (throw 'return js2-BITXOR)))
5871 (?&
5872 (if (js2-match-char ?&)
5873 (throw 'return js2-AND)
5874 (if (js2-match-char ?=)
5875 js2-ASSIGN_BITAND
5876 (throw 'return js2-BITAND))))
5877 (?=
5878 (if (js2-match-char ?=)
5879 (if (js2-match-char ?=)
5880 js2-SHEQ
5881 (throw 'return js2-EQ))
5882 (if (js2-match-char ?>)
5883 (js2-ts-return token js2-ARROW)
5884 (throw 'return js2-ASSIGN))))
5885 (?!
5886 (if (js2-match-char ?=)
5887 (if (js2-match-char ?=)
5888 js2-SHNE
5889 js2-NE)
5890 (throw 'return js2-NOT)))
5891 (?<
5892 ;; NB:treat HTML begin-comment as comment-till-eol
5893 (when (js2-match-char ?!)
5894 (when (js2-match-char ?-)
5895 (when (js2-match-char ?-)
5896 (js2-skip-line)
5897 (setf (js2-token-comment-type (js2-current-token)) 'html)
5898 (throw 'return js2-COMMENT)))
5899 (js2-unget-char))
5900 (if (js2-match-char ?<)
5901 (if (js2-match-char ?=)
5902 js2-ASSIGN_LSH
5903 js2-LSH)
5904 (if (js2-match-char ?=)
5905 js2-LE
5906 (throw 'return js2-LT))))
5907 (?>
5908 (if (js2-match-char ?>)
5909 (if (js2-match-char ?>)
5910 (if (js2-match-char ?=)
5911 js2-ASSIGN_URSH
5912 js2-URSH)
5913 (if (js2-match-char ?=)
5914 js2-ASSIGN_RSH
5915 js2-RSH))
5916 (if (js2-match-char ?=)
5917 js2-GE
5918 (throw 'return js2-GT))))
5919 (?*
5920 (if (js2-match-char ?=)
5921 js2-ASSIGN_MUL
5922 (throw 'return js2-MUL)))
5923 (?/
5924 ;; is it a // comment?
5925 (when (js2-match-char ?/)
5926 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5927 (js2-skip-line)
5928 (setf (js2-token-comment-type token) 'line)
5929 ;; include newline so highlighting goes to end of window
5930 (incf (js2-token-end token))
5931 (throw 'return js2-COMMENT))
5932 ;; is it a /* comment?
5933 (when (js2-match-char ?*)
5934 (setf look-for-slash nil
5935 (js2-token-beg token) (- js2-ts-cursor 2)
5936 (js2-token-comment-type token)
5937 (if (js2-match-char ?*)
5938 (progn
5939 (setq look-for-slash t)
5940 'jsdoc)
5941 'block))
5942 (while t
5943 (setq c (js2-get-char))
5944 (cond
5945 ((eq c js2-EOF_CHAR)
5946 (setf (js2-token-end token) (1- js2-ts-cursor))
5947 (js2-report-error "msg.unterminated.comment")
5948 (throw 'return js2-COMMENT))
5949 ((eq c ?*)
5950 (setq look-for-slash t))
5951 ((eq c ?/)
5952 (if look-for-slash
5953 (js2-ts-return token js2-COMMENT)))
5954 (t
5955 (setf look-for-slash nil
5956 (js2-token-end token) js2-ts-cursor)))))
5957 (if (js2-match-char ?=)
5958 js2-ASSIGN_DIV
5959 (throw 'return js2-DIV)))
5960 (?#
5961 (when js2-skip-preprocessor-directives
5962 (js2-skip-line)
5963 (setf (js2-token-comment-type token) 'preprocessor
5964 (js2-token-end token) js2-ts-cursor)
5965 (throw 'return js2-COMMENT))
5966 (throw 'return js2-ERROR))
5967 (?%
5968 (if (js2-match-char ?=)
5969 js2-ASSIGN_MOD
5970 (throw 'return js2-MOD)))
5971 (?~
5972 (throw 'return js2-BITNOT))
5973 (?+
5974 (if (js2-match-char ?=)
5975 js2-ASSIGN_ADD
5976 (if (js2-match-char ?+)
5977 js2-INC
5978 (throw 'return js2-ADD))))
5979 (?-
5980 (cond
5981 ((js2-match-char ?=)
5982 (setq c js2-ASSIGN_SUB))
5983 ((js2-match-char ?-)
5984 (unless js2-ts-dirty-line
5985 ;; treat HTML end-comment after possible whitespace
5986 ;; after line start as comment-until-eol
5987 (when (js2-match-char ?>)
5988 (js2-skip-line)
5989 (setf (js2-token-comment-type (js2-current-token)) 'html)
5990 (throw 'return js2-COMMENT)))
5991 (setq c js2-DEC))
5992 (t
5993 (setq c js2-SUB)))
5994 (setq js2-ts-dirty-line t)
5995 c)
5996 (otherwise
5997 (js2-report-scan-error "msg.illegal.character")))))))
5998 (setf (js2-token-type token) tt)
5999 token))
6000
6001 (defsubst js2-string-to-number (str base)
6002 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
6003 (condition-case nil
6004 (string-to-number str base)
6005 (overflow-error -1)))
6006
6007 (defun js2-read-regexp (start-tt)
6008 "Called by parser when it gets / or /= in literal context."
6009 (let (c err
6010 in-class ; inside a '[' .. ']' character-class
6011 flags
6012 (continue t)
6013 (token (js2-new-token 0)))
6014 (setq js2-ts-string-buffer nil)
6015 (if (eq start-tt js2-ASSIGN_DIV)
6016 ;; mis-scanned /=
6017 (js2-add-to-string ?=)
6018 (if (not (eq start-tt js2-DIV))
6019 (error "failed assertion")))
6020 (while (and (not err)
6021 (or (/= (setq c (js2-get-char)) ?/)
6022 in-class))
6023 (cond
6024 ((or (= c ?\n)
6025 (= c js2-EOF_CHAR))
6026 (setf (js2-token-end token) (1- js2-ts-cursor)
6027 err t
6028 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6029 (js2-report-error "msg.unterminated.re.lit"))
6030 (t (cond
6031 ((= c ?\\)
6032 (js2-add-to-string c)
6033 (setq c (js2-get-char)))
6034 ((= c ?\[)
6035 (setq in-class t))
6036 ((= c ?\])
6037 (setq in-class nil)))
6038 (js2-add-to-string c))))
6039 (unless err
6040 (while continue
6041 (cond
6042 ((js2-match-char ?g)
6043 (push ?g flags))
6044 ((js2-match-char ?i)
6045 (push ?i flags))
6046 ((js2-match-char ?m)
6047 (push ?m flags))
6048 ((and (js2-match-char ?u)
6049 (>= js2-language-version 200))
6050 (push ?u flags))
6051 ((and (js2-match-char ?y)
6052 (>= js2-language-version 200))
6053 (push ?y flags))
6054 (t
6055 (setq continue nil))))
6056 (if (js2-alpha-p (js2-peek-char))
6057 (js2-report-scan-error "msg.invalid.re.flag" t
6058 js2-ts-cursor 1))
6059 (js2-set-string-from-buffer token))
6060 (js2-collect-string flags)))
6061
6062 (defun js2-get-first-xml-token ()
6063 (setq js2-ts-xml-open-tags-count 0
6064 js2-ts-is-xml-attribute nil
6065 js2-ts-xml-is-tag-content nil)
6066 (js2-unget-char)
6067 (js2-get-next-xml-token))
6068
6069 (defun js2-xml-discard-string (token)
6070 "Throw away the string in progress and flag an XML parse error."
6071 (setf js2-ts-string-buffer nil
6072 (js2-token-string token) nil)
6073 (js2-report-scan-error "msg.XML.bad.form" t))
6074
6075 (defun js2-get-next-xml-token ()
6076 (setq js2-ts-string-buffer nil) ; for recording the XML
6077 (let ((token (js2-new-token 0))
6078 c result)
6079 (setq result
6080 (catch 'return
6081 (while t
6082 (setq c (js2-get-char))
6083 (cond
6084 ((= c js2-EOF_CHAR)
6085 (throw 'return js2-ERROR))
6086 (js2-ts-xml-is-tag-content
6087 (case c
6088 (?>
6089 (js2-add-to-string c)
6090 (setq js2-ts-xml-is-tag-content nil
6091 js2-ts-is-xml-attribute nil))
6092 (?/
6093 (js2-add-to-string c)
6094 (when (eq ?> (js2-peek-char))
6095 (setq c (js2-get-char))
6096 (js2-add-to-string c)
6097 (setq js2-ts-xml-is-tag-content nil)
6098 (decf js2-ts-xml-open-tags-count)))
6099 (?{
6100 (js2-unget-char)
6101 (js2-set-string-from-buffer token)
6102 (throw 'return js2-XML))
6103 ((?\' ?\")
6104 (js2-add-to-string c)
6105 (unless (js2-read-quoted-string c token)
6106 (throw 'return js2-ERROR)))
6107 (?=
6108 (js2-add-to-string c)
6109 (setq js2-ts-is-xml-attribute t))
6110 ((? ?\t ?\r ?\n)
6111 (js2-add-to-string c))
6112 (t
6113 (js2-add-to-string c)
6114 (setq js2-ts-is-xml-attribute nil)))
6115 (when (and (not js2-ts-xml-is-tag-content)
6116 (zerop js2-ts-xml-open-tags-count))
6117 (js2-set-string-from-buffer token)
6118 (throw 'return js2-XMLEND)))
6119 (t
6120 ;; else not tag content
6121 (case c
6122 (?<
6123 (js2-add-to-string c)
6124 (setq c (js2-peek-char))
6125 (case c
6126 (?!
6127 (setq c (js2-get-char)) ;; skip !
6128 (js2-add-to-string c)
6129 (setq c (js2-peek-char))
6130 (case c
6131 (?-
6132 (setq c (js2-get-char)) ;; skip -
6133 (js2-add-to-string c)
6134 (if (eq c ?-)
6135 (progn
6136 (js2-add-to-string c)
6137 (unless (js2-read-xml-comment token)
6138 (throw 'return js2-ERROR)))
6139 (js2-xml-discard-string token)
6140 (throw 'return js2-ERROR)))
6141 (?\[
6142 (setq c (js2-get-char)) ;; skip [
6143 (js2-add-to-string c)
6144 (if (and (= (js2-get-char) ?C)
6145 (= (js2-get-char) ?D)
6146 (= (js2-get-char) ?A)
6147 (= (js2-get-char) ?T)
6148 (= (js2-get-char) ?A)
6149 (= (js2-get-char) ?\[))
6150 (progn
6151 (js2-add-to-string ?C)
6152 (js2-add-to-string ?D)
6153 (js2-add-to-string ?A)
6154 (js2-add-to-string ?T)
6155 (js2-add-to-string ?A)
6156 (js2-add-to-string ?\[)
6157 (unless (js2-read-cdata token)
6158 (throw 'return js2-ERROR)))
6159 (js2-xml-discard-string token)
6160 (throw 'return js2-ERROR)))
6161 (t
6162 (unless (js2-read-entity token)
6163 (throw 'return js2-ERROR))))
6164 ;; Allow bare CDATA section, e.g.:
6165 ;; let xml = <![CDATA[ foo bar baz ]]>;
6166 (when (zerop js2-ts-xml-open-tags-count)
6167 (throw 'return js2-XMLEND)))
6168 (??
6169 (setq c (js2-get-char)) ;; skip ?
6170 (js2-add-to-string c)
6171 (unless (js2-read-PI token)
6172 (throw 'return js2-ERROR)))
6173 (?/
6174 ;; end tag
6175 (setq c (js2-get-char)) ;; skip /
6176 (js2-add-to-string c)
6177 (when (zerop js2-ts-xml-open-tags-count)
6178 (js2-xml-discard-string token)
6179 (throw 'return js2-ERROR))
6180 (setq js2-ts-xml-is-tag-content t)
6181 (decf js2-ts-xml-open-tags-count))
6182 (t
6183 ;; start tag
6184 (setq js2-ts-xml-is-tag-content t)
6185 (incf js2-ts-xml-open-tags-count))))
6186 (?{
6187 (js2-unget-char)
6188 (js2-set-string-from-buffer token)
6189 (throw 'return js2-XML))
6190 (t
6191 (js2-add-to-string c))))))))
6192 (setf (js2-token-end token) js2-ts-cursor)
6193 (setf (js2-token-type token) result)
6194 result))
6195
6196 (defun js2-read-quoted-string (quote token)
6197 (let (c)
6198 (catch 'return
6199 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6200 (js2-add-to-string c)
6201 (if (eq c quote)
6202 (throw 'return t)))
6203 (js2-xml-discard-string token) ;; throw away string in progress
6204 nil)))
6205
6206 (defun js2-read-xml-comment (token)
6207 (let ((c (js2-get-char)))
6208 (catch 'return
6209 (while (/= c js2-EOF_CHAR)
6210 (catch 'continue
6211 (js2-add-to-string c)
6212 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6213 (setq c (js2-get-char))
6214 (js2-add-to-string c)
6215 (if (eq (js2-peek-char) ?>)
6216 (progn
6217 (setq c (js2-get-char)) ;; skip >
6218 (js2-add-to-string c)
6219 (throw 'return t))
6220 (throw 'continue nil)))
6221 (setq c (js2-get-char))))
6222 (js2-xml-discard-string token)
6223 nil)))
6224
6225 (defun js2-read-cdata (token)
6226 (let ((c (js2-get-char)))
6227 (catch 'return
6228 (while (/= c js2-EOF_CHAR)
6229 (catch 'continue
6230 (js2-add-to-string c)
6231 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6232 (setq c (js2-get-char))
6233 (js2-add-to-string c)
6234 (if (eq (js2-peek-char) ?>)
6235 (progn
6236 (setq c (js2-get-char)) ;; Skip >
6237 (js2-add-to-string c)
6238 (throw 'return t))
6239 (throw 'continue nil)))
6240 (setq c (js2-get-char))))
6241 (js2-xml-discard-string token)
6242 nil)))
6243
6244 (defun js2-read-entity (token)
6245 (let ((decl-tags 1)
6246 c)
6247 (catch 'return
6248 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6249 (js2-add-to-string c)
6250 (case c
6251 (?<
6252 (incf decl-tags))
6253 (?>
6254 (decf decl-tags)
6255 (if (zerop decl-tags)
6256 (throw 'return t)))))
6257 (js2-xml-discard-string token)
6258 nil)))
6259
6260 (defun js2-read-PI (token)
6261 "Scan an XML processing instruction."
6262 (let (c)
6263 (catch 'return
6264 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6265 (js2-add-to-string c)
6266 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6267 (setq c (js2-get-char)) ;; Skip >
6268 (js2-add-to-string c)
6269 (throw 'return t)))
6270 (js2-xml-discard-string token)
6271 nil)))
6272
6273 ;;; Highlighting
6274
6275 (defun js2-set-face (beg end face &optional record)
6276 "Fontify a region. If RECORD is non-nil, record for later."
6277 (when (plusp js2-highlight-level)
6278 (setq beg (min (point-max) beg)
6279 beg (max (point-min) beg)
6280 end (min (point-max) end)
6281 end (max (point-min) end))
6282 (if record
6283 (push (list beg end face) js2-mode-fontifications)
6284 (put-text-property beg end 'font-lock-face face))))
6285
6286 (defsubst js2-clear-face (beg end)
6287 (remove-text-properties beg end '(font-lock-face nil
6288 help-echo nil
6289 point-entered nil
6290 c-in-sws nil)))
6291
6292 (defconst js2-ecma-global-props
6293 (concat "^"
6294 (regexp-opt
6295 '("Infinity" "NaN" "undefined" "arguments") t)
6296 "$")
6297 "Value properties of the Ecma-262 Global Object.
6298 Shown at or above `js2-highlight-level' 2.")
6299
6300 ;; might want to add the name "arguments" to this list?
6301 (defconst js2-ecma-object-props
6302 (concat "^"
6303 (regexp-opt
6304 '("prototype" "__proto__" "__parent__") t)
6305 "$")
6306 "Value properties of the Ecma-262 Object constructor.
6307 Shown at or above `js2-highlight-level' 2.")
6308
6309 (defconst js2-ecma-global-funcs
6310 (concat
6311 "^"
6312 (regexp-opt
6313 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6314 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6315 "$")
6316 "Function properties of the Ecma-262 Global object.
6317 Shown at or above `js2-highlight-level' 2.")
6318
6319 (defconst js2-ecma-number-props
6320 (concat "^"
6321 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6322 "NEGATIVE_INFINITY"
6323 "POSITIVE_INFINITY") t)
6324 "$")
6325 "Properties of the Ecma-262 Number constructor.
6326 Shown at or above `js2-highlight-level' 2.")
6327
6328 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6329 "Properties of the Ecma-262 Date constructor.
6330 Shown at or above `js2-highlight-level' 2.")
6331
6332 (defconst js2-ecma-math-props
6333 (concat "^"
6334 (regexp-opt
6335 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6336 t)
6337 "$")
6338 "Properties of the Ecma-262 Math object.
6339 Shown at or above `js2-highlight-level' 2.")
6340
6341 (defconst js2-ecma-math-funcs
6342 (concat "^"
6343 (regexp-opt
6344 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6345 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6346 "$")
6347 "Function properties of the Ecma-262 Math object.
6348 Shown at or above `js2-highlight-level' 2.")
6349
6350 (defconst js2-ecma-function-props
6351 (concat
6352 "^"
6353 (regexp-opt
6354 '(;; properties of the Object prototype object
6355 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6356 "toLocaleString" "toString" "valueOf"
6357 ;; properties of the Function prototype object
6358 "apply" "call"
6359 ;; properties of the Array prototype object
6360 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6361 "splice" "unshift"
6362 ;; properties of the String prototype object
6363 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6364 "localeCompare" "match" "replace" "search" "split" "substring"
6365 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6366 "toUpperCase"
6367 ;; properties of the Number prototype object
6368 "toExponential" "toFixed" "toPrecision"
6369 ;; properties of the Date prototype object
6370 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6371 "getMinutes" "getMonth" "getSeconds" "getTime"
6372 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6373 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6374 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6375 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6376 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6377 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6378 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6379 "toTimeString" "toUTCString"
6380 ;; properties of the RegExp prototype object
6381 "exec" "test"
6382 ;; properties of the JSON prototype object
6383 "parse" "stringify"
6384 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6385 "toSource" "__defineGetter__" "__defineSetter__"
6386 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6387 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6388 t)
6389 "$")
6390 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6391 Shown at or above `js2-highlight-level' 3.")
6392
6393 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6394 (let ((target-name (and target
6395 (js2-name-node-p target)
6396 (js2-name-node-name target)))
6397 (prop-name (if prop (js2-name-node-name prop)))
6398 (level2 (>= js2-highlight-level 2))
6399 (level3 (>= js2-highlight-level 3)))
6400 (when level2
6401 (let ((face
6402 (if call-p
6403 (cond
6404 ((and target prop)
6405 (cond
6406 ((and level3 (string-match js2-ecma-function-props prop-name))
6407 'font-lock-builtin-face)
6408 ((and target-name prop)
6409 (cond
6410 ((string= target-name "Date")
6411 (if (string-match js2-ecma-date-props prop-name)
6412 'font-lock-builtin-face))
6413 ((string= target-name "Math")
6414 (if (string-match js2-ecma-math-funcs prop-name)
6415 'font-lock-builtin-face))))))
6416 (prop
6417 (if (string-match js2-ecma-global-funcs prop-name)
6418 'font-lock-builtin-face)))
6419 (cond
6420 ((and target prop)
6421 (cond
6422 ((string= target-name "Number")
6423 (if (string-match js2-ecma-number-props prop-name)
6424 'font-lock-constant-face))
6425 ((string= target-name "Math")
6426 (if (string-match js2-ecma-math-props prop-name)
6427 'font-lock-constant-face))))
6428 (prop
6429 (if (string-match js2-ecma-object-props prop-name)
6430 'font-lock-constant-face))))))
6431 (when face
6432 (let ((pos (+ (js2-node-pos parent) ; absolute
6433 (js2-node-pos prop)))) ; relative
6434 (js2-set-face pos
6435 (+ pos (js2-node-len prop))
6436 face 'record)))))))
6437
6438 (defun js2-parse-highlight-member-expr-node (node)
6439 "Perform syntax highlighting of EcmaScript built-in properties.
6440 The variable `js2-highlight-level' governs this highighting."
6441 (let (face target prop name pos end parent call-p callee)
6442 (cond
6443 ;; case 1: simple name, e.g. foo
6444 ((js2-name-node-p node)
6445 (setq name (js2-name-node-name node))
6446 ;; possible for name to be nil in rare cases - saw it when
6447 ;; running js2-mode on an elisp buffer. Might as well try to
6448 ;; make it so js2-mode never barfs.
6449 (when name
6450 (setq face (if (string-match js2-ecma-global-props name)
6451 'font-lock-constant-face))
6452 (when face
6453 (setq pos (js2-node-pos node)
6454 end (+ pos (js2-node-len node)))
6455 (js2-set-face pos end face 'record))))
6456 ;; case 2: property access or function call
6457 ((or (js2-prop-get-node-p node)
6458 ;; highlight function call if expr is a prop-get node
6459 ;; or a plain name (i.e. unqualified function call)
6460 (and (setq call-p (js2-call-node-p node))
6461 (setq callee (js2-call-node-target node)) ; separate setq!
6462 (or (js2-prop-get-node-p callee)
6463 (js2-name-node-p callee))))
6464 (setq parent node
6465 node (if call-p callee node))
6466 (if (and call-p (js2-name-node-p callee))
6467 (setq prop callee)
6468 (setq target (js2-prop-get-node-left node)
6469 prop (js2-prop-get-node-right node)))
6470 (cond
6471 ((js2-name-node-p prop)
6472 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6473 (js2-parse-highlight-prop-get parent target prop call-p))
6474 ((js2-name-node-p target)
6475 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6476 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6477
6478 (defun js2-parse-highlight-member-expr-fn-name (expr)
6479 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6480 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6481 We currently only handle the case where the last component is a prop-get
6482 of a simple name. Called before EXPR has a parent node."
6483 (let (pos
6484 (name (and (js2-prop-get-node-p expr)
6485 (js2-prop-get-node-right expr))))
6486 (when (js2-name-node-p name)
6487 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6488 (js2-node-pos name)))
6489 (+ pos (js2-node-len name))
6490 'font-lock-function-name-face
6491 'record))))
6492
6493 ;; source: http://jsdoc.sourceforge.net/
6494 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6495 ;; allows type specifications, and needs work before entering the wild.
6496
6497 (defconst js2-jsdoc-param-tag-regexp
6498 (concat "^\\s-*\\*+\\s-*\\(@"
6499 "\\(?:param\\|argument\\)"
6500 "\\)"
6501 "\\s-*\\({[^}]+}\\)?" ; optional type
6502 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6503 "\\>")
6504 "Matches jsdoc tags with optional type and optional param name.")
6505
6506 (defconst js2-jsdoc-typed-tag-regexp
6507 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6508 (regexp-opt
6509 '("enum"
6510 "extends"
6511 "field"
6512 "id"
6513 "implements"
6514 "lends"
6515 "mods"
6516 "requires"
6517 "return"
6518 "returns"
6519 "throw"
6520 "throws"))
6521 "\\)\\)\\s-*\\({[^}]+}\\)?")
6522 "Matches jsdoc tags with optional type.")
6523
6524 (defconst js2-jsdoc-arg-tag-regexp
6525 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6526 (regexp-opt
6527 '("alias"
6528 "augments"
6529 "borrows"
6530 "bug"
6531 "base"
6532 "config"
6533 "default"
6534 "define"
6535 "exception"
6536 "function"
6537 "member"
6538 "memberOf"
6539 "name"
6540 "namespace"
6541 "property"
6542 "since"
6543 "suppress"
6544 "this"
6545 "throws"
6546 "type"
6547 "version"))
6548 "\\)\\)\\s-+\\([^ \t]+\\)")
6549 "Matches jsdoc tags with a single argument.")
6550
6551 (defconst js2-jsdoc-empty-tag-regexp
6552 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6553 (regexp-opt
6554 '("addon"
6555 "author"
6556 "class"
6557 "const"
6558 "constant"
6559 "constructor"
6560 "constructs"
6561 "deprecated"
6562 "desc"
6563 "description"
6564 "event"
6565 "example"
6566 "exec"
6567 "export"
6568 "fileoverview"
6569 "final"
6570 "function"
6571 "hidden"
6572 "ignore"
6573 "implicitCast"
6574 "inheritDoc"
6575 "inner"
6576 "interface"
6577 "license"
6578 "noalias"
6579 "noshadow"
6580 "notypecheck"
6581 "override"
6582 "owner"
6583 "preserve"
6584 "preserveTry"
6585 "private"
6586 "protected"
6587 "public"
6588 "static"
6589 "supported"
6590 ))
6591 "\\)\\)\\s-*")
6592 "Matches empty jsdoc tags.")
6593
6594 (defconst js2-jsdoc-link-tag-regexp
6595 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6596 "Matches a jsdoc link or code tag.")
6597
6598 (defconst js2-jsdoc-see-tag-regexp
6599 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6600 "Matches a jsdoc @see tag.")
6601
6602 (defconst js2-jsdoc-html-tag-regexp
6603 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6604 "Matches a simple (no attributes) html start- or end-tag.")
6605
6606 (defun js2-jsdoc-highlight-helper ()
6607 (js2-set-face (match-beginning 1)
6608 (match-end 1)
6609 'js2-jsdoc-tag)
6610 (if (match-beginning 2)
6611 (if (save-excursion
6612 (goto-char (match-beginning 2))
6613 (= (char-after) ?{))
6614 (js2-set-face (1+ (match-beginning 2))
6615 (1- (match-end 2))
6616 'js2-jsdoc-type)
6617 (js2-set-face (match-beginning 2)
6618 (match-end 2)
6619 'js2-jsdoc-value)))
6620 (if (match-beginning 3)
6621 (js2-set-face (match-beginning 3)
6622 (match-end 3)
6623 'js2-jsdoc-value)))
6624
6625 (defun js2-highlight-jsdoc (ast)
6626 "Highlight doc comment tags."
6627 (let ((comments (js2-ast-root-comments ast))
6628 beg end)
6629 (save-excursion
6630 (dolist (node comments)
6631 (when (eq (js2-comment-node-format node) 'jsdoc)
6632 (setq beg (js2-node-abs-pos node)
6633 end (+ beg (js2-node-len node)))
6634 (save-restriction
6635 (narrow-to-region beg end)
6636 (dolist (re (list js2-jsdoc-param-tag-regexp
6637 js2-jsdoc-typed-tag-regexp
6638 js2-jsdoc-arg-tag-regexp
6639 js2-jsdoc-link-tag-regexp
6640 js2-jsdoc-see-tag-regexp
6641 js2-jsdoc-empty-tag-regexp))
6642 (goto-char beg)
6643 (while (re-search-forward re nil t)
6644 (js2-jsdoc-highlight-helper)))
6645 ;; simple highlighting for html tags
6646 (goto-char beg)
6647 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6648 (js2-set-face (match-beginning 1)
6649 (match-end 1)
6650 'js2-jsdoc-html-tag-delimiter)
6651 (js2-set-face (match-beginning 2)
6652 (match-end 2)
6653 'js2-jsdoc-html-tag-name)
6654 (js2-set-face (match-beginning 3)
6655 (match-end 3)
6656 'js2-jsdoc-html-tag-delimiter))))))))
6657
6658 (defun js2-highlight-assign-targets (_node left right)
6659 "Highlight function properties and external variables."
6660 (let (leftpos name)
6661 ;; highlight vars and props assigned function values
6662 (when (or (js2-function-node-p right)
6663 (js2-class-node-p right))
6664 (cond
6665 ;; var foo = function() {...}
6666 ((js2-name-node-p left)
6667 (setq name left))
6668 ;; foo.bar.baz = function() {...}
6669 ((and (js2-prop-get-node-p left)
6670 (js2-name-node-p (js2-prop-get-node-right left)))
6671 (setq name (js2-prop-get-node-right left))))
6672 (when name
6673 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6674 (+ leftpos (js2-node-len name))
6675 'font-lock-function-name-face
6676 'record)))))
6677
6678 (defun js2-record-name-node (node)
6679 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6680 later. NODE must be a name node."
6681 (let ((leftpos (js2-node-abs-pos node)))
6682 (push (list node js2-current-scope
6683 leftpos
6684 (+ leftpos (js2-node-len node)))
6685 js2-recorded-identifiers)))
6686
6687 (defun js2-highlight-undeclared-vars ()
6688 "After entire parse is finished, look for undeclared variable references.
6689 We have to wait until entire buffer is parsed, since JavaScript permits var
6690 decls to occur after they're used.
6691
6692 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6693 it is considered declared."
6694 (let (name)
6695 (dolist (entry js2-recorded-identifiers)
6696 (destructuring-bind (name-node scope pos end) entry
6697 (setq name (js2-name-node-name name-node))
6698 (unless (or (member name js2-global-externs)
6699 (member name js2-default-externs)
6700 (member name js2-additional-externs)
6701 (js2-get-defining-scope scope name))
6702 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6703 'js2-external-variable))))
6704 (setq js2-recorded-identifiers nil)))
6705
6706 (defun js2-set-default-externs ()
6707 "Set the value of `js2-default-externs' based on the various
6708 `js2-include-?-externs' variables."
6709 (setq js2-default-externs
6710 (append js2-ecma-262-externs
6711 (if js2-include-browser-externs js2-browser-externs)
6712 (if (and js2-include-browser-externs
6713 (>= js2-language-version 200)) js2-harmony-externs)
6714 (if js2-include-rhino-externs js2-rhino-externs)
6715 (if js2-include-node-externs js2-node-externs)
6716 (if (or js2-include-browser-externs js2-include-node-externs)
6717 js2-typed-array-externs))))
6718
6719 (defun js2-apply-jslint-globals ()
6720 (setq js2-additional-externs
6721 (nconc (js2-get-jslint-globals)
6722 js2-additional-externs)))
6723
6724 (defun js2-get-jslint-globals ()
6725 (loop for node in (js2-ast-root-comments js2-mode-ast)
6726 when (and (eq 'block (js2-comment-node-format node))
6727 (save-excursion
6728 (goto-char (js2-node-abs-pos node))
6729 (looking-at "/\\*global ")))
6730 append (js2-get-jslint-globals-in
6731 (match-end 0)
6732 (js2-node-abs-end node))))
6733
6734 (defun js2-get-jslint-globals-in (beg end)
6735 (let (res)
6736 (save-excursion
6737 (goto-char beg)
6738 (while (re-search-forward js2-mode-identifier-re end t)
6739 (let ((match (match-string 0)))
6740 (unless (member match '("true" "false"))
6741 (push match res)))))
6742 (nreverse res)))
6743
6744 ;;; IMenu support
6745
6746 ;; We currently only support imenu, but eventually should support speedbar and
6747 ;; possibly other browsing mechanisms.
6748
6749 ;; The basic strategy is to identify function assignment targets of the form
6750 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6751 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6752 ;; for imenu after parsing is finished.
6753
6754 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6755 ;; JavaScript, and the general problem is undecidable. However, several forms
6756 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6757 ;; include:
6758
6759 ;; function foo() -- function declaration
6760 ;; foo = function() -- function expression assigned to variable
6761 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6762 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6763 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6764 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6765 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6766 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6767 ;; function foo() {function bar() {...}} -- nested function
6768 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6769
6770 ;; This list boils down to a few forms that can be combined recursively.
6771 ;; Top-level named function declarations include both the left-hand (name)
6772 ;; and the right-hand (function value) expressions needed to produce an imenu
6773 ;; entry. The other "right-hand" forms we need to look for are:
6774 ;; - functions declared as props/getters/setters in object literals
6775 ;; - nested named function declarations
6776 ;; The "left-hand" expressions that functions can be assigned to include:
6777 ;; - local/global variables
6778 ;; - nested property-get expressions like a.b.c.d
6779 ;; - element gets like foo[10] or foo['bar'] where the index
6780 ;; expression can be trivially converted to a property name. They
6781 ;; effectively then become property gets.
6782
6783 ;; All the different definition types are canonicalized into the form
6784 ;; foo.bar.baz = position-of-function-keyword
6785
6786 ;; We need to build a trie-like structure for imenu. As an example,
6787 ;; consider the following JavaScript code:
6788
6789 ;; a = function() {...} // function at position 5
6790 ;; b = function() {...} // function at position 25
6791 ;; foo = function() {...} // function at position 100
6792 ;; foo.bar = function() {...} // function at position 200
6793 ;; foo.bar.baz = function() {...} // function at position 300
6794 ;; foo.bar.zab = function() {...} // function at position 400
6795
6796 ;; During parsing we accumulate an entry for each definition in
6797 ;; the variable `js2-imenu-recorder', like so:
6798
6799 ;; '((fn a 5)
6800 ;; (fn b 25)
6801 ;; (fn foo 100)
6802 ;; (fn foo bar 200)
6803 ;; (fn foo bar baz 300)
6804 ;; (fn foo bar zab 400))
6805
6806 ;; Where 'fn' is the respective function node.
6807 ;; After parsing these entries are merged into this alist-trie:
6808
6809 ;; '((a . 1)
6810 ;; (b . 2)
6811 ;; (foo (<definition> . 3)
6812 ;; (bar (<definition> . 6)
6813 ;; (baz . 100)
6814 ;; (zab . 200))))
6815
6816 ;; Note the wacky need for a <definition> name. The token can be anything
6817 ;; that isn't a valid JavaScript identifier, because you might make foo
6818 ;; a function and then start setting properties on it that are also functions.
6819
6820 (defun js2-prop-node-name (node)
6821 "Return the name of a node that may be a property-get/property-name.
6822 If NODE is not a valid name-node, string-node or integral number-node,
6823 returns nil. Otherwise returns the string name/value of the node."
6824 (cond
6825 ((js2-name-node-p node)
6826 (js2-name-node-name node))
6827 ((js2-string-node-p node)
6828 (js2-string-node-value node))
6829 ((and (js2-number-node-p node)
6830 (string-match "^[0-9]+$" (js2-number-node-value node)))
6831 (js2-number-node-value node))
6832 ((eq (js2-node-type node) js2-THIS)
6833 "this")
6834 ((eq (js2-node-type node) js2-SUPER)
6835 "super")))
6836
6837 (defun js2-node-qname-component (node)
6838 "Return the name of this node, if it contributes to a qname.
6839 Returns nil if the node doesn't contribute."
6840 (copy-sequence
6841 (or (js2-prop-node-name node)
6842 (if (and (js2-function-node-p node)
6843 (js2-function-node-name node))
6844 (js2-name-node-name (js2-function-node-name node))))))
6845
6846 (defun js2-record-imenu-entry (fn-node qname pos)
6847 "Add an entry to `js2-imenu-recorder'.
6848 FN-NODE should be the current item's function node.
6849
6850 Associate FN-NODE with its QNAME for later lookup.
6851 This is used in postprocessing the chain list. For each chain, we find
6852 the parent function, look up its qname, then prepend a copy of it to the chain."
6853 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6854 (unless js2-imenu-function-map
6855 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6856 (puthash fn-node qname js2-imenu-function-map))
6857
6858 (defun js2-record-imenu-functions (node &optional var)
6859 "Record function definitions for imenu.
6860 NODE is a function node or an object literal.
6861 VAR, if non-nil, is the expression that NODE is being assigned to.
6862 When passed arguments of wrong type, does nothing."
6863 (when js2-parse-ide-mode
6864 (let ((fun-p (js2-function-node-p node))
6865 qname fname-node)
6866 (cond
6867 ;; non-anonymous function declaration?
6868 ((and fun-p
6869 (not var)
6870 (setq fname-node (js2-function-node-name node)))
6871 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6872 ;; for remaining forms, compute left-side tree branch first
6873 ((and var (setq qname (js2-compute-nested-prop-get var)))
6874 (cond
6875 ;; foo.bar.baz = function
6876 (fun-p
6877 (js2-record-imenu-entry node qname (js2-node-pos node)))
6878 ;; foo.bar.baz = object-literal
6879 ;; look for nested functions: {a: {b: function() {...} }}
6880 ((js2-object-node-p node)
6881 ;; Node position here is still absolute, since the parser
6882 ;; passes the assignment target and value expressions
6883 ;; to us before they are added as children of the assignment node.
6884 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6885
6886 (defun js2-compute-nested-prop-get (node)
6887 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6888 component nodes as a list. Otherwise return nil. Element-gets are treated
6889 as property-gets if the index expression is a string, or a positive integer."
6890 (let (left right head)
6891 (cond
6892 ((or (js2-name-node-p node)
6893 (js2-this-or-super-node-p node))
6894 (list node))
6895 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6896 ((js2-prop-get-node-p node) ; foo.bar
6897 (setq left (js2-prop-get-node-left node)
6898 right (js2-prop-get-node-right node))
6899 (if (setq head (js2-compute-nested-prop-get left))
6900 (nconc head (list right))))
6901 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6902 (setq left (js2-elem-get-node-target node)
6903 right (js2-elem-get-node-element node))
6904 (if (or (js2-string-node-p right) ; ['bar']
6905 (and (js2-number-node-p right) ; [10]
6906 (string-match "^[0-9]+$"
6907 (js2-number-node-value right))))
6908 (if (setq head (js2-compute-nested-prop-get left))
6909 (nconc head (list right))))))))
6910
6911 (defun js2-record-object-literal (node qname pos)
6912 "Recursively process an object literal looking for functions.
6913 NODE is an object literal that is the right-hand child of an assignment
6914 expression. QNAME is a list of nodes representing the assignment target,
6915 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6916 POS is the absolute position of the node.
6917 We do a depth-first traversal of NODE. For any functions we find,
6918 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6919 (let (right)
6920 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6921 (let ((left (js2-infix-node-left e))
6922 ;; Element positions are relative to the parent position.
6923 (pos (+ pos (js2-node-pos e))))
6924 (cond
6925 ;; foo: function() {...}
6926 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6927 (when (js2-prop-node-name left)
6928 ;; As a policy decision, we record the position of the property,
6929 ;; not the position of the `function' keyword, since the property
6930 ;; is effectively the name of the function.
6931 (js2-record-imenu-entry right (append qname (list left)) pos)))
6932 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6933 ((js2-object-node-p right)
6934 (js2-record-object-literal right
6935 (append qname (list (js2-infix-node-left e)))
6936 (+ pos (js2-node-pos right)))))))))
6937
6938 (defun js2-node-top-level-decl-p (node)
6939 "Return t if NODE's name is defined in the top-level scope.
6940 Also returns t if NODE's name is not defined in any scope, since it implies
6941 that it's an external variable, which must also be in the top-level scope."
6942 (let* ((name (js2-prop-node-name node))
6943 (this-scope (js2-node-get-enclosing-scope node))
6944 defining-scope)
6945 (cond
6946 ((js2-this-or-super-node-p node)
6947 nil)
6948 ((null this-scope)
6949 t)
6950 ((setq defining-scope (js2-get-defining-scope this-scope name))
6951 (js2-ast-root-p defining-scope))
6952 (t t))))
6953
6954 (defun js2-wrapper-function-p (node)
6955 "Return t if NODE is a function expression that's immediately invoked.
6956 NODE must be `js2-function-node'."
6957 (let ((parent (js2-node-parent node)))
6958 (or
6959 ;; function(){...}();
6960 (and (js2-call-node-p parent)
6961 (eq node (js2-call-node-target parent)))
6962 (and (js2-paren-node-p parent)
6963 ;; (function(){...})();
6964 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6965 ;; (function(){...}).call(this);
6966 (and (js2-prop-get-node-p parent)
6967 (member (js2-name-node-name (js2-prop-get-node-right parent))
6968 '("call" "apply"))
6969 (js2-call-node-p (js2-node-parent parent))))))))
6970
6971 (defun js2-browse-postprocess-chains ()
6972 "Modify function-declaration name chains after parsing finishes.
6973 Some of the information is only available after the parse tree is complete.
6974 For instance, processing a nested scope requires a parent function node."
6975 (let (result fn parent-qname p elem)
6976 (dolist (entry js2-imenu-recorder)
6977 ;; function node goes first
6978 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6979 ;; Examine head's defining scope:
6980 ;; Pre-processed chain, or top-level/external, keep as-is.
6981 (if (or (stringp head) (js2-node-top-level-decl-p head))
6982 (push chain result)
6983 (when (js2-this-or-super-node-p head)
6984 (setq chain (cdr chain))) ; discard this-node
6985 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6986 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6987 (when (eq parent-qname 'not-found)
6988 ;; anonymous function expressions are not recorded
6989 ;; during the parse, so we need to handle this case here
6990 (setq parent-qname
6991 (if (js2-wrapper-function-p fn)
6992 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6993 (if (js2-ast-root-p grandparent)
6994 nil
6995 (gethash grandparent js2-imenu-function-map 'skip)))
6996 'skip))
6997 (puthash fn parent-qname js2-imenu-function-map))
6998 (if (eq parent-qname 'skip)
6999 ;; We don't show it, let's record that fact.
7000 (remhash current-fn js2-imenu-function-map)
7001 ;; Prepend parent fn qname to this chain.
7002 (let ((qname (append parent-qname chain)))
7003 (puthash current-fn (butlast qname) js2-imenu-function-map)
7004 (push qname result)))))))
7005 ;; Collect chains obtained by third-party code.
7006 (let (js2-imenu-recorder)
7007 (run-hooks 'js2-build-imenu-callbacks)
7008 (dolist (entry js2-imenu-recorder)
7009 (push (cdr entry) result)))
7010 ;; Finally replace each node in each chain with its name.
7011 (dolist (chain result)
7012 (setq p chain)
7013 (while p
7014 (if (js2-node-p (setq elem (car p)))
7015 (setcar p (js2-node-qname-component elem)))
7016 (setq p (cdr p))))
7017 result))
7018
7019 ;; Merge name chains into a trie-like tree structure of nested lists.
7020 ;; To simplify construction of the trie, we first build it out using the rule
7021 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7022 ;; [key, num-or-list]. The second element can be a number; if so, this key
7023 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7024 ;; associated with the key at this level.) Otherwise the second element is
7025 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7026 ;; a simple recursive formulation.
7027 ;;
7028 ;; js2-mode is building the data structure for imenu. The imenu documentation
7029 ;; claims that it's the structure above, but in practice it wants the children
7030 ;; at the same list level as the key for that level, which is how I've drawn
7031 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7032 ;; list wrapper around the children at each level.
7033 ;;
7034 ;; A completed nested imenu-alist entry looks like this:
7035 ;; '(("foo"
7036 ;; ("<definition>" . 7)
7037 ;; ("bar"
7038 ;; ("a" . 40)
7039 ;; ("b" . 60))))
7040 ;;
7041 ;; In particular, the documentation for `imenu--index-alist' says that
7042 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7043 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7044
7045 (defun js2-treeify (lst)
7046 "Convert (a b c d) to (a ((b ((c d)))))."
7047 (if (null (cddr lst)) ; list length <= 2
7048 lst
7049 (list (car lst) (list (js2-treeify (cdr lst))))))
7050
7051 (defun js2-build-alist-trie (chains trie)
7052 "Merge declaration name chains into a trie-like alist structure for imenu.
7053 CHAINS is the qname chain list produced during parsing. TRIE is a
7054 list of elements built up so far."
7055 (let (head tail pos branch kids)
7056 (dolist (chain chains)
7057 (setq head (car chain)
7058 tail (cdr chain)
7059 pos (if (numberp (car tail)) (car tail))
7060 branch (js2-find-if (lambda (n)
7061 (string= (car n) head))
7062 trie)
7063 kids (second branch))
7064 (cond
7065 ;; case 1: this key isn't in the trie yet
7066 ((null branch)
7067 (if trie
7068 (setcdr (last trie) (list (js2-treeify chain)))
7069 (setq trie (list (js2-treeify chain)))))
7070 ;; case 2: key is present with a single number entry: replace w/ list
7071 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7072 ;; ("<definition>" 20)))
7073 ((numberp kids)
7074 (setcar (cdr branch)
7075 (list (list "<definition-1>" kids)
7076 (if pos
7077 (list "<definition-2>" pos)
7078 (js2-treeify tail)))))
7079 ;; case 3: key is there (with kids), and we're a number entry
7080 (pos
7081 (setcdr (last kids)
7082 (list
7083 (list (format "<definition-%d>"
7084 (1+ (loop for kid in kids
7085 count (eq ?< (aref (car kid) 0)))))
7086 pos))))
7087 ;; case 4: key is there with kids, need to merge in our chain
7088 (t
7089 (js2-build-alist-trie (list tail) kids))))
7090 trie))
7091
7092 (defun js2-flatten-trie (trie)
7093 "Convert TRIE to imenu-format.
7094 Recurses through nodes, and for each one whose second element is a list,
7095 appends the list's flattened elements to the current element. Also
7096 changes the tails into conses. For instance, this pre-flattened trie
7097
7098 '(a ((b 20)
7099 (c ((d 30)
7100 (e 40)))))
7101
7102 becomes
7103
7104 '(a (b . 20)
7105 (c (d . 30)
7106 (e . 40)))
7107
7108 Note that the root of the trie has no key, just a list of chains.
7109 This is also true for the value of any key with multiple children,
7110 e.g. key 'c' in the example above."
7111 (cond
7112 ((listp (car trie))
7113 (mapcar #'js2-flatten-trie trie))
7114 (t
7115 (if (numberp (second trie))
7116 (cons (car trie) (second trie))
7117 ;; else pop list and append its kids
7118 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7119
7120 (defun js2-build-imenu-index ()
7121 "Turn `js2-imenu-recorder' into an imenu data structure."
7122 (when (eq js2-imenu-recorder 'empty)
7123 (setq js2-imenu-recorder nil))
7124 (let* ((chains (js2-browse-postprocess-chains))
7125 (result (js2-build-alist-trie chains nil)))
7126 (js2-flatten-trie result)))
7127
7128 (defun js2-test-print-chains (chains)
7129 "Print a list of qname chains.
7130 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7131 i.e. one or more nodes, and an integer position as the list tail."
7132 (mapconcat (lambda (chain)
7133 (concat "("
7134 (mapconcat (lambda (elem)
7135 (if (js2-node-p elem)
7136 (or (js2-node-qname-component elem)
7137 "nil")
7138 (number-to-string elem)))
7139 chain
7140 " ")
7141 ")"))
7142 chains
7143 "\n"))
7144
7145 ;;; Parser
7146
7147 (defconst js2-version "1.8.5"
7148 "Version of JavaScript supported.")
7149
7150 (defun js2-record-face (face &optional token)
7151 "Record a style run of FACE for TOKEN or the current token."
7152 (unless token (setq token (js2-current-token)))
7153 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7154
7155 (defsubst js2-node-end (n)
7156 "Computes the absolute end of node N.
7157 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7158 is only true until the node is added to its parent; i.e., while parsing."
7159 (+ (js2-node-pos n)
7160 (js2-node-len n)))
7161
7162 (defun js2-record-comment (token)
7163 "Record a comment in `js2-scanned-comments'."
7164 (let ((ct (js2-token-comment-type token))
7165 (beg (js2-token-beg token))
7166 (end (js2-token-end token)))
7167 (push (make-js2-comment-node :len (- end beg)
7168 :format ct)
7169 js2-scanned-comments)
7170 (when js2-parse-ide-mode
7171 (js2-record-face (if (eq ct 'jsdoc)
7172 'font-lock-doc-face
7173 'font-lock-comment-face)
7174 token)
7175 (when (memq ct '(html preprocessor))
7176 ;; Tell cc-engine the bounds of the comment.
7177 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7178
7179 (defun js2-peek-token ()
7180 "Return the next token type without consuming it.
7181 If `js2-ti-lookahead' is positive, return the type of next token
7182 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7183 (if (not (zerop js2-ti-lookahead))
7184 (js2-token-type
7185 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7186 (let ((tt (js2-get-token-internal)))
7187 (js2-unget-token)
7188 tt)))
7189
7190 (defalias 'js2-next-token 'js2-get-token)
7191
7192 (defun js2-match-token (match &optional dont-unget)
7193 "Get next token and return t if it matches MATCH, a bytecode.
7194 Returns nil and consumes nothing if MATCH is not the next token."
7195 (if (/= (js2-get-token) match)
7196 (ignore (unless dont-unget (js2-unget-token)))
7197 t))
7198
7199 (defun js2-match-contextual-kwd (name)
7200 "Consume and return t if next token is `js2-NAME', and its
7201 string is NAME. Returns nil and keeps current token otherwise."
7202 (if (or (/= (js2-get-token) js2-NAME)
7203 (not (string= (js2-current-token-string) name)))
7204 (progn
7205 (js2-unget-token)
7206 nil)
7207 (js2-record-face 'font-lock-keyword-face)
7208 t))
7209
7210 (defun js2-valid-prop-name-token (tt)
7211 (or (= tt js2-NAME)
7212 (and js2-allow-keywords-as-property-names
7213 (plusp tt)
7214 (or (= tt js2-RESERVED)
7215 (aref js2-kwd-tokens tt)))))
7216
7217 (defun js2-match-prop-name ()
7218 "Consume token and return t if next token is a valid property name.
7219 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7220 is non-nil and it's a keyword token."
7221 (if (js2-valid-prop-name-token (js2-get-token))
7222 t
7223 (js2-unget-token)
7224 nil))
7225
7226 (defun js2-must-match-prop-name (msg-id &optional pos len)
7227 (if (js2-match-prop-name)
7228 t
7229 (js2-report-error msg-id nil pos len)
7230 nil))
7231
7232 (defun js2-peek-token-or-eol ()
7233 "Return js2-EOL if the next token immediately follows a newline.
7234 Else returns the next token. Used in situations where we don't
7235 consider certain token types valid if they are preceded by a newline.
7236 One example is the postfix ++ or -- operator, which has to be on the
7237 same line as its operand."
7238 (let ((tt (js2-get-token))
7239 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7240 (js2-unget-token)
7241 (if follows-eol
7242 js2-EOL
7243 tt)))
7244
7245 (defun js2-must-match (token msg-id &optional pos len)
7246 "Match next token to token code TOKEN, or record a syntax error.
7247 MSG-ID is the error message to report if the match fails.
7248 Returns t on match, nil if no match."
7249 (if (js2-match-token token t)
7250 t
7251 (js2-report-error msg-id nil pos len)
7252 (js2-unget-token)
7253 nil))
7254
7255 (defun js2-must-match-name (msg-id)
7256 (if (js2-match-token js2-NAME t)
7257 t
7258 (if (eq (js2-current-token-type) js2-RESERVED)
7259 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7260 (js2-report-error msg-id)
7261 (js2-unget-token))
7262 nil))
7263
7264 (defsubst js2-inside-function ()
7265 (plusp js2-nesting-of-function))
7266
7267 (defun js2-set-requires-activation ()
7268 (if (js2-function-node-p js2-current-script-or-fn)
7269 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7270
7271 (defun js2-check-activation-name (name _token)
7272 (when (js2-inside-function)
7273 ;; skip language-version 1.2 check from Rhino
7274 (if (or (string= "arguments" name)
7275 (and js2-compiler-activation-names ; only used in codegen
7276 (gethash name js2-compiler-activation-names)))
7277 (js2-set-requires-activation))))
7278
7279 (defun js2-set-is-generator ()
7280 (let ((fn-node js2-current-script-or-fn))
7281 (when (and (js2-function-node-p fn-node)
7282 (not (js2-function-node-generator-type fn-node)))
7283 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7284
7285 (defun js2-must-have-xml ()
7286 (unless js2-compiler-xml-available
7287 (js2-report-error "msg.XML.not.available")))
7288
7289 (defun js2-push-scope (scope)
7290 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7291 (assert (js2-scope-p scope))
7292 (assert (null (js2-scope-parent-scope scope)))
7293 (assert (not (eq js2-current-scope scope)))
7294 (setf (js2-scope-parent-scope scope) js2-current-scope
7295 js2-current-scope scope))
7296
7297 (defsubst js2-pop-scope ()
7298 (setq js2-current-scope
7299 (js2-scope-parent-scope js2-current-scope)))
7300
7301 (defun js2-enter-loop (loop-node)
7302 (push loop-node js2-loop-set)
7303 (push loop-node js2-loop-and-switch-set)
7304 (js2-push-scope loop-node)
7305 ;; Tell the current labeled statement (if any) its statement,
7306 ;; and set the jump target of the first label to the loop.
7307 ;; These are used in `js2-parse-continue' to verify that the
7308 ;; continue target is an actual labeled loop. (And for codegen.)
7309 (when js2-labeled-stmt
7310 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7311 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7312 js2-labeled-stmt))) loop-node)))
7313
7314 (defun js2-exit-loop ()
7315 (pop js2-loop-set)
7316 (pop js2-loop-and-switch-set)
7317 (js2-pop-scope))
7318
7319 (defsubst js2-enter-switch (switch-node)
7320 (push switch-node js2-loop-and-switch-set))
7321
7322 (defsubst js2-exit-switch ()
7323 (pop js2-loop-and-switch-set))
7324
7325 (defun js2-parse (&optional buf cb)
7326 "Tell the js2 parser to parse a region of JavaScript.
7327
7328 BUF is a buffer or buffer name containing the code to parse.
7329 Call `narrow-to-region' first to parse only part of the buffer.
7330
7331 The returned AST root node is given some additional properties:
7332 `node-count' - total number of nodes in the AST
7333 `buffer' - BUF. The buffer it refers to may change or be killed,
7334 so the value is not necessarily reliable.
7335
7336 An optional callback CB can be specified to report parsing
7337 progress. If `(functionp CB)' returns t, it will be called with
7338 the current line number once before parsing begins, then again
7339 each time the lexer reaches a new line number.
7340
7341 CB can also be a list of the form `(symbol cb ...)' to specify
7342 multiple callbacks with different criteria. Each symbol is a
7343 criterion keyword, and the following element is the callback to
7344 call
7345
7346 :line - called whenever the line number changes
7347 :token - called for each new token consumed
7348
7349 The list of criteria could be extended to include entering or
7350 leaving a statement, an expression, or a function definition."
7351 (if (and cb (not (functionp cb)))
7352 (error "criteria callbacks not yet implemented"))
7353 (let ((inhibit-point-motion-hooks t)
7354 (js2-compiler-xml-available (>= js2-language-version 160))
7355 ;; This is a recursive-descent parser, so give it a big stack.
7356 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7357 (max-specpdl-size (max max-specpdl-size 3000))
7358 (case-fold-search nil)
7359 ast)
7360 (with-current-buffer (or buf (current-buffer))
7361 (setq js2-scanned-comments nil
7362 js2-parsed-errors nil
7363 js2-parsed-warnings nil
7364 js2-imenu-recorder nil
7365 js2-imenu-function-map nil
7366 js2-label-set nil)
7367 (js2-init-scanner)
7368 (setq ast (with-silent-modifications
7369 (js2-do-parse)))
7370 (unless js2-ts-hit-eof
7371 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7372 (setf (js2-ast-root-errors ast) js2-parsed-errors
7373 (js2-ast-root-warnings ast) js2-parsed-warnings)
7374 ;; if we didn't find any declarations, put a dummy in this list so we
7375 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7376 (unless js2-imenu-recorder
7377 (setq js2-imenu-recorder 'empty))
7378 (run-hooks 'js2-parse-finished-hook)
7379 ast)))
7380
7381 ;; Corresponds to Rhino's Parser.parse() method.
7382 (defun js2-do-parse ()
7383 "Parse current buffer starting from current point.
7384 Scanner should be initialized."
7385 (let ((pos js2-ts-cursor)
7386 (end js2-ts-cursor) ; in case file is empty
7387 root n tt)
7388 ;; initialize buffer-local parsing vars
7389 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7390 js2-current-script-or-fn root
7391 js2-current-scope root
7392 js2-nesting-of-function 0
7393 js2-labeled-stmt nil
7394 js2-recorded-identifiers nil) ; for js2-highlight
7395 (while (/= (setq tt (js2-get-token)) js2-EOF)
7396 (if (= tt js2-FUNCTION)
7397 (progn
7398 (setq n (if js2-called-by-compile-function
7399 (js2-parse-function-expr)
7400 (js2-parse-function-stmt))))
7401 ;; not a function - parse a statement
7402 (js2-unget-token)
7403 (setq n (js2-parse-statement)))
7404 ;; add function or statement to script
7405 (setq end (js2-node-end n))
7406 (js2-block-node-push root n))
7407 ;; add comments to root in lexical order
7408 (when js2-scanned-comments
7409 ;; if we find a comment beyond end of normal kids, use its end
7410 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7411 (dolist (comment js2-scanned-comments)
7412 (push comment (js2-ast-root-comments root))
7413 (js2-node-add-children root comment)))
7414 (setf (js2-node-len root) (- end pos))
7415 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7416 ;; Give extensions a chance to muck with things before highlighting starts.
7417 (let ((js2-additional-externs js2-additional-externs))
7418 (save-excursion
7419 (run-hooks 'js2-post-parse-callbacks))
7420 (js2-highlight-undeclared-vars))
7421 root))
7422
7423 (defun js2-parse-function-closure-body (fn-node)
7424 "Parse a JavaScript 1.8 function closure body."
7425 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7426 (if js2-ts-hit-eof
7427 (js2-report-error "msg.no.brace.body" nil
7428 (js2-node-pos fn-node)
7429 (- js2-ts-cursor (js2-node-pos fn-node)))
7430 (js2-node-add-children fn-node
7431 (setf (js2-function-node-body fn-node)
7432 (js2-parse-expr t))))))
7433
7434 (defun js2-parse-function-body (fn-node)
7435 (js2-must-match js2-LC "msg.no.brace.body"
7436 (js2-node-pos fn-node)
7437 (- js2-ts-cursor (js2-node-pos fn-node)))
7438 (let ((pos (js2-current-token-beg)) ; LC position
7439 (pn (make-js2-block-node)) ; starts at LC position
7440 tt
7441 end)
7442 (incf js2-nesting-of-function)
7443 (unwind-protect
7444 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7445 (= tt js2-EOF)
7446 (= tt js2-RC)))
7447 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7448 (js2-parse-statement)
7449 (js2-get-token)
7450 (js2-parse-function-stmt))))
7451 (decf js2-nesting-of-function))
7452 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7453 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7454 (setq end (js2-current-token-end)))
7455 (setf (js2-node-pos pn) pos
7456 (js2-node-len pn) (- end pos))
7457 (setf (js2-function-node-body fn-node) pn)
7458 (js2-node-add-children fn-node pn)
7459 pn))
7460
7461 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7462 "Declare and fontify destructuring parameters inside NODE.
7463 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7464 (cond
7465 ((js2-name-node-p node)
7466 (let (leftpos)
7467 (js2-define-symbol decl-type (js2-name-node-name node)
7468 node ignore-not-in-block)
7469 (when face
7470 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7471 (+ leftpos (js2-node-len node))
7472 face 'record))))
7473 ((js2-object-node-p node)
7474 (dolist (elem (js2-object-node-elems node))
7475 (js2-define-destruct-symbols
7476 ;; In abbreviated destructuring {a, b}, right == left.
7477 (js2-object-prop-node-right elem)
7478 decl-type face ignore-not-in-block)))
7479 ((js2-array-node-p node)
7480 (dolist (elem (js2-array-node-elems node))
7481 (when elem
7482 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7483 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7484 (js2-node-len node)))))
7485
7486 (defun js2-parse-function-params (function-type fn-node pos)
7487 (if (js2-match-token js2-RP)
7488 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7489 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7490 (eq (js2-current-token-type) js2-NAME)))
7491 params param default-found rest-param-at)
7492 (when paren-free-arrow
7493 (js2-unget-token))
7494 (loop for tt = (js2-peek-token)
7495 do
7496 (cond
7497 ;; destructuring param
7498 ((and (not paren-free-arrow)
7499 (or (= tt js2-LB) (= tt js2-LC)))
7500 (js2-get-token)
7501 (when default-found
7502 (js2-report-error "msg.no.default.after.default.param"))
7503 (setq param (js2-parse-destruct-primary-expr))
7504 (js2-define-destruct-symbols param
7505 js2-LP
7506 'js2-function-param)
7507 (push param params))
7508 ;; variable name
7509 (t
7510 (when (and (>= js2-language-version 200)
7511 (not paren-free-arrow)
7512 (js2-match-token js2-TRIPLEDOT)
7513 (not rest-param-at))
7514 ;; to report errors if there are more parameters
7515 (setq rest-param-at (length params)))
7516 (js2-must-match-name "msg.no.parm")
7517 (js2-record-face 'js2-function-param)
7518 (setq param (js2-create-name-node))
7519 (js2-define-symbol js2-LP (js2-current-token-string) param)
7520 ;; default parameter value
7521 (when (or (and default-found
7522 (not rest-param-at)
7523 (js2-must-match js2-ASSIGN
7524 "msg.no.default.after.default.param"
7525 (js2-node-pos param)
7526 (js2-node-len param)))
7527 (and (>= js2-language-version 200)
7528 (js2-match-token js2-ASSIGN)))
7529 (assert (not paren-free-arrow))
7530 (let* ((pos (js2-node-pos param))
7531 (tt (js2-current-token-type))
7532 (op-pos (- (js2-current-token-beg) pos))
7533 (left param)
7534 (right (js2-parse-assign-expr))
7535 (len (- (js2-node-end right) pos)))
7536 (setq param (make-js2-assign-node
7537 :type tt :pos pos :len len :op-pos op-pos
7538 :left left :right right)
7539 default-found t)
7540 (js2-node-add-children param left right)))
7541 (push param params)))
7542 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7543 (js2-report-error "msg.param.after.rest" nil
7544 (js2-node-pos param) (js2-node-len param)))
7545 while
7546 (js2-match-token js2-COMMA))
7547 (when (and (not paren-free-arrow)
7548 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7549 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7550 (when rest-param-at
7551 (setf (js2-function-node-rest-p fn-node) t))
7552 (dolist (p params)
7553 (js2-node-add-children fn-node p)
7554 (push p (js2-function-node-params fn-node))))))
7555
7556 (defun js2-check-inconsistent-return-warning (fn-node name)
7557 "Possibly show inconsistent-return warning.
7558 Last token scanned is the close-curly for the function body."
7559 (when (and js2-mode-show-strict-warnings
7560 js2-strict-inconsistent-return-warning
7561 (not (js2-has-consistent-return-usage
7562 (js2-function-node-body fn-node))))
7563 ;; Have it extend from close-curly to bol or beginning of block.
7564 (let ((pos (save-excursion
7565 (goto-char (js2-current-token-end))
7566 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7567 (point-at-bol))))
7568 (end (js2-current-token-end)))
7569 (if (plusp (js2-name-node-length name))
7570 (js2-add-strict-warning "msg.no.return.value"
7571 (js2-name-node-name name) pos end)
7572 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7573
7574 (defun js2-parse-function-stmt ()
7575 (let ((pos (js2-current-token-beg))
7576 (star-p (js2-match-token js2-MUL)))
7577 (js2-must-match-name "msg.unnamed.function.stmt")
7578 (let ((name (js2-create-name-node t))
7579 pn member-expr)
7580 (cond
7581 ((js2-match-token js2-LP)
7582 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7583 (js2-allow-member-expr-as-function-name
7584 (setq member-expr (js2-parse-member-expr-tail nil name))
7585 (js2-parse-highlight-member-expr-fn-name member-expr)
7586 (js2-must-match js2-LP "msg.no.paren.parms")
7587 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7588 (js2-function-node-member-expr pn) member-expr)
7589 pn)
7590 (t
7591 (js2-report-error "msg.no.paren.parms")
7592 (make-js2-error-node))))))
7593
7594 (defun js2-parse-function-expr ()
7595 (let ((pos (js2-current-token-beg))
7596 (star-p (js2-match-token js2-MUL))
7597 name)
7598 (when (js2-match-token js2-NAME)
7599 (setq name (js2-create-name-node t)))
7600 (js2-must-match js2-LP "msg.no.paren.parms")
7601 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7602
7603 (defun js2-parse-function (function-type pos star-p &optional name)
7604 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7605 beginning of the first token (function keyword, unless it's an
7606 arrow function), NAME is js2-name-node."
7607 (let (fn-node lp)
7608 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7609 (setq lp (js2-current-token-beg)))
7610 (setf fn-node (make-js2-function-node :pos pos
7611 :name name
7612 :form function-type
7613 :lp (if lp (- lp pos))
7614 :generator-type (and star-p 'STAR)))
7615 (when name
7616 (js2-set-face (js2-node-pos name) (js2-node-end name)
7617 'font-lock-function-name-face 'record)
7618 (when (plusp (js2-name-node-length name))
7619 ;; Function statements define a symbol in the enclosing scope
7620 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7621 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7622 ;; 1. Nested functions are not affected by the dynamic scope flag
7623 ;; as dynamic scope is already a parent of their scope.
7624 ;; 2. Functions defined under the with statement also immune to
7625 ;; this setup, in which case dynamic scope is ignored in favor
7626 ;; of the with object.
7627 (setf (js2-function-node-ignore-dynamic fn-node) t))
7628 ;; dynamically bind all the per-function variables
7629 (let ((js2-current-script-or-fn fn-node)
7630 (js2-current-scope fn-node)
7631 (js2-nesting-of-with 0)
7632 (js2-end-flags 0)
7633 js2-label-set
7634 js2-loop-set
7635 js2-loop-and-switch-set)
7636 (js2-parse-function-params function-type fn-node pos)
7637 (when (eq function-type 'FUNCTION_ARROW)
7638 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7639 (if (and (>= js2-language-version 180)
7640 (/= (js2-peek-token) js2-LC))
7641 (js2-parse-function-closure-body fn-node)
7642 (js2-parse-function-body fn-node))
7643 (js2-check-inconsistent-return-warning fn-node name)
7644
7645 (when name
7646 (js2-node-add-children fn-node name)
7647 ;; Function expressions define a name only in the body of the
7648 ;; function, and only if not hidden by a parameter name
7649 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7650 (null (js2-scope-get-symbol js2-current-scope
7651 (js2-name-node-name name))))
7652 (js2-define-symbol js2-FUNCTION
7653 (js2-name-node-name name)
7654 fn-node))
7655 (when (eq function-type 'FUNCTION_STATEMENT)
7656 (js2-record-imenu-functions fn-node))))
7657
7658 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7659 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7660 ;; We wait until after parsing the function to set its parent scope,
7661 ;; since `js2-define-symbol' needs the defining-scope check to stop
7662 ;; at the function boundary when checking for redeclarations.
7663 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7664 fn-node))
7665
7666 (defun js2-parse-statements (&optional parent)
7667 "Parse a statement list. Last token consumed must be js2-LC.
7668
7669 PARENT can be a `js2-block-node', in which case the statements are
7670 appended to PARENT. Otherwise a new `js2-block-node' is created
7671 and returned.
7672
7673 This function does not match the closing js2-RC: the caller
7674 matches the RC so it can provide a suitable error message if not
7675 matched. This means it's up to the caller to set the length of
7676 the node to include the closing RC. The node start pos is set to
7677 the absolute buffer start position, and the caller should fix it
7678 up to be relative to the parent node. All children of this block
7679 node are given relative start positions and correct lengths."
7680 (let ((pn (or parent (make-js2-block-node)))
7681 tt)
7682 (setf (js2-node-pos pn) (js2-current-token-beg))
7683 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7684 (/= tt js2-RC))
7685 (js2-block-node-push pn (js2-parse-statement)))
7686 pn))
7687
7688 (defun js2-parse-statement ()
7689 (let (pn beg end)
7690 ;; coarse-grained user-interrupt check - needs work
7691 (and js2-parse-interruptable-p
7692 (zerop (% (incf js2-parse-stmt-count)
7693 js2-statements-per-pause))
7694 (input-pending-p)
7695 (throw 'interrupted t))
7696 (setq pn (js2-statement-helper))
7697 ;; no-side-effects warning check
7698 (unless (js2-node-has-side-effects pn)
7699 (setq end (js2-node-end pn))
7700 (save-excursion
7701 (goto-char end)
7702 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7703 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7704 pn))
7705
7706 ;; These correspond to the switch cases in Parser.statementHelper
7707 (defconst js2-parsers
7708 (let ((parsers (make-vector js2-num-tokens
7709 #'js2-parse-expr-stmt)))
7710 (aset parsers js2-BREAK #'js2-parse-break)
7711 (aset parsers js2-CLASS #'js2-parse-class-stmt)
7712 (aset parsers js2-CONST #'js2-parse-const-var)
7713 (aset parsers js2-CONTINUE #'js2-parse-continue)
7714 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7715 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7716 (aset parsers js2-DO #'js2-parse-do)
7717 (aset parsers js2-FOR #'js2-parse-for)
7718 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7719 (aset parsers js2-IF #'js2-parse-if)
7720 (aset parsers js2-LC #'js2-parse-block)
7721 (aset parsers js2-LET #'js2-parse-let-stmt)
7722 (aset parsers js2-NAME #'js2-parse-name-or-label)
7723 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7724 (aset parsers js2-SEMI #'js2-parse-semi)
7725 (aset parsers js2-SWITCH #'js2-parse-switch)
7726 (aset parsers js2-THROW #'js2-parse-throw)
7727 (aset parsers js2-TRY #'js2-parse-try)
7728 (aset parsers js2-VAR #'js2-parse-const-var)
7729 (aset parsers js2-WHILE #'js2-parse-while)
7730 (aset parsers js2-WITH #'js2-parse-with)
7731 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7732 parsers)
7733 "A vector mapping token types to parser functions.")
7734
7735 (defun js2-parse-warn-missing-semi (beg end)
7736 (and js2-mode-show-strict-warnings
7737 js2-strict-missing-semi-warning
7738 (js2-add-strict-warning
7739 "msg.missing.semi" nil
7740 ;; back up to beginning of statement or line
7741 (max beg (save-excursion
7742 (goto-char end)
7743 (point-at-bol)))
7744 end)))
7745
7746 (defconst js2-no-semi-insertion
7747 (list js2-IF
7748 js2-SWITCH
7749 js2-WHILE
7750 js2-DO
7751 js2-FOR
7752 js2-TRY
7753 js2-WITH
7754 js2-LC
7755 js2-ERROR
7756 js2-SEMI
7757 js2-CLASS
7758 js2-FUNCTION)
7759 "List of tokens that don't do automatic semicolon insertion.")
7760
7761 (defconst js2-autoinsert-semi-and-warn
7762 (list js2-ERROR js2-EOF js2-RC))
7763
7764 (defun js2-statement-helper ()
7765 (let* ((tt (js2-get-token))
7766 (first-tt tt)
7767 (parser (if (= tt js2-ERROR)
7768 #'js2-parse-semi
7769 (aref js2-parsers tt)))
7770 pn)
7771 ;; If the statement is set, then it's been told its label by now.
7772 (and js2-labeled-stmt
7773 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7774 (setq js2-labeled-stmt nil))
7775 (setq pn (funcall parser))
7776 ;; Don't do auto semi insertion for certain statement types.
7777 (unless (or (memq first-tt js2-no-semi-insertion)
7778 (js2-labeled-stmt-node-p pn))
7779 (js2-auto-insert-semicolon pn))
7780 pn))
7781
7782 (defun js2-auto-insert-semicolon (pn)
7783 (let* ((tt (js2-get-token))
7784 (pos (js2-node-pos pn)))
7785 (cond
7786 ((= tt js2-SEMI)
7787 ;; extend the node bounds to include the semicolon.
7788 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7789 ((memq tt js2-autoinsert-semi-and-warn)
7790 (js2-unget-token) ; Not ';', do not consume.
7791 ;; Autoinsert ;
7792 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7793 (t
7794 (if (not (js2-token-follows-eol-p (js2-current-token)))
7795 ;; Report error if no EOL or autoinsert ';' otherwise
7796 (js2-report-error "msg.no.semi.stmt")
7797 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7798 (js2-unget-token) ; Not ';', do not consume.
7799 ))))
7800
7801 (defun js2-parse-condition ()
7802 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7803 The parens are discarded and the expression node is returned.
7804 The `pos' field of the return value is set to an absolute position
7805 that must be fixed up by the caller.
7806 Return value is a list (EXPR LP RP), with absolute paren positions."
7807 (let (pn lp rp)
7808 (if (js2-must-match js2-LP "msg.no.paren.cond")
7809 (setq lp (js2-current-token-beg)))
7810 (setq pn (js2-parse-expr))
7811 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7812 (setq rp (js2-current-token-beg)))
7813 ;; Report strict warning on code like "if (a = 7) ..."
7814 (if (and js2-strict-cond-assign-warning
7815 (js2-assign-node-p pn))
7816 (js2-add-strict-warning "msg.equal.as.assign" nil
7817 (js2-node-pos pn)
7818 (+ (js2-node-pos pn)
7819 (js2-node-len pn))))
7820 (list pn lp rp)))
7821
7822 (defun js2-parse-if ()
7823 "Parser for if-statement. Last matched token must be js2-IF."
7824 (let ((pos (js2-current-token-beg))
7825 cond if-true if-false else-pos end pn)
7826 (setq cond (js2-parse-condition)
7827 if-true (js2-parse-statement)
7828 if-false (if (js2-match-token js2-ELSE)
7829 (progn
7830 (setq else-pos (- (js2-current-token-beg) pos))
7831 (js2-parse-statement)))
7832 end (js2-node-end (or if-false if-true))
7833 pn (make-js2-if-node :pos pos
7834 :len (- end pos)
7835 :condition (car cond)
7836 :then-part if-true
7837 :else-part if-false
7838 :else-pos else-pos
7839 :lp (js2-relpos (second cond) pos)
7840 :rp (js2-relpos (third cond) pos)))
7841 (js2-node-add-children pn (car cond) if-true if-false)
7842 pn))
7843
7844 (defun js2-parse-switch ()
7845 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7846 (let ((pos (js2-current-token-beg))
7847 tt pn discriminant has-default case-expr case-node
7848 case-pos cases stmt lp)
7849 (if (js2-must-match js2-LP "msg.no.paren.switch")
7850 (setq lp (js2-current-token-beg)))
7851 (setq discriminant (js2-parse-expr)
7852 pn (make-js2-switch-node :discriminant discriminant
7853 :pos pos
7854 :lp (js2-relpos lp pos)))
7855 (js2-node-add-children pn discriminant)
7856 (js2-enter-switch pn)
7857 (unwind-protect
7858 (progn
7859 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7860 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7861 (js2-must-match js2-LC "msg.no.brace.switch")
7862 (catch 'break
7863 (while t
7864 (setq tt (js2-next-token)
7865 case-pos (js2-current-token-beg))
7866 (cond
7867 ((= tt js2-RC)
7868 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7869 (throw 'break nil)) ; done
7870 ((= tt js2-CASE)
7871 (setq case-expr (js2-parse-expr))
7872 (js2-must-match js2-COLON "msg.no.colon.case"))
7873 ((= tt js2-DEFAULT)
7874 (if has-default
7875 (js2-report-error "msg.double.switch.default"))
7876 (setq has-default t
7877 case-expr nil)
7878 (js2-must-match js2-COLON "msg.no.colon.case"))
7879 (t
7880 (js2-report-error "msg.bad.switch")
7881 (throw 'break nil)))
7882 (setq case-node (make-js2-case-node :pos case-pos
7883 :len (- (js2-current-token-end) case-pos)
7884 :expr case-expr))
7885 (js2-node-add-children case-node case-expr)
7886 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7887 (/= tt js2-CASE)
7888 (/= tt js2-DEFAULT)
7889 (/= tt js2-EOF))
7890 (setf stmt (js2-parse-statement)
7891 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7892 (js2-block-node-push case-node stmt))
7893 (push case-node cases)))
7894 ;; add cases last, as pushing reverses the order to be correct
7895 (dolist (kid cases)
7896 (js2-node-add-children pn kid)
7897 (push kid (js2-switch-node-cases pn)))
7898 pn) ; return value
7899 (js2-exit-switch))))
7900
7901 (defun js2-parse-while ()
7902 "Parser for while-statement. Last matched token must be js2-WHILE."
7903 (let ((pos (js2-current-token-beg))
7904 (pn (make-js2-while-node))
7905 cond body)
7906 (js2-enter-loop pn)
7907 (unwind-protect
7908 (progn
7909 (setf cond (js2-parse-condition)
7910 (js2-while-node-condition pn) (car cond)
7911 body (js2-parse-statement)
7912 (js2-while-node-body pn) body
7913 (js2-node-len pn) (- (js2-node-end body) pos)
7914 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7915 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7916 (js2-node-add-children pn body (car cond)))
7917 (js2-exit-loop))
7918 pn))
7919
7920 (defun js2-parse-do ()
7921 "Parser for do-statement. Last matched token must be js2-DO."
7922 (let ((pos (js2-current-token-beg))
7923 (pn (make-js2-do-node))
7924 cond body end)
7925 (js2-enter-loop pn)
7926 (unwind-protect
7927 (progn
7928 (setq body (js2-parse-statement))
7929 (js2-must-match js2-WHILE "msg.no.while.do")
7930 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7931 cond (js2-parse-condition)
7932 (js2-do-node-condition pn) (car cond)
7933 (js2-do-node-body pn) body
7934 end js2-ts-cursor
7935 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7936 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7937 (js2-node-add-children pn (car cond) body))
7938 (js2-exit-loop))
7939 ;; Always auto-insert semicolon to follow SpiderMonkey:
7940 ;; It is required by ECMAScript but is ignored by the rest of
7941 ;; world; see bug 238945
7942 (if (js2-match-token js2-SEMI)
7943 (setq end js2-ts-cursor))
7944 (setf (js2-node-len pn) (- end pos))
7945 pn))
7946
7947 (defun js2-parse-for ()
7948 "Parser for for-statement. Last matched token must be js2-FOR.
7949 Parses for, for-in, and for each-in statements."
7950 (let ((for-pos (js2-current-token-beg))
7951 pn is-for-each is-for-in-or-of is-for-of
7952 in-pos each-pos tmp-pos
7953 init ; Node init is also foo in 'foo in object'
7954 cond ; Node cond is also object in 'foo in object'
7955 incr ; 3rd section of for-loop initializer
7956 body tt lp rp)
7957 ;; See if this is a for each () instead of just a for ()
7958 (when (js2-match-token js2-NAME)
7959 (if (string= "each" (js2-current-token-string))
7960 (progn
7961 (setq is-for-each t
7962 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7963 (js2-record-face 'font-lock-keyword-face))
7964 (js2-report-error "msg.no.paren.for")))
7965 (if (js2-must-match js2-LP "msg.no.paren.for")
7966 (setq lp (- (js2-current-token-beg) for-pos)))
7967 (setq tt (js2-get-token))
7968 ;; 'for' makes local scope
7969 (js2-push-scope (make-js2-scope))
7970 (unwind-protect
7971 ;; parse init clause
7972 (let ((js2-in-for-init t)) ; set as dynamic variable
7973 (cond
7974 ((= tt js2-SEMI)
7975 (js2-unget-token)
7976 (setq init (make-js2-empty-expr-node)))
7977 ((or (= tt js2-VAR) (= tt js2-LET))
7978 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7979 (t
7980 (js2-unget-token)
7981 (setq init (js2-parse-expr)))))
7982 (if (or (js2-match-token js2-IN)
7983 (and (>= js2-language-version 200)
7984 (js2-match-contextual-kwd "of")
7985 (setq is-for-of t)))
7986 (setq is-for-in-or-of t
7987 in-pos (- (js2-current-token-beg) for-pos)
7988 ;; scope of iteration target object is not the scope we've created above.
7989 ;; stash current scope temporary.
7990 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7991 (js2-parse-expr))) ; object over which we're iterating
7992 ;; else ordinary for loop - parse cond and incr
7993 (js2-must-match js2-SEMI "msg.no.semi.for")
7994 (setq cond (if (= (js2-peek-token) js2-SEMI)
7995 (make-js2-empty-expr-node) ; no loop condition
7996 (js2-parse-expr)))
7997 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7998 (setq tmp-pos (js2-current-token-end)
7999 incr (if (= (js2-peek-token) js2-RP)
8000 (make-js2-empty-expr-node :pos tmp-pos)
8001 (js2-parse-expr))))
8002 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8003 (setq rp (- (js2-current-token-beg) for-pos)))
8004 (if (not is-for-in-or-of)
8005 (setq pn (make-js2-for-node :init init
8006 :condition cond
8007 :update incr
8008 :lp lp
8009 :rp rp))
8010 ;; cond could be null if 'in obj' got eaten by the init node.
8011 (if (js2-infix-node-p init)
8012 ;; it was (foo in bar) instead of (var foo in bar)
8013 (setq cond (js2-infix-node-right init)
8014 init (js2-infix-node-left init))
8015 (if (and (js2-var-decl-node-p init)
8016 (> (length (js2-var-decl-node-kids init)) 1))
8017 (js2-report-error "msg.mult.index")))
8018 (setq pn (make-js2-for-in-node :iterator init
8019 :object cond
8020 :in-pos in-pos
8021 :foreach-p is-for-each
8022 :each-pos each-pos
8023 :forof-p is-for-of
8024 :lp lp
8025 :rp rp)))
8026 (unwind-protect
8027 (progn
8028 (js2-enter-loop pn)
8029 ;; We have to parse the body -after- creating the loop node,
8030 ;; so that the loop node appears in the js2-loop-set, allowing
8031 ;; break/continue statements to find the enclosing loop.
8032 (setf body (js2-parse-statement)
8033 (js2-loop-node-body pn) body
8034 (js2-node-pos pn) for-pos
8035 (js2-node-len pn) (- (js2-node-end body) for-pos))
8036 (js2-node-add-children pn init cond incr body))
8037 ;; finally
8038 (js2-exit-loop))
8039 (js2-pop-scope))
8040 pn))
8041
8042 (defun js2-parse-try ()
8043 "Parser for try-statement. Last matched token must be js2-TRY."
8044 (let ((try-pos (js2-current-token-beg))
8045 try-end
8046 try-block
8047 catch-blocks
8048 finally-block
8049 saw-default-catch
8050 peek
8051 param
8052 catch-cond
8053 catch-node
8054 guard-kwd
8055 catch-pos
8056 finally-pos
8057 pn
8058 block
8059 lp
8060 rp)
8061 (if (/= (js2-peek-token) js2-LC)
8062 (js2-report-error "msg.no.brace.try"))
8063 (setq try-block (js2-parse-statement)
8064 try-end (js2-node-end try-block)
8065 peek (js2-peek-token))
8066 (cond
8067 ((= peek js2-CATCH)
8068 (while (js2-match-token js2-CATCH)
8069 (setq catch-pos (js2-current-token-beg)
8070 guard-kwd nil
8071 catch-cond nil
8072 lp nil
8073 rp nil)
8074 (if saw-default-catch
8075 (js2-report-error "msg.catch.unreachable"))
8076 (if (js2-must-match js2-LP "msg.no.paren.catch")
8077 (setq lp (- (js2-current-token-beg) catch-pos)))
8078 (js2-push-scope (make-js2-scope))
8079 (let ((tt (js2-peek-token)))
8080 (cond
8081 ;; destructuring pattern
8082 ;; catch ({ message, file }) { ... }
8083 ((or (= tt js2-LB) (= tt js2-LC))
8084 (js2-get-token)
8085 (setq param (js2-parse-destruct-primary-expr))
8086 (js2-define-destruct-symbols param js2-LET nil))
8087 ;; simple name
8088 (t
8089 (js2-must-match-name "msg.bad.catchcond")
8090 (setq param (js2-create-name-node))
8091 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8092 ;; pattern guard
8093 (if (js2-match-token js2-IF)
8094 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8095 catch-cond (js2-parse-expr))
8096 (setq saw-default-catch t))
8097 (if (js2-must-match js2-RP "msg.bad.catchcond")
8098 (setq rp (- (js2-current-token-beg) catch-pos)))
8099 (js2-must-match js2-LC "msg.no.brace.catchblock")
8100 (setq block (js2-parse-statements)
8101 try-end (js2-node-end block)
8102 catch-node (make-js2-catch-node :pos catch-pos
8103 :param param
8104 :guard-expr catch-cond
8105 :guard-kwd guard-kwd
8106 :block block
8107 :lp lp
8108 :rp rp))
8109 (js2-pop-scope)
8110 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8111 (setq try-end (js2-current-token-beg)))
8112 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8113 (js2-node-len catch-node) (- try-end catch-pos))
8114 (js2-node-add-children catch-node param catch-cond block)
8115 (push catch-node catch-blocks)))
8116 ((/= peek js2-FINALLY)
8117 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8118 (js2-node-pos try-block)
8119 (- (setq try-end (js2-node-end try-block))
8120 (js2-node-pos try-block)))))
8121 (when (js2-match-token js2-FINALLY)
8122 (setq finally-pos (js2-current-token-beg)
8123 block (js2-parse-statement)
8124 try-end (js2-node-end block)
8125 finally-block (make-js2-finally-node :pos finally-pos
8126 :len (- try-end finally-pos)
8127 :body block))
8128 (js2-node-add-children finally-block block))
8129 (setq pn (make-js2-try-node :pos try-pos
8130 :len (- try-end try-pos)
8131 :try-block try-block
8132 :finally-block finally-block))
8133 (js2-node-add-children pn try-block finally-block)
8134 ;; push them onto the try-node, which reverses and corrects their order
8135 (dolist (cb catch-blocks)
8136 (js2-node-add-children pn cb)
8137 (push cb (js2-try-node-catch-clauses pn)))
8138 pn))
8139
8140 (defun js2-parse-throw ()
8141 "Parser for throw-statement. Last matched token must be js2-THROW."
8142 (let ((pos (js2-current-token-beg))
8143 expr pn)
8144 (if (= (js2-peek-token-or-eol) js2-EOL)
8145 ;; ECMAScript does not allow new lines before throw expression,
8146 ;; see bug 256617
8147 (js2-report-error "msg.bad.throw.eol"))
8148 (setq expr (js2-parse-expr)
8149 pn (make-js2-throw-node :pos pos
8150 :len (- (js2-node-end expr) pos)
8151 :expr expr))
8152 (js2-node-add-children pn expr)
8153 pn))
8154
8155 (defun js2-match-jump-label-name (label-name)
8156 "If break/continue specified a label, return that label's labeled stmt.
8157 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8158 does not match an existing label, reports an error and returns nil."
8159 (let ((bundle (cdr (assoc label-name js2-label-set))))
8160 (if (null bundle)
8161 (js2-report-error "msg.undef.label"))
8162 bundle))
8163
8164 (defun js2-parse-break ()
8165 "Parser for break-statement. Last matched token must be js2-BREAK."
8166 (let ((pos (js2-current-token-beg))
8167 (end (js2-current-token-end))
8168 break-target ; statement to break from
8169 break-label ; in "break foo", name-node representing the foo
8170 labels ; matching labeled statement to break to
8171 pn)
8172 (when (eq (js2-peek-token-or-eol) js2-NAME)
8173 (js2-get-token)
8174 (setq break-label (js2-create-name-node)
8175 end (js2-node-end break-label)
8176 ;; matchJumpLabelName only matches if there is one
8177 labels (js2-match-jump-label-name (js2-current-token-string))
8178 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8179 (unless (or break-target break-label)
8180 ;; no break target specified - try for innermost enclosing loop/switch
8181 (if (null js2-loop-and-switch-set)
8182 (unless break-label
8183 (js2-report-error "msg.bad.break" nil pos (length "break")))
8184 (setq break-target (car js2-loop-and-switch-set))))
8185 (setq pn (make-js2-break-node :pos pos
8186 :len (- end pos)
8187 :label break-label
8188 :target break-target))
8189 (js2-node-add-children pn break-label) ; but not break-target
8190 pn))
8191
8192 (defun js2-parse-continue ()
8193 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8194 (let ((pos (js2-current-token-beg))
8195 (end (js2-current-token-end))
8196 label ; optional user-specified label, a `js2-name-node'
8197 labels ; current matching labeled stmt, if any
8198 target ; the `js2-loop-node' target of this continue stmt
8199 pn)
8200 (when (= (js2-peek-token-or-eol) js2-NAME)
8201 (js2-get-token)
8202 (setq label (js2-create-name-node)
8203 end (js2-node-end label)
8204 ;; matchJumpLabelName only matches if there is one
8205 labels (js2-match-jump-label-name (js2-current-token-string))))
8206 (cond
8207 ((null labels) ; no current label to go to
8208 (if (null js2-loop-set) ; no loop to continue to
8209 (js2-report-error "msg.continue.outside" nil pos
8210 (length "continue"))
8211 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8212 (t
8213 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8214 (setq target (js2-labeled-stmt-node-stmt labels))
8215 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8216 (setq pn (make-js2-continue-node :pos pos
8217 :len (- end pos)
8218 :label label
8219 :target target))
8220 (js2-node-add-children pn label) ; but not target - it's not our child
8221 pn))
8222
8223 (defun js2-parse-with ()
8224 "Parser for with-statement. Last matched token must be js2-WITH."
8225 (let ((pos (js2-current-token-beg))
8226 obj body pn lp rp)
8227 (if (js2-must-match js2-LP "msg.no.paren.with")
8228 (setq lp (js2-current-token-beg)))
8229 (setq obj (js2-parse-expr))
8230 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8231 (setq rp (js2-current-token-beg)))
8232 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8233 (setq body (js2-parse-statement)))
8234 (setq pn (make-js2-with-node :pos pos
8235 :len (- (js2-node-end body) pos)
8236 :object obj
8237 :body body
8238 :lp (js2-relpos lp pos)
8239 :rp (js2-relpos rp pos)))
8240 (js2-node-add-children pn obj body)
8241 pn))
8242
8243 (defun js2-parse-const-var ()
8244 "Parser for var- or const-statement.
8245 Last matched token must be js2-CONST or js2-VAR."
8246 (let ((tt (js2-current-token-type))
8247 (pos (js2-current-token-beg))
8248 expr pn)
8249 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8250 pn (make-js2-expr-stmt-node :pos pos
8251 :len (- (js2-node-end expr) pos)
8252 :expr expr))
8253 (js2-node-add-children pn expr)
8254 pn))
8255
8256 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8257 (let ((pn (make-js2-expr-stmt-node :pos pos
8258 :len (js2-node-len expr)
8259 :type (if (js2-inside-function)
8260 js2-EXPR_VOID
8261 js2-EXPR_RESULT)
8262 :expr expr)))
8263 (if add-child
8264 (js2-node-add-children pn expr))
8265 pn))
8266
8267 (defun js2-parse-let-stmt ()
8268 "Parser for let-statement. Last matched token must be js2-LET."
8269 (let ((pos (js2-current-token-beg))
8270 expr pn)
8271 (if (= (js2-peek-token) js2-LP)
8272 ;; let expression in statement context
8273 (setq expr (js2-parse-let pos 'statement)
8274 pn (js2-wrap-with-expr-stmt pos expr t))
8275 ;; else we're looking at a statement like let x=6, y=7;
8276 (setf expr (js2-parse-variables js2-LET pos)
8277 pn (js2-wrap-with-expr-stmt pos expr t)
8278 (js2-node-type pn) js2-EXPR_RESULT))
8279 pn))
8280
8281 (defun js2-parse-ret-yield ()
8282 (js2-parse-return-or-yield (js2-current-token-type) nil))
8283
8284 (defconst js2-parse-return-stmt-enders
8285 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8286
8287 (defsubst js2-now-all-set (before after mask)
8288 "Return whether or not the bits in the mask have changed to all set.
8289 BEFORE is bits before change, AFTER is bits after change, and MASK is
8290 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8291 but not BEFORE."
8292 (and (/= (logand before mask) mask)
8293 (= (logand after mask) mask)))
8294
8295 (defun js2-parse-return-or-yield (tt expr-context)
8296 (let* ((pos (js2-current-token-beg))
8297 (end (js2-current-token-end))
8298 (before js2-end-flags)
8299 (inside-function (js2-inside-function))
8300 (gen-type (and inside-function (js2-function-node-generator-type
8301 js2-current-script-or-fn)))
8302 e ret name yield-star-p)
8303 (unless inside-function
8304 (js2-report-error (if (eq tt js2-RETURN)
8305 "msg.bad.return"
8306 "msg.bad.yield")))
8307 (when (and inside-function
8308 (eq gen-type 'STAR)
8309 (js2-match-token js2-MUL))
8310 (setq yield-star-p t))
8311 ;; This is ugly, but we don't want to require a semicolon.
8312 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8313 (setq e (js2-parse-expr)
8314 end (js2-node-end e)))
8315 (cond
8316 ((eq tt js2-RETURN)
8317 (js2-set-flag js2-end-flags (if (null e)
8318 js2-end-returns
8319 js2-end-returns-value))
8320 (setq ret (make-js2-return-node :pos pos
8321 :len (- end pos)
8322 :retval e))
8323 (js2-node-add-children ret e)
8324 ;; See if we need a strict mode warning.
8325 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8326 ;; more thorough and accurate than this before/after flag check.
8327 ;; E.g. if there's a finally-block that always returns, we shouldn't
8328 ;; show a warning generated by inconsistent returns in the catch blocks.
8329 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8330 ;; so we know which returns/yields to highlight, and we should get rid of
8331 ;; all the checking in `js2-parse-return-or-yield'.
8332 (if (and js2-strict-inconsistent-return-warning
8333 (js2-now-all-set before js2-end-flags
8334 (logior js2-end-returns js2-end-returns-value)))
8335 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8336 ((eq gen-type 'COMPREHENSION)
8337 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8338 ;; like SpiderMonkey does.
8339 (js2-report-error "msg.syntax" nil pos 5))
8340 (t
8341 (setq ret (make-js2-yield-node :pos pos
8342 :len (- end pos)
8343 :value e
8344 :star-p yield-star-p))
8345 (js2-node-add-children ret e)
8346 (unless expr-context
8347 (setq e ret
8348 ret (js2-wrap-with-expr-stmt pos e t))
8349 (js2-set-requires-activation)
8350 (js2-set-is-generator))))
8351 ;; see if we are mixing yields and value returns.
8352 (when (and inside-function
8353 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8354 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8355 'LEGACY))
8356 (setq name (js2-function-name js2-current-script-or-fn))
8357 (if (zerop (length name))
8358 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8359 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8360 ret))
8361
8362 (defun js2-parse-debugger ()
8363 (make-js2-keyword-node :type js2-DEBUGGER))
8364
8365 (defun js2-parse-block ()
8366 "Parser for a curly-delimited statement block.
8367 Last token matched must be `js2-LC'."
8368 (let ((pos (js2-current-token-beg))
8369 (pn (make-js2-scope)))
8370 (js2-push-scope pn)
8371 (unwind-protect
8372 (progn
8373 (js2-parse-statements pn)
8374 (js2-must-match js2-RC "msg.no.brace.block")
8375 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8376 (js2-pop-scope))
8377 pn))
8378
8379 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8380 (defun js2-parse-semi ()
8381 "Parse a statement or handle an error.
8382 Current token type is `js2-SEMI' or `js2-ERROR'."
8383 (let ((tt (js2-current-token-type)) pos len)
8384 (if (eq tt js2-SEMI)
8385 (make-js2-empty-expr-node :len 1)
8386 (setq pos (js2-current-token-beg)
8387 len (- (js2-current-token-end) pos))
8388 (js2-report-error "msg.syntax" nil pos len)
8389 (make-js2-error-node :pos pos :len len))))
8390
8391 (defun js2-parse-default-xml-namespace ()
8392 "Parse a `default xml namespace = <expr>' e4x statement."
8393 (let ((pos (js2-current-token-beg))
8394 end len expr unary)
8395 (js2-must-have-xml)
8396 (js2-set-requires-activation)
8397 (setq len (- js2-ts-cursor pos))
8398 (unless (and (js2-match-token js2-NAME)
8399 (string= (js2-current-token-string) "xml"))
8400 (js2-report-error "msg.bad.namespace" nil pos len))
8401 (unless (and (js2-match-token js2-NAME)
8402 (string= (js2-current-token-string) "namespace"))
8403 (js2-report-error "msg.bad.namespace" nil pos len))
8404 (unless (js2-match-token js2-ASSIGN)
8405 (js2-report-error "msg.bad.namespace" nil pos len))
8406 (setq expr (js2-parse-expr)
8407 end (js2-node-end expr)
8408 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8409 :pos pos
8410 :len (- end pos)
8411 :operand expr))
8412 (js2-node-add-children unary expr)
8413 (make-js2-expr-stmt-node :pos pos
8414 :len (- end pos)
8415 :expr unary)))
8416
8417 (defun js2-record-label (label bundle)
8418 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8419 (js2-get-token)
8420 (let ((name (js2-label-node-name label))
8421 labeled-stmt
8422 dup)
8423 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8424 ;; flag both labels if possible when used in editing mode
8425 (if (and js2-parse-ide-mode
8426 (setq dup (js2-get-label-by-name labeled-stmt name)))
8427 (js2-report-error "msg.dup.label" nil
8428 (js2-node-abs-pos dup) (js2-node-len dup)))
8429 (js2-report-error "msg.dup.label" nil
8430 (js2-node-pos label) (js2-node-len label)))
8431 (js2-labeled-stmt-node-add-label bundle label)
8432 (js2-node-add-children bundle label)
8433 ;; Add one reference to the bundle per label in `js2-label-set'
8434 (push (cons name bundle) js2-label-set)))
8435
8436 (defun js2-parse-name-or-label ()
8437 "Parser for identifier or label. Last token matched must be js2-NAME.
8438 Called when we found a name in a statement context. If it's a label, we gather
8439 up any following labels and the next non-label statement into a
8440 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8441 expression and return it wrapped in a `js2-expr-stmt-node'."
8442 (let ((pos (js2-current-token-beg))
8443 expr stmt bundle
8444 (continue t))
8445 ;; set check for label and call down to `js2-parse-primary-expr'
8446 (setq expr (js2-maybe-parse-label))
8447 (if (null expr)
8448 ;; Parse the non-label expression and wrap with expression stmt.
8449 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8450 ;; else parsed a label
8451 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8452 (js2-record-label expr bundle)
8453 ;; look for more labels
8454 (while (and continue (= (js2-get-token) js2-NAME))
8455 (if (setq expr (js2-maybe-parse-label))
8456 (js2-record-label expr bundle)
8457 (setq expr (js2-parse-expr)
8458 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8459 continue nil)
8460 (js2-auto-insert-semicolon stmt)))
8461 ;; no more labels; now parse the labeled statement
8462 (unwind-protect
8463 (unless stmt
8464 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8465 (js2-unget-token)
8466 (setq stmt (js2-statement-helper))))
8467 ;; remove the labels for this statement from the global set
8468 (dolist (label (js2-labeled-stmt-node-labels bundle))
8469 (setq js2-label-set (remove label js2-label-set))))
8470 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8471 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8472 (js2-node-add-children bundle stmt)
8473 bundle)))
8474
8475 (defun js2-maybe-parse-label ()
8476 (assert (= (js2-current-token-type) js2-NAME))
8477 (let (label-pos
8478 (next-tt (js2-get-token))
8479 (label-end (js2-current-token-end)))
8480 ;; Do not consume colon, it is used as unwind indicator
8481 ;; to return to statementHelper.
8482 (js2-unget-token)
8483 (if (= next-tt js2-COLON)
8484 (prog2
8485 (setq label-pos (js2-current-token-beg))
8486 (make-js2-label-node :pos label-pos
8487 :len (- label-end label-pos)
8488 :name (js2-current-token-string))
8489 (js2-set-face label-pos
8490 label-end
8491 'font-lock-variable-name-face 'record))
8492 ;; Backtrack from the name token, too.
8493 (js2-unget-token)
8494 nil)))
8495
8496 (defun js2-parse-expr-stmt ()
8497 "Default parser in statement context, if no recognized statement found."
8498 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8499 (progn
8500 (js2-unget-token)
8501 (js2-parse-expr)) t))
8502
8503 (defun js2-parse-variables (decl-type pos)
8504 "Parse a comma-separated list of variable declarations.
8505 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8506
8507 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8508 For 'var' or 'const', the keyword should be the token last scanned.
8509
8510 POS is the position where the node should start. It's sometimes the
8511 var/const/let keyword, and other times the beginning of the first token
8512 in the first variable declaration.
8513
8514 Returns the parsed `js2-var-decl-node' expression node."
8515 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8516 :pos pos))
8517 destructuring kid-pos tt init name end nbeg nend vi
8518 (continue t))
8519 ;; Example:
8520 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8521 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8522 ;; var {a, b} = baz;
8523 (while continue
8524 (setq destructuring nil
8525 name nil
8526 tt (js2-get-token)
8527 kid-pos (js2-current-token-beg)
8528 end (js2-current-token-end)
8529 init nil)
8530 (if (or (= tt js2-LB) (= tt js2-LC))
8531 ;; Destructuring assignment, e.g., var [a, b] = ...
8532 (setq destructuring (js2-parse-destruct-primary-expr)
8533 end (js2-node-end destructuring))
8534 ;; Simple variable name
8535 (js2-unget-token)
8536 (when (js2-must-match-name "msg.bad.var")
8537 (setq name (js2-create-name-node)
8538 nbeg (js2-current-token-beg)
8539 nend (js2-current-token-end)
8540 end nend)
8541 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8542 (when (js2-match-token js2-ASSIGN)
8543 (setq init (js2-parse-assign-expr)
8544 end (js2-node-end init))
8545 (js2-record-imenu-functions init name))
8546 (when name
8547 (js2-set-face nbeg nend (if (js2-function-node-p init)
8548 'font-lock-function-name-face
8549 'font-lock-variable-name-face)
8550 'record))
8551 (setq vi (make-js2-var-init-node :pos kid-pos
8552 :len (- end kid-pos)
8553 :type decl-type))
8554 (if destructuring
8555 (progn
8556 (if (and (null init) (not js2-in-for-init))
8557 (js2-report-error "msg.destruct.assign.no.init"))
8558 (js2-define-destruct-symbols destructuring
8559 decl-type
8560 'font-lock-variable-name-face)
8561 (setf (js2-var-init-node-target vi) destructuring))
8562 (setf (js2-var-init-node-target vi) name))
8563 (setf (js2-var-init-node-initializer vi) init)
8564 (js2-node-add-children vi name destructuring init)
8565 (js2-block-node-push result vi)
8566 (unless (js2-match-token js2-COMMA)
8567 (setq continue nil)))
8568 (setf (js2-node-len result) (- end pos))
8569 result))
8570
8571 (defun js2-parse-let (pos &optional stmt-p)
8572 "Parse a let expression or statement.
8573 A let-expression is of the form `let (vars) expr'.
8574 A let-statment is of the form `let (vars) {statements}'.
8575 The third form of let is a variable declaration list, handled
8576 by `js2-parse-variables'."
8577 (let ((pn (make-js2-let-node :pos pos))
8578 beg vars body)
8579 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8580 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8581 (js2-push-scope pn)
8582 (unwind-protect
8583 (progn
8584 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8585 (if (js2-must-match js2-RP "msg.no.paren.let")
8586 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8587 (if (and stmt-p (js2-match-token js2-LC))
8588 ;; let statement
8589 (progn
8590 (setf beg (js2-current-token-beg) ; position stmt at LC
8591 body (js2-parse-statements))
8592 (js2-must-match js2-RC "msg.no.curly.let")
8593 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8594 (js2-node-len pn) (- (js2-current-token-end) pos)
8595 (js2-let-node-body pn) body
8596 (js2-node-type pn) js2-LET))
8597 ;; let expression
8598 (setf body (js2-parse-expr)
8599 (js2-node-len pn) (- (js2-node-end body) pos)
8600 (js2-let-node-body pn) body))
8601 (setf (js2-let-node-vars pn) vars)
8602 (js2-node-add-children pn vars body))
8603 (js2-pop-scope))
8604 pn))
8605
8606 (defun js2-define-new-symbol (decl-type name node &optional scope)
8607 (js2-scope-put-symbol (or scope js2-current-scope)
8608 name
8609 (make-js2-symbol decl-type name node)))
8610
8611 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8612 "Define a symbol in the current scope.
8613 If NODE is non-nil, it is the AST node associated with the symbol."
8614 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8615 (symbol (if defining-scope
8616 (js2-scope-get-symbol defining-scope name)))
8617 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8618 (cond
8619 ((and symbol ; already defined
8620 (or (= sdt js2-CONST) ; old version is const
8621 (= decl-type js2-CONST) ; new version is const
8622 ;; two let-bound vars in this block have same name
8623 (and (= sdt js2-LET)
8624 (eq defining-scope js2-current-scope))))
8625 (js2-report-error
8626 (cond
8627 ((= sdt js2-CONST) "msg.const.redecl")
8628 ((= sdt js2-LET) "msg.let.redecl")
8629 ((= sdt js2-VAR) "msg.var.redecl")
8630 ((= sdt js2-FUNCTION) "msg.function.redecl")
8631 (t "msg.parm.redecl"))
8632 name))
8633 ((= decl-type js2-LET)
8634 (if (and (not ignore-not-in-block)
8635 (or (= (js2-node-type js2-current-scope) js2-IF)
8636 (js2-loop-node-p js2-current-scope)))
8637 (js2-report-error "msg.let.decl.not.in.block")
8638 (js2-define-new-symbol decl-type name node)))
8639 ((or (= decl-type js2-VAR)
8640 (= decl-type js2-CONST)
8641 (= decl-type js2-FUNCTION))
8642 (if symbol
8643 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8644 (js2-add-strict-warning "msg.var.redecl" name)
8645 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8646 (js2-add-strict-warning "msg.var.hides.arg" name)))
8647 (js2-define-new-symbol decl-type name node
8648 js2-current-script-or-fn)))
8649 ((= decl-type js2-LP)
8650 (if symbol
8651 ;; must be duplicate parameter. Second parameter hides the
8652 ;; first, so go ahead and add the second pararameter
8653 (js2-report-warning "msg.dup.parms" name))
8654 (js2-define-new-symbol decl-type name node))
8655 (t (js2-code-bug)))))
8656
8657 (defun js2-parse-paren-expr-or-generator-comp ()
8658 (let ((px-pos (js2-current-token-beg)))
8659 (if (and (>= js2-language-version 200)
8660 (js2-match-token js2-FOR))
8661 (js2-parse-generator-comp px-pos)
8662 (let* ((js2-in-for-init nil)
8663 (expr (js2-parse-expr))
8664 (pn (make-js2-paren-node :pos px-pos
8665 :expr expr
8666 :len (- (js2-current-token-end)
8667 px-pos))))
8668 (js2-node-add-children pn (js2-paren-node-expr pn))
8669 (js2-must-match js2-RP "msg.no.paren")
8670 pn))))
8671
8672 (defun js2-parse-expr (&optional oneshot)
8673 (let* ((pn (js2-parse-assign-expr))
8674 (pos (js2-node-pos pn))
8675 left
8676 right
8677 op-pos)
8678 (while (and (not oneshot)
8679 (js2-match-token js2-COMMA))
8680 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8681 (if (= (js2-peek-token) js2-YIELD)
8682 (js2-report-error "msg.yield.parenthesized"))
8683 (setq right (js2-parse-assign-expr)
8684 left pn
8685 pn (make-js2-infix-node :type js2-COMMA
8686 :pos pos
8687 :len (- js2-ts-cursor pos)
8688 :op-pos op-pos
8689 :left left
8690 :right right))
8691 (js2-node-add-children pn left right))
8692 pn))
8693
8694 (defun js2-parse-assign-expr ()
8695 (let ((tt (js2-get-token))
8696 (pos (js2-current-token-beg))
8697 pn left right op-pos
8698 ts-state recorded-identifiers parsed-errors)
8699 (if (= tt js2-YIELD)
8700 (js2-parse-return-or-yield tt t)
8701 ;; Save the tokenizer state in case we find an arrow function
8702 ;; and have to rewind.
8703 (setq ts-state (make-js2-ts-state)
8704 recorded-identifiers js2-recorded-identifiers
8705 parsed-errors js2-parsed-errors)
8706 ;; not yield - parse assignment expression
8707 (setq pn (js2-parse-cond-expr)
8708 tt (js2-get-token))
8709 (cond
8710 ((and (<= js2-first-assign tt)
8711 (<= tt js2-last-assign))
8712 ;; tt express assignment (=, |=, ^=, ..., %=)
8713 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8714 left pn)
8715 (setq right (js2-parse-assign-expr)
8716 pn (make-js2-assign-node :type tt
8717 :pos pos
8718 :len (- (js2-node-end right) pos)
8719 :op-pos op-pos
8720 :left left
8721 :right right))
8722 (when js2-parse-ide-mode
8723 (js2-highlight-assign-targets pn left right)
8724 (js2-record-imenu-functions right left))
8725 ;; do this last so ide checks above can use absolute positions
8726 (js2-node-add-children pn left right))
8727 ((and (= tt js2-ARROW)
8728 (>= js2-language-version 200))
8729 (js2-ts-seek ts-state)
8730 (setq js2-recorded-identifiers recorded-identifiers
8731 js2-parsed-errors parsed-errors)
8732 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8733 (t
8734 (js2-unget-token)))
8735 pn)))
8736
8737 (defun js2-parse-cond-expr ()
8738 (let ((pos (js2-current-token-beg))
8739 (pn (js2-parse-or-expr))
8740 test-expr
8741 if-true
8742 if-false
8743 q-pos
8744 c-pos)
8745 (when (js2-match-token js2-HOOK)
8746 (setq q-pos (- (js2-current-token-beg) pos)
8747 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8748 (js2-must-match js2-COLON "msg.no.colon.cond")
8749 (setq c-pos (- (js2-current-token-beg) pos)
8750 if-false (js2-parse-assign-expr)
8751 test-expr pn
8752 pn (make-js2-cond-node :pos pos
8753 :len (- (js2-node-end if-false) pos)
8754 :test-expr test-expr
8755 :true-expr if-true
8756 :false-expr if-false
8757 :q-pos q-pos
8758 :c-pos c-pos))
8759 (js2-node-add-children pn test-expr if-true if-false))
8760 pn))
8761
8762 (defun js2-make-binary (type left parser)
8763 "Helper for constructing a binary-operator AST node.
8764 LEFT is the left-side-expression, already parsed, and the
8765 binary operator should have just been matched.
8766 PARSER is a function to call to parse the right operand,
8767 or a `js2-node' struct if it has already been parsed.
8768 FIXME: The latter option is unused?"
8769 (let* ((pos (js2-node-pos left))
8770 (op-pos (- (js2-current-token-beg) pos))
8771 (right (if (js2-node-p parser)
8772 parser
8773 (js2-get-token)
8774 (funcall parser)))
8775 (pn (make-js2-infix-node :type type
8776 :pos pos
8777 :len (- (js2-node-end right) pos)
8778 :op-pos op-pos
8779 :left left
8780 :right right)))
8781 (js2-node-add-children pn left right)
8782 pn))
8783
8784 (defun js2-parse-or-expr ()
8785 (let ((pn (js2-parse-and-expr)))
8786 (when (js2-match-token js2-OR)
8787 (setq pn (js2-make-binary js2-OR
8788 pn
8789 'js2-parse-or-expr)))
8790 pn))
8791
8792 (defun js2-parse-and-expr ()
8793 (let ((pn (js2-parse-bit-or-expr)))
8794 (when (js2-match-token js2-AND)
8795 (setq pn (js2-make-binary js2-AND
8796 pn
8797 'js2-parse-and-expr)))
8798 pn))
8799
8800 (defun js2-parse-bit-or-expr ()
8801 (let ((pn (js2-parse-bit-xor-expr)))
8802 (while (js2-match-token js2-BITOR)
8803 (setq pn (js2-make-binary js2-BITOR
8804 pn
8805 'js2-parse-bit-xor-expr)))
8806 pn))
8807
8808 (defun js2-parse-bit-xor-expr ()
8809 (let ((pn (js2-parse-bit-and-expr)))
8810 (while (js2-match-token js2-BITXOR)
8811 (setq pn (js2-make-binary js2-BITXOR
8812 pn
8813 'js2-parse-bit-and-expr)))
8814 pn))
8815
8816 (defun js2-parse-bit-and-expr ()
8817 (let ((pn (js2-parse-eq-expr)))
8818 (while (js2-match-token js2-BITAND)
8819 (setq pn (js2-make-binary js2-BITAND
8820 pn
8821 'js2-parse-eq-expr)))
8822 pn))
8823
8824 (defconst js2-parse-eq-ops
8825 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8826
8827 (defun js2-parse-eq-expr ()
8828 (let ((pn (js2-parse-rel-expr))
8829 tt)
8830 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8831 (setq pn (js2-make-binary tt
8832 pn
8833 'js2-parse-rel-expr)))
8834 (js2-unget-token)
8835 pn))
8836
8837 (defconst js2-parse-rel-ops
8838 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8839
8840 (defun js2-parse-rel-expr ()
8841 (let ((pn (js2-parse-shift-expr))
8842 (continue t)
8843 tt)
8844 (while continue
8845 (setq tt (js2-get-token))
8846 (cond
8847 ((and js2-in-for-init (= tt js2-IN))
8848 (js2-unget-token)
8849 (setq continue nil))
8850 ((memq tt js2-parse-rel-ops)
8851 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8852 (t
8853 (js2-unget-token)
8854 (setq continue nil))))
8855 pn))
8856
8857 (defconst js2-parse-shift-ops
8858 (list js2-LSH js2-URSH js2-RSH))
8859
8860 (defun js2-parse-shift-expr ()
8861 (let ((pn (js2-parse-add-expr))
8862 tt
8863 (continue t))
8864 (while continue
8865 (setq tt (js2-get-token))
8866 (if (memq tt js2-parse-shift-ops)
8867 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8868 (js2-unget-token)
8869 (setq continue nil)))
8870 pn))
8871
8872 (defun js2-parse-add-expr ()
8873 (let ((pn (js2-parse-mul-expr))
8874 tt
8875 (continue t))
8876 (while continue
8877 (setq tt (js2-get-token))
8878 (if (or (= tt js2-ADD) (= tt js2-SUB))
8879 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8880 (js2-unget-token)
8881 (setq continue nil)))
8882 pn))
8883
8884 (defconst js2-parse-mul-ops
8885 (list js2-MUL js2-DIV js2-MOD))
8886
8887 (defun js2-parse-mul-expr ()
8888 (let ((pn (js2-parse-unary-expr))
8889 tt
8890 (continue t))
8891 (while continue
8892 (setq tt (js2-get-token))
8893 (if (memq tt js2-parse-mul-ops)
8894 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8895 (js2-unget-token)
8896 (setq continue nil)))
8897 pn))
8898
8899 (defun js2-make-unary (type parser &rest args)
8900 "Make a unary node of type TYPE.
8901 PARSER is either a node (for postfix operators) or a function to call
8902 to parse the operand (for prefix operators)."
8903 (let* ((pos (js2-current-token-beg))
8904 (postfix (js2-node-p parser))
8905 (expr (if postfix
8906 parser
8907 (apply parser args)))
8908 end
8909 pn)
8910 (if postfix ; e.g. i++
8911 (setq pos (js2-node-pos expr)
8912 end (js2-current-token-end))
8913 (setq end (js2-node-end expr)))
8914 (setq pn (make-js2-unary-node :type type
8915 :pos pos
8916 :len (- end pos)
8917 :operand expr))
8918 (js2-node-add-children pn expr)
8919 pn))
8920
8921 (defconst js2-incrementable-node-types
8922 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8923 "Node types that can be the operand of a ++ or -- operator.")
8924
8925 (defun js2-check-bad-inc-dec (tt beg end unary)
8926 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8927 js2-incrementable-node-types)
8928 (js2-report-error (if (= tt js2-INC)
8929 "msg.bad.incr"
8930 "msg.bad.decr")
8931 nil beg (- end beg))))
8932
8933 (defun js2-parse-unary-expr ()
8934 (let ((tt (js2-current-token-type))
8935 pn expr beg end)
8936 (cond
8937 ((or (= tt js2-VOID)
8938 (= tt js2-NOT)
8939 (= tt js2-BITNOT)
8940 (= tt js2-TYPEOF))
8941 (js2-get-token)
8942 (js2-make-unary tt 'js2-parse-unary-expr))
8943 ((= tt js2-ADD)
8944 (js2-get-token)
8945 ;; Convert to special POS token in decompiler and parse tree
8946 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8947 ((= tt js2-SUB)
8948 (js2-get-token)
8949 ;; Convert to special NEG token in decompiler and parse tree
8950 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8951 ((or (= tt js2-INC)
8952 (= tt js2-DEC))
8953 (js2-get-token)
8954 (prog1
8955 (setq beg (js2-current-token-beg)
8956 end (js2-current-token-end)
8957 expr (js2-make-unary tt 'js2-parse-member-expr t))
8958 (js2-check-bad-inc-dec tt beg end expr)))
8959 ((= tt js2-DELPROP)
8960 (js2-get-token)
8961 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8962 ((= tt js2-ERROR)
8963 (js2-get-token)
8964 (make-js2-error-node)) ; try to continue
8965 ((and (= tt js2-LT)
8966 js2-compiler-xml-available)
8967 ;; XML stream encountered in expression.
8968 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8969 (t
8970 (setq pn (js2-parse-member-expr t)
8971 ;; Don't look across a newline boundary for a postfix incop.
8972 tt (js2-peek-token-or-eol))
8973 (when (or (= tt js2-INC) (= tt js2-DEC))
8974 (js2-get-token)
8975 (setf expr pn
8976 pn (js2-make-unary tt expr))
8977 (js2-node-set-prop pn 'postfix t)
8978 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8979 pn))))
8980
8981 (defun js2-parse-xml-initializer ()
8982 "Parse an E4X XML initializer.
8983 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8984 Then I'll postprocess the result, depending on whether we're in IDE
8985 mode or codegen mode, and generate the appropriate rewritten AST.
8986 IDE mode uses a rich AST that models the XML structure. Codegen mode
8987 just concatenates everything and makes a new XML or XMLList out of it."
8988 (let ((tt (js2-get-first-xml-token))
8989 pn-xml pn expr kids expr-pos
8990 (continue t)
8991 (first-token t))
8992 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8993 (js2-report-error "msg.syntax"))
8994 (setq pn-xml (make-js2-xml-node))
8995 (while continue
8996 (if first-token
8997 (setq first-token nil)
8998 (setq tt (js2-get-next-xml-token)))
8999 (cond
9000 ;; js2-XML means we found a {expr} in the XML stream.
9001 ;; The token string is the XML up to the left-curly.
9002 ((= tt js2-XML)
9003 (push (make-js2-string-node :pos (js2-current-token-beg)
9004 :len (- js2-ts-cursor (js2-current-token-beg)))
9005 kids)
9006 (js2-must-match js2-LC "msg.syntax")
9007 (setq expr-pos js2-ts-cursor
9008 expr (if (eq (js2-peek-token) js2-RC)
9009 (make-js2-empty-expr-node :pos expr-pos)
9010 (js2-parse-expr)))
9011 (js2-must-match js2-RC "msg.syntax")
9012 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9013 :len (js2-node-len expr)
9014 :expr expr))
9015 (js2-node-add-children pn expr)
9016 (push pn kids))
9017 ;; a js2-XMLEND token means we hit the final close-tag.
9018 ((= tt js2-XMLEND)
9019 (push (make-js2-string-node :pos (js2-current-token-beg)
9020 :len (- js2-ts-cursor (js2-current-token-beg)))
9021 kids)
9022 (dolist (kid (nreverse kids))
9023 (js2-block-node-push pn-xml kid))
9024 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9025 (js2-node-pos pn-xml))
9026 continue nil))
9027 (t
9028 (js2-report-error "msg.syntax")
9029 (setq continue nil))))
9030 pn-xml))
9031
9032
9033 (defun js2-parse-argument-list ()
9034 "Parse an argument list and return it as a Lisp list of nodes.
9035 Returns the list in reverse order. Consumes the right-paren token."
9036 (let (result)
9037 (unless (js2-match-token js2-RP)
9038 (loop do
9039 (let ((tt (js2-get-token)))
9040 (if (= tt js2-YIELD)
9041 (js2-report-error "msg.yield.parenthesized"))
9042 (if (and (= tt js2-TRIPLEDOT)
9043 (>= js2-language-version 200))
9044 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9045 (js2-unget-token)
9046 (push (js2-parse-assign-expr) result)))
9047 while
9048 (js2-match-token js2-COMMA))
9049 (js2-must-match js2-RP "msg.no.paren.arg")
9050 result)))
9051
9052 (defun js2-parse-member-expr (&optional allow-call-syntax)
9053 (let ((tt (js2-current-token-type))
9054 pn pos target args beg end init)
9055 (if (/= tt js2-NEW)
9056 (setq pn (js2-parse-primary-expr))
9057 ;; parse a 'new' expression
9058 (js2-get-token)
9059 (setq pos (js2-current-token-beg)
9060 beg pos
9061 target (js2-parse-member-expr)
9062 end (js2-node-end target)
9063 pn (make-js2-new-node :pos pos
9064 :target target
9065 :len (- end pos)))
9066 (js2-highlight-function-call (js2-current-token))
9067 (js2-node-add-children pn target)
9068 (when (js2-match-token js2-LP)
9069 ;; Add the arguments to pn, if any are supplied.
9070 (setf beg pos ; start of "new" keyword
9071 pos (js2-current-token-beg)
9072 args (nreverse (js2-parse-argument-list))
9073 (js2-new-node-args pn) args
9074 end (js2-current-token-end)
9075 (js2-new-node-lp pn) (- pos beg)
9076 (js2-new-node-rp pn) (- end 1 beg))
9077 (apply #'js2-node-add-children pn args))
9078 (when (and js2-allow-rhino-new-expr-initializer
9079 (js2-match-token js2-LC))
9080 (setf init (js2-parse-object-literal)
9081 end (js2-node-end init)
9082 (js2-new-node-initializer pn) init)
9083 (js2-node-add-children pn init))
9084 (setf (js2-node-len pn) (- end beg))) ; end outer if
9085 (js2-parse-member-expr-tail allow-call-syntax pn)))
9086
9087 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9088 "Parse a chain of property/array accesses or function calls.
9089 Includes parsing for E4X operators like `..' and `.@'.
9090 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9091 Returns an expression tree that includes PN, the parent node."
9092 (let (tt
9093 (continue t))
9094 (while continue
9095 (setq tt (js2-get-token))
9096 (cond
9097 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9098 (setq pn (js2-parse-property-access tt pn)))
9099 ((= tt js2-DOTQUERY)
9100 (setq pn (js2-parse-dot-query pn)))
9101 ((= tt js2-LB)
9102 (setq pn (js2-parse-element-get pn)))
9103 ((= tt js2-LP)
9104 (js2-unget-token)
9105 (if allow-call-syntax
9106 (setq pn (js2-parse-function-call pn))
9107 (setq continue nil)))
9108 (t
9109 (js2-unget-token)
9110 (setq continue nil))))
9111 (if (>= js2-highlight-level 2)
9112 (js2-parse-highlight-member-expr-node pn))
9113 pn))
9114
9115 (defun js2-parse-dot-query (pn)
9116 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9117 Last token parsed must be `js2-DOTQUERY'."
9118 (let ((pos (js2-node-pos pn))
9119 op-pos expr end)
9120 (js2-must-have-xml)
9121 (js2-set-requires-activation)
9122 (setq op-pos (js2-current-token-beg)
9123 expr (js2-parse-expr)
9124 end (js2-node-end expr)
9125 pn (make-js2-xml-dot-query-node :left pn
9126 :pos pos
9127 :op-pos op-pos
9128 :right expr))
9129 (js2-node-add-children pn
9130 (js2-xml-dot-query-node-left pn)
9131 (js2-xml-dot-query-node-right pn))
9132 (if (js2-must-match js2-RP "msg.no.paren")
9133 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9134 end (js2-current-token-end)))
9135 (setf (js2-node-len pn) (- end pos))
9136 pn))
9137
9138 (defun js2-parse-element-get (pn)
9139 "Parse an element-get expression, e.g. foo[bar].
9140 Last token parsed must be `js2-RB'."
9141 (let ((lb (js2-current-token-beg))
9142 (pos (js2-node-pos pn))
9143 rb expr)
9144 (setq expr (js2-parse-expr))
9145 (if (js2-must-match js2-RB "msg.no.bracket.index")
9146 (setq rb (js2-current-token-beg)))
9147 (setq pn (make-js2-elem-get-node :target pn
9148 :pos pos
9149 :element expr
9150 :lb (js2-relpos lb pos)
9151 :rb (js2-relpos rb pos)
9152 :len (- (js2-current-token-end) pos)))
9153 (js2-node-add-children pn
9154 (js2-elem-get-node-target pn)
9155 (js2-elem-get-node-element pn))
9156 pn))
9157
9158 (defun js2-highlight-function-call (token)
9159 (when (eq (js2-token-type token) js2-NAME)
9160 (js2-record-face 'js2-function-call token)))
9161
9162 (defun js2-parse-function-call (pn)
9163 (js2-highlight-function-call (js2-current-token))
9164 (js2-get-token)
9165 (let (args
9166 (pos (js2-node-pos pn)))
9167 (setq pn (make-js2-call-node :pos pos
9168 :target pn
9169 :lp (- (js2-current-token-beg) pos)))
9170 (js2-node-add-children pn (js2-call-node-target pn))
9171 ;; Add the arguments to pn, if any are supplied.
9172 (setf args (nreverse (js2-parse-argument-list))
9173 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9174 (js2-call-node-args pn) args)
9175 (apply #'js2-node-add-children pn args)
9176 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9177 pn))
9178
9179 (defun js2-parse-property-access (tt pn)
9180 "Parse a property access, XML descendants access, or XML attr access."
9181 (let ((member-type-flags 0)
9182 (dot-pos (js2-current-token-beg))
9183 (dot-len (if (= tt js2-DOTDOT) 2 1))
9184 name
9185 ref ; right side of . or .. operator
9186 result)
9187 (when (= tt js2-DOTDOT)
9188 (js2-must-have-xml)
9189 (setq member-type-flags js2-descendants-flag))
9190 (if (not js2-compiler-xml-available)
9191 (progn
9192 (js2-must-match-prop-name "msg.no.name.after.dot")
9193 (setq name (js2-create-name-node t js2-GETPROP)
9194 result (make-js2-prop-get-node :left pn
9195 :pos (js2-current-token-beg)
9196 :right name
9197 :len (js2-current-token-len)))
9198 (js2-node-add-children result pn name)
9199 result)
9200 ;; otherwise look for XML operators
9201 (setf result (if (= tt js2-DOT)
9202 (make-js2-prop-get-node)
9203 (make-js2-infix-node :type js2-DOTDOT))
9204 (js2-node-pos result) (js2-node-pos pn)
9205 (js2-infix-node-op-pos result) dot-pos
9206 (js2-infix-node-left result) pn ; do this after setting position
9207 tt (js2-next-token))
9208 (cond
9209 ;; needed for generator.throw()
9210 ((= tt js2-THROW)
9211 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9212 ;; handles: name, ns::name, ns::*, ns::[expr]
9213 ((js2-valid-prop-name-token tt)
9214 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9215 ;; handles: *, *::name, *::*, *::[expr]
9216 ((= tt js2-MUL)
9217 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9218 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9219 ((= tt js2-XMLATTR)
9220 (setq result (js2-parse-attribute-access)))
9221 (t
9222 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9223 (if ref
9224 (setf (js2-node-len result) (- (js2-node-end ref)
9225 (js2-node-pos result))
9226 (js2-infix-node-right result) ref))
9227 (if (js2-infix-node-p result)
9228 (js2-node-add-children result
9229 (js2-infix-node-left result)
9230 (js2-infix-node-right result)))
9231 result)))
9232
9233 (defun js2-parse-attribute-access ()
9234 "Parse an E4X XML attribute expression.
9235 This includes expressions of the forms:
9236
9237 @attr @ns::attr @ns::*
9238 @* @*::attr @*::*
9239 @[expr] @*::[expr] @ns::[expr]
9240
9241 Called if we peeked an '@' token."
9242 (let ((tt (js2-next-token))
9243 (at-pos (js2-current-token-beg)))
9244 (cond
9245 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9246 ((js2-valid-prop-name-token tt)
9247 (js2-parse-property-name at-pos nil 0))
9248 ;; handles: @*, @*::name, @*::*, @*::[expr]
9249 ((= tt js2-MUL)
9250 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9251 ;; handles @[expr]
9252 ((= tt js2-LB)
9253 (js2-parse-xml-elem-ref at-pos))
9254 (t
9255 (js2-report-error "msg.no.name.after.xmlAttr")
9256 ;; Avoid cascaded errors that happen if we make an error node here.
9257 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9258
9259 (defun js2-parse-property-name (at-pos s member-type-flags)
9260 "Check if :: follows name in which case it becomes qualified name.
9261
9262 AT-POS is a natural number if we just read an '@' token, else nil.
9263 S is the name or string that was matched: an identifier, 'throw' or '*'.
9264 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9265
9266 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9267 operator, or the name is followed by ::. For a plain name, returns a
9268 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9269 (let ((pos (or at-pos (js2-current-token-beg)))
9270 colon-pos
9271 (name (js2-create-name-node t (js2-current-token-type) s))
9272 ns tt pn)
9273 (catch 'return
9274 (when (js2-match-token js2-COLONCOLON)
9275 (setq ns name
9276 colon-pos (js2-current-token-beg)
9277 tt (js2-next-token))
9278 (cond
9279 ;; handles name::name
9280 ((js2-valid-prop-name-token tt)
9281 (setq name (js2-create-name-node)))
9282 ;; handles name::*
9283 ((= tt js2-MUL)
9284 (setq name (js2-create-name-node nil nil "*")))
9285 ;; handles name::[expr]
9286 ((= tt js2-LB)
9287 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9288 (t
9289 (js2-report-error "msg.no.name.after.coloncolon"))))
9290 (if (and (null ns) (zerop member-type-flags))
9291 name
9292 (prog1
9293 (setq pn
9294 (make-js2-xml-prop-ref-node :pos pos
9295 :len (- (js2-node-end name) pos)
9296 :at-pos at-pos
9297 :colon-pos colon-pos
9298 :propname name))
9299 (js2-node-add-children pn name))))))
9300
9301 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9302 "Parse the [expr] portion of an xml element reference.
9303 For instance, @[expr], @*::[expr], or ns::[expr]."
9304 (let* ((lb (js2-current-token-beg))
9305 (pos (or at-pos lb))
9306 rb
9307 (expr (js2-parse-expr))
9308 (end (js2-node-end expr))
9309 pn)
9310 (if (js2-must-match js2-RB "msg.no.bracket.index")
9311 (setq rb (js2-current-token-beg)
9312 end (js2-current-token-end)))
9313 (prog1
9314 (setq pn
9315 (make-js2-xml-elem-ref-node :pos pos
9316 :len (- end pos)
9317 :namespace namespace
9318 :colon-pos colon-pos
9319 :at-pos at-pos
9320 :expr expr
9321 :lb (js2-relpos lb pos)
9322 :rb (js2-relpos rb pos)))
9323 (js2-node-add-children pn namespace expr))))
9324
9325 (defun js2-parse-destruct-primary-expr ()
9326 (let ((js2-is-in-destructuring t))
9327 (js2-parse-primary-expr)))
9328
9329 (defun js2-parse-primary-expr ()
9330 "Parse a literal (leaf) expression of some sort.
9331 Includes complex literals such as functions, object-literals,
9332 array-literals, array comprehensions and regular expressions."
9333 (let (pn ; parent node (usually return value)
9334 tt)
9335 (setq tt (js2-current-token-type))
9336 (cond
9337 ((= tt js2-CLASS)
9338 (js2-parse-class-expr))
9339 ((= tt js2-FUNCTION)
9340 (js2-parse-function-expr))
9341 ((= tt js2-LB)
9342 (js2-parse-array-comp-or-literal))
9343 ((= tt js2-LC)
9344 (js2-parse-object-literal))
9345 ((= tt js2-LET)
9346 (js2-parse-let (js2-current-token-beg)))
9347 ((= tt js2-LP)
9348 (js2-parse-paren-expr-or-generator-comp))
9349 ((= tt js2-XMLATTR)
9350 (js2-must-have-xml)
9351 (js2-parse-attribute-access))
9352 ((= tt js2-NAME)
9353 (js2-parse-name tt))
9354 ((= tt js2-NUMBER)
9355 (make-js2-number-node))
9356 ((or (= tt js2-STRING) (= tt js2-TEMPLATE_STRING))
9357 (prog1
9358 (make-js2-string-node :type tt)
9359 (js2-record-face 'font-lock-string-face)))
9360 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9361 ;; Got / or /= which in this context means a regexp literal
9362 (let ((px-pos (js2-current-token-beg))
9363 (flags (js2-read-regexp tt))
9364 (end (js2-current-token-end)))
9365 (prog1
9366 (make-js2-regexp-node :pos px-pos
9367 :len (- end px-pos)
9368 :value (js2-current-token-string)
9369 :flags flags)
9370 (js2-set-face px-pos end 'font-lock-string-face 'record)
9371 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9372 ((or (= tt js2-NULL)
9373 (= tt js2-THIS)
9374 (= tt js2-SUPER)
9375 (= tt js2-FALSE)
9376 (= tt js2-TRUE))
9377 (make-js2-keyword-node :type tt))
9378 ((= tt js2-RP)
9379 ;; Not valid expression syntax, but this is valid in an arrow
9380 ;; function with no params: () => body.
9381 (if (eq (js2-peek-token) js2-ARROW)
9382 (progn
9383 (js2-unget-token) ; Put back the right paren.
9384 ;; Return whatever, it will hopefully be rewinded and
9385 ;; reparsed when we reach the =>.
9386 (make-js2-keyword-node :type js2-NULL))
9387 (js2-report-error "msg.syntax")
9388 (make-js2-error-node)))
9389 ((= tt js2-TRIPLEDOT)
9390 ;; Likewise, only valid in an arrow function with a rest param.
9391 (if (and (js2-match-token js2-NAME)
9392 (js2-match-token js2-RP)
9393 (eq (js2-peek-token) js2-ARROW))
9394 (progn
9395 (js2-unget-token) ; Put back the right paren.
9396 ;; See the previous case.
9397 (make-js2-keyword-node :type js2-NULL))
9398 (js2-report-error "msg.syntax")
9399 (make-js2-error-node)))
9400 ((= tt js2-RESERVED)
9401 (js2-report-error "msg.reserved.id")
9402 (make-js2-name-node))
9403 ((= tt js2-ERROR)
9404 ;; the scanner or one of its subroutines reported the error.
9405 (make-js2-error-node))
9406 ((= tt js2-EOF)
9407 (let* ((px-pos (point-at-bol))
9408 (len (- js2-ts-cursor px-pos)))
9409 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9410 (make-js2-error-node :pos (1- js2-ts-cursor)))
9411 (t
9412 (js2-report-error "msg.syntax")
9413 (make-js2-error-node)))))
9414
9415 (defun js2-parse-name (_tt)
9416 (let ((name (js2-current-token-string))
9417 node)
9418 (setq node (if js2-compiler-xml-available
9419 (js2-parse-property-name nil name 0)
9420 (js2-create-name-node 'check-activation nil name)))
9421 (if js2-highlight-external-variables
9422 (js2-record-name-node node))
9423 node))
9424
9425 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9426 (js2-add-strict-warning
9427 msg nil
9428 ;; back up from comma to beginning of line or array/objlit
9429 (max (if elems
9430 (js2-node-pos (car elems))
9431 pos)
9432 (save-excursion
9433 (goto-char comma-pos)
9434 (back-to-indentation)
9435 (point)))
9436 comma-pos))
9437
9438 (defun js2-parse-array-comp-or-literal ()
9439 (let ((pos (js2-current-token-beg)))
9440 (if (and (>= js2-language-version 200)
9441 (js2-match-token js2-FOR))
9442 (js2-parse-array-comp pos)
9443 (js2-parse-array-literal pos))))
9444
9445 (defun js2-parse-array-literal (pos)
9446 (let ((after-lb-or-comma t)
9447 after-comma tt elems pn
9448 (continue t))
9449 (unless js2-is-in-destructuring
9450 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9451 (while continue
9452 (setq tt (js2-get-token))
9453 (cond
9454 ;; comma
9455 ((= tt js2-COMMA)
9456 (setq after-comma (js2-current-token-end))
9457 (if (not after-lb-or-comma)
9458 (setq after-lb-or-comma t)
9459 (push nil elems)))
9460 ;; end of array
9461 ((or (= tt js2-RB)
9462 (= tt js2-EOF)) ; prevent infinite loop
9463 (if (= tt js2-EOF)
9464 (js2-report-error "msg.no.bracket.arg" nil pos))
9465 (when (and after-comma (< js2-language-version 170))
9466 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9467 pos (remove nil elems) after-comma))
9468 (setq continue nil
9469 pn (make-js2-array-node :pos pos
9470 :len (- js2-ts-cursor pos)
9471 :elems (nreverse elems)))
9472 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9473 ;; destructuring binding
9474 (js2-is-in-destructuring
9475 (push (if (or (= tt js2-LC)
9476 (= tt js2-LB)
9477 (= tt js2-NAME))
9478 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9479 (js2-parse-destruct-primary-expr)
9480 ;; invalid pattern
9481 (js2-report-error "msg.bad.var")
9482 (make-js2-error-node))
9483 elems)
9484 (setq after-lb-or-comma nil
9485 after-comma nil))
9486 ;; array comp
9487 ((and (>= js2-language-version 170)
9488 (= tt js2-FOR) ; check for array comprehension
9489 (not after-lb-or-comma) ; "for" can't follow a comma
9490 elems ; must have at least 1 element
9491 (not (cdr elems))) ; but no 2nd element
9492 (js2-unget-token)
9493 (setf continue nil
9494 pn (js2-parse-legacy-array-comp (car elems) pos)))
9495 ;; another element
9496 (t
9497 (unless after-lb-or-comma
9498 (js2-report-error "msg.no.bracket.arg"))
9499 (if (and (= tt js2-TRIPLEDOT)
9500 (>= js2-language-version 200))
9501 ;; spread operator
9502 (push (js2-make-unary tt 'js2-parse-assign-expr)
9503 elems)
9504 (js2-unget-token)
9505 (push (js2-parse-assign-expr) elems))
9506 (setq after-lb-or-comma nil
9507 after-comma nil))))
9508 (unless js2-is-in-destructuring
9509 (js2-pop-scope))
9510 pn))
9511
9512 (defun js2-parse-legacy-array-comp (expr pos)
9513 "Parse a legacy array comprehension (JavaScript 1.7).
9514 EXPR is the first expression after the opening left-bracket.
9515 POS is the beginning of the LB token preceding EXPR.
9516 We should have just parsed the 'for' keyword before calling this function."
9517 (let ((current-scope js2-current-scope)
9518 loops first filter result)
9519 (unwind-protect
9520 (progn
9521 (while (js2-match-token js2-FOR)
9522 (let ((loop (make-js2-comp-loop-node)))
9523 (js2-push-scope loop)
9524 (push loop loops)
9525 (js2-parse-comp-loop loop)))
9526 ;; First loop takes expr scope's parent.
9527 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9528 (js2-scope-parent-scope current-scope))
9529 ;; Set expr scope's parent to the last loop.
9530 (setf (js2-scope-parent-scope current-scope) (car loops))
9531 (if (/= (js2-get-token) js2-IF)
9532 (js2-unget-token)
9533 (setq filter (js2-parse-condition))))
9534 (dotimes (_ (1- (length loops)))
9535 (js2-pop-scope)))
9536 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9537 (setq result (make-js2-comp-node :pos pos
9538 :len (- js2-ts-cursor pos)
9539 :result expr
9540 :loops (nreverse loops)
9541 :filters (and filter (list (car filter)))
9542 :form 'LEGACY_ARRAY))
9543 (apply #'js2-node-add-children result expr (car filter)
9544 (js2-comp-node-loops result))
9545 result))
9546
9547 (defun js2-parse-array-comp (pos)
9548 "Parse an ES6 array comprehension.
9549 POS is the beginning of the LB token.
9550 We should have just parsed the 'for' keyword before calling this function."
9551 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9552 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9553 pn))
9554
9555 (defun js2-parse-generator-comp (pos)
9556 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9557 (js2-current-script-or-fn
9558 (make-js2-function-node :generator-type 'COMPREHENSION))
9559 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9560 (js2-must-match js2-RP "msg.no.paren" pos)
9561 pn))
9562
9563 (defun js2-parse-comprehension (pos form)
9564 (let (loops filters expr result)
9565 (unwind-protect
9566 (progn
9567 (js2-unget-token)
9568 (while (js2-match-token js2-FOR)
9569 (let ((loop (make-js2-comp-loop-node)))
9570 (js2-push-scope loop)
9571 (push loop loops)
9572 (js2-parse-comp-loop loop)))
9573 (while (js2-match-token js2-IF)
9574 (push (car (js2-parse-condition)) filters))
9575 (setq expr (js2-parse-assign-expr)))
9576 (dolist (_ loops)
9577 (js2-pop-scope)))
9578 (setq result (make-js2-comp-node :pos pos
9579 :len (- js2-ts-cursor pos)
9580 :result expr
9581 :loops (nreverse loops)
9582 :filters (nreverse filters)
9583 :form form))
9584 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9585 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9586 result))
9587
9588 (defun js2-parse-comp-loop (pn &optional only-of-p)
9589 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9590 The current token should be the initial FOR.
9591 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9592 (let ((pos (js2-comp-loop-node-pos pn))
9593 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9594 (when (and (not only-of-p) (js2-match-token js2-NAME))
9595 (if (string= (js2-current-token-string) "each")
9596 (progn
9597 (setq foreach-p t
9598 each-pos (- (js2-current-token-beg) pos)) ; relative
9599 (js2-record-face 'font-lock-keyword-face))
9600 (js2-report-error "msg.no.paren.for")))
9601 (if (js2-must-match js2-LP "msg.no.paren.for")
9602 (setq lp (- (js2-current-token-beg) pos)))
9603 (setq tt (js2-peek-token))
9604 (cond
9605 ((or (= tt js2-LB)
9606 (= tt js2-LC))
9607 (js2-get-token)
9608 (setq iter (js2-parse-destruct-primary-expr))
9609 (js2-define-destruct-symbols iter js2-LET
9610 'font-lock-variable-name-face t))
9611 ((js2-match-token js2-NAME)
9612 (setq iter (js2-create-name-node)))
9613 (t
9614 (js2-report-error "msg.bad.var")))
9615 ;; Define as a let since we want the scope of the variable to
9616 ;; be restricted to the array comprehension
9617 (if (js2-name-node-p iter)
9618 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9619 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9620 (and (>= js2-language-version 200)
9621 (js2-match-contextual-kwd "of")
9622 (setq forof-p t)))
9623 (setq in-pos (- (js2-current-token-beg) pos))
9624 (js2-report-error "msg.in.after.for.name"))
9625 (setq obj (js2-parse-expr))
9626 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9627 (setq rp (- (js2-current-token-beg) pos)))
9628 (setf (js2-node-pos pn) pos
9629 (js2-node-len pn) (- js2-ts-cursor pos)
9630 (js2-comp-loop-node-iterator pn) iter
9631 (js2-comp-loop-node-object pn) obj
9632 (js2-comp-loop-node-in-pos pn) in-pos
9633 (js2-comp-loop-node-each-pos pn) each-pos
9634 (js2-comp-loop-node-foreach-p pn) foreach-p
9635 (js2-comp-loop-node-forof-p pn) forof-p
9636 (js2-comp-loop-node-lp pn) lp
9637 (js2-comp-loop-node-rp pn) rp)
9638 (js2-node-add-children pn iter obj)
9639 pn))
9640
9641 (defun js2-parse-class-stmt ()
9642 (let ((pos (js2-current-token-beg)))
9643 (js2-must-match-name "msg.unnamed.class.stmt")
9644 (js2-parse-class pos 'CLASS_STATEMENT (js2-create-name-node t))))
9645
9646 (defun js2-parse-class-expr ()
9647 (let ((pos (js2-current-token-beg))
9648 name)
9649 (when (js2-match-token js2-NAME)
9650 (setq name (js2-create-name-node t)))
9651 (js2-parse-class pos 'CLASS_EXPRESSION name)))
9652
9653 (defun js2-parse-class (pos form name)
9654 ;; class X [extends ...] {
9655 (let (pn elems extends)
9656 (when name
9657 (js2-set-face (js2-node-pos name) (js2-node-end name)
9658 'font-lock-function-name-face 'record))
9659 (if (js2-match-token js2-EXTENDS)
9660 (if (= (js2-peek-token) js2-LC)
9661 (js2-report-error "msg.missing.extends")
9662 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
9663 (setq extends (js2-parse-assign-expr))
9664 (if (not extends)
9665 (js2-report-error "msg.bad.extends"))))
9666 (js2-must-match js2-LC "msg.no.brace.class")
9667 (setq elems (js2-parse-object-literal-elems t)
9668 pn (make-js2-class-node :pos pos
9669 :len (- js2-ts-cursor pos)
9670 :form form
9671 :name name
9672 :extends extends
9673 :elems elems))
9674 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
9675 pn))
9676
9677 (defun js2-parse-object-literal ()
9678 (let* ((pos (js2-current-token-beg))
9679 (elems (js2-parse-object-literal-elems))
9680 (result (make-js2-object-node :pos pos
9681 :len (- js2-ts-cursor pos)
9682 :elems elems)))
9683 (apply #'js2-node-add-children result (js2-object-node-elems result))
9684 result))
9685
9686 (defun js2-parse-object-literal-elems (&optional class-p)
9687 (let ((pos (js2-current-token-beg))
9688 (static nil)
9689 (continue t)
9690 tt elems elem after-comma)
9691 (while continue
9692 (setq static (and class-p (js2-match-token js2-STATIC))
9693 tt (js2-get-token)
9694 elem nil)
9695 (cond
9696 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9697 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9698 ;; TODO(sdh): support *foo() {...}
9699 ((or (js2-valid-prop-name-token tt)
9700 (= tt js2-STRING))
9701 (setq after-comma nil
9702 elem (js2-parse-named-prop tt))
9703 (if (and (null elem)
9704 (not js2-recover-from-parse-errors))
9705 (setq continue nil)))
9706 ;; {[Symbol.iterator]: ...}
9707 ((and (= tt js2-LB)
9708 (>= js2-language-version 200))
9709 (let ((expr (js2-parse-expr)))
9710 (js2-must-match js2-RB "msg.missing.computed.rb")
9711 (setq after-comma nil
9712 elem (js2-parse-plain-property expr))))
9713 ;; {12: x} or {10.7: x}
9714 ((= tt js2-NUMBER)
9715 (setq after-comma nil
9716 elem (js2-parse-plain-property (make-js2-number-node))))
9717 ;; Break out of loop, and handle trailing commas.
9718 ((or (= tt js2-RC)
9719 (= tt js2-EOF))
9720 (js2-unget-token)
9721 (setq continue nil)
9722 (if after-comma
9723 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9724 pos elems after-comma)))
9725 (t
9726 (js2-report-error "msg.bad.prop")
9727 (unless js2-recover-from-parse-errors
9728 (setq continue nil)))) ; end switch
9729 ;; Handle static for classes' codegen.
9730 (if static
9731 (if elem (js2-node-set-prop elem 'STATIC t)
9732 (js2-report-error "msg.unexpected.static")))
9733 ;; Handle commas, depending on class-p.
9734 (let ((comma (js2-match-token js2-COMMA)))
9735 (if class-p
9736 (if comma
9737 (js2-report-error "msg.class.unexpected.comma"))
9738 (if comma
9739 (setq after-comma (js2-current-token-end))
9740 (setq continue nil))))
9741 ;; Append any parsed element.
9742 (if elem (push elem elems))) ; end loop
9743 (js2-must-match js2-RC "msg.no.brace.prop")
9744 (nreverse elems)))
9745
9746 (defun js2-parse-named-prop (tt)
9747 "Parse a name, string, or getter/setter object property.
9748 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9749 (let ((string-prop (and (= tt js2-STRING)
9750 (make-js2-string-node)))
9751 expr
9752 (ppos (js2-current-token-beg))
9753 (pend (js2-current-token-end))
9754 (name (js2-create-name-node))
9755 (prop (js2-current-token-string)))
9756 (cond
9757 ;; getter/setter prop
9758 ((and (= tt js2-NAME)
9759 (= (js2-peek-token) js2-NAME)
9760 (or (string= prop "get")
9761 (string= prop "set")))
9762 (js2-get-token)
9763 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9764 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9765 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9766 (js2-parse-getter-setter-prop ppos name prop))
9767 ;; method definition: {f() {...}}
9768 ((and (= (js2-peek-token) js2-LP)
9769 (>= js2-language-version 200))
9770 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9771 (js2-parse-getter-setter-prop ppos name ""))
9772 ;; regular prop
9773 (t
9774 (prog1
9775 (setq expr (js2-parse-plain-property (or string-prop name)))
9776 (when (and (not string-prop)
9777 (not js2-is-in-destructuring)
9778 js2-highlight-external-variables
9779 (js2-node-get-prop expr 'SHORTHAND))
9780 (js2-record-name-node name))
9781 (js2-set-face ppos pend
9782 (if (js2-function-node-p
9783 (js2-object-prop-node-right expr))
9784 'font-lock-function-name-face
9785 'font-lock-variable-name-face)
9786 'record))))))
9787
9788 (defun js2-parse-plain-property (prop)
9789 "Parse a non-getter/setter property in an object literal.
9790 PROP is the node representing the property: a number, name or string."
9791 (let* ((tt (js2-get-token))
9792 (pos (js2-node-pos prop))
9793 colon expr result)
9794 (cond
9795 ;; Abbreviated property, as in {foo, bar}
9796 ((and (>= js2-language-version 200)
9797 (or (= tt js2-COMMA)
9798 (= tt js2-RC))
9799 (not (js2-number-node-p prop)))
9800 (js2-unget-token)
9801 (setq result (make-js2-object-prop-node
9802 :pos pos
9803 :left prop
9804 :right prop
9805 :op-pos (js2-current-token-len)))
9806 (js2-node-add-children result prop)
9807 (js2-node-set-prop result 'SHORTHAND t)
9808 result)
9809 ;; Normal property
9810 (t
9811 (if (= tt js2-COLON)
9812 (setq colon (- (js2-current-token-beg) pos)
9813 expr (js2-parse-assign-expr))
9814 (js2-report-error "msg.no.colon.prop")
9815 (setq expr (make-js2-error-node)))
9816 (setq result (make-js2-object-prop-node
9817 :pos pos
9818 ;; don't include last consumed token in length
9819 :len (- (+ (js2-node-pos expr)
9820 (js2-node-len expr))
9821 pos)
9822 :left prop
9823 :right expr
9824 :op-pos colon))
9825 (js2-node-add-children result prop expr)
9826 result))))
9827
9828 (defun js2-parse-getter-setter-prop (pos prop type-string)
9829 "Parse getter or setter property in an object literal.
9830 JavaScript syntax is:
9831
9832 { get foo() {...}, set foo(x) {...} }
9833
9834 and expression closure style is also supported
9835
9836 { get foo() x, set foo(x) _x = x }
9837
9838 POS is the start position of the `get' or `set' keyword.
9839 PROP is the `js2-name-node' representing the property name.
9840 GET-P is non-nil if the keyword was `get'."
9841 (let ((type (cond
9842 ((string= "get" type-string) js2-GET)
9843 ((string= "set" type-string) js2-SET)
9844 (t js2-FUNCTION)))
9845 result end
9846 (fn (js2-parse-function-expr)))
9847 ;; it has to be an anonymous function, as we already parsed the name
9848 (if (/= (js2-node-type fn) js2-FUNCTION)
9849 (js2-report-error "msg.bad.prop")
9850 (if (plusp (length (js2-function-name fn)))
9851 (js2-report-error "msg.bad.prop")))
9852 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9853 (setq end (js2-node-end fn)
9854 result (make-js2-getter-setter-node :type type
9855 :pos pos
9856 :len (- end pos)
9857 :left prop
9858 :right fn))
9859 (js2-node-add-children result prop fn)
9860 result))
9861
9862 (defun js2-create-name-node (&optional check-activation-p token string)
9863 "Create a name node using the current token and, optionally, STRING.
9864 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9865 (let* ((beg (js2-current-token-beg))
9866 (tt (js2-current-token-type))
9867 (s (or string
9868 (if (= js2-NAME tt)
9869 (js2-current-token-string)
9870 (js2-tt-name tt))))
9871 name)
9872 (setq name (make-js2-name-node :pos beg
9873 :name s
9874 :len (length s)))
9875 (if check-activation-p
9876 (js2-check-activation-name s (or token js2-NAME)))
9877 name))
9878
9879 ;;; Indentation support
9880
9881 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9882 ;; Karl cleverly deduces that the desired indentation level is often a
9883 ;; function of paren/bracket/brace nesting depth, which can be determined
9884 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9885 ;; then does some equally clever checks to see if we're in the context of a
9886 ;; substatement of a possibly braceless statement keyword such as if, while,
9887 ;; or finally. This approach yields pretty good results.
9888
9889 ;; The indenter is often "wrong", however, and needs to be overridden.
9890 ;; The right long-term solution is probably to emulate (or integrate
9891 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9892 ;; parse tree from `js2-parse' is present, which is not true at the
9893 ;; moment the user is typing, computing indentation is still thousands
9894 ;; of lines of code to handle every possible syntactic edge case.
9895
9896 ;; In the meantime, the compromise solution is that we offer a "bounce
9897 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9898 ;; current line indent among various likely guess points. This approach
9899 ;; is far from perfect, but should at least make it slightly easier to
9900 ;; move the line towards its desired indentation when manually
9901 ;; overriding Karl's heuristic nesting guesser.
9902
9903 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9904 ;; extensions such as `let' and Array comprehensions. Major kudos to
9905 ;; Karl for coming up with the initial approach, which packs a lot of
9906 ;; punch for so little code.
9907
9908 (defconst js2-possibly-braceless-keywords-re
9909 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9910 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9911 "try" "while" "with" "let")))
9912 "Regular expression matching keywords that are optionally
9913 followed by an opening brace.")
9914
9915 (defconst js2-indent-operator-re
9916 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9917 (regexp-opt '("in" "instanceof") 'words))
9918 "Regular expression matching operators that affect indentation
9919 of continued expressions.")
9920
9921 (defconst js2-declaration-keyword-re
9922 (regexp-opt '("var" "let" "const") 'words)
9923 "Regular expression matching variable declaration keywords.")
9924
9925 (defun js2-re-search-forward-inner (regexp &optional bound count)
9926 "Auxiliary function for `js2-re-search-forward'."
9927 (let (parse saved-point)
9928 (while (> count 0)
9929 (re-search-forward regexp bound)
9930 (setq parse (if saved-point
9931 (parse-partial-sexp saved-point (point))
9932 (syntax-ppss (point))))
9933 (cond ((nth 3 parse)
9934 (re-search-forward
9935 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9936 (save-excursion (end-of-line) (point)) t))
9937 ((nth 7 parse)
9938 (forward-line))
9939 ((or (nth 4 parse)
9940 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9941 (re-search-forward "\\*/"))
9942 (t
9943 (setq count (1- count))))
9944 (setq saved-point (point))))
9945 (point))
9946
9947 (defun js2-re-search-forward (regexp &optional bound noerror count)
9948 "Search forward but ignore strings and comments.
9949 Invokes `re-search-forward' but treats the buffer as if strings
9950 and comments have been removed."
9951 (let ((saved-point (point)))
9952 (condition-case err
9953 (cond ((null count)
9954 (js2-re-search-forward-inner regexp bound 1))
9955 ((< count 0)
9956 (js2-re-search-backward-inner regexp bound (- count)))
9957 ((> count 0)
9958 (js2-re-search-forward-inner regexp bound count)))
9959 (search-failed
9960 (goto-char saved-point)
9961 (unless noerror
9962 (error (error-message-string err)))))))
9963
9964 (defun js2-re-search-backward-inner (regexp &optional bound count)
9965 "Auxiliary function for `js2-re-search-backward'."
9966 (let (parse)
9967 (while (> count 0)
9968 (re-search-backward regexp bound)
9969 (setq parse (syntax-ppss (point)))
9970 (cond ((nth 3 parse)
9971 (re-search-backward
9972 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9973 (line-beginning-position) t))
9974 ((nth 7 parse)
9975 (goto-char (nth 8 parse)))
9976 ((or (nth 4 parse)
9977 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9978 (re-search-backward "/\\*"))
9979 (t
9980 (setq count (1- count))))))
9981 (point))
9982
9983 (defun js2-re-search-backward (regexp &optional bound noerror count)
9984 "Search backward but ignore strings and comments.
9985 Invokes `re-search-backward' but treats the buffer as if strings
9986 and comments have been removed."
9987 (let ((saved-point (point)))
9988 (condition-case err
9989 (cond ((null count)
9990 (js2-re-search-backward-inner regexp bound 1))
9991 ((< count 0)
9992 (js2-re-search-forward-inner regexp bound (- count)))
9993 ((> count 0)
9994 (js2-re-search-backward-inner regexp bound count)))
9995 (search-failed
9996 (goto-char saved-point)
9997 (unless noerror
9998 (error (error-message-string err)))))))
9999
10000 (defun js2-looking-at-operator-p ()
10001 "Return non-nil if text after point is a non-comma operator."
10002 (and (looking-at js2-indent-operator-re)
10003 (or (not (looking-at ":"))
10004 (save-excursion
10005 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10006 (looking-at "?"))))))
10007
10008 (defun js2-continued-expression-p ()
10009 "Return non-nil if the current line continues an expression."
10010 (save-excursion
10011 (back-to-indentation)
10012 (or (js2-looking-at-operator-p)
10013 (when (catch 'found
10014 (while (and (re-search-backward "\n" nil t)
10015 (let ((state (syntax-ppss)))
10016 (when (nth 4 state)
10017 (goto-char (nth 8 state))) ;; skip comments
10018 (skip-chars-backward " \t")
10019 (if (bolp)
10020 t
10021 (throw 'found t))))))
10022 (backward-char)
10023 (when (js2-looking-at-operator-p)
10024 (backward-char)
10025 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10026
10027 (defun js2-end-of-do-while-loop-p ()
10028 "Return non-nil if word after point is `while' of a do-while
10029 statement, else returns nil. A braceless do-while statement
10030 spanning several lines requires that the start of the loop is
10031 indented to the same column as the current line."
10032 (interactive)
10033 (save-excursion
10034 (when (looking-at "\\s-*\\<while\\>")
10035 (if (save-excursion
10036 (skip-chars-backward "[ \t\n]*}")
10037 (looking-at "[ \t\n]*}"))
10038 (save-excursion
10039 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10040 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10041 (or (looking-at "\\<do\\>")
10042 (let ((saved-indent (current-indentation)))
10043 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10044 (/= (current-indentation) saved-indent)))
10045 (and (looking-at "[ \t]*\\<do\\>")
10046 (not (js2-re-search-forward
10047 "\\<while\\>" (point-at-eol) t))
10048 (= (current-indentation) saved-indent))))))))
10049
10050 (defun js2-multiline-decl-indentation ()
10051 "Return the declaration indentation column if the current line belongs
10052 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10053 (let (forward-sexp-function ; use Lisp version
10054 at-opening-bracket)
10055 (save-excursion
10056 (back-to-indentation)
10057 (when (not (looking-at js2-declaration-keyword-re))
10058 (when (looking-at js2-indent-operator-re)
10059 (goto-char (match-end 0))) ; continued expressions are ok
10060 (while (and (not at-opening-bracket)
10061 (not (bobp))
10062 (let ((pos (point)))
10063 (save-excursion
10064 (js2-backward-sws)
10065 (or (eq (char-before) ?,)
10066 (and (not (eq (char-before) ?\;))
10067 (prog2 (skip-syntax-backward ".")
10068 (looking-at js2-indent-operator-re)
10069 (js2-backward-sws))
10070 (not (eq (char-before) ?\;)))
10071 (js2-same-line pos)))))
10072 (condition-case _
10073 (backward-sexp)
10074 (scan-error (setq at-opening-bracket t))))
10075 (when (looking-at js2-declaration-keyword-re)
10076 (goto-char (match-end 0))
10077 (1+ (current-column)))))))
10078
10079 (defun js2-ctrl-statement-indentation ()
10080 "Return the proper indentation of current line if it is a control statement.
10081 Returns an indentation if this line starts the body of a control
10082 statement without braces, else returns nil."
10083 (let (forward-sexp-function)
10084 (save-excursion
10085 (back-to-indentation)
10086 (when (and (not (js2-same-line (point-min)))
10087 (not (looking-at "{"))
10088 (js2-re-search-backward "[[:graph:]]" nil t)
10089 (not (looking-at "[{([]"))
10090 (progn
10091 (forward-char)
10092 (when (= (char-before) ?\))
10093 ;; scan-sexps sometimes throws an error
10094 (ignore-errors (backward-sexp))
10095 (skip-chars-backward " \t" (point-at-bol)))
10096 (let ((pt (point)))
10097 (back-to-indentation)
10098 (when (looking-at "}[ \t]*")
10099 (goto-char (match-end 0)))
10100 (and (looking-at js2-possibly-braceless-keywords-re)
10101 (= (match-end 0) pt)
10102 (not (js2-end-of-do-while-loop-p))))))
10103 (+ (current-indentation) js2-basic-offset)))))
10104
10105 (defun js2-indent-in-array-comp (parse-status)
10106 "Return non-nil if we think we're in an array comprehension.
10107 In particular, return the buffer position of the first `for' kwd."
10108 (let ((bracket (nth 1 parse-status))
10109 (end (point)))
10110 (when bracket
10111 (save-excursion
10112 (goto-char bracket)
10113 (when (looking-at "\\[")
10114 (forward-char 1)
10115 (js2-forward-sws)
10116 (if (looking-at "[[{]")
10117 (let (forward-sexp-function) ; use Lisp version
10118 (forward-sexp) ; skip destructuring form
10119 (js2-forward-sws)
10120 (if (and (/= (char-after) ?,) ; regular array
10121 (looking-at "for"))
10122 (match-beginning 0)))
10123 ;; to skip arbitrary expressions we need the parser,
10124 ;; so we'll just guess at it.
10125 (if (and (> end (point)) ; not empty literal
10126 (re-search-forward "[^,]]* \\(for\\) " end t)
10127 ;; not inside comment or string literal
10128 (let ((state (parse-partial-sexp bracket (point))))
10129 (not (or (nth 3 state) (nth 4 state)))))
10130 (match-beginning 1))))))))
10131
10132 (defun js2-array-comp-indentation (parse-status for-kwd)
10133 (if (js2-same-line for-kwd)
10134 ;; first continuation line
10135 (save-excursion
10136 (goto-char (nth 1 parse-status))
10137 (forward-char 1)
10138 (skip-chars-forward " \t")
10139 (current-column))
10140 (save-excursion
10141 (goto-char for-kwd)
10142 (current-column))))
10143
10144 (defun js2-proper-indentation (parse-status)
10145 "Return the proper indentation for the current line."
10146 (save-excursion
10147 (back-to-indentation)
10148 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10149 (at-closing-bracket (looking-at "[]})]"))
10150 (same-indent-p (or at-closing-bracket
10151 (looking-at "\\<case\\>[^:]")
10152 (and (looking-at "\\<default:")
10153 (save-excursion
10154 (js2-backward-sws)
10155 (not (memq (char-before) '(?, ?{)))))))
10156 (continued-expr-p (js2-continued-expression-p))
10157 (declaration-indent (and js2-pretty-multiline-declarations
10158 (js2-multiline-decl-indentation)))
10159 (bracket (nth 1 parse-status))
10160 beg indent)
10161 (cond
10162 ;; indent array comprehension continuation lines specially
10163 ((and bracket
10164 (>= js2-language-version 170)
10165 (not (js2-same-line bracket))
10166 (setq beg (js2-indent-in-array-comp parse-status))
10167 (>= (point) (save-excursion
10168 (goto-char beg)
10169 (point-at-bol)))) ; at or after first loop?
10170 (js2-array-comp-indentation parse-status beg))
10171
10172 (ctrl-stmt-indent)
10173
10174 ((and declaration-indent continued-expr-p)
10175 (+ declaration-indent js2-basic-offset))
10176
10177 (declaration-indent)
10178
10179 (bracket
10180 (goto-char bracket)
10181 (cond
10182 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10183 (when (save-excursion (skip-chars-backward " \t)")
10184 (looking-at ")"))
10185 (backward-list))
10186 (back-to-indentation)
10187 (and (eq js2-pretty-multiline-declarations 'all)
10188 (looking-at js2-declaration-keyword-re)
10189 (goto-char (1+ (match-end 0))))
10190 (setq indent
10191 (cond (same-indent-p
10192 (current-column))
10193 (continued-expr-p
10194 (+ (current-column) (* 2 js2-basic-offset)))
10195 (t
10196 (+ (current-column) js2-basic-offset))))
10197 (if (and js2-indent-switch-body
10198 (not at-closing-bracket)
10199 (looking-at "\\_<switch\\_>"))
10200 (+ indent js2-basic-offset)
10201 indent))
10202 (t
10203 (unless same-indent-p
10204 (forward-char)
10205 (skip-chars-forward " \t"))
10206 (current-column))))
10207
10208 (continued-expr-p js2-basic-offset)
10209
10210 (t 0)))))
10211
10212 (defun js2-lineup-comment (parse-status)
10213 "Indent a multi-line block comment continuation line."
10214 (let* ((beg (nth 8 parse-status))
10215 (first-line (js2-same-line beg))
10216 (offset (save-excursion
10217 (goto-char beg)
10218 (if (looking-at "/\\*")
10219 (+ 1 (current-column))
10220 0))))
10221 (unless first-line
10222 (indent-line-to offset))))
10223
10224 (defun js2-backward-sws ()
10225 "Move backward through whitespace and comments."
10226 (interactive)
10227 (while (forward-comment -1)))
10228
10229 (defun js2-forward-sws ()
10230 "Move forward through whitespace and comments."
10231 (interactive)
10232 (while (forward-comment 1)))
10233
10234 (defun js2-current-indent (&optional pos)
10235 "Return column of indentation on current line.
10236 If POS is non-nil, go to that point and return indentation for that line."
10237 (save-excursion
10238 (if pos
10239 (goto-char pos))
10240 (back-to-indentation)
10241 (current-column)))
10242
10243 (defun js2-arglist-close ()
10244 "Return non-nil if we're on a line beginning with a close-paren/brace."
10245 (save-excursion
10246 (goto-char (point-at-bol))
10247 (js2-forward-sws)
10248 (looking-at "[])}]")))
10249
10250 (defun js2-indent-looks-like-label-p ()
10251 (goto-char (point-at-bol))
10252 (js2-forward-sws)
10253 (looking-at (concat js2-mode-identifier-re ":")))
10254
10255 (defun js2-indent-in-objlit-p (parse-status)
10256 "Return non-nil if this looks like an object-literal entry."
10257 (let ((start (nth 1 parse-status)))
10258 (and
10259 start
10260 (save-excursion
10261 (and (zerop (forward-line -1))
10262 (not (< (point) start)) ; crossed a {} boundary
10263 (js2-indent-looks-like-label-p)))
10264 (save-excursion
10265 (js2-indent-looks-like-label-p)))))
10266
10267 ;; If prev line looks like foobar({ then we're passing an object
10268 ;; literal to a function call, and people pretty much always want to
10269 ;; de-dent back to the previous line, so move the 'basic-offset'
10270 ;; position to the front.
10271 (defun js2-indent-objlit-arg-p (parse-status)
10272 (save-excursion
10273 (back-to-indentation)
10274 (js2-backward-sws)
10275 (and (eq (1- (point)) (nth 1 parse-status))
10276 (eq (char-before) ?{)
10277 (progn
10278 (forward-char -1)
10279 (skip-chars-backward " \t")
10280 (eq (char-before) ?\()))))
10281
10282 (defun js2-indent-case-block-p ()
10283 (save-excursion
10284 (back-to-indentation)
10285 (js2-backward-sws)
10286 (goto-char (point-at-bol))
10287 (skip-chars-forward " \t")
10288 (looking-at "case\\s-.+:")))
10289
10290 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10291 "Cycle among alternate computed indentation positions.
10292 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10293 of the buffer to the current point. NORMAL-COL is the indentation
10294 column computed by the heuristic guesser based on current paren,
10295 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10296 in reverse."
10297 (let ((cur-indent (js2-current-indent))
10298 (old-buffer-undo-list buffer-undo-list)
10299 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10300 (current-line (save-excursion
10301 (forward-line 0) ; move to bol
10302 (1+ (count-lines (point-min) (point)))))
10303 positions pos main-pos anchor arglist-cont same-indent
10304 basic-offset computed-pos)
10305 ;; temporarily don't record undo info, if user requested this
10306 (when js2-mode-indent-inhibit-undo
10307 (setq buffer-undo-list t))
10308 (unwind-protect
10309 (progn
10310 ;; First likely point: indent from beginning of previous code line
10311 (push (setq basic-offset
10312 (+ (save-excursion
10313 (back-to-indentation)
10314 (js2-backward-sws)
10315 (back-to-indentation)
10316 (current-column))
10317 js2-basic-offset))
10318 positions)
10319
10320 ;; (First + epsilon) likely point: indent 2x from beginning of
10321 ;; previous code line. Google does it this way.
10322 (push (setq basic-offset
10323 (+ (save-excursion
10324 (back-to-indentation)
10325 (js2-backward-sws)
10326 (back-to-indentation)
10327 (current-column))
10328 (* 2 js2-basic-offset)))
10329 positions)
10330
10331 ;; Second likely point: indent from assign-expr RHS. This
10332 ;; is just a crude guess based on finding " = " on the previous
10333 ;; line containing actual code.
10334 (setq pos (save-excursion
10335 (forward-line -1)
10336 (goto-char (point-at-bol))
10337 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10338 (point-at-eol) t)
10339 (goto-char (match-end 1))
10340 (skip-chars-forward " \t\r\n")
10341 (current-column))))
10342 (when pos
10343 (incf pos js2-basic-offset)
10344 (push pos positions))
10345
10346 ;; Third likely point: same indent as previous line of code.
10347 ;; Make it the first likely point if we're not on an
10348 ;; arglist-close line and previous line ends in a comma, or
10349 ;; both this line and prev line look like object-literal
10350 ;; elements.
10351 (setq pos (save-excursion
10352 (goto-char (point-at-bol))
10353 (js2-backward-sws)
10354 (back-to-indentation)
10355 (prog1
10356 (current-column)
10357 ;; while we're here, look for trailing comma
10358 (if (save-excursion
10359 (goto-char (point-at-eol))
10360 (js2-backward-sws)
10361 (eq (char-before) ?,))
10362 (setq arglist-cont (1- (point)))))))
10363 (when pos
10364 (if (and (or arglist-cont
10365 (js2-indent-in-objlit-p parse-status))
10366 (not (js2-arglist-close)))
10367 (setq same-indent pos))
10368 (push pos positions))
10369
10370 ;; Fourth likely point: first preceding code with less indentation.
10371 ;; than the immediately preceding code line.
10372 (setq pos (save-excursion
10373 (back-to-indentation)
10374 (js2-backward-sws)
10375 (back-to-indentation)
10376 (setq anchor (current-column))
10377 (while (and (zerop (forward-line -1))
10378 (>= (progn
10379 (back-to-indentation)
10380 (current-column))
10381 anchor)))
10382 (setq pos (current-column))))
10383 (push pos positions)
10384
10385 ;; nesting-heuristic position, main by default
10386 (push (setq main-pos normal-col) positions)
10387
10388 ;; delete duplicates and sort positions list
10389 (setq positions (sort (delete-dups positions) '<))
10390
10391 ;; comma-list continuation lines: prev line indent takes precedence
10392 (if same-indent
10393 (setq main-pos same-indent))
10394
10395 ;; common special cases where we want to indent in from previous line
10396 (if (or (js2-indent-case-block-p)
10397 (js2-indent-objlit-arg-p parse-status))
10398 (setq main-pos basic-offset))
10399
10400 ;; if bouncing backwards, reverse positions list
10401 (if backwards
10402 (setq positions (reverse positions)))
10403
10404 ;; record whether we're already sitting on one of the alternatives
10405 (setq pos (member cur-indent positions))
10406
10407 (cond
10408 ;; case 0: we're one one of the alternatives and this is the
10409 ;; first time they've pressed TAB on this line (best-guess).
10410 ((and js2-mode-indent-ignore-first-tab
10411 pos
10412 ;; first time pressing TAB on this line?
10413 (not (eq js2-mode-last-indented-line current-line)))
10414 ;; do nothing
10415 (setq computed-pos nil))
10416 ;; case 1: only one computed position => use it
10417 ((null (cdr positions))
10418 (setq computed-pos 0))
10419 ;; case 2: not on any of the computed spots => use main spot
10420 ((not pos)
10421 (setq computed-pos (js2-position main-pos positions)))
10422 ;; case 3: on last position: cycle to first position
10423 ((null (cdr pos))
10424 (setq computed-pos 0))
10425 ;; case 4: on intermediate position: cycle to next position
10426 (t
10427 (setq computed-pos (js2-position (second pos) positions))))
10428
10429 ;; see if any hooks want to indent; otherwise we do it
10430 (loop with result = nil
10431 for hook in js2-indent-hook
10432 while (null result)
10433 do
10434 (setq result (funcall hook positions computed-pos))
10435 finally do
10436 (unless (or result (null computed-pos))
10437 (indent-line-to (nth computed-pos positions)))))
10438
10439 ;; finally
10440 (if js2-mode-indent-inhibit-undo
10441 (setq buffer-undo-list old-buffer-undo-list))
10442 ;; see commentary for `js2-mode-last-indented-line'
10443 (setq js2-mode-last-indented-line current-line))))
10444
10445 (defun js2-indent-bounce-backwards ()
10446 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10447 cycles between the computed indentation positions in reverse order."
10448 (interactive)
10449 (js2-indent-line t))
10450
10451 (defun js2-1-line-comment-continuation-p ()
10452 "Return t if we're in a 1-line comment continuation.
10453 If so, we don't ever want to use bounce-indent."
10454 (save-excursion
10455 (and (progn
10456 (forward-line 0)
10457 (looking-at "\\s-*//"))
10458 (progn
10459 (forward-line -1)
10460 (forward-line 0)
10461 (when (looking-at "\\s-*$")
10462 (js2-backward-sws)
10463 (forward-line 0))
10464 (looking-at "\\s-*//")))))
10465
10466 (defun js2-indent-line (&optional bounce-backwards)
10467 "Indent the current line as JavaScript source text."
10468 (interactive)
10469 (let (parse-status offset indent-col
10470 ;; Don't whine about errors/warnings when we're indenting.
10471 ;; This has to be set before calling parse-partial-sexp below.
10472 (inhibit-point-motion-hooks t))
10473 (setq parse-status (save-excursion
10474 (syntax-ppss (point-at-bol)))
10475 offset (- (point) (save-excursion
10476 (back-to-indentation)
10477 (point))))
10478 (js2-with-underscore-as-word-syntax
10479 (if (nth 4 parse-status)
10480 (js2-lineup-comment parse-status)
10481 (setq indent-col (js2-proper-indentation parse-status))
10482 ;; See comments below about `js2-mode-last-indented-line'.
10483 (cond
10484 ;; bounce-indenting is disabled during electric-key indent.
10485 ;; It doesn't work well on first line of buffer.
10486 ((and js2-bounce-indent-p
10487 (not (js2-same-line (point-min)))
10488 (not (js2-1-line-comment-continuation-p)))
10489 (js2-bounce-indent indent-col parse-status bounce-backwards))
10490 ;; just indent to the guesser's likely spot
10491 (t (indent-line-to indent-col))))
10492 (when (plusp offset)
10493 (forward-char offset)))))
10494
10495 (defun js2-indent-region (start end)
10496 "Indent the region, but don't use bounce indenting."
10497 (let ((js2-bounce-indent-p nil)
10498 (indent-region-function nil)
10499 (after-change-functions (remq 'js2-mode-edit
10500 after-change-functions)))
10501 (indent-region start end nil) ; nil for byte-compiler
10502 (js2-mode-edit start end (- end start))))
10503
10504 (defvar js2-minor-mode-map
10505 (let ((map (make-sparse-keymap)))
10506 (define-key map (kbd "C-c C-`") #'js2-next-error)
10507 (define-key map [mouse-1] #'js2-mode-show-node)
10508 map)
10509 "Keymap used when `js2-minor-mode' is active.")
10510
10511 ;;;###autoload
10512 (define-minor-mode js2-minor-mode
10513 "Minor mode for running js2 as a background linter.
10514 This allows you to use a different major mode for JavaScript editing,
10515 such as `js-mode', while retaining the asynchronous error/warning
10516 highlighting features of `js2-mode'."
10517 :group 'js2-mode
10518 :lighter " js-lint"
10519 (if js2-minor-mode
10520 (js2-minor-mode-enter)
10521 (js2-minor-mode-exit)))
10522
10523 (defun js2-minor-mode-enter ()
10524 "Initialization for `js2-minor-mode'."
10525 (set (make-local-variable 'max-lisp-eval-depth)
10526 (max max-lisp-eval-depth 3000))
10527 (setq next-error-function #'js2-next-error)
10528 (js2-set-default-externs)
10529 ;; Experiment: make reparse-delay longer for longer files.
10530 (if (plusp js2-dynamic-idle-timer-adjust)
10531 (setq js2-idle-timer-delay
10532 (* js2-idle-timer-delay
10533 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10534 (setq js2-mode-buffer-dirty-p t
10535 js2-mode-parsing nil)
10536 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10537 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10538 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10539 (when js2-include-jslint-globals
10540 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10541 (run-hooks 'js2-init-hook)
10542 (js2-reparse))
10543
10544 (defun js2-minor-mode-exit ()
10545 "Turn off `js2-minor-mode'."
10546 (setq next-error-function nil)
10547 (remove-hook 'after-change-functions #'js2-mode-edit t)
10548 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10549 (when js2-mode-node-overlay
10550 (delete-overlay js2-mode-node-overlay)
10551 (setq js2-mode-node-overlay nil))
10552 (js2-remove-overlays)
10553 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10554 (setq js2-mode-ast nil))
10555
10556 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10557 (make-variable-buffer-local 'js2-source-buffer)
10558
10559 (defun* js2-display-error-list ()
10560 "Display a navigable buffer listing parse errors/warnings."
10561 (interactive)
10562 (unless (js2-have-errors-p)
10563 (message "No errors")
10564 (return-from js2-display-error-list))
10565 (labels ((annotate-list
10566 (lst type)
10567 "Add diagnostic TYPE and line number to errs list"
10568 (mapcar (lambda (err)
10569 (list err type (line-number-at-pos (nth 1 err))))
10570 lst)))
10571 (let* ((srcbuf (current-buffer))
10572 (errbuf (get-buffer-create "*js-lint*"))
10573 (errors (annotate-list
10574 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10575 'js2-error)) ; must be a valid face name
10576 (warnings (annotate-list
10577 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10578 'js2-warning)) ; must be a valid face name
10579 (all-errs (sort (append errors warnings)
10580 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10581 (with-current-buffer errbuf
10582 (let ((inhibit-read-only t))
10583 (erase-buffer)
10584 (dolist (err all-errs)
10585 (destructuring-bind ((msg-key beg _end &rest) type line) err
10586 (insert-text-button
10587 (format "line %d: %s" line (js2-get-msg msg-key))
10588 'face type
10589 'follow-link "\C-m"
10590 'action 'js2-error-buffer-jump
10591 'js2-msg (js2-get-msg msg-key)
10592 'js2-pos beg)
10593 (insert "\n"))))
10594 (js2-error-buffer-mode)
10595 (setq js2-source-buffer srcbuf)
10596 (pop-to-buffer errbuf)
10597 (goto-char (point-min))
10598 (unless (eobp)
10599 (js2-error-buffer-view))))))
10600
10601 (defvar js2-error-buffer-mode-map
10602 (let ((map (make-sparse-keymap)))
10603 (define-key map "n" #'js2-error-buffer-next)
10604 (define-key map "p" #'js2-error-buffer-prev)
10605 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10606 (define-key map "o" #'js2-error-buffer-view)
10607 (define-key map "q" #'js2-error-buffer-quit)
10608 map)
10609 "Keymap used for js2 diagnostics buffers.")
10610
10611 (defun js2-error-buffer-mode ()
10612 "Major mode for js2 diagnostics buffers.
10613 Selecting an error will jump it to the corresponding source-buffer error.
10614 \\{js2-error-buffer-mode-map}"
10615 (interactive)
10616 (setq major-mode 'js2-error-buffer-mode
10617 mode-name "JS Lint Diagnostics")
10618 (use-local-map js2-error-buffer-mode-map)
10619 (setq truncate-lines t)
10620 (set-buffer-modified-p nil)
10621 (setq buffer-read-only t)
10622 (run-hooks 'js2-error-buffer-mode-hook))
10623
10624 (defun js2-error-buffer-next ()
10625 "Move to next error and view it."
10626 (interactive)
10627 (when (zerop (forward-line 1))
10628 (js2-error-buffer-view)))
10629
10630 (defun js2-error-buffer-prev ()
10631 "Move to previous error and view it."
10632 (interactive)
10633 (when (zerop (forward-line -1))
10634 (js2-error-buffer-view)))
10635
10636 (defun js2-error-buffer-quit ()
10637 "Kill the current buffer."
10638 (interactive)
10639 (kill-buffer))
10640
10641 (defun js2-error-buffer-jump (&rest ignored)
10642 "Jump cursor to current error in source buffer."
10643 (interactive)
10644 (when (js2-error-buffer-view)
10645 (pop-to-buffer js2-source-buffer)))
10646
10647 (defun js2-error-buffer-view ()
10648 "Scroll source buffer to show error at current line."
10649 (interactive)
10650 (cond
10651 ((not (eq major-mode 'js2-error-buffer-mode))
10652 (message "Not in a js2 errors buffer"))
10653 ((not (buffer-live-p js2-source-buffer))
10654 (message "Source buffer has been killed"))
10655 ((not (wholenump (get-text-property (point) 'js2-pos)))
10656 (message "There does not seem to be an error here"))
10657 (t
10658 (let ((pos (get-text-property (point) 'js2-pos))
10659 (msg (get-text-property (point) 'js2-msg)))
10660 (save-selected-window
10661 (pop-to-buffer js2-source-buffer)
10662 (goto-char pos)
10663 (message msg))))))
10664
10665 ;;;###autoload
10666 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10667 ;; FIXME: Should derive from js-mode.
10668 "Major mode for editing JavaScript code."
10669 ;; Used by comment-region; don't change it.
10670 (set (make-local-variable 'comment-start) "//")
10671 (set (make-local-variable 'comment-end) "")
10672 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10673 (set (make-local-variable 'max-lisp-eval-depth)
10674 (max max-lisp-eval-depth 3000))
10675 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10676 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10677 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10678 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10679 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10680 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10681 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10682 ;; for characters inside regexp literals.
10683 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10684 ;; this is necessary to make `show-paren-function' work properly
10685 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10686 ;; needed for M-x rgrep, among other things
10687 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10688
10689 (set (make-local-variable 'electric-indent-chars)
10690 (append "{}()[]:;,*." electric-indent-chars))
10691 (set (make-local-variable 'electric-layout-rules)
10692 '((?\; . after) (?\{ . after) (?\} . before)))
10693
10694 ;; some variables needed by cc-engine for paragraph-fill, etc.
10695 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10696 c-comment-start-regexp "/[*/]\\|\\s|"
10697 c-line-comment-starter "//"
10698 c-paragraph-start js2-paragraph-start
10699 c-paragraph-separate "$"
10700 c-syntactic-ws-start js2-syntactic-ws-start
10701 c-syntactic-ws-end js2-syntactic-ws-end
10702 c-syntactic-eol js2-syntactic-eol)
10703
10704 (let ((c-buffer-is-cc-mode t))
10705 ;; Copied from `js-mode'. Also see Bug#6071.
10706 (make-local-variable 'paragraph-start)
10707 (make-local-variable 'paragraph-separate)
10708 (make-local-variable 'paragraph-ignore-fill-prefix)
10709 (make-local-variable 'adaptive-fill-mode)
10710 (make-local-variable 'adaptive-fill-regexp)
10711 (c-setup-paragraph-variables))
10712
10713 (setq font-lock-defaults '(nil t))
10714
10715 ;; Experiment: make reparse-delay longer for longer files.
10716 (when (plusp js2-dynamic-idle-timer-adjust)
10717 (setq js2-idle-timer-delay
10718 (* js2-idle-timer-delay
10719 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10720
10721 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10722 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10723 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10724 (setq next-error-function #'js2-next-error)
10725 (imenu-add-to-menubar (concat "IM-" mode-name))
10726 (add-to-invisibility-spec '(js2-outline . t))
10727 (set (make-local-variable 'line-move-ignore-invisible) t)
10728 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10729
10730 (setq js2-mode-functions-hidden nil
10731 js2-mode-comments-hidden nil
10732 js2-mode-buffer-dirty-p t
10733 js2-mode-parsing nil)
10734
10735 (js2-set-default-externs)
10736
10737 (when js2-include-jslint-globals
10738 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10739
10740 (run-hooks 'js2-init-hook)
10741
10742 (js2-reparse))
10743
10744 (defun js2-mode-exit ()
10745 "Exit `js2-mode' and clean up."
10746 (interactive)
10747 (when js2-mode-node-overlay
10748 (delete-overlay js2-mode-node-overlay)
10749 (setq js2-mode-node-overlay nil))
10750 (js2-remove-overlays)
10751 (setq js2-mode-ast nil)
10752 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10753 (remove-from-invisibility-spec '(js2-outline . t))
10754 (js2-mode-show-all)
10755 (with-silent-modifications
10756 (js2-clear-face (point-min) (point-max))))
10757
10758 (defun js2-mode-reset-timer ()
10759 "Cancel any existing parse timer and schedule a new one."
10760 (if js2-mode-parse-timer
10761 (cancel-timer js2-mode-parse-timer))
10762 (setq js2-mode-parsing nil)
10763 (let ((timer (timer-create)))
10764 (setq js2-mode-parse-timer timer)
10765 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10766 (timer-set-idle-time timer js2-idle-timer-delay)
10767 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10768 (timer-activate-when-idle timer nil)))
10769
10770 (defun js2-mode-idle-reparse (buffer)
10771 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10772 it to be reparsed when the buffer is selected."
10773 (cond ((eq buffer (current-buffer))
10774 (js2-reparse))
10775 ((buffer-live-p buffer)
10776 ;; reparse when the buffer is selected again
10777 (with-current-buffer buffer
10778 (add-hook 'window-configuration-change-hook
10779 #'js2-mode-idle-reparse-inner
10780 nil t)))))
10781
10782 (defun js2-mode-idle-reparse-inner ()
10783 (remove-hook 'window-configuration-change-hook
10784 #'js2-mode-idle-reparse-inner
10785 t)
10786 (js2-reparse))
10787
10788 (defun js2-mode-edit (_beg _end _len)
10789 "Schedule a new parse after buffer is edited.
10790 Buffer edit spans from BEG to END and is of length LEN."
10791 (setq js2-mode-buffer-dirty-p t)
10792 (js2-mode-hide-overlay)
10793 (js2-mode-reset-timer))
10794
10795 (defun js2-minor-mode-edit (_beg _end _len)
10796 "Callback for buffer edits in `js2-mode'.
10797 Schedules a new parse after buffer is edited.
10798 Buffer edit spans from BEG to END and is of length LEN."
10799 (setq js2-mode-buffer-dirty-p t)
10800 (js2-mode-hide-overlay)
10801 (js2-mode-reset-timer))
10802
10803 (defun js2-reparse (&optional force)
10804 "Re-parse current buffer after user finishes some data entry.
10805 If we get any user input while parsing, including cursor motion,
10806 we discard the parse and reschedule it. If FORCE is nil, then the
10807 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10808 (let (time
10809 interrupted-p
10810 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10811 (unless js2-mode-parsing
10812 (setq js2-mode-parsing t)
10813 (unwind-protect
10814 (when (or js2-mode-buffer-dirty-p force)
10815 (js2-remove-overlays)
10816 (with-silent-modifications
10817 (setq js2-mode-buffer-dirty-p nil
10818 js2-mode-fontifications nil
10819 js2-mode-deferred-properties nil)
10820 (if js2-mode-verbose-parse-p
10821 (message "parsing..."))
10822 (setq time
10823 (js2-time
10824 (setq interrupted-p
10825 (catch 'interrupted
10826 (js2-parse)
10827 ;; if parsing is interrupted, comments and regex
10828 ;; literals stay ignored by `parse-partial-sexp'
10829 (remove-text-properties (point-min) (point-max)
10830 '(syntax-table))
10831 (js2-mode-apply-deferred-properties)
10832 (js2-mode-remove-suppressed-warnings)
10833 (js2-mode-show-warnings)
10834 (js2-mode-show-errors)
10835 (if (>= js2-highlight-level 1)
10836 (js2-highlight-jsdoc js2-mode-ast))
10837 nil))))
10838 (if interrupted-p
10839 (progn
10840 ;; unfinished parse => try again
10841 (setq js2-mode-buffer-dirty-p t)
10842 (js2-mode-reset-timer))
10843 (if js2-mode-verbose-parse-p
10844 (message "Parse time: %s" time)))))
10845 (setq js2-mode-parsing nil)
10846 (unless interrupted-p
10847 (setq js2-mode-parse-timer nil))))))
10848
10849 (defun js2-mode-show-node (event)
10850 "Debugging aid: highlight selected AST node on mouse click."
10851 (interactive "e")
10852 (mouse-set-point event)
10853 (setq deactivate-mark t)
10854 (when js2-mode-show-overlay
10855 (let ((node (js2-node-at-point))
10856 beg end)
10857 (if (null node)
10858 (message "No node found at location %s" (point))
10859 (setq beg (js2-node-abs-pos node)
10860 end (+ beg (js2-node-len node)))
10861 (if js2-mode-node-overlay
10862 (move-overlay js2-mode-node-overlay beg end)
10863 (setq js2-mode-node-overlay (make-overlay beg end))
10864 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10865 (with-silent-modifications
10866 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10867 (message "%s, parent: %s"
10868 (js2-node-short-name node)
10869 (if (js2-node-parent node)
10870 (js2-node-short-name (js2-node-parent node))
10871 "nil"))))))
10872
10873 (defun js2-mode-hide-overlay (&optional _p1 p2)
10874 "Remove the debugging overlay when the point moves.
10875 P1 and P2 are the old and new values of point, respectively."
10876 (when js2-mode-node-overlay
10877 (let ((beg (overlay-start js2-mode-node-overlay))
10878 (end (overlay-end js2-mode-node-overlay)))
10879 ;; Sometimes we're called spuriously.
10880 (unless (and p2
10881 (>= p2 beg)
10882 (<= p2 end))
10883 (with-silent-modifications
10884 (remove-text-properties beg end '(point-left nil)))
10885 (delete-overlay js2-mode-node-overlay)
10886 (setq js2-mode-node-overlay nil)))))
10887
10888 (defun js2-mode-reset ()
10889 "Debugging helper: reset everything."
10890 (interactive)
10891 (js2-mode-exit)
10892 (js2-mode))
10893
10894 (defun js2-mode-show-warn-or-err (e face)
10895 "Highlight a warning or error E with FACE.
10896 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10897 The last element is optional. When present, use instead of FACE."
10898 (let* ((key (first e))
10899 (beg (second e))
10900 (end (+ beg (third e)))
10901 ;; Don't inadvertently go out of bounds.
10902 (beg (max (point-min) (min beg (point-max))))
10903 (end (max (point-min) (min end (point-max))))
10904 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10905 (ovl (make-overlay beg end)))
10906 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10907 (overlay-put ovl 'js2-error t)
10908 (put-text-property beg end 'help-echo (js2-get-msg key))
10909 (put-text-property beg end 'point-entered #'js2-echo-error)))
10910
10911 (defun js2-remove-overlays ()
10912 "Remove overlays from buffer that have a `js2-error' property."
10913 (let ((beg (point-min))
10914 (end (point-max)))
10915 (save-excursion
10916 (dolist (o (overlays-in beg end))
10917 (when (overlay-get o 'js2-error)
10918 (delete-overlay o))))))
10919
10920 (defun js2-error-at-point (&optional pos)
10921 "Return non-nil if there's an error overlay at POS.
10922 Defaults to point."
10923 (loop with pos = (or pos (point))
10924 for o in (overlays-at pos)
10925 thereis (overlay-get o 'js2-error)))
10926
10927 (defun js2-mode-apply-deferred-properties ()
10928 "Apply fontifications and other text properties recorded during parsing."
10929 (when (plusp js2-highlight-level)
10930 ;; We defer clearing faces as long as possible to eliminate flashing.
10931 (js2-clear-face (point-min) (point-max))
10932 ;; Have to reverse the recorded fontifications list so that errors
10933 ;; and warnings overwrite the normal fontifications.
10934 (dolist (f (nreverse js2-mode-fontifications))
10935 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10936 (setq js2-mode-fontifications nil))
10937 (dolist (p js2-mode-deferred-properties)
10938 (apply #'put-text-property p))
10939 (setq js2-mode-deferred-properties nil))
10940
10941 (defun js2-mode-show-errors ()
10942 "Highlight syntax errors."
10943 (when js2-mode-show-parse-errors
10944 (dolist (e (js2-ast-root-errors js2-mode-ast))
10945 (js2-mode-show-warn-or-err e 'js2-error))))
10946
10947 (defun js2-mode-remove-suppressed-warnings ()
10948 "Take suppressed warnings out of the AST warnings list.
10949 This ensures that the counts and `next-error' are correct."
10950 (setf (js2-ast-root-warnings js2-mode-ast)
10951 (js2-delete-if
10952 (lambda (e)
10953 (let ((key (caar e)))
10954 (or
10955 (and (not js2-strict-trailing-comma-warning)
10956 (string-match "trailing\\.comma" key))
10957 (and (not js2-strict-cond-assign-warning)
10958 (string= key "msg.equal.as.assign"))
10959 (and js2-missing-semi-one-line-override
10960 (string= key "msg.missing.semi")
10961 (let* ((beg (second e))
10962 (node (js2-node-at-point beg))
10963 (fn (js2-mode-find-parent-fn node))
10964 (body (and fn (js2-function-node-body fn)))
10965 (lc (and body (js2-node-abs-pos body)))
10966 (rc (and lc (+ lc (js2-node-len body)))))
10967 (and fn
10968 (or (null body)
10969 (save-excursion
10970 (goto-char beg)
10971 (and (js2-same-line lc)
10972 (js2-same-line rc))))))))))
10973 (js2-ast-root-warnings js2-mode-ast))))
10974
10975 (defun js2-mode-show-warnings ()
10976 "Highlight strict-mode warnings."
10977 (when js2-mode-show-strict-warnings
10978 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10979 (js2-mode-show-warn-or-err e 'js2-warning))))
10980
10981 (defun js2-echo-error (_old-point new-point)
10982 "Called by point-motion hooks."
10983 (let ((msg (get-text-property new-point 'help-echo)))
10984 (when (and (stringp msg)
10985 (not (active-minibuffer-window))
10986 (not (current-message)))
10987 (message msg))))
10988
10989 (defalias 'js2-echo-help #'js2-echo-error)
10990
10991 (defun js2-line-break (&optional _soft)
10992 "Break line at point and indent, continuing comment if within one.
10993 If inside a string, and `js2-concat-multiline-strings' is not
10994 nil, turn it into concatenation."
10995 (interactive)
10996 (let ((parse-status (syntax-ppss)))
10997 (cond
10998 ;; Check if we're inside a string.
10999 ((nth 3 parse-status)
11000 (if js2-concat-multiline-strings
11001 (js2-mode-split-string parse-status)
11002 (insert "\n")))
11003 ;; Check if inside a block comment.
11004 ((nth 4 parse-status)
11005 (js2-mode-extend-comment (nth 8 parse-status)))
11006 (t
11007 (newline-and-indent)))))
11008
11009 (defun js2-mode-split-string (parse-status)
11010 "Turn a newline in mid-string into a string concatenation.
11011 PARSE-STATUS is as documented in `parse-partial-sexp'."
11012 (let* ((quote-char (nth 3 parse-status))
11013 (at-eol (eq js2-concat-multiline-strings 'eol)))
11014 (insert quote-char)
11015 (insert (if at-eol " +\n" "\n"))
11016 (unless at-eol
11017 (insert "+ "))
11018 (js2-indent-line)
11019 (insert quote-char)
11020 (when (eolp)
11021 (insert quote-char)
11022 (backward-char 1))))
11023
11024 (defun js2-mode-extend-comment (start-pos)
11025 "Indent the line and, when inside a comment block, add comment prefix."
11026 (let (star single col first-line needs-close)
11027 (save-excursion
11028 (back-to-indentation)
11029 (when (< (point) start-pos)
11030 (goto-char start-pos))
11031 (cond
11032 ((looking-at "\\*[^/]")
11033 (setq star t
11034 col (current-column)))
11035 ((looking-at "/\\*")
11036 (setq star t
11037 first-line t
11038 col (1+ (current-column))))
11039 ((looking-at "//")
11040 (setq single t
11041 col (current-column)))))
11042 ;; Heuristic for whether we need to close the comment:
11043 ;; if we've got a parse error here, assume it's an unterminated
11044 ;; comment.
11045 (setq needs-close
11046 (or
11047 (eq (get-text-property (1- (point)) 'point-entered)
11048 'js2-echo-error)
11049 ;; The heuristic above doesn't work well when we're
11050 ;; creating a comment and there's another one downstream,
11051 ;; as our parser thinks this one ends at the end of the
11052 ;; next one. (You can have a /* inside a js block comment.)
11053 ;; So just close it if the next non-ws char isn't a *.
11054 (and first-line
11055 (eolp)
11056 (save-excursion
11057 (skip-chars-forward " \t\r\n")
11058 (not (eq (char-after) ?*))))))
11059 (delete-horizontal-space)
11060 (insert "\n")
11061 (cond
11062 (star
11063 (indent-to col)
11064 (insert "* ")
11065 (if (and first-line needs-close)
11066 (save-excursion
11067 (insert "\n")
11068 (indent-to col)
11069 (insert "*/"))))
11070 ((and single
11071 (save-excursion
11072 (and (zerop (forward-line 1))
11073 (looking-at "\\s-*//"))))
11074 (indent-to col)
11075 (insert "// ")))
11076 ;; Don't need to extend the comment after all.
11077 (js2-indent-line)))
11078
11079 (defun js2-beginning-of-line ()
11080 "Toggle point between bol and first non-whitespace char in line.
11081 Also moves past comment delimiters when inside comments."
11082 (interactive)
11083 (let (node)
11084 (cond
11085 ((bolp)
11086 (back-to-indentation))
11087 ((looking-at "//")
11088 (skip-chars-forward "/ \t"))
11089 ((and (eq (char-after) ?*)
11090 (setq node (js2-comment-at-point))
11091 (memq (js2-comment-node-format node) '(jsdoc block))
11092 (save-excursion
11093 (skip-chars-backward " \t")
11094 (bolp)))
11095 (skip-chars-forward "\* \t"))
11096 (t
11097 (goto-char (point-at-bol))))))
11098
11099 (defun js2-end-of-line ()
11100 "Toggle point between eol and last non-whitespace char in line."
11101 (interactive)
11102 (if (eolp)
11103 (skip-chars-backward " \t")
11104 (goto-char (point-at-eol))))
11105
11106 (defun js2-mode-wait-for-parse (callback)
11107 "Invoke CALLBACK when parsing is finished.
11108 If parsing is already finished, calls CALLBACK immediately."
11109 (if (not js2-mode-buffer-dirty-p)
11110 (funcall callback)
11111 (push callback js2-mode-pending-parse-callbacks)
11112 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11113
11114 (defun js2-mode-parse-finished ()
11115 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11116 ;; We can't let errors propagate up, since it prevents the
11117 ;; `js2-parse' method from completing normally and returning
11118 ;; the ast, which makes things mysteriously not work right.
11119 (unwind-protect
11120 (dolist (cb js2-mode-pending-parse-callbacks)
11121 (condition-case err
11122 (funcall cb)
11123 (error (message "%s" err))))
11124 (setq js2-mode-pending-parse-callbacks nil)))
11125
11126 (defun js2-mode-flag-region (from to flag)
11127 "Hide or show text from FROM to TO, according to FLAG.
11128 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11129 Returns the created overlay if FLAG is non-nil."
11130 (remove-overlays from to 'invisible 'js2-outline)
11131 (when flag
11132 (let ((o (make-overlay from to)))
11133 (overlay-put o 'invisible 'js2-outline)
11134 (overlay-put o 'isearch-open-invisible
11135 'js2-isearch-open-invisible)
11136 o)))
11137
11138 ;; Function to be set as an outline-isearch-open-invisible' property
11139 ;; to the overlay that makes the outline invisible (see
11140 ;; `js2-mode-flag-region').
11141 (defun js2-isearch-open-invisible (_overlay)
11142 ;; We rely on the fact that isearch places point on the matched text.
11143 (js2-mode-show-element))
11144
11145 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11146 "Return cons cell of bounds of folding overlay at POS.
11147 Returns nil if not found."
11148 (let ((overlays (overlays-at (or pos (point))))
11149 o)
11150 (while (and overlays
11151 (not o))
11152 (if (overlay-get (car overlays) 'invisible)
11153 (setq o (car overlays))
11154 (setq overlays (cdr overlays))))
11155 (if o
11156 (cons (overlay-start o) (overlay-end o)))))
11157
11158 (defun js2-mode-function-at-point (&optional pos)
11159 "Return the innermost function node enclosing current point.
11160 Returns nil if point is not in a function."
11161 (let ((node (js2-node-at-point pos)))
11162 (while (and node (not (js2-function-node-p node)))
11163 (setq node (js2-node-parent node)))
11164 (if (js2-function-node-p node)
11165 node)))
11166
11167 (defun js2-mode-toggle-element ()
11168 "Hide or show the foldable element at the point."
11169 (interactive)
11170 (let (comment fn pos)
11171 (save-excursion
11172 (cond
11173 ;; /* ... */ comment?
11174 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11175 (if (js2-mode-invisible-overlay-bounds
11176 (setq pos (+ 3 (js2-node-abs-pos comment))))
11177 (progn
11178 (goto-char pos)
11179 (js2-mode-show-element))
11180 (js2-mode-hide-element)))
11181 ;; //-comment?
11182 ((save-excursion
11183 (back-to-indentation)
11184 (looking-at js2-mode-//-comment-re))
11185 (js2-mode-toggle-//-comment))
11186 ;; function?
11187 ((setq fn (js2-mode-function-at-point))
11188 (setq pos (and (js2-function-node-body fn)
11189 (js2-node-abs-pos (js2-function-node-body fn))))
11190 (goto-char (1+ pos))
11191 (if (js2-mode-invisible-overlay-bounds)
11192 (js2-mode-show-element)
11193 (js2-mode-hide-element)))
11194 (t
11195 (message "Nothing at point to hide or show"))))))
11196
11197 (defun js2-mode-hide-element ()
11198 "Fold/hide contents of a block, showing ellipses.
11199 Show the hidden text with \\[js2-mode-show-element]."
11200 (interactive)
11201 (if js2-mode-buffer-dirty-p
11202 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11203 (let (node body beg end)
11204 (cond
11205 ((js2-mode-invisible-overlay-bounds)
11206 (message "already hidden"))
11207 (t
11208 (setq node (js2-node-at-point))
11209 (cond
11210 ((js2-block-comment-p node)
11211 (js2-mode-hide-comment node))
11212 (t
11213 (while (and node (not (js2-function-node-p node)))
11214 (setq node (js2-node-parent node)))
11215 (if (and node
11216 (setq body (js2-function-node-body node)))
11217 (progn
11218 (setq beg (js2-node-abs-pos body)
11219 end (+ beg (js2-node-len body)))
11220 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11221 (message "No collapsable element found at point"))))))))
11222
11223 (defun js2-mode-show-element ()
11224 "Show the hidden element at current point."
11225 (interactive)
11226 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11227 (if bounds
11228 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11229 (message "Nothing to un-hide"))))
11230
11231 (defun js2-mode-show-all ()
11232 "Show all of the text in the buffer."
11233 (interactive)
11234 (js2-mode-flag-region (point-min) (point-max) nil))
11235
11236 (defun js2-mode-toggle-hide-functions ()
11237 (interactive)
11238 (if js2-mode-functions-hidden
11239 (js2-mode-show-functions)
11240 (js2-mode-hide-functions)))
11241
11242 (defun js2-mode-hide-functions ()
11243 "Hides all non-nested function bodies in the buffer.
11244 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11245 to open an individual entry."
11246 (interactive)
11247 (if js2-mode-buffer-dirty-p
11248 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11249 (if (null js2-mode-ast)
11250 (message "Oops - parsing failed")
11251 (setq js2-mode-functions-hidden t)
11252 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11253
11254 (defun js2-mode-function-hider (n endp)
11255 (when (not endp)
11256 (let ((tt (js2-node-type n))
11257 body beg end)
11258 (cond
11259 ((and (= tt js2-FUNCTION)
11260 (setq body (js2-function-node-body n)))
11261 (setq beg (js2-node-abs-pos body)
11262 end (+ beg (js2-node-len body)))
11263 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11264 nil) ; don't process children of function
11265 (t
11266 t))))) ; keep processing other AST nodes
11267
11268 (defun js2-mode-show-functions ()
11269 "Un-hide any folded function bodies in the buffer."
11270 (interactive)
11271 (setq js2-mode-functions-hidden nil)
11272 (save-excursion
11273 (goto-char (point-min))
11274 (while (/= (goto-char (next-overlay-change (point)))
11275 (point-max))
11276 (dolist (o (overlays-at (point)))
11277 (when (and (overlay-get o 'invisible)
11278 (not (overlay-get o 'comment)))
11279 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11280
11281 (defun js2-mode-hide-comment (n)
11282 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11283 3 ; /**
11284 2)) ; /*
11285 (beg (+ (js2-node-abs-pos n) head))
11286 (end (- (+ beg (js2-node-len n)) head 2))
11287 (o (js2-mode-flag-region beg end 'hide)))
11288 (overlay-put o 'comment t)))
11289
11290 (defun js2-mode-toggle-hide-comments ()
11291 "Folds all block comments in the buffer.
11292 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11293 to open an individual entry."
11294 (interactive)
11295 (if js2-mode-comments-hidden
11296 (js2-mode-show-comments)
11297 (js2-mode-hide-comments)))
11298
11299 (defun js2-mode-hide-comments ()
11300 (interactive)
11301 (if js2-mode-buffer-dirty-p
11302 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11303 (if (null js2-mode-ast)
11304 (message "Oops - parsing failed")
11305 (setq js2-mode-comments-hidden t)
11306 (dolist (n (js2-ast-root-comments js2-mode-ast))
11307 (when (js2-block-comment-p n)
11308 (js2-mode-hide-comment n)))
11309 (js2-mode-hide-//-comments)))
11310
11311 (defun js2-mode-extend-//-comment (direction)
11312 "Find start or end of a block of similar //-comment lines.
11313 DIRECTION is -1 to look back, 1 to look forward.
11314 INDENT is the indentation level to match.
11315 Returns the end-of-line position of the furthest adjacent
11316 //-comment line with the same indentation as the current line.
11317 If there is no such matching line, returns current end of line."
11318 (let ((pos (point-at-eol))
11319 (indent (current-indentation)))
11320 (save-excursion
11321 (while (and (zerop (forward-line direction))
11322 (looking-at js2-mode-//-comment-re)
11323 (eq indent (length (match-string 1))))
11324 (setq pos (point-at-eol)))
11325 pos)))
11326
11327 (defun js2-mode-hide-//-comments ()
11328 "Fold adjacent 1-line comments, showing only snippet of first one."
11329 (let (beg end)
11330 (save-excursion
11331 (goto-char (point-min))
11332 (while (re-search-forward js2-mode-//-comment-re nil t)
11333 (setq beg (point)
11334 end (js2-mode-extend-//-comment 1))
11335 (unless (eq beg end)
11336 (overlay-put (js2-mode-flag-region beg end 'hide)
11337 'comment t))
11338 (goto-char end)
11339 (forward-char 1)))))
11340
11341 (defun js2-mode-toggle-//-comment ()
11342 "Fold or un-fold any multi-line //-comment at point.
11343 Caller should have determined that this line starts with a //-comment."
11344 (let* ((beg (point-at-eol))
11345 (end beg))
11346 (save-excursion
11347 (goto-char end)
11348 (if (js2-mode-invisible-overlay-bounds)
11349 (js2-mode-show-element)
11350 ;; else hide the comment
11351 (setq beg (js2-mode-extend-//-comment -1)
11352 end (js2-mode-extend-//-comment 1))
11353 (unless (eq beg end)
11354 (overlay-put (js2-mode-flag-region beg end 'hide)
11355 'comment t))))))
11356
11357 (defun js2-mode-show-comments ()
11358 "Un-hide any hidden comments, leaving other hidden elements alone."
11359 (interactive)
11360 (setq js2-mode-comments-hidden nil)
11361 (save-excursion
11362 (goto-char (point-min))
11363 (while (/= (goto-char (next-overlay-change (point)))
11364 (point-max))
11365 (dolist (o (overlays-at (point)))
11366 (when (overlay-get o 'comment)
11367 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11368
11369 (defun js2-mode-display-warnings-and-errors ()
11370 "Turn on display of warnings and errors."
11371 (interactive)
11372 (setq js2-mode-show-parse-errors t
11373 js2-mode-show-strict-warnings t)
11374 (js2-reparse 'force))
11375
11376 (defun js2-mode-hide-warnings-and-errors ()
11377 "Turn off display of warnings and errors."
11378 (interactive)
11379 (setq js2-mode-show-parse-errors nil
11380 js2-mode-show-strict-warnings nil)
11381 (js2-reparse 'force))
11382
11383 (defun js2-mode-toggle-warnings-and-errors ()
11384 "Toggle the display of warnings and errors.
11385 Some users don't like having warnings/errors reported while they type."
11386 (interactive)
11387 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11388 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11389 (if (called-interactively-p 'any)
11390 (message "warnings and errors %s"
11391 (if js2-mode-show-parse-errors
11392 "enabled"
11393 "disabled")))
11394 (js2-reparse 'force))
11395
11396 (defun js2-mode-customize ()
11397 (interactive)
11398 (customize-group 'js2-mode))
11399
11400 (defun js2-mode-forward-sexp (&optional arg)
11401 "Move forward across one statement or balanced expression.
11402 With ARG, do it that many times. Negative arg -N means
11403 move backward across N balanced expressions."
11404 (interactive "p")
11405 (setq arg (or arg 1))
11406 (save-restriction
11407 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11408 (js2-reparse)
11409 (let (forward-sexp-function
11410 node (start (point)) pos lp rp child)
11411 (cond
11412 ;; backward-sexp
11413 ;; could probably make this better for some cases:
11414 ;; - if in statement block (e.g. function body), go to parent
11415 ;; - infix exprs like (foo in bar) - maybe go to beginning
11416 ;; of infix expr if in the right-side expression?
11417 ((and arg (minusp arg))
11418 (dotimes (_ (- arg))
11419 (js2-backward-sws)
11420 (forward-char -1) ; Enter the node we backed up to.
11421 (when (setq node (js2-node-at-point (point) t))
11422 (setq pos (js2-node-abs-pos node))
11423 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11424 (setq lp (car parens)
11425 rp (cdr parens)))
11426 (when (and lp (> start lp))
11427 (if (and rp (<= start rp))
11428 ;; Between parens, check if there's a child node we can jump.
11429 (when (setq child (js2-node-closest-child node (point) lp t))
11430 (setq pos (js2-node-abs-pos child)))
11431 ;; Before both parens.
11432 (setq pos lp)))
11433 (let ((state (parse-partial-sexp start pos)))
11434 (goto-char (if (not (zerop (car state)))
11435 ;; Stumble at the unbalanced paren if < 0, or
11436 ;; jump a bit further if > 0.
11437 (scan-sexps start -1)
11438 pos))))
11439 (unless pos (goto-char (point-min)))))
11440 (t
11441 ;; forward-sexp
11442 (dotimes (_ arg)
11443 (js2-forward-sws)
11444 (when (setq node (js2-node-at-point (point) t))
11445 (setq pos (js2-node-abs-pos node))
11446 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11447 (setq lp (car parens)
11448 rp (cdr parens)))
11449 (or
11450 (when (and rp (<= start rp))
11451 (if (> start lp)
11452 (when (setq child (js2-node-closest-child node (point) rp))
11453 (setq pos (js2-node-abs-end child)))
11454 (setq pos (1+ rp))))
11455 ;; No parens or child nodes, looks for the end of the curren node.
11456 (incf pos (js2-node-len
11457 (if (js2-expr-stmt-node-p (js2-node-parent node))
11458 ;; Stop after the semicolon.
11459 (js2-node-parent node)
11460 node))))
11461 (let ((state (save-excursion (parse-partial-sexp start pos))))
11462 (goto-char (if (not (zerop (car state)))
11463 (scan-sexps start 1)
11464 pos))))
11465 (unless pos (goto-char (point-max)))))))))
11466
11467 (defun js2-mode-forward-sexp-parens (node abs-pos)
11468 "Return a cons cell with positions of main parens in NODE."
11469 (cond
11470 ((or (js2-array-node-p node)
11471 (js2-object-node-p node)
11472 (js2-comp-node-p node)
11473 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11474 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11475 ((js2-paren-expr-node-p node)
11476 (let ((lp (js2-node-lp node))
11477 (rp (js2-node-rp node)))
11478 (cons (when lp (+ abs-pos lp))
11479 (when rp (+ abs-pos rp)))))))
11480
11481 (defun js2-node-closest-child (parent point limit &optional before)
11482 (let* ((parent-pos (js2-node-abs-pos parent))
11483 (rpoint (- point parent-pos))
11484 (rlimit (- limit parent-pos))
11485 (min (min rpoint rlimit))
11486 (max (max rpoint rlimit))
11487 found)
11488 (catch 'done
11489 (js2-visit-ast
11490 parent
11491 (lambda (node _end-p)
11492 (if (eq node parent)
11493 t
11494 (let ((pos (js2-node-pos node)) ;; Both relative values.
11495 (end (+ (js2-node-pos node) (js2-node-len node))))
11496 (when (and (>= pos min) (<= end max)
11497 (if before (< pos rpoint) (> end rpoint)))
11498 (setq found node))
11499 (when (> end rpoint)
11500 (throw 'done nil)))
11501 nil))))
11502 found))
11503
11504 (defun js2-errors ()
11505 "Return a list of errors found."
11506 (and js2-mode-ast
11507 (js2-ast-root-errors js2-mode-ast)))
11508
11509 (defun js2-warnings ()
11510 "Return a list of warnings found."
11511 (and js2-mode-ast
11512 (js2-ast-root-warnings js2-mode-ast)))
11513
11514 (defun js2-have-errors-p ()
11515 "Return non-nil if any parse errors or warnings were found."
11516 (or (js2-errors) (js2-warnings)))
11517
11518 (defun js2-errors-and-warnings ()
11519 "Return a copy of the concatenated errors and warnings lists.
11520 They are appended: first the errors, then the warnings.
11521 Entries are of the form (MSG BEG END)."
11522 (when js2-mode-ast
11523 (append (js2-ast-root-errors js2-mode-ast)
11524 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11525
11526 (defun js2-next-error (&optional arg reset)
11527 "Move to next parse error.
11528 Typically invoked via \\[next-error].
11529 ARG is the number of errors, forward or backward, to move.
11530 RESET means start over from the beginning."
11531 (interactive "p")
11532 (if (not (or (js2-errors) (js2-warnings)))
11533 (message "No errors")
11534 (when reset
11535 (goto-char (point-min)))
11536 (let* ((errs (js2-errors-and-warnings))
11537 (continue t)
11538 (start (point))
11539 (count (or arg 1))
11540 (backward (minusp count))
11541 (sorter (if backward '> '<))
11542 (stopper (if backward '< '>))
11543 (count (abs count))
11544 all-errs err)
11545 ;; Sort by start position.
11546 (setq errs (sort errs (lambda (e1 e2)
11547 (funcall sorter (second e1) (second e2))))
11548 all-errs errs)
11549 ;; Find nth error with pos > start.
11550 (while (and errs continue)
11551 (when (funcall stopper (cadar errs) start)
11552 (setq err (car errs))
11553 (if (zerop (decf count))
11554 (setq continue nil)))
11555 (setq errs (cdr errs)))
11556 ;; Clear for `js2-echo-error'.
11557 (message nil)
11558 (if err
11559 (goto-char (second err))
11560 ;; Wrap around to first error.
11561 (goto-char (second (car all-errs)))
11562 ;; If we were already on it, echo msg again.
11563 (if (= (point) start)
11564 (js2-echo-error (point) (point)))))))
11565
11566 (defun js2-down-mouse-3 ()
11567 "Make right-click move the point to the click location.
11568 This makes right-click context menu operations a bit more intuitive.
11569 The point will not move if the region is active, however, to avoid
11570 destroying the region selection."
11571 (interactive)
11572 (when (and js2-move-point-on-right-click
11573 (not mark-active))
11574 (let ((e last-input-event))
11575 (ignore-errors
11576 (goto-char (cadadr e))))))
11577
11578 (defun js2-mode-create-imenu-index ()
11579 "Return an alist for `imenu--index-alist'."
11580 ;; This is built up in `js2-parse-record-imenu' during parsing.
11581 (when js2-mode-ast
11582 ;; if we have an ast but no recorder, they're requesting a rescan
11583 (unless js2-imenu-recorder
11584 (js2-reparse 'force))
11585 (prog1
11586 (js2-build-imenu-index)
11587 (setq js2-imenu-recorder nil
11588 js2-imenu-function-map nil))))
11589
11590 (defun js2-mode-find-tag ()
11591 "Replacement for `find-tag-default'.
11592 `find-tag-default' returns a ridiculous answer inside comments."
11593 (let (beg end)
11594 (js2-with-underscore-as-word-syntax
11595 (save-excursion
11596 (if (and (not (looking-at "[[:alnum:]_$]"))
11597 (looking-back "[[:alnum:]_$]"))
11598 (setq beg (progn (forward-word -1) (point))
11599 end (progn (forward-word 1) (point)))
11600 (setq beg (progn (forward-word 1) (point))
11601 end (progn (forward-word -1) (point))))
11602 (replace-regexp-in-string
11603 "[\"']" ""
11604 (buffer-substring-no-properties beg end))))))
11605
11606 (defun js2-mode-forward-sibling ()
11607 "Move to the end of the sibling following point in parent.
11608 Returns non-nil if successful, or nil if there was no following sibling."
11609 (let* ((node (js2-node-at-point))
11610 (parent (js2-mode-find-enclosing-fn node))
11611 sib)
11612 (when (setq sib (js2-node-find-child-after (point) parent))
11613 (goto-char (+ (js2-node-abs-pos sib)
11614 (js2-node-len sib))))))
11615
11616 (defun js2-mode-backward-sibling ()
11617 "Move to the beginning of the sibling node preceding point in parent.
11618 Parent is defined as the enclosing script or function."
11619 (let* ((node (js2-node-at-point))
11620 (parent (js2-mode-find-enclosing-fn node))
11621 sib)
11622 (when (setq sib (js2-node-find-child-before (point) parent))
11623 (goto-char (js2-node-abs-pos sib)))))
11624
11625 (defun js2-beginning-of-defun (&optional arg)
11626 "Go to line on which current function starts, and return t on success.
11627 If we're not in a function or already at the beginning of one, go
11628 to beginning of previous script-level element.
11629 With ARG N, do that N times. If N is negative, move forward."
11630 (setq arg (or arg 1))
11631 (if (plusp arg)
11632 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11633 (when (cond
11634 ((js2-function-node-p parent)
11635 (goto-char (js2-node-abs-pos parent)))
11636 (t
11637 (js2-mode-backward-sibling)))
11638 (if (> arg 1)
11639 (js2-beginning-of-defun (1- arg))
11640 t)))
11641 (when (js2-end-of-defun)
11642 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11643
11644 (defun js2-end-of-defun ()
11645 "Go to the char after the last position of the current function
11646 or script-level element."
11647 (let* ((node (js2-node-at-point))
11648 (parent (or (and (js2-function-node-p node) node)
11649 (js2-node-parent-script-or-fn node)))
11650 script)
11651 (unless (js2-function-node-p parent)
11652 ;; Use current script-level node, or, if none, the next one.
11653 (setq script (or parent node)
11654 parent (js2-node-find-child-before (point) script))
11655 (when (or (null parent)
11656 (>= (point) (+ (js2-node-abs-pos parent)
11657 (js2-node-len parent))))
11658 (setq parent (js2-node-find-child-after (point) script))))
11659 (when parent
11660 (goto-char (+ (js2-node-abs-pos parent)
11661 (js2-node-len parent))))))
11662
11663 (defun js2-mark-defun (&optional allow-extend)
11664 "Put mark at end of this function, point at beginning.
11665 The function marked is the one that contains point.
11666
11667 Interactively, if this command is repeated,
11668 or (in Transient Mark mode) if the mark is active,
11669 it marks the next defun after the ones already marked."
11670 (interactive "p")
11671 (let (extended)
11672 (when (and allow-extend
11673 (or (and (eq last-command this-command) (mark t))
11674 (and transient-mark-mode mark-active)))
11675 (let ((sib (save-excursion
11676 (goto-char (mark))
11677 (if (js2-mode-forward-sibling)
11678 (point)))))
11679 (if sib
11680 (progn
11681 (set-mark sib)
11682 (setq extended t))
11683 ;; no more siblings - try extending to enclosing node
11684 (goto-char (mark t)))))
11685 (when (not extended)
11686 (let ((node (js2-node-at-point (point) t)) ; skip comments
11687 ast fn stmt parent beg end)
11688 (when (js2-ast-root-p node)
11689 (setq ast node
11690 node (or (js2-node-find-child-after (point) node)
11691 (js2-node-find-child-before (point) node))))
11692 ;; only mark whole buffer if we can't find any children
11693 (if (null node)
11694 (setq node ast))
11695 (if (js2-function-node-p node)
11696 (setq parent node)
11697 (setq fn (js2-mode-find-enclosing-fn node)
11698 stmt (if (or (null fn)
11699 (js2-ast-root-p fn))
11700 (js2-mode-find-first-stmt node))
11701 parent (or stmt fn)))
11702 (setq beg (js2-node-abs-pos parent)
11703 end (+ beg (js2-node-len parent)))
11704 (push-mark beg)
11705 (goto-char end)
11706 (exchange-point-and-mark)))))
11707
11708 (defun js2-narrow-to-defun ()
11709 "Narrow to the function enclosing point."
11710 (interactive)
11711 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11712 (fn (if (js2-script-node-p node)
11713 node
11714 (js2-mode-find-enclosing-fn node)))
11715 (beg (js2-node-abs-pos fn)))
11716 (unless (js2-ast-root-p fn)
11717 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11718
11719 (provide 'js2-mode)
11720
11721 ;;; js2-mode.el ends here