1 ;;; js2-mode.el --- Improved JavaScript editing mode
3 ;; Copyright (C) 2009, 2011-2015 Free Software Foundation, Inc.
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/
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
14 ;; This file is part of GNU Emacs.
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.
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.
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/>.
31 ;; This JavaScript editing mode supports:
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
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
50 ;; To install it as your major mode for JavaScript editing:
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
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:
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
59 ;; You may also want to hook it in for shell scripts running via node.js:
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
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.
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.
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.
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
90 (require 'cc-cmds) ; for `c-fill-paragraph'
93 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
94 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
96 (defvar electric-layout-rules)
98 ;;; Externs (variables presumed to be defined by the host system)
100 (defvar js2-ecma-262-externs
102 '(Array Boolean Date Error EvalError Function Infinity JSON
103 Math NaN Number Object RangeError ReferenceError RegExp
104 String SyntaxError TypeError URIError
105 decodeURI decodeURIComponent encodeURI
106 encodeURIComponent escape eval isFinite isNaN
107 parseFloat parseInt undefined unescape))
108 "Ecma-262 externs. Included in `js2-externs' by default.")
110 (defvar js2-browser-externs
113 Attr CDATASection CharacterData Comment DOMException
114 DOMImplementation Document DocumentFragment
115 DocumentType Element Entity EntityReference
116 ExceptionCode NamedNodeMap Node NodeList Notation
117 ProcessingInstruction Text
120 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
121 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
122 HTMLBodyElement HTMLButtonElement HTMLCollection
123 HTMLDListElement HTMLDirectoryElement HTMLDivElement
124 HTMLDocument HTMLElement HTMLFieldSetElement
125 HTMLFontElement HTMLFormElement HTMLFrameElement
126 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
127 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
128 HTMLImageElement HTMLInputElement HTMLIsIndexElement
129 HTMLLIElement HTMLLabelElement HTMLLegendElement
130 HTMLLinkElement HTMLMapElement HTMLMenuElement
131 HTMLMetaElement HTMLModElement HTMLOListElement
132 HTMLObjectElement HTMLOptGroupElement
133 HTMLOptionElement HTMLOptionsCollection
134 HTMLParagraphElement HTMLParamElement HTMLPreElement
135 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
136 HTMLStyleElement HTMLTableCaptionElement
137 HTMLTableCellElement HTMLTableColElement
138 HTMLTableElement HTMLTableRowElement
139 HTMLTableSectionElement HTMLTextAreaElement
140 HTMLTitleElement HTMLUListElement
143 DOMConfiguration DOMError DOMException
144 DOMImplementationList DOMImplementationSource
145 DOMLocator DOMStringList NameList TypeInfo
149 window alert confirm document java navigator prompt screen
150 self top requestAnimationFrame cancelAnimationFrame
153 CSSCharsetRule CSSFontFace CSSFontFaceRule
154 CSSImportRule CSSMediaRule CSSPageRule
155 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
156 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
157 CSSValue CSSValueList Counter DOMImplementationCSS
158 DocumentCSS DocumentStyle ElementCSSInlineStyle
159 LinkStyle MediaList RGBColor Rect StyleSheet
160 StyleSheetList ViewCSS
163 EventListener EventTarget Event DocumentEvent UIEvent
164 MouseEvent MutationEvent KeyboardEvent
167 DocumentRange Range RangeException
170 XPathResult XMLHttpRequest
172 ;; console object. Provided by at least Chrome and Firefox.
175 You can cause these to be included or excluded with the custom
176 variable `js2-include-browser-externs'.")
178 (defvar js2-rhino-externs
180 '(Packages importClass importPackage com org java
181 ;; Global object (shell) externs.
182 defineClass deserialize doctest gc help load
183 loadClass print quit readFile readUrl runCommand seal
184 serialize spawn sync toint32 version))
185 "Mozilla Rhino externs.
186 Set `js2-include-rhino-externs' to t to include them.")
188 (defvar js2-node-externs
190 '(__dirname __filename Buffer clearInterval clearTimeout require
191 console exports global module process setInterval setTimeout))
193 Set `js2-include-node-externs' to t to include them.")
195 (defvar js2-typed-array-externs
197 '(ArrayBuffer Uint8ClampedArray DataView
198 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
199 Float32Array Float64Array))
200 "Khronos typed array externs. Available in most modern browsers and
201 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
202 are enabled, these will also be included.")
204 (defvar js2-harmony-externs
206 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
207 "ES6 externs. If `js2-include-browser-externs' is enabled and
208 `js2-language-version' is sufficiently high, these will be included.")
212 (defun js2-mark-safe-local (name pred)
213 "Make the variable NAME buffer-local and mark it as safe file-local
214 variable with predicate PRED."
215 (make-variable-buffer-local name)
216 (put name 'safe-local-variable pred))
218 (defcustom js2-highlight-level 2
219 "Amount of syntax highlighting to perform.
220 0 or a negative value means none.
221 1 adds basic syntax highlighting.
222 2 adds highlighting of some Ecma built-in properties.
223 3 adds highlighting of many Ecma built-in functions."
225 :type '(choice (const :tag "None" 0)
226 (const :tag "Basic" 1)
227 (const :tag "Include Properties" 2)
228 (const :tag "Include Functions" 3)))
230 (defvar js2-mode-dev-mode-p nil
231 "Non-nil if running in development mode. Normally nil.")
233 (defgroup js2-mode nil
234 "An improved JavaScript mode."
237 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
238 (numberp c-basic-offset))
241 "Number of spaces to indent nested statements.
242 Similar to `c-basic-offset'."
245 (js2-mark-safe-local 'js2-basic-offset 'integerp)
247 (defcustom js2-bounce-indent-p nil
248 "Non-nil to have indent-line function choose among alternatives.
249 If nil, the indent-line function will indent to a predetermined column
250 based on heuristic guessing. If non-nil, then if the current line is
251 already indented to that predetermined column, indenting will choose
252 another likely column and indent to that spot. Repeated invocation of
253 the indent-line function will cycle among the computed alternatives.
254 See the function `js2-bounce-indent' for details. When it is non-nil,
255 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
259 (defcustom js2-pretty-multiline-declarations t
260 "Non-nil to line up multiline declarations vertically:
266 If the value is not `all', and the first assigned value in
267 declaration is a function/array/object literal spanning several
268 lines, it won't be indented additionally:
270 var o = { var bar = 2,
276 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
278 (defcustom js2-indent-switch-body nil
279 "When nil, case labels are indented on the same level as the
280 containing switch statement. Otherwise, all lines inside
281 switch statement body are indented one additional level."
284 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
286 (defcustom js2-idle-timer-delay 0.2
287 "Delay in secs before re-parsing after user makes changes.
288 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
291 (make-variable-buffer-local 'js2-idle-timer-delay)
293 (defcustom js2-dynamic-idle-timer-adjust 0
294 "Positive to adjust `js2-idle-timer-delay' based on file size.
295 The idea is that for short files, parsing is faster so we can be
296 more responsive to user edits without interfering with editing.
297 The buffer length in characters (typically bytes) is divided by
298 this value and used to multiply `js2-idle-timer-delay' for the
299 buffer. For example, a 21k file and 10k adjust yields 21k/10k
300 == 2, so js2-idle-timer-delay is multiplied by 2.
301 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
302 `js2-idle-timer-delay' is not dependent on the file size."
306 (defcustom js2-concat-multiline-strings t
307 "When non-nil, `js2-line-break' in mid-string will make it a
308 string concatenation. When `eol', the '+' will be inserted at the
309 end of the line, otherwise, at the beginning of the next line."
310 :type '(choice (const t) (const eol) (const nil))
313 (defcustom js2-mode-show-parse-errors t
314 "True to highlight parse errors."
318 (defcustom js2-mode-show-strict-warnings t
319 "Non-nil to emit Ecma strict-mode warnings.
320 Some of the warnings can be individually disabled by other flags,
321 even if this flag is non-nil."
325 (defcustom js2-strict-trailing-comma-warning t
326 "Non-nil to warn about trailing commas in array literals.
327 Ecma-262-5.1 allows them, but older versions of IE raise an error."
331 (defcustom js2-strict-missing-semi-warning t
332 "Non-nil to warn about semicolon auto-insertion after statement.
333 Technically this is legal per Ecma-262, but some style guides disallow
338 (defcustom js2-missing-semi-one-line-override nil
339 "Non-nil to permit missing semicolons in one-line functions.
340 In one-liner functions such as `function identity(x) {return x}'
341 people often omit the semicolon for a cleaner look. If you are
342 such a person, you can suppress the missing-semicolon warning
343 by setting this variable to t."
347 (defcustom js2-strict-inconsistent-return-warning t
348 "Non-nil to warn about mixing returns with value-returns.
349 It's perfectly legal to have a `return' and a `return foo' in the
350 same function, but it's often an indicator of a bug, and it also
351 interferes with type inference (in systems that support it.)"
355 (defcustom js2-strict-cond-assign-warning t
356 "Non-nil to warn about expressions like if (a = b).
357 This often should have been '==' instead of '='. If the warning
358 is enabled, you can suppress it on a per-expression basis by
359 parenthesizing the expression, e.g. if ((a = b)) ..."
363 (defcustom js2-strict-var-redeclaration-warning t
364 "Non-nil to warn about redeclaring variables in a script or function."
368 (defcustom js2-strict-var-hides-function-arg-warning t
369 "Non-nil to warn about a var decl hiding a function argument."
373 (defcustom js2-skip-preprocessor-directives nil
374 "Non-nil to treat lines beginning with # as comments.
375 Useful for viewing Mozilla JavaScript source code."
379 (defcustom js2-language-version 200
380 "Configures what JavaScript language version to recognize.
381 Currently versions 150, 160, 170, 180 and 200 are supported,
382 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
383 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
384 yield, and Array comprehensions, and 1.8 adds function closures."
388 (defcustom js2-instanceof-has-side-effects nil
389 "If non-nil, treats the instanceof operator as having side effects.
390 This is useful for xulrunner apps."
394 (defcustom js2-move-point-on-right-click t
395 "Non-nil to move insertion point when you right-click.
396 This makes right-click context menu behavior a bit more intuitive,
397 since menu operations generally apply to the point. The exception
398 is if there is a region selection, in which case the point does -not-
399 move, so cut/copy/paste can work properly.
401 Note that IntelliJ moves the point, and Eclipse leaves it alone,
402 so this behavior is customizable."
406 (defcustom js2-allow-rhino-new-expr-initializer t
407 "Non-nil to support a Rhino's experimental syntactic construct.
409 Rhino supports the ability to follow a `new' expression with an object
410 literal, which is used to set additional properties on the new object
411 after calling its constructor. Syntax:
413 new <expr> [ ( arglist ) ] [initializer]
415 Hence, this expression:
417 new Object {a: 1, b: 2}
419 results in an Object with properties a=1 and b=2. This syntax is
420 apparently not configurable in Rhino - it's currently always enabled,
421 as of Rhino version 1.7R2."
425 (defcustom js2-allow-member-expr-as-function-name nil
426 "Non-nil to support experimental Rhino syntax for function names.
428 Rhino supports an experimental syntax configured via the Rhino Context
429 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
431 function <member-expr> ( [ arg-list ] ) { <body> }
433 Where member-expr is a non-parenthesized 'member expression', which
434 is anything at the grammar level of a new-expression or lower, meaning
435 any expression that does not involve infix or unary operators.
437 When <member-expr> is not a simple identifier, then it is syntactic
438 sugar for assigning the anonymous function to the <member-expr>. Hence,
441 function a.b().c[2] (x, y) { ... }
445 a.b().c[2] = function(x, y) {...}
447 which doesn't seem particularly useful, but Rhino permits it."
453 (defmacro js2-deflocal (name value &optional comment)
454 "Define a buffer-local variable NAME with VALUE and COMMENT."
455 (declare (debug defvar) (doc-string 3))
457 (defvar ,name ,value ,comment)
458 (make-variable-buffer-local ',name)))
460 (defvar js2-EOF_CHAR -1
461 "Represents end of stream. Distinct from js2-EOF token type.")
463 ;; I originally used symbols to represent tokens, but Rhino uses
464 ;; ints and then sets various flag bits in them, so ints it is.
465 ;; The upshot is that we need a `js2-' prefix in front of each name.
466 (defvar js2-ERROR -1)
469 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
470 (defvar js2-LEAVEWITH 3)
471 (defvar js2-RETURN 4)
475 (defvar js2-SETNAME 8)
477 (defvar js2-BITXOR 10)
478 (defvar js2-BITAND 11)
488 (defvar js2-ADD 21) ; infix plus
489 (defvar js2-SUB 22) ; infix minus
494 (defvar js2-BITNOT 27)
495 (defvar js2-POS 28) ; unary plus
496 (defvar js2-NEG 29) ; unary minus
498 (defvar js2-DELPROP 31)
499 (defvar js2-TYPEOF 32)
500 (defvar js2-GETPROP 33)
501 (defvar js2-GETPROPNOWARN 34)
502 (defvar js2-SETPROP 35)
503 (defvar js2-GETELEM 36)
504 (defvar js2-SETELEM 37)
506 (defvar js2-NAME 39) ; an identifier
507 (defvar js2-NUMBER 40)
508 (defvar js2-STRING 41)
511 (defvar js2-FALSE 44)
513 (defvar js2-SHEQ 46) ; shallow equality (===)
514 (defvar js2-SHNE 47) ; shallow inequality (!==)
515 (defvar js2-REGEXP 48)
516 (defvar js2-BINDNAME 49)
517 (defvar js2-THROW 50)
518 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
520 (defvar js2-INSTANCEOF 53)
521 (defvar js2-LOCAL_LOAD 54)
522 (defvar js2-GETVAR 55)
523 (defvar js2-SETVAR 56)
524 (defvar js2-CATCH_SCOPE 57)
525 (defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
526 (defvar js2-ENUM_INIT_VALUES 59)
527 (defvar js2-ENUM_INIT_ARRAY 60)
528 (defvar js2-ENUM_NEXT 61)
529 (defvar js2-ENUM_ID 62)
530 (defvar js2-THISFN 63)
531 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
532 (defvar js2-ARRAYLIT 65) ; array literal
533 (defvar js2-OBJECTLIT 66) ; object literal
534 (defvar js2-GET_REF 67) ; *reference
535 (defvar js2-SET_REF 68) ; *reference = something
536 (defvar js2-DEL_REF 69) ; delete reference
537 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
538 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
539 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
542 (defvar js2-DEFAULTNAMESPACE 73)
543 (defvar js2-ESCXMLATTR 74)
544 (defvar js2-ESCXMLTEXT 75)
545 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
546 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
547 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
548 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
550 (defvar js2-first-bytecode js2-ENTERWITH)
551 (defvar js2-last-bytecode js2-REF_NS_NAME)
554 (defvar js2-SEMI 81) ; semicolon
555 (defvar js2-LB 82) ; left and right brackets
557 (defvar js2-LC 84) ; left and right curly-braces
559 (defvar js2-LP 86) ; left and right parens
561 (defvar js2-COMMA 88) ; comma operator
563 (defvar js2-ASSIGN 89) ; simple assignment (=)
564 (defvar js2-ASSIGN_BITOR 90) ; |=
565 (defvar js2-ASSIGN_BITXOR 91) ; ^=
566 (defvar js2-ASSIGN_BITAND 92) ; &=
567 (defvar js2-ASSIGN_LSH 93) ; <<=
568 (defvar js2-ASSIGN_RSH 94) ; >>=
569 (defvar js2-ASSIGN_URSH 95) ; >>>=
570 (defvar js2-ASSIGN_ADD 96) ; +=
571 (defvar js2-ASSIGN_SUB 97) ; -=
572 (defvar js2-ASSIGN_MUL 98) ; *=
573 (defvar js2-ASSIGN_DIV 99) ; /=
574 (defvar js2-ASSIGN_MOD 100) ; %=
576 (defvar js2-first-assign js2-ASSIGN)
577 (defvar js2-last-assign js2-ASSIGN_MOD)
579 (defvar js2-HOOK 101) ; conditional (?:)
580 (defvar js2-COLON 102)
581 (defvar js2-OR 103) ; logical or (||)
582 (defvar js2-AND 104) ; logical and (&&)
583 (defvar js2-INC 105) ; increment/decrement (++ --)
585 (defvar js2-DOT 107) ; member operator (.)
586 (defvar js2-FUNCTION 108) ; function keyword
587 (defvar js2-EXPORT 109) ; export keyword
588 (defvar js2-IMPORT 110) ; import keyword
589 (defvar js2-IF 111) ; if keyword
590 (defvar js2-ELSE 112) ; else keyword
591 (defvar js2-SWITCH 113) ; switch keyword
592 (defvar js2-CASE 114) ; case keyword
593 (defvar js2-DEFAULT 115) ; default keyword
594 (defvar js2-WHILE 116) ; while keyword
595 (defvar js2-DO 117) ; do keyword
596 (defvar js2-FOR 118) ; for keyword
597 (defvar js2-BREAK 119) ; break keyword
598 (defvar js2-CONTINUE 120) ; continue keyword
599 (defvar js2-VAR 121) ; var keyword
600 (defvar js2-WITH 122) ; with keyword
601 (defvar js2-CATCH 123) ; catch keyword
602 (defvar js2-FINALLY 124) ; finally keyword
603 (defvar js2-VOID 125) ; void keyword
604 (defvar js2-RESERVED 126) ; reserved keywords
606 (defvar js2-EMPTY 127)
608 ;; Types used for the parse tree - never returned by scanner.
610 (defvar js2-BLOCK 128) ; statement block
611 (defvar js2-LABEL 129) ; label
612 (defvar js2-TARGET 130)
613 (defvar js2-LOOP 131)
614 (defvar js2-EXPR_VOID 132) ; expression statement in functions
615 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
617 (defvar js2-SCRIPT 135) ; top-level node for entire script
618 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
619 (defvar js2-USE_STACK 137)
620 (defvar js2-SETPROP_OP 138) ; x.y op= something
621 (defvar js2-SETELEM_OP 139) ; x[y] op= something
622 (defvar js2-LOCAL_BLOCK 140)
623 (defvar js2-SET_REF_OP 141) ; *reference op= something
626 (defvar js2-DOTDOT 142) ; member operator (..)
627 (defvar js2-COLONCOLON 143) ; namespace::name
628 (defvar js2-XML 144) ; XML type
629 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
630 (defvar js2-XMLATTR 146) ; @
631 (defvar js2-XMLEND 147)
633 ;; Optimizer-only tokens
634 (defvar js2-TO_OBJECT 148)
635 (defvar js2-TO_DOUBLE 149)
637 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
638 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
639 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
640 (defvar js2-CONST 153)
641 (defvar js2-SETCONST 154)
642 (defvar js2-SETCONSTVAR 155)
643 (defvar js2-ARRAYCOMP 156)
644 (defvar js2-LETEXPR 157)
645 (defvar js2-WITHEXPR 158)
646 (defvar js2-DEBUGGER 159)
648 (defvar js2-COMMENT 160)
649 (defvar js2-TRIPLEDOT 161) ; for rest parameter
650 (defvar js2-ARROW 162) ; function arrow (=>)
651 (defvar js2-CLASS 163)
652 (defvar js2-EXTENDS 164)
653 (defvar js2-STATIC 165)
654 (defvar js2-SUPER 166)
655 (defvar js2-TEMPLATE_HEAD 167) ; part of template literal before substitution
656 (defvar js2-NO_SUBS_TEMPLATE 168) ; template literal without substitutions
657 (defvar js2-TAGGED_TEMPLATE 169) ; tagged template literal
659 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
661 (defconst js2-debug-print-trees nil)
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
675 (js2-deflocal js2-ts-hit-eof nil
676 "Token stream buffer-local variable.")
679 (js2-deflocal js2-ts-line-start 0
680 "Token stream buffer-local variable.")
682 (js2-deflocal js2-ts-lineno 1
683 "Token stream buffer-local variable.")
686 (js2-deflocal js2-ts-line-end-char -1
687 "Token stream buffer-local variable.")
689 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
690 "Token stream buffer-local variable.
691 Current scan position.")
694 (js2-deflocal js2-ts-is-xml-attribute nil
695 "Token stream buffer-local variable.")
697 (js2-deflocal js2-ts-xml-is-tag-content nil
698 "Token stream buffer-local variable.")
700 (js2-deflocal js2-ts-xml-open-tags-count 0
701 "Token stream buffer-local variable.")
703 (js2-deflocal js2-ts-string-buffer nil
704 "Token stream buffer-local variable.
705 List of chars built up while scanning various tokens.")
707 (cl-defstruct (js2-token
709 (:constructor make-js2-token (beg)))
710 "Value returned from the token stream."
720 ;; Have to call `js2-init-scanner' to initialize the values.
721 (js2-deflocal js2-ti-tokens nil)
722 (js2-deflocal js2-ti-tokens-cursor nil)
723 (js2-deflocal js2-ti-lookahead nil)
725 (cl-defstruct (js2-ts-state
726 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
727 (cursor js2-ts-cursor)
728 (tokens (copy-sequence js2-ti-tokens))
729 (tokens-cursor js2-ti-tokens-cursor)
730 (lookahead js2-ti-lookahead))))
739 (js2-deflocal js2-parsed-errors nil
740 "List of errors produced during scanning/parsing.")
742 (js2-deflocal js2-parsed-warnings nil
743 "List of warnings produced during scanning/parsing.")
745 (js2-deflocal js2-recover-from-parse-errors t
746 "Non-nil to continue parsing after a syntax error.
748 In recovery mode, the AST will be built in full, and any error
749 nodes will be flagged with appropriate error information. If
750 this flag is nil, a syntax error will result in an error being
753 The variable is automatically buffer-local, because different
754 modes that use the parser will need different settings.")
756 (js2-deflocal js2-parse-hook nil
757 "List of callbacks for receiving parsing progress.")
759 (defvar js2-parse-finished-hook nil
760 "List of callbacks to notify when parsing finishes.
761 Not called if parsing was interrupted.")
763 (js2-deflocal js2-is-eval-code nil
764 "True if we're evaluating code in a string.
765 If non-nil, the tokenizer will record the token text, and the AST nodes
766 will record their source text. Off by default for IDE modes, since the
767 text is available in the buffer.")
769 (defvar js2-parse-ide-mode t
770 "Non-nil if the parser is being used for `js2-mode'.
771 If non-nil, the parser will set text properties for fontification
772 and the syntax table. The value should be nil when using the
773 parser as a frontend to an interpreter or byte compiler.")
775 ;;; Parser instance variables (buffer-local vars for js2-parse)
777 (defconst js2-ti-after-eol (lsh 1 16)
778 "Flag: first token of the source line.")
780 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
782 (js2-deflocal js2-compiler-generate-debug-info t)
783 (js2-deflocal js2-compiler-use-dynamic-scope nil)
784 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
785 (js2-deflocal js2-compiler-xml-available t)
786 (js2-deflocal js2-compiler-optimization-level 0)
787 (js2-deflocal js2-compiler-generating-source t)
788 (js2-deflocal js2-compiler-strict-mode nil)
789 (js2-deflocal js2-compiler-report-warning-as-error nil)
790 (js2-deflocal js2-compiler-generate-observer-count nil)
791 (js2-deflocal js2-compiler-activation-names nil)
795 ;; There's a compileFunction method in Context.java - may need it.
796 (js2-deflocal js2-called-by-compile-function nil
797 "True if `js2-parse' was called by `js2-compile-function'.
798 Will only be used when we finish implementing the interpreter.")
800 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
802 ;; SKIP: node factory - we're going to just call functions directly,
803 ;; and eventually go to a unified AST format.
805 (js2-deflocal js2-nesting-of-function 0)
807 (js2-deflocal js2-recorded-identifiers nil
808 "Tracks identifiers found during parsing.")
810 (js2-deflocal js2-is-in-destructuring nil
811 "True while parsing destructuring expression.")
813 (defcustom js2-global-externs nil
814 "A list of any extern names you'd like to consider always declared.
815 This list is global and is used by all `js2-mode' files.
816 You can create buffer-local externs list using `js2-additional-externs'.
818 There is also a buffer-local variable `js2-default-externs',
819 which is initialized by default to include the Ecma-262 externs
820 and the standard browser externs. The three lists are all
821 checked during highlighting."
825 (js2-deflocal js2-default-externs nil
826 "Default external declarations.
828 These are currently only used for highlighting undeclared variables,
829 which only worries about top-level (unqualified) references.
830 As js2-mode's processing improves, we will flesh out this list.
832 The initial value is set to `js2-ecma-262-externs', unless some
833 of the `js2-include-?-externs' variables are set to t, in which
834 case the browser, Rhino and/or Node.js externs are also included.
836 See `js2-additional-externs' for more information.")
838 (defcustom js2-include-browser-externs t
839 "Non-nil to include browser externs in the master externs list.
840 If you work on JavaScript files that are not intended for browsers,
841 such as Mozilla Rhino server-side JavaScript, set this to nil.
842 See `js2-additional-externs' for more information about externs."
846 (defcustom js2-include-rhino-externs nil
847 "Non-nil to include Mozilla Rhino externs in the master externs list.
848 See `js2-additional-externs' for more information about externs."
852 (defcustom js2-include-node-externs nil
853 "Non-nil to include Node.js externs in the master externs list.
854 See `js2-additional-externs' for more information about externs."
858 (js2-deflocal js2-additional-externs nil
859 "A buffer-local list of additional external declarations.
860 It is used to decide whether variables are considered undeclared
861 for purposes of highlighting.
863 Each entry is a Lisp string. The string should be the fully qualified
864 name of an external entity. All externs should be added to this list,
865 so that as js2-mode's processing improves it can take advantage of them.
867 You may want to declare your externs in three ways.
868 First, you can add externs that are valid for all your JavaScript files.
869 You should probably do this by adding them to `js2-global-externs', which
870 is a global list used for all js2-mode files.
872 Next, you can add a function to `js2-init-hook' that adds additional
873 externs appropriate for the specific file, perhaps based on its path.
874 These should go in `js2-additional-externs', which is buffer-local.
876 Third, you can use JSLint's global declaration, as long as
877 `js2-include-jslint-globals' is non-nil, which see.
879 Finally, you can add a function to `js2-post-parse-callbacks',
880 which is called after parsing completes, and `js2-mode-ast' is bound to
881 the root of the parse tree. At this stage you can set up an AST
882 node visitor using `js2-visit-ast' and examine the parse tree
883 for specific import patterns that may imply the existence of
884 other externs, possibly tied to your build system. These should also
885 be added to `js2-additional-externs'.
887 Your post-parse callback may of course also use the simpler and
888 faster (but perhaps less robust) approach of simply scanning the
889 buffer text for your imports, using regular expressions.")
892 ;; SKIP: encoded-source
894 ;;; The following variables are per-function and should be saved/restored
895 ;;; during function parsing...
897 (js2-deflocal js2-current-script-or-fn nil)
898 (js2-deflocal js2-current-scope nil)
899 (js2-deflocal js2-nesting-of-with 0)
900 (js2-deflocal js2-label-set nil
901 "An alist mapping label names to nodes.")
903 (js2-deflocal js2-loop-set nil)
904 (js2-deflocal js2-loop-and-switch-set nil)
905 (js2-deflocal js2-has-return-value nil)
906 (js2-deflocal js2-end-flags 0)
908 ;;; ...end of per function variables
910 ;; These flags enumerate the possible ways a statement/function can
911 ;; terminate. These flags are used by endCheck() and by the Parser to
912 ;; detect inconsistent return usage.
914 ;; END_UNREACHED is reserved for code paths that are assumed to always be
915 ;; able to execute (example: throw, continue)
917 ;; END_DROPS_OFF indicates if the statement can transfer control to the
918 ;; next one. Statement such as return dont. A compound statement may have
919 ;; some branch that drops off control to the next statement.
921 ;; END_RETURNS indicates that the statement can return (without arguments)
922 ;; END_RETURNS_VALUE indicates that the statement can return a value.
924 ;; A compound statement such as
928 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
930 (defconst js2-end-unreached #x0)
931 (defconst js2-end-drops-off #x1)
932 (defconst js2-end-returns #x2)
933 (defconst js2-end-returns-value #x4)
935 ;; Rhino awkwardly passes a statementLabel parameter to the
936 ;; statementHelper() function, the main statement parser, which
937 ;; is then used by quite a few of the sub-parsers. We just make
938 ;; it a buffer-local variable and make sure it's cleaned up properly.
939 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
941 ;; Similarly, Rhino passes an inForInit boolean through about half
942 ;; the expression parsers. We use a dynamically-scoped variable,
943 ;; which makes it easier to funcall the parsers individually without
944 ;; worrying about whether they take the parameter or not.
945 (js2-deflocal js2-in-for-init nil)
946 (js2-deflocal js2-temp-name-counter 0)
947 (js2-deflocal js2-parse-stmt-count 0)
949 (defsubst js2-get-next-temp-name ()
950 (format "$%d" (cl-incf js2-temp-name-counter)))
952 (defvar js2-parse-interruptable-p t
953 "Set this to nil to force parse to continue until finished.
954 This will mostly be useful for interpreters.")
956 (defvar js2-statements-per-pause 50
957 "Pause after this many statements to check for user input.
958 If user input is pending, stop the parse and discard the tree.
959 This makes for a smoother user experience for large files.
960 You may have to wait a second or two before the highlighting
961 and error-reporting appear, but you can always type ahead if
962 you wish. This appears to be more or less how Eclipse, IntelliJ
963 and other editors work.")
965 (js2-deflocal js2-record-comments t
966 "Instructs the scanner to record comments in `js2-scanned-comments'.")
968 (js2-deflocal js2-scanned-comments nil
969 "List of all comments from the current parse.")
971 (defcustom js2-mode-indent-inhibit-undo nil
972 "Non-nil to disable collection of Undo information when indenting lines.
973 Some users have requested this behavior. It's nil by default because
974 other Emacs modes don't work this way."
978 (defcustom js2-mode-indent-ignore-first-tab nil
979 "If non-nil, ignore first TAB keypress if we look indented properly.
980 It's fairly common for users to navigate to an already-indented line
981 and press TAB for reassurance that it's been indented. For this class
982 of users, we want the first TAB press on a line to be ignored if the
983 line is already indented to one of the precomputed alternatives.
985 This behavior is only partly implemented. If you TAB-indent a line,
986 navigate to another line, and then navigate back, it fails to clear
987 the last-indented variable, so it thinks you've already hit TAB once,
988 and performs the indent. A full solution would involve getting on the
989 point-motion hooks for the entire buffer. If we come across another
990 use cases that requires watching point motion, I'll consider doing it.
992 If you set this variable to nil, then the TAB key will always change
993 the indentation of the current line, if more than one alternative
994 indentation spot exists."
998 (defvar js2-indent-hook nil
999 "A hook for user-defined indentation rules.
1001 Functions on this hook should expect two arguments: (LIST INDEX)
1002 The LIST argument is the list of computed indentation points for
1003 the current line. INDEX is the list index of the indentation point
1004 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1005 indent function is not going to change the current line indentation.
1007 If a hook function on this list returns a non-nil value, then
1008 `js2-bounce-indent' assumes the hook function has performed its own
1009 indentation, and will do nothing. If all hook functions on the list
1010 return nil, then `js2-bounce-indent' will use its computed indentation
1011 and reindent the line.
1013 When hook functions on this hook list are called, the variable
1014 `js2-mode-ast' may or may not be set, depending on whether the
1015 parse tree is available. If the variable is nil, you can pass a
1016 callback to `js2-mode-wait-for-parse', and your callback will be
1017 called after the new parse tree is built. This can take some time
1020 (defface js2-warning
1021 `((((class color) (background light))
1022 (:underline "orange"))
1023 (((class color) (background dark))
1024 (:underline "orange"))
1026 "Face for JavaScript warnings."
1030 `((((class color) (background light))
1031 (:foreground "red"))
1032 (((class color) (background dark))
1033 (:foreground "red"))
1034 (t (:foreground "red")))
1035 "Face for JavaScript errors."
1038 (defface js2-jsdoc-tag
1039 '((t :foreground "SlateGray"))
1040 "Face used to highlight @whatever tags in jsdoc comments."
1043 (defface js2-jsdoc-type
1044 '((t :foreground "SteelBlue"))
1045 "Face used to highlight {FooBar} types in jsdoc comments."
1048 (defface js2-jsdoc-value
1049 '((t :foreground "PeachPuff3"))
1050 "Face used to highlight tag values in jsdoc comments."
1053 (defface js2-function-param
1054 '((t :foreground "SeaGreen"))
1055 "Face used to highlight function parameters in javascript."
1058 (defface js2-function-call
1059 '((t :inherit default))
1060 "Face used to highlight function name in calls."
1063 (defface js2-instance-member
1064 '((t :foreground "DarkOrchid"))
1065 "Face used to highlight instance variables in javascript.
1066 Not currently used."
1069 (defface js2-private-member
1070 '((t :foreground "PeachPuff3"))
1071 "Face used to highlight calls to private methods in javascript.
1072 Not currently used."
1075 (defface js2-private-function-call
1076 '((t :foreground "goldenrod"))
1077 "Face used to highlight calls to private functions in javascript.
1078 Not currently used."
1081 (defface js2-jsdoc-html-tag-name
1082 '((((class color) (min-colors 88) (background light))
1083 (:foreground "rosybrown"))
1084 (((class color) (min-colors 8) (background dark))
1085 (:foreground "yellow"))
1086 (((class color) (min-colors 8) (background light))
1087 (:foreground "magenta")))
1088 "Face used to highlight jsdoc html tag names"
1091 (defface js2-jsdoc-html-tag-delimiter
1092 '((((class color) (min-colors 88) (background light))
1093 (:foreground "dark khaki"))
1094 (((class color) (min-colors 8) (background dark))
1095 (:foreground "green"))
1096 (((class color) (min-colors 8) (background light))
1097 (:foreground "green")))
1098 "Face used to highlight brackets in jsdoc html tags."
1101 (defface js2-external-variable
1102 '((t :foreground "orange"))
1103 "Face used to highlight undeclared variable identifiers.")
1105 (defcustom js2-init-hook nil
1106 "List of functions to be called after `js2-mode' or
1107 `js2-minor-mode' has initialized all variables, before parsing
1108 the buffer for the first time."
1111 :version "20130608")
1113 (defcustom js2-post-parse-callbacks nil
1114 "List of callback functions invoked after parsing finishes.
1115 Currently, the main use for this function is to add synthetic
1116 declarations to `js2-recorded-identifiers', which see."
1120 (defcustom js2-build-imenu-callbacks nil
1121 "List of functions called during Imenu index generation.
1122 It's a good place to add additional entries to it, using
1123 `js2-record-imenu-entry'."
1127 (defcustom js2-highlight-external-variables t
1128 "Non-nil to highlight undeclared variable identifiers.
1129 An undeclared variable is any variable not declared with var or let
1130 in the current scope or any lexically enclosing scope. If you use
1131 such a variable, then you are either expecting it to originate from
1132 another file, or you've got a potential bug."
1136 (defcustom js2-include-jslint-globals t
1137 "Non-nil to include the identifiers from JSLint global
1138 declaration (see http://www.jslint.com/lint.html#global) in the
1139 buffer-local externs list. See `js2-additional-externs' for more
1144 (defvar js2-mode-map
1145 (let ((map (make-sparse-keymap)))
1146 (define-key map [mouse-1] #'js2-mode-show-node)
1147 (define-key map (kbd "M-j") #'js2-line-break)
1148 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1149 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1150 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1151 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1152 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1153 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1154 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1155 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1156 (when js2-bounce-indent-p
1157 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1159 (define-key map [menu-bar javascript]
1160 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1162 (define-key map [menu-bar javascript customize-js2-mode]
1163 '(menu-item "Customize js2-mode" js2-mode-customize
1164 :help "Customize the behavior of this mode"))
1166 (define-key map [menu-bar javascript js2-force-refresh]
1167 '(menu-item "Force buffer refresh" js2-mode-reset
1168 :help "Re-parse the buffer from scratch"))
1170 (define-key map [menu-bar javascript separator-2]
1173 (define-key map [menu-bar javascript next-error]
1174 '(menu-item "Next warning or error" next-error
1175 :enabled (and js2-mode-ast
1176 (or (js2-ast-root-errors js2-mode-ast)
1177 (js2-ast-root-warnings js2-mode-ast)))
1178 :help "Move to next warning or error"))
1180 (define-key map [menu-bar javascript display-errors]
1181 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1182 :visible (not js2-mode-show-parse-errors)
1183 :help "Turn on display of warnings and errors"))
1185 (define-key map [menu-bar javascript hide-errors]
1186 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1187 :visible js2-mode-show-parse-errors
1188 :help "Turn off display of warnings and errors"))
1190 (define-key map [menu-bar javascript separator-1]
1193 (define-key map [menu-bar javascript js2-toggle-function]
1194 '(menu-item "Show/collapse element" js2-mode-toggle-element
1195 :help "Hide or show function body or comment"))
1197 (define-key map [menu-bar javascript show-comments]
1198 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1199 :visible js2-mode-comments-hidden
1200 :help "Expand all hidden block comments"))
1202 (define-key map [menu-bar javascript hide-comments]
1203 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1204 :visible (not js2-mode-comments-hidden)
1205 :help "Show block comments as /*...*/"))
1207 (define-key map [menu-bar javascript show-all-functions]
1208 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1209 :visible js2-mode-functions-hidden
1210 :help "Expand all hidden function bodies"))
1212 (define-key map [menu-bar javascript hide-all-functions]
1213 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1214 :visible (not js2-mode-functions-hidden)
1215 :help "Show {...} for all top-level function bodies"))
1218 "Keymap used in `js2-mode' buffers.")
1220 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1222 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1223 "Matches a //-comment line. Must be first non-whitespace on line.
1224 First match-group is the leading whitespace.")
1226 (defvar js2-mode-hook nil)
1228 (js2-deflocal js2-mode-ast nil "Private variable.")
1229 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1230 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1231 (js2-deflocal js2-mode-parsing nil "Private variable.")
1232 (js2-deflocal js2-mode-node-overlay nil)
1234 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1235 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1237 (js2-deflocal js2-mode-fontifications nil "Private variable")
1238 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1239 (js2-deflocal js2-imenu-recorder nil "Private variable")
1240 (js2-deflocal js2-imenu-function-map nil "Private variable")
1242 (defvar js2-paragraph-start
1243 "\\(@[[:alpha:]]+\\>\\|$\\)")
1245 ;; Note that we also set a 'c-in-sws text property in html comments,
1246 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1247 (defvar js2-syntactic-ws-start
1248 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1250 (defvar js2-syntactic-ws-end
1251 "\\s \\|[\n\r/]\\|\\s!")
1253 (defvar js2-syntactic-eol
1254 (concat "\\s *\\(/\\*[^*\n\r]*"
1255 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1257 "\\(//\\|/\\*[^*\n\r]*"
1258 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1260 "Copied from `java-mode'. Needed for some cc-engine functions.")
1262 (defvar js2-comment-prefix-regexp
1265 (defvar js2-comment-start-skip
1266 "\\(//+\\|/\\*+\\)\\s *")
1268 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1269 "Non-nil to emit status messages during parsing.")
1271 (defvar js2-mode-functions-hidden nil "Private variable.")
1272 (defvar js2-mode-comments-hidden nil "Private variable.")
1274 (defvar js2-mode-syntax-table
1275 (let ((table (make-syntax-table)))
1276 (c-populate-syntax-table table)
1278 "Syntax table used in `js2-mode' buffers.")
1280 (defvar js2-mode-abbrev-table nil
1281 "Abbrev table in use in `js2-mode' buffers.")
1282 (define-abbrev-table 'js2-mode-abbrev-table ())
1284 (defvar js2-mode-pending-parse-callbacks nil
1285 "List of functions waiting to be notified that parse is finished.")
1287 (defvar js2-mode-last-indented-line -1)
1289 ;;; Localizable error and warning messages
1291 ;; Messages are copied from Rhino's Messages.properties.
1292 ;; Many of the Java-specific messages have been elided.
1293 ;; Add any js2-specific ones at the end, so we can keep
1294 ;; this file synced with changes to Rhino's.
1296 (defvar js2-message-table
1297 (make-hash-table :test 'equal :size 250)
1298 "Contains localized messages for `js2-mode'.")
1300 ;; TODO(stevey): construct this table at compile-time.
1301 (defmacro js2-msg (key &rest strings)
1302 `(puthash ,key (concat ,@strings)
1305 (defun js2-get-msg (msg-key)
1306 "Look up a localized message.
1307 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1308 the correct number of ARGS must be provided."
1309 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1310 (args (if (listp msg-key) (cdr msg-key)))
1311 (msg (gethash key js2-message-table)))
1313 (apply #'format msg args)
1314 key))) ; default to showing the key
1316 (js2-msg "msg.dup.parms"
1317 "Duplicate parameter name '%s'.")
1319 (js2-msg "msg.too.big.jump"
1320 "Program too complex: jump offset too big.")
1322 (js2-msg "msg.too.big.index"
1323 "Program too complex: internal index exceeds 64K limit.")
1325 (js2-msg "msg.while.compiling.fn"
1326 "Encountered code generation error while compiling function '%s': %s")
1328 (js2-msg "msg.while.compiling.script"
1329 "Encountered code generation error while compiling script: %s")
1332 (js2-msg "msg.ctor.not.found"
1333 "Constructor for '%s' not found.")
1335 (js2-msg "msg.not.ctor"
1336 "'%s' is not a constructor.")
1339 (js2-msg "msg.varargs.ctor"
1340 "Method or constructor '%s' must be static "
1341 "with the signature (Context cx, Object[] args, "
1342 "Function ctorObj, boolean inNewExpr) "
1343 "to define a variable arguments constructor.")
1345 (js2-msg "msg.varargs.fun"
1346 "Method '%s' must be static with the signature "
1347 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1348 "to define a variable arguments function.")
1350 (js2-msg "msg.incompat.call"
1351 "Method '%s' called on incompatible object.")
1353 (js2-msg "msg.bad.parms"
1354 "Unsupported parameter type '%s' in method '%s'.")
1356 (js2-msg "msg.bad.method.return"
1357 "Unsupported return type '%s' in method '%s'.")
1359 (js2-msg "msg.bad.ctor.return"
1360 "Construction of objects of type '%s' is not supported.")
1362 (js2-msg "msg.no.overload"
1363 "Method '%s' occurs multiple times in class '%s'.")
1365 (js2-msg "msg.method.not.found"
1366 "Method '%s' not found in '%s'.")
1370 (js2-msg "msg.bad.for.in.lhs"
1371 "Invalid left-hand side of for..in loop.")
1373 (js2-msg "msg.mult.index"
1374 "Only one variable allowed in for..in loop.")
1376 (js2-msg "msg.bad.for.in.destruct"
1377 "Left hand side of for..in loop must be an array of "
1378 "length 2 to accept key/value pair.")
1380 (js2-msg "msg.cant.convert"
1381 "Can't convert to type '%s'.")
1383 (js2-msg "msg.bad.assign.left"
1384 "Invalid assignment left-hand side.")
1386 (js2-msg "msg.bad.decr"
1387 "Invalid decerement operand.")
1389 (js2-msg "msg.bad.incr"
1390 "Invalid increment operand.")
1392 (js2-msg "msg.bad.yield"
1393 "yield must be in a function.")
1395 (js2-msg "msg.yield.parenthesized"
1396 "yield expression must be parenthesized.")
1399 (js2-msg "msg.cant.call.indirect"
1400 "Function '%s' must be called directly, and not by way of a "
1401 "function of another name.")
1403 (js2-msg "msg.eval.nonstring"
1404 "Calling eval() with anything other than a primitive "
1405 "string value will simply return the value. "
1406 "Is this what you intended?")
1408 (js2-msg "msg.eval.nonstring.strict"
1409 "Calling eval() with anything other than a primitive "
1410 "string value is not allowed in strict mode.")
1412 (js2-msg "msg.bad.destruct.op"
1413 "Invalid destructuring assignment operator")
1416 (js2-msg "msg.only.from.new"
1417 "'%s' may only be invoked from a `new' expression.")
1419 (js2-msg "msg.deprec.ctor"
1420 "The '%s' constructor is deprecated.")
1423 (js2-msg "msg.no.function.ref.found"
1424 "no source found to decompile function reference %s")
1426 (js2-msg "msg.arg.isnt.array"
1427 "second argument to Function.prototype.apply must be an array")
1430 (js2-msg "msg.bad.esc.mask"
1431 "invalid string escape mask")
1434 (js2-msg "msg.bad.quant"
1435 "Invalid quantifier %s")
1437 (js2-msg "msg.overlarge.backref"
1438 "Overly large back reference %s")
1440 (js2-msg "msg.overlarge.min"
1441 "Overly large minimum %s")
1443 (js2-msg "msg.overlarge.max"
1444 "Overly large maximum %s")
1446 (js2-msg "msg.zero.quant"
1447 "Zero quantifier %s")
1449 (js2-msg "msg.max.lt.min"
1450 "Maximum %s less than minimum")
1452 (js2-msg "msg.unterm.quant"
1453 "Unterminated quantifier %s")
1455 (js2-msg "msg.unterm.paren"
1456 "Unterminated parenthetical %s")
1458 (js2-msg "msg.unterm.class"
1459 "Unterminated character class %s")
1461 (js2-msg "msg.bad.range"
1462 "Invalid range in character class.")
1464 (js2-msg "msg.trail.backslash"
1465 "Trailing \\ in regular expression.")
1467 (js2-msg "msg.re.unmatched.right.paren"
1468 "unmatched ) in regular expression.")
1470 (js2-msg "msg.no.regexp"
1471 "Regular expressions are not available.")
1473 (js2-msg "msg.bad.backref"
1474 "back-reference exceeds number of capturing parentheses.")
1476 (js2-msg "msg.bad.regexp.compile"
1477 "Only one argument may be specified if the first "
1478 "argument to RegExp.prototype.compile is a RegExp object.")
1481 (js2-msg "msg.got.syntax.errors"
1482 "Compilation produced %s syntax errors.")
1484 (js2-msg "msg.var.redecl"
1485 "TypeError: redeclaration of var %s.")
1487 (js2-msg "msg.const.redecl"
1488 "TypeError: redeclaration of const %s.")
1490 (js2-msg "msg.let.redecl"
1491 "TypeError: redeclaration of variable %s.")
1493 (js2-msg "msg.parm.redecl"
1494 "TypeError: redeclaration of formal parameter %s.")
1496 (js2-msg "msg.fn.redecl"
1497 "TypeError: redeclaration of function %s.")
1499 (js2-msg "msg.let.decl.not.in.block"
1500 "SyntaxError: let declaration not directly within block")
1502 (js2-msg "msg.mod.import.decl.at.top.level"
1503 "SyntaxError: import declarations may only appear at the top level")
1505 (js2-msg "msg.mod.as.after.reserved.word"
1506 "SyntaxError: missing keyword 'as' after reserved word %s")
1508 (js2-msg "msg.mod.rc.after.import.spec.list"
1509 "SyntaxError: missing '}' after module specifier list")
1511 (js2-msg "msg.mod.from.after.import.spec.set"
1512 "SyntaxError: missing keyword 'from' after import specifier set")
1514 (js2-msg "msg.mod.declaration.after.import"
1515 "SyntaxError: missing declaration after 'import' keyword")
1517 (js2-msg "msg.mod.spec.after.from"
1518 "SyntaxError: missing module specifier after 'from' keyword")
1520 (js2-msg "msg.mod.export.decl.at.top.level"
1521 "SyntaxError: export declarations may only appear at top level")
1523 (js2-msg "msg.mod.rc.after.export.spec.list"
1524 "SyntaxError: missing '}' after export specifier list")
1527 (js2-msg "msg.dup.label"
1530 (js2-msg "msg.undef.label"
1533 (js2-msg "msg.bad.break"
1534 "unlabelled break must be inside loop or switch")
1536 (js2-msg "msg.continue.outside"
1537 "continue must be inside loop")
1539 (js2-msg "msg.continue.nonloop"
1540 "continue can only use labels of iteration statements")
1542 (js2-msg "msg.bad.throw.eol"
1543 "Line terminator is not allowed between the throw "
1544 "keyword and throw expression.")
1546 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1547 "function statement requires a name")
1549 (js2-msg "msg.no.paren.parms"
1550 "missing ( before function parameters.")
1552 (js2-msg "msg.no.parm"
1553 "missing formal parameter")
1555 (js2-msg "msg.no.paren.after.parms"
1556 "missing ) after formal parameters")
1558 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1559 "parameter without default follows parameter with default")
1561 (js2-msg "msg.param.after.rest" ; added by js2-mode
1562 "parameter after rest parameter")
1564 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1565 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1567 (js2-msg "msg.no.brace.body"
1568 "missing '{' before function body")
1570 (js2-msg "msg.no.brace.after.body"
1571 "missing } after function body")
1573 (js2-msg "msg.no.paren.cond"
1574 "missing ( before condition")
1576 (js2-msg "msg.no.paren.after.cond"
1577 "missing ) after condition")
1579 (js2-msg "msg.no.semi.stmt"
1580 "missing ; before statement")
1582 (js2-msg "msg.missing.semi"
1583 "missing ; after statement")
1585 (js2-msg "msg.no.name.after.dot"
1586 "missing name after . operator")
1588 (js2-msg "msg.no.name.after.coloncolon"
1589 "missing name after :: operator")
1591 (js2-msg "msg.no.name.after.dotdot"
1592 "missing name after .. operator")
1594 (js2-msg "msg.no.name.after.xmlAttr"
1595 "missing name after .@")
1597 (js2-msg "msg.no.bracket.index"
1598 "missing ] in index expression")
1600 (js2-msg "msg.no.paren.switch"
1601 "missing ( before switch expression")
1603 (js2-msg "msg.no.paren.after.switch"
1604 "missing ) after switch expression")
1606 (js2-msg "msg.no.brace.switch"
1607 "missing '{' before switch body")
1609 (js2-msg "msg.bad.switch"
1610 "invalid switch statement")
1612 (js2-msg "msg.no.colon.case"
1613 "missing : after case expression")
1615 (js2-msg "msg.double.switch.default"
1616 "double default label in the switch statement")
1618 (js2-msg "msg.no.while.do"
1619 "missing while after do-loop body")
1621 (js2-msg "msg.no.paren.for"
1622 "missing ( after for")
1624 (js2-msg "msg.no.semi.for"
1625 "missing ; after for-loop initializer")
1627 (js2-msg "msg.no.semi.for.cond"
1628 "missing ; after for-loop condition")
1630 (js2-msg "msg.in.after.for.name"
1631 "missing in or of after for")
1633 (js2-msg "msg.no.paren.for.ctrl"
1634 "missing ) after for-loop control")
1636 (js2-msg "msg.no.paren.with"
1637 "missing ( before with-statement object")
1639 (js2-msg "msg.no.paren.after.with"
1640 "missing ) after with-statement object")
1642 (js2-msg "msg.no.paren.after.let"
1643 "missing ( after let")
1645 (js2-msg "msg.no.paren.let"
1646 "missing ) after variable list")
1648 (js2-msg "msg.no.curly.let"
1649 "missing } after let statement")
1651 (js2-msg "msg.bad.return"
1654 (js2-msg "msg.no.brace.block"
1655 "missing } in compound statement")
1657 (js2-msg "msg.bad.label"
1660 (js2-msg "msg.bad.var"
1661 "missing variable name")
1663 (js2-msg "msg.bad.var.init"
1664 "invalid variable initialization")
1666 (js2-msg "msg.no.colon.cond"
1667 "missing : in conditional expression")
1669 (js2-msg "msg.no.paren.arg"
1670 "missing ) after argument list")
1672 (js2-msg "msg.no.bracket.arg"
1673 "missing ] after element list")
1675 (js2-msg "msg.bad.prop"
1676 "invalid property id")
1678 (js2-msg "msg.no.colon.prop"
1679 "missing : after property id")
1681 (js2-msg "msg.no.brace.prop"
1682 "missing } after property list")
1684 (js2-msg "msg.no.paren"
1685 "missing ) in parenthetical")
1687 (js2-msg "msg.reserved.id"
1688 "'%s' is a reserved identifier")
1690 (js2-msg "msg.no.paren.catch"
1691 "missing ( before catch-block condition")
1693 (js2-msg "msg.bad.catchcond"
1694 "invalid catch block condition")
1696 (js2-msg "msg.catch.unreachable"
1697 "any catch clauses following an unqualified catch are unreachable")
1699 (js2-msg "msg.no.brace.try"
1700 "missing '{' before try block")
1702 (js2-msg "msg.no.brace.catchblock"
1703 "missing '{' before catch-block body")
1705 (js2-msg "msg.try.no.catchfinally"
1706 "'try' without 'catch' or 'finally'")
1708 (js2-msg "msg.no.return.value"
1709 "function %s does not always return a value")
1711 (js2-msg "msg.anon.no.return.value"
1712 "anonymous function does not always return a value")
1714 (js2-msg "msg.return.inconsistent"
1715 "return statement is inconsistent with previous usage")
1717 (js2-msg "msg.generator.returns"
1718 "TypeError: legacy generator function '%s' returns a value")
1720 (js2-msg "msg.anon.generator.returns"
1721 "TypeError: anonymous legacy generator function returns a value")
1723 (js2-msg "msg.syntax"
1726 (js2-msg "msg.unexpected.eof"
1727 "Unexpected end of file")
1729 (js2-msg "msg.XML.bad.form"
1730 "illegally formed XML syntax")
1732 (js2-msg "msg.XML.not.available"
1733 "XML runtime not available")
1735 (js2-msg "msg.too.deep.parser.recursion"
1736 "Too deep recursion while parsing")
1738 (js2-msg "msg.no.side.effects"
1739 "Code has no side effects")
1741 (js2-msg "msg.extra.trailing.comma"
1742 "Trailing comma is not supported in some browsers")
1744 (js2-msg "msg.array.trailing.comma"
1745 "Trailing comma yields different behavior across browsers")
1747 (js2-msg "msg.equal.as.assign"
1748 (concat "Test for equality (==) mistyped as assignment (=)?"
1749 " (parenthesize to suppress warning)"))
1751 (js2-msg "msg.var.hides.arg"
1752 "Variable %s hides argument")
1754 (js2-msg "msg.destruct.assign.no.init"
1755 "Missing = in destructuring declaration")
1758 (js2-msg "msg.no.properties"
1759 "%s has no properties.")
1761 (js2-msg "msg.invalid.iterator"
1762 "Invalid iterator value")
1764 (js2-msg "msg.iterator.primitive"
1765 "__iterator__ returned a primitive value")
1767 (js2-msg "msg.assn.create.strict"
1768 "Assignment to undeclared variable %s")
1770 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1771 "Undeclared variable or function '%s'")
1773 (js2-msg "msg.ref.undefined.prop"
1774 "Reference to undefined property '%s'")
1776 (js2-msg "msg.prop.not.found"
1777 "Property %s not found.")
1779 (js2-msg "msg.invalid.type"
1780 "Invalid JavaScript value of type %s")
1782 (js2-msg "msg.primitive.expected"
1783 "Primitive type expected (had %s instead)")
1785 (js2-msg "msg.namespace.expected"
1786 "Namespace object expected to left of :: (found %s instead)")
1788 (js2-msg "msg.null.to.object"
1789 "Cannot convert null to an object.")
1791 (js2-msg "msg.undef.to.object"
1792 "Cannot convert undefined to an object.")
1794 (js2-msg "msg.cyclic.value"
1795 "Cyclic %s value not allowed.")
1797 (js2-msg "msg.is.not.defined"
1798 "'%s' is not defined.")
1800 (js2-msg "msg.undef.prop.read"
1801 "Cannot read property '%s' from %s")
1803 (js2-msg "msg.undef.prop.write"
1804 "Cannot set property '%s' of %s to '%s'")
1806 (js2-msg "msg.undef.prop.delete"
1807 "Cannot delete property '%s' of %s")
1809 (js2-msg "msg.undef.method.call"
1810 "Cannot call method '%s' of %s")
1812 (js2-msg "msg.undef.with"
1813 "Cannot apply 'with' to %s")
1815 (js2-msg "msg.isnt.function"
1816 "%s is not a function, it is %s.")
1818 (js2-msg "msg.isnt.function.in"
1819 "Cannot call property %s in object %s. "
1820 "It is not a function, it is '%s'.")
1822 (js2-msg "msg.function.not.found"
1823 "Cannot find function %s.")
1825 (js2-msg "msg.function.not.found.in"
1826 "Cannot find function %s in object %s.")
1828 (js2-msg "msg.isnt.xml.object"
1829 "%s is not an xml object.")
1831 (js2-msg "msg.no.ref.to.get"
1832 "%s is not a reference to read reference value.")
1834 (js2-msg "msg.no.ref.to.set"
1835 "%s is not a reference to set reference value to %s.")
1837 (js2-msg "msg.no.ref.from.function"
1838 "Function %s can not be used as the left-hand "
1839 "side of assignment or as an operand of ++ or -- operator.")
1841 (js2-msg "msg.bad.default.value"
1842 "Object's getDefaultValue() method returned an object.")
1844 (js2-msg "msg.instanceof.not.object"
1845 "Can't use instanceof on a non-object.")
1847 (js2-msg "msg.instanceof.bad.prototype"
1848 "'prototype' property of %s is not an object.")
1850 (js2-msg "msg.bad.radix"
1851 "illegal radix %s.")
1854 (js2-msg "msg.default.value"
1855 "Cannot find default value for object.")
1857 (js2-msg "msg.zero.arg.ctor"
1858 "Cannot load class '%s' which has no zero-parameter constructor.")
1860 (js2-msg "msg.ctor.multiple.parms"
1861 "Can't define constructor or class %s since more than "
1862 "one constructor has multiple parameters.")
1864 (js2-msg "msg.extend.scriptable"
1865 "%s must extend ScriptableObject in order to define property %s.")
1867 (js2-msg "msg.bad.getter.parms"
1868 "In order to define a property, getter %s must have zero "
1869 "parameters or a single ScriptableObject parameter.")
1871 (js2-msg "msg.obj.getter.parms"
1872 "Expected static or delegated getter %s to take "
1873 "a ScriptableObject parameter.")
1875 (js2-msg "msg.getter.static"
1876 "Getter and setter must both be static or neither be static.")
1878 (js2-msg "msg.setter.return"
1879 "Setter must have void return type: %s")
1881 (js2-msg "msg.setter2.parms"
1882 "Two-parameter setter must take a ScriptableObject as "
1883 "its first parameter.")
1885 (js2-msg "msg.setter1.parms"
1886 "Expected single parameter setter for %s")
1888 (js2-msg "msg.setter2.expected"
1889 "Expected static or delegated setter %s to take two parameters.")
1891 (js2-msg "msg.setter.parms"
1892 "Expected either one or two parameters for setter.")
1894 (js2-msg "msg.setter.bad.type"
1895 "Unsupported parameter type '%s' in setter '%s'.")
1897 (js2-msg "msg.add.sealed"
1898 "Cannot add a property to a sealed object: %s.")
1900 (js2-msg "msg.remove.sealed"
1901 "Cannot remove a property from a sealed object: %s.")
1903 (js2-msg "msg.modify.sealed"
1904 "Cannot modify a property of a sealed object: %s.")
1906 (js2-msg "msg.modify.readonly"
1907 "Cannot modify readonly property: %s.")
1910 (js2-msg "msg.missing.exponent"
1913 (js2-msg "msg.caught.nfe"
1914 "number format error")
1916 (js2-msg "msg.unterminated.string.lit"
1917 "unterminated string literal")
1919 (js2-msg "msg.unterminated.comment"
1920 "unterminated comment")
1922 (js2-msg "msg.unterminated.re.lit"
1923 "unterminated regular expression literal")
1925 (js2-msg "msg.invalid.re.flag"
1926 "invalid flag after regular expression")
1928 (js2-msg "msg.no.re.input.for"
1931 (js2-msg "msg.illegal.character"
1932 "illegal character")
1934 (js2-msg "msg.invalid.escape"
1935 "invalid Unicode escape sequence")
1937 (js2-msg "msg.bad.namespace"
1938 "not a valid default namespace statement. "
1939 "Syntax is: default xml namespace = EXPRESSION;")
1941 ;; TokensStream warnings
1942 (js2-msg "msg.bad.octal.literal"
1943 "illegal octal literal digit %s; "
1944 "interpreting it as a decimal digit")
1946 (js2-msg "msg.missing.hex.digits"
1947 "missing hexadecimal digits after '0x'")
1949 (js2-msg "msg.missing.binary.digits"
1950 "missing binary digits after '0b'")
1952 (js2-msg "msg.missing.octal.digits"
1953 "missing octal digits after '0o'")
1955 (js2-msg "msg.script.is.not.constructor"
1956 "Script objects are not constructors.")
1959 (js2-msg "msg.arraylength.bad"
1960 "Inappropriate array length.")
1963 (js2-msg "msg.arraylength.too.big"
1964 "Array length %s exceeds supported capacity limit.")
1967 (js2-msg "msg.bad.uri"
1968 "Malformed URI sequence.")
1971 (js2-msg "msg.bad.precision"
1972 "Precision %s out of range.")
1975 (js2-msg "msg.send.newborn"
1976 "Attempt to send value to newborn generator")
1978 (js2-msg "msg.already.exec.gen"
1979 "Already executing generator")
1981 (js2-msg "msg.StopIteration.invalid"
1982 "StopIteration may not be changed to an arbitrary object.")
1985 (js2-msg "msg.yield.closing"
1986 "Yield from closing generator")
1989 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1990 "class statement requires a name")
1992 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1993 "unexpected ',' between class properties")
1995 (js2-msg "msg.unexpected.static" ; added by js2-mode
1996 "unexpected 'static'")
1998 (js2-msg "msg.missing.extends" ; added by js2-mode
1999 "name is required after extends")
2001 (js2-msg "msg.no.brace.class" ; added by js2-mode
2002 "missing '{' before class body")
2004 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2005 "missing ']' after computed property expression")
2009 (defconst js2-ti-max-lookahead 2)
2010 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2012 (defun js2-new-token (offset)
2013 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2014 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2015 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2018 (defsubst js2-current-token ()
2019 (aref js2-ti-tokens js2-ti-tokens-cursor))
2021 (defsubst js2-current-token-string ()
2022 (js2-token-string (js2-current-token)))
2024 (defsubst js2-current-token-type ()
2025 (js2-token-type (js2-current-token)))
2027 (defsubst js2-current-token-beg ()
2028 (js2-token-beg (js2-current-token)))
2030 (defsubst js2-current-token-end ()
2031 (js2-token-end (js2-current-token)))
2033 (defun js2-current-token-len ()
2034 (let ((token (js2-current-token)))
2035 (- (js2-token-end token)
2036 (js2-token-beg token))))
2038 (defun js2-ts-seek (state)
2039 (setq js2-ts-lineno (js2-ts-state-lineno state)
2040 js2-ts-cursor (js2-ts-state-cursor state)
2041 js2-ti-tokens (js2-ts-state-tokens state)
2042 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2043 js2-ti-lookahead (js2-ts-state-lookahead state)))
2047 (defun js2-delete-if (predicate list)
2048 "Remove all items satisfying PREDICATE in LIST."
2049 (cl-loop for item in list
2050 if (not (funcall predicate item))
2053 (defun js2-position (element list)
2054 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2055 Returns nil if element is not found in the list."
2058 (while (and list (not found))
2059 (if (eq element (car list))
2061 (setq count (1+ count)
2065 (defun js2-find-if (predicate list)
2066 "Find first item satisfying PREDICATE in LIST."
2068 (while (and list (not result))
2069 (if (funcall predicate (car list))
2070 (setq result (car list)))
2071 (setq list (cdr list)))
2074 (defmacro js2-time (form)
2075 "Evaluate FORM, discard result, and return elapsed time in sec."
2077 (let ((beg (make-symbol "--js2-time-beg--")))
2078 `(let ((,beg (current-time)))
2080 (/ (truncate (* (- (float-time (current-time))
2085 (defsubst js2-same-line (pos)
2086 "Return t if POS is on the same line as current point."
2087 (and (>= pos (point-at-bol))
2088 (<= pos (point-at-eol))))
2090 (defun js2-code-bug ()
2091 "Signal an error when we encounter an unexpected code path."
2092 (error "failed assertion"))
2094 (defsubst js2-record-text-property (beg end prop value)
2095 "Record a text property to set when parsing finishes."
2096 (push (list beg end prop value) js2-mode-deferred-properties))
2098 ;; I'd like to associate errors with nodes, but for now the
2099 ;; easiest thing to do is get the context info from the last token.
2100 (defun js2-record-parse-error (msg &optional arg pos len)
2101 (push (list (list msg arg)
2102 (or pos (js2-current-token-beg))
2103 (or len (js2-current-token-len)))
2106 (defun js2-report-error (msg &optional msg-arg pos len)
2107 "Signal a syntax error or record a parse error."
2108 (if js2-recover-from-parse-errors
2109 (js2-record-parse-error msg msg-arg pos len)
2110 (signal 'js2-syntax-error
2114 (goto-char js2-ts-cursor)
2118 (defun js2-report-warning (msg &optional msg-arg pos len face)
2119 (if js2-compiler-report-warning-as-error
2120 (js2-report-error msg msg-arg pos len)
2121 (push (list (list msg msg-arg)
2122 (or pos (js2-current-token-beg))
2123 (or len (js2-current-token-len))
2125 js2-parsed-warnings)))
2127 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2128 (if js2-compiler-strict-mode
2129 (js2-report-warning msg-id msg-arg beg
2130 (and beg end (- end beg)))))
2132 (put 'js2-syntax-error 'error-conditions
2133 '(error syntax-error js2-syntax-error))
2134 (put 'js2-syntax-error 'error-message "Syntax error")
2136 (put 'js2-parse-error 'error-conditions
2137 '(error parse-error js2-parse-error))
2138 (put 'js2-parse-error 'error-message "Parse error")
2140 (defmacro js2-clear-flag (flags flag)
2141 `(setq ,flags (logand ,flags (lognot ,flag))))
2143 (defmacro js2-set-flag (flags flag)
2144 "Logical-or FLAG into FLAGS."
2145 `(setq ,flags (logior ,flags ,flag)))
2147 (defsubst js2-flag-set-p (flags flag)
2148 (/= 0 (logand flags flag)))
2150 (defsubst js2-flag-not-set-p (flags flag)
2151 (zerop (logand flags flag)))
2153 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2154 "Evaluate BODY with the _ character set to be word-syntax."
2155 (declare (indent 0) (debug t))
2156 (let ((old-syntax (make-symbol "old-syntax")))
2157 `(let ((,old-syntax (string (char-syntax ?_))))
2160 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2162 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2164 ;;; AST struct and function definitions
2166 ;; flags for ast node property 'member-type (used for e4x operators)
2167 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2168 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2169 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2171 (defsubst js2-relpos (pos anchor)
2172 "Convert POS to be relative to ANCHOR.
2173 If POS is nil, returns nil."
2174 (and pos (- pos anchor)))
2176 (defun js2-make-pad (indent)
2179 (make-string (* indent js2-basic-offset) ? )))
2181 (defun js2-visit-ast (node callback)
2182 "Visit every node in ast NODE with visitor CALLBACK.
2184 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2185 called twice: once to visit the node, and again after all the node's
2186 children have been processed. The END-P argument is nil on the first
2187 call and non-nil on the second call. The return value of the callback
2188 affects the traversal: if non-nil, the children of NODE are processed.
2189 If the callback returns nil, or if the node has no children, then the
2190 callback is called immediately with a non-nil END-P argument.
2192 The node traversal is approximately lexical-order, although there
2193 are currently no guarantees around this."
2195 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2197 (when (funcall callback node nil)
2200 ((eq vfunc 'js2-visit-none)
2201 nil) ; don't even bother calling it
2202 ;; Each AST node type has to define a `js2-visitor' function
2203 ;; that takes a node and a callback, and calls `js2-visit-ast'
2204 ;; on each child of the node.
2206 (funcall vfunc node callback))
2208 (error "%s does not define a visitor-traversal function"
2210 ;; call the end-visit
2211 (funcall callback node t))))
2213 (cl-defstruct (js2-node
2214 (:constructor nil)) ; abstract
2215 "Base AST node type."
2216 (type -1) ; token type
2217 (pos -1) ; start position of this AST node in parsed input
2218 (len 1) ; num characters spanned by the node
2219 props ; optional node property list (an alist)
2220 parent) ; link to parent node; null for root
2222 (defsubst js2-node-get-prop (node prop &optional default)
2223 (or (cadr (assoc prop (js2-node-props node))) default))
2225 (defsubst js2-node-set-prop (node prop value)
2226 (setf (js2-node-props node)
2227 (cons (list prop value) (js2-node-props node))))
2229 (defun js2-fixup-starts (n nodes)
2230 "Adjust the start positions of NODES to be relative to N.
2231 Any node in the list may be nil, for convenience."
2232 (dolist (node nodes)
2234 (setf (js2-node-pos node) (- (js2-node-pos node)
2235 (js2-node-pos n))))))
2237 (defun js2-node-add-children (parent &rest nodes)
2238 "Set parent node of NODES to PARENT, and return PARENT.
2239 Does nothing if we're not recording parent links.
2240 If any given node in NODES is nil, doesn't record that link."
2241 (js2-fixup-starts parent nodes)
2242 (dolist (node nodes)
2244 (setf (js2-node-parent node) parent))))
2246 ;; Non-recursive since it's called a frightening number of times.
2247 (defun js2-node-abs-pos (n)
2248 (let ((pos (js2-node-pos n)))
2249 (while (setq n (js2-node-parent n))
2250 (setq pos (+ pos (js2-node-pos n))))
2253 (defsubst js2-node-abs-end (n)
2254 "Return absolute buffer position of end of N."
2255 (+ (js2-node-abs-pos n) (js2-node-len n)))
2257 ;; It's important to make sure block nodes have a Lisp list for the
2258 ;; child nodes, to limit printing recursion depth in an AST that
2259 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2260 ;; a sufficiently large vector tree.
2262 (cl-defstruct (js2-block-node
2265 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2266 (pos (js2-current-token-beg))
2270 "A block of statements."
2271 kids) ; a Lisp list of the child statement nodes
2273 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2274 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2276 (defun js2-visit-block (ast callback)
2277 "Visit the `js2-block-node' children of AST."
2278 (dolist (kid (js2-block-node-kids ast))
2279 (js2-visit-ast kid callback)))
2281 (defun js2-print-block (n i)
2282 (let ((pad (js2-make-pad i)))
2284 (dolist (kid (js2-block-node-kids n))
2285 (js2-print-ast kid (1+ i)))
2288 (cl-defstruct (js2-scope
2289 (:include js2-block-node)
2291 (:constructor make-js2-scope (&key (type js2-BLOCK)
2292 (pos (js2-current-token-beg))
2295 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2296 ;; I don't have one of those handy, so I'll use an alist for now.
2297 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2298 ;; and is much lighter-weight to construct (both CPU and mem).
2299 ;; The keys are interned strings (symbols) for faster lookup.
2300 ;; Should switch to hybrid alist/hashtable eventually.
2301 symbol-table ; an alist of (symbol . js2-symbol)
2302 parent-scope ; a `js2-scope'
2303 top) ; top-level `js2-scope' (script/function)
2305 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2306 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2308 (defun js2-node-get-enclosing-scope (node)
2309 "Return the innermost `js2-scope' node surrounding NODE.
2310 Returns nil if there is no enclosing scope node."
2311 (let ((parent (js2-node-parent node)))
2312 (while (not (js2-scope-p parent))
2313 (setq parent (js2-node-parent parent)))
2316 (defun js2-get-defining-scope (scope name &optional point)
2317 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2318 Returns `js2-scope' in which NAME is defined, or nil if not found.
2320 If POINT is non-nil, and if the found declaration type is
2321 `js2-LET', also check that the declaration node is before POINT."
2322 (let ((sym (if (symbolp name)
2327 (while (and scope continue)
2329 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2332 (not (eq js2-LET (js2-symbol-decl-type entry)))
2334 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2335 (and (eq sym 'arguments)
2336 (js2-function-node-p scope)))
2339 (setq scope (js2-scope-parent-scope scope))))
2342 (defun js2-scope-get-symbol (scope name)
2343 "Return symbol table entry for NAME in SCOPE.
2344 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2345 (and (js2-scope-symbol-table scope)
2346 (cdr (assq (if (symbolp name)
2349 (js2-scope-symbol-table scope)))))
2351 (defun js2-scope-put-symbol (scope name symbol)
2352 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2353 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2354 (let* ((table (js2-scope-symbol-table scope))
2355 (sym (if (symbolp name) name (intern name)))
2356 (entry (assq sym table)))
2358 (setcdr entry symbol)
2359 (push (cons sym symbol)
2360 (js2-scope-symbol-table scope)))))
2362 (cl-defstruct (js2-symbol
2364 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2365 "A symbol table entry."
2366 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2367 ;; js2-LET, or js2-CONST
2370 ast-node) ; a `js2-node'
2372 (cl-defstruct (js2-error-node
2374 (:constructor nil) ; silence emacs21 byte-compiler
2375 (:constructor make-js2-error-node (&key (type js2-ERROR)
2376 (pos (js2-current-token-beg))
2378 "AST node representing a parse error.")
2380 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2381 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2383 (cl-defstruct (js2-script-node
2384 (:include js2-scope)
2386 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2387 (pos (js2-current-token-beg))
2389 ;; FIXME: What are those?
2392 functions ; Lisp list of nested functions
2393 regexps ; Lisp list of (string . flags)
2394 symbols ; alist (every symbol gets unique index)
2396 var-names ; vector of string names
2397 consts ; bool-vector matching var-decls
2398 (temp-number 0)) ; for generating temp variables
2400 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2401 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2403 (defun js2-print-script (node indent)
2404 (dolist (kid (js2-block-node-kids node))
2405 (js2-print-ast kid indent)))
2407 (cl-defstruct (js2-ast-root
2408 (:include js2-script-node)
2410 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2411 (pos (js2-current-token-beg))
2414 "The root node of a js2 AST."
2415 buffer ; the source buffer from which the code was parsed
2416 comments ; a Lisp list of comments, ordered by start position
2417 errors ; a Lisp list of errors found during parsing
2418 warnings ; a Lisp list of warnings found during parsing
2419 node-count) ; number of nodes in the tree, including the root
2421 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2422 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2424 (defun js2-visit-ast-root (ast callback)
2425 (dolist (kid (js2-ast-root-kids ast))
2426 (js2-visit-ast kid callback))
2427 (dolist (comment (js2-ast-root-comments ast))
2428 (js2-visit-ast comment callback)))
2430 (cl-defstruct (js2-comment-node
2433 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2434 (pos (js2-current-token-beg))
2437 format) ; 'line, 'block, 'jsdoc or 'html
2439 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2440 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2442 (defun js2-print-comment (n i)
2443 ;; We really ought to link end-of-line comments to their nodes.
2444 ;; Or maybe we could add a new comment type, 'endline.
2445 (insert (js2-make-pad i)
2446 (js2-node-string n)))
2448 (cl-defstruct (js2-expr-stmt-node
2451 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2455 "An expression statement."
2458 (defsubst js2-expr-stmt-node-set-has-result (node)
2459 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2460 (setf (js2-node-type node) js2-EXPR_RESULT))
2462 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2463 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2465 (defun js2-visit-expr-stmt-node (n v)
2466 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2468 (defun js2-print-expr-stmt-node (n indent)
2469 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2472 (cl-defstruct (js2-loop-node
2473 (:include js2-scope)
2475 "Abstract supertype of loop nodes."
2476 body ; a `js2-block-node'
2477 lp ; position of left-paren, nil if omitted
2478 rp) ; position of right-paren, nil if omitted
2480 (cl-defstruct (js2-do-node
2481 (:include js2-loop-node)
2483 (:constructor make-js2-do-node (&key (type js2-DO)
2484 (pos (js2-current-token-beg))
2491 "AST node for do-loop."
2492 condition ; while (expression)
2493 while-pos) ; buffer position of 'while' keyword
2495 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2496 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2498 (defun js2-visit-do-node (n v)
2499 (js2-visit-ast (js2-do-node-body n) v)
2500 (js2-visit-ast (js2-do-node-condition n) v))
2502 (defun js2-print-do-node (n i)
2503 (let ((pad (js2-make-pad i)))
2504 (insert pad "do {\n")
2505 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2506 (js2-print-ast kid (1+ i)))
2507 (insert pad "} while (")
2508 (js2-print-ast (js2-do-node-condition n) 0)
2511 (cl-defstruct (js2-export-node
2514 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2515 (pos) (js2-current-token-beg)
2521 "AST node for an export statement. There are many things that can be exported,
2522 so many of its properties will be nil.
2524 exports-list ; lisp list of js2-export-binding-node to export
2525 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2526 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2527 default) ; js2-function-node or js2-assign-node
2529 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2530 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2532 (defun js2-visit-export-node (n v)
2533 (let ((exports-list (js2-export-node-exports-list n))
2534 (from (js2-export-node-from-clause n))
2535 (declaration (js2-export-node-declaration n))
2536 (default (js2-export-node-default n)))
2538 (dolist (export exports-list)
2539 (js2-visit-ast export v)))
2541 (js2-visit-ast from v))
2543 (js2-visit-ast declaration v))
2545 (js2-visit-ast default v))))
2547 (defun js2-print-export-node (n i)
2548 (let ((pad (js2-make-pad i))
2549 (exports-list (js2-export-node-exports-list n))
2550 (from (js2-export-node-from-clause n))
2551 (declaration (js2-export-node-declaration n))
2552 (default (js2-export-node-default n)))
2553 (insert pad "export ")
2557 (js2-print-ast default i))
2559 (js2-print-ast declaration i))
2560 ((and exports-list from)
2561 (js2-print-named-imports exports-list)
2563 (js2-print-from-clause from))
2566 (js2-print-from-clause from))
2568 (js2-print-named-imports exports-list)))
2571 (cl-defstruct (js2-while-node
2572 (:include js2-loop-node)
2574 (:constructor make-js2-while-node (&key (type js2-WHILE)
2575 (pos (js2-current-token-beg))
2579 "AST node for while-loop."
2580 condition) ; while-condition
2582 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2583 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2585 (defun js2-visit-while-node (n v)
2586 (js2-visit-ast (js2-while-node-condition n) v)
2587 (js2-visit-ast (js2-while-node-body n) v))
2589 (defun js2-print-while-node (n i)
2590 (let ((pad (js2-make-pad i)))
2591 (insert pad "while (")
2592 (js2-print-ast (js2-while-node-condition n) 0)
2594 (js2-print-body (js2-while-node-body n) (1+ i))
2595 (insert pad "}\n")))
2597 (cl-defstruct (js2-for-node
2598 (:include js2-loop-node)
2600 (:constructor make-js2-for-node (&key (type js2-FOR)
2605 "AST node for a C-style for-loop."
2606 init ; initialization expression
2607 condition ; loop condition
2608 update) ; update clause
2610 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2611 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2613 (defun js2-visit-for-node (n v)
2614 (js2-visit-ast (js2-for-node-init n) v)
2615 (js2-visit-ast (js2-for-node-condition n) v)
2616 (js2-visit-ast (js2-for-node-update n) v)
2617 (js2-visit-ast (js2-for-node-body n) v))
2619 (defun js2-print-for-node (n i)
2620 (let ((pad (js2-make-pad i)))
2621 (insert pad "for (")
2622 (js2-print-ast (js2-for-node-init n) 0)
2624 (js2-print-ast (js2-for-node-condition n) 0)
2626 (js2-print-ast (js2-for-node-update n) 0)
2628 (js2-print-body (js2-for-node-body n) (1+ i))
2629 (insert pad "}\n")))
2631 (cl-defstruct (js2-for-in-node
2632 (:include js2-loop-node)
2634 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2643 "AST node for a for..in loop."
2644 iterator ; [var] foo in ...
2645 object ; object over which we're iterating
2646 in-pos ; buffer position of 'in' keyword
2647 each-pos ; buffer position of 'each' keyword, if foreach-p
2648 foreach-p ; t if it's a for-each loop
2649 forof-p) ; t if it's a for-of loop
2651 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2652 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2654 (defun js2-visit-for-in-node (n v)
2655 (js2-visit-ast (js2-for-in-node-iterator n) v)
2656 (js2-visit-ast (js2-for-in-node-object n) v)
2657 (js2-visit-ast (js2-for-in-node-body n) v))
2659 (defun js2-print-for-in-node (n i)
2660 (let ((pad (js2-make-pad i))
2661 (foreach (js2-for-in-node-foreach-p n))
2662 (forof (js2-for-in-node-forof-p n)))
2667 (js2-print-ast (js2-for-in-node-iterator n) 0)
2668 (insert (if forof " of " " in "))
2669 (js2-print-ast (js2-for-in-node-object n) 0)
2671 (js2-print-body (js2-for-in-node-body n) (1+ i))
2672 (insert pad "}\n")))
2674 (cl-defstruct (js2-return-node
2677 (:constructor make-js2-return-node (&key (type js2-RETURN)
2681 "AST node for a return statement."
2682 retval) ; expression to return, or 'undefined
2684 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2685 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2687 (defun js2-visit-return-node (n v)
2688 (js2-visit-ast (js2-return-node-retval n) v))
2690 (defun js2-print-return-node (n i)
2691 (insert (js2-make-pad i) "return")
2692 (when (js2-return-node-retval n)
2694 (js2-print-ast (js2-return-node-retval n) 0))
2697 (cl-defstruct (js2-if-node
2700 (:constructor make-js2-if-node (&key (type js2-IF)
2707 "AST node for an if-statement."
2708 condition ; expression
2709 then-part ; statement or block
2710 else-pos ; optional buffer position of 'else' keyword
2711 else-part ; optional statement or block
2712 lp ; position of left-paren, nil if omitted
2713 rp) ; position of right-paren, nil if omitted
2715 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2716 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2718 (defun js2-visit-if-node (n v)
2719 (js2-visit-ast (js2-if-node-condition n) v)
2720 (js2-visit-ast (js2-if-node-then-part n) v)
2721 (js2-visit-ast (js2-if-node-else-part n) v))
2723 (defun js2-print-if-node (n i)
2724 (let ((pad (js2-make-pad i))
2725 (then-part (js2-if-node-then-part n))
2726 (else-part (js2-if-node-else-part n)))
2728 (js2-print-ast (js2-if-node-condition n) 0)
2730 (js2-print-body then-part (1+ i))
2735 ((js2-if-node-p else-part)
2737 (js2-print-body else-part i))
2739 (insert " else {\n")
2740 (js2-print-body else-part (1+ i))
2741 (insert pad "}\n")))))
2743 (cl-defstruct (js2-export-binding-node
2746 (:constructor make-js2-export-binding-node (&key (type -1)
2751 "AST node for an external symbol binding.
2752 It contains a local-name node which is the name of the value in the
2753 current scope, and extern-name which is the name of the value in the
2754 imported or exported scope. By default these are the same, but if the
2755 name is aliased as in {foo as bar}, it would have an extern-name node
2756 containing 'foo' and a local-name node containing 'bar'."
2757 local-name ; js2-name-node with the variable name in this scope
2758 extern-name) ; js2-name-node with the value name in the exporting module
2760 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2761 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2763 (defun js2-visit-extern-binding (n v)
2764 "Visit an extern binding node. First visit the local-name, and, if
2765 different, visit the extern-name."
2766 (let ((local-name (js2-export-binding-node-local-name n))
2767 (extern-name (js2-export-binding-node-extern-name n)))
2769 (js2-visit-ast local-name v))
2770 (when (not (equal local-name extern-name))
2771 (js2-visit-ast extern-name v))))
2773 (defun js2-print-extern-binding (n i)
2774 "Print a representation of a single extern binding. E.g. 'foo' or
2776 (let ((local-name (js2-export-binding-node-local-name n))
2777 (extern-name (js2-export-binding-node-extern-name n)))
2778 (insert (js2-name-node-name extern-name))
2779 (when (not (equal local-name extern-name))
2781 (insert (js2-name-node-name local-name)))))
2784 (cl-defstruct (js2-import-node
2787 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2788 (pos (js2-current-token-beg))
2793 "AST node for an import statement. It follows the form
2795 import ModuleSpecifier;
2796 import ImportClause FromClause;"
2797 import ; js2-import-clause-node specifying which names are to imported.
2798 from ; js2-from-clause-node indicating the module from which to import.
2799 module-id) ; module-id of the import. E.g. 'src/mylib'.
2801 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2802 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2804 (defun js2-visit-import (n v)
2805 (let ((import-clause (js2-import-node-import n))
2806 (from-clause (js2-import-node-from n)))
2808 (js2-visit-ast import-clause v))
2810 (js2-visit-ast from-clause v))))
2812 (defun js2-print-import (n i)
2813 "Prints a representation of the import node"
2814 (let ((pad (js2-make-pad i))
2815 (import-clause (js2-import-node-import n))
2816 (from-clause (js2-import-node-from n))
2817 (module-id (js2-import-node-module-id n)))
2818 (insert pad "import ")
2821 (js2-print-import-clause import-clause)
2823 (js2-print-from-clause from-clause))
2829 (cl-defstruct (js2-import-clause-node
2832 (:constructor make-js2-import-clause-node (&key (type -1)
2838 "AST node corresponding to the import clause of an import statement. This is
2839 the portion of the import that bindings names from the external context to the
2841 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2842 named-imports ; lisp list of js2-export-binding-node for all named imports.
2843 default-binding) ; js2-export-binding-node for the default import binding
2845 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2846 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2848 (defun js2-visit-import-clause (n v)
2849 (let ((ns-import (js2-import-clause-node-namespace-import n))
2850 (named-imports (js2-import-clause-node-named-imports n))
2851 (default (js2-import-clause-node-default-binding n)))
2853 (js2-visit-ast ns-import v))
2855 (dolist (import named-imports)
2856 (js2-visit-ast import v)))
2858 (js2-visit-ast default v))))
2860 (defun js2-print-import-clause (n)
2861 (let ((ns-import (js2-import-clause-node-namespace-import n))
2862 (named-imports (js2-import-clause-node-named-imports n))
2863 (default (js2-import-clause-node-default-binding n)))
2865 ((and default ns-import)
2866 (js2-print-ast default)
2868 (js2-print-namespace-import ns-import))
2869 ((and default named-imports)
2870 (js2-print-ast default)
2872 (js2-print-named-imports named-imports))
2874 (js2-print-ast default))
2876 (js2-print-namespace-import ns-import))
2878 (js2-print-named-imports named-imports)))))
2880 (defun js2-print-namespace-import (node)
2882 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2884 (defun js2-print-named-imports (imports)
2886 (let ((len (length imports))
2889 (js2-print-extern-binding (nth n imports) 0)
2890 (unless (= n (- len 1))
2895 (cl-defstruct (js2-namespace-import-node
2898 (:constructor make-js2-namespace-import-node (&key (type -1)
2902 "AST node for a complete namespace import.
2903 E.g. the '* as lib' expression in:
2905 import * as lib from 'src/lib'
2907 It contains a single name node referring to the bound name."
2908 name) ; js2-name-node of the bound name.
2910 (defun js2-visit-namespace-import (n v)
2911 (js2-visit-ast (js2-namespace-import-node-name n) v))
2913 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2914 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2916 (cl-defstruct (js2-from-clause-node
2919 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2924 "AST node for the from clause in an import or export statement.
2925 E.g. from 'my/module'. It can refere to either an external module, or to the
2926 modules metadata itself."
2927 module-id ; string containing the module specifier.
2928 metadata-p) ; true if this clause refers to the module's metadata
2930 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2931 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2933 (defun js2-print-from-clause (n)
2935 (if (js2-from-clause-node-metadata-p n)
2936 (insert "this module")
2938 (insert (js2-from-clause-node-module-id n))
2941 (cl-defstruct (js2-try-node
2944 (:constructor make-js2-try-node (&key (type js2-TRY)
2950 "AST node for a try-statement."
2952 catch-clauses ; a Lisp list of `js2-catch-node'
2953 finally-block) ; a `js2-finally-node'
2955 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2956 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2958 (defun js2-visit-try-node (n v)
2959 (js2-visit-ast (js2-try-node-try-block n) v)
2960 (dolist (clause (js2-try-node-catch-clauses n))
2961 (js2-visit-ast clause v))
2962 (js2-visit-ast (js2-try-node-finally-block n) v))
2964 (defun js2-print-try-node (n i)
2965 (let ((pad (js2-make-pad i))
2966 (catches (js2-try-node-catch-clauses n))
2967 (finally (js2-try-node-finally-block n)))
2968 (insert pad "try {\n")
2969 (js2-print-body (js2-try-node-try-block n) (1+ i))
2972 (dolist (catch catches)
2973 (js2-print-ast catch i)))
2975 (js2-print-ast finally i)
2978 (cl-defstruct (js2-catch-node
2979 (:include js2-scope)
2981 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2988 "AST node for a catch clause."
2989 param ; destructuring form or simple name node
2990 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2991 guard-expr ; catch condition, a `js2-node'
2992 lp ; buffer position of left-paren, nil if omitted
2993 rp) ; buffer position of right-paren, nil if omitted
2995 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2996 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2998 (defun js2-visit-catch-node (n v)
2999 (js2-visit-ast (js2-catch-node-param n) v)
3000 (when (js2-catch-node-guard-kwd n)
3001 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3002 (js2-visit-block n v))
3004 (defun js2-print-catch-node (n i)
3005 (let ((pad (js2-make-pad i))
3006 (guard-kwd (js2-catch-node-guard-kwd n))
3007 (guard-expr (js2-catch-node-guard-expr n)))
3009 (js2-print-ast (js2-catch-node-param n) 0)
3012 (js2-print-ast guard-expr 0))
3014 (js2-print-body n (1+ i))
3017 (cl-defstruct (js2-finally-node
3020 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3023 "AST node for a finally clause."
3024 body) ; a `js2-node', often but not always a block node
3026 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3027 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3029 (defun js2-visit-finally-node (n v)
3030 (js2-visit-ast (js2-finally-node-body n) v))
3032 (defun js2-print-finally-node (n i)
3033 (let ((pad (js2-make-pad i)))
3034 (insert " finally {\n")
3035 (js2-print-body (js2-finally-node-body n) (1+ i))
3036 (insert pad "}\n")))
3038 (cl-defstruct (js2-switch-node
3041 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3047 "AST node for a switch statement."
3048 discriminant ; a `js2-node' (switch expression)
3049 cases ; a Lisp list of `js2-case-node'
3050 lp ; position of open-paren for discriminant, nil if omitted
3051 rp) ; position of close-paren for discriminant, nil if omitted
3053 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3054 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3056 (defun js2-visit-switch-node (n v)
3057 (js2-visit-ast (js2-switch-node-discriminant n) v)
3058 (dolist (c (js2-switch-node-cases n))
3059 (js2-visit-ast c v)))
3061 (defun js2-print-switch-node (n i)
3062 (let ((pad (js2-make-pad i))
3063 (cases (js2-switch-node-cases n)))
3064 (insert pad "switch (")
3065 (js2-print-ast (js2-switch-node-discriminant n) 0)
3067 (dolist (case cases)
3068 (js2-print-ast case i))
3069 (insert pad "}\n")))
3071 (cl-defstruct (js2-case-node
3072 (:include js2-block-node)
3074 (:constructor make-js2-case-node (&key (type js2-CASE)
3077 "AST node for a case clause of a switch statement."
3078 expr) ; the case expression (nil for default)
3080 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3081 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3083 (defun js2-visit-case-node (n v)
3084 (js2-visit-ast (js2-case-node-expr n) v)
3085 (js2-visit-block n v))
3087 (defun js2-print-case-node (n i)
3088 (let ((pad (js2-make-pad i))
3089 (expr (js2-case-node-expr n)))
3092 (insert "default:\n")
3094 (js2-print-ast expr 0)
3096 (dolist (kid (js2-case-node-kids n))
3097 (js2-print-ast kid (1+ i)))))
3099 (cl-defstruct (js2-throw-node
3102 (:constructor make-js2-throw-node (&key (type js2-THROW)
3105 "AST node for a throw statement."
3106 expr) ; the expression to throw
3108 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3109 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3111 (defun js2-visit-throw-node (n v)
3112 (js2-visit-ast (js2-throw-node-expr n) v))
3114 (defun js2-print-throw-node (n i)
3115 (insert (js2-make-pad i) "throw ")
3116 (js2-print-ast (js2-throw-node-expr n) 0)
3119 (cl-defstruct (js2-with-node
3122 (:constructor make-js2-with-node (&key (type js2-WITH)
3126 "AST node for a with-statement."
3129 lp ; buffer position of left-paren around object, nil if omitted
3130 rp) ; buffer position of right-paren around object, nil if omitted
3132 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3133 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3135 (defun js2-visit-with-node (n v)
3136 (js2-visit-ast (js2-with-node-object n) v)
3137 (js2-visit-ast (js2-with-node-body n) v))
3139 (defun js2-print-with-node (n i)
3140 (let ((pad (js2-make-pad i)))
3141 (insert pad "with (")
3142 (js2-print-ast (js2-with-node-object n) 0)
3144 (js2-print-body (js2-with-node-body n) (1+ i))
3145 (insert pad "}\n")))
3147 (cl-defstruct (js2-label-node
3150 (:constructor make-js2-label-node (&key (type js2-LABEL)
3153 "AST node for a statement label or case label."
3155 loop) ; for validating and code-generating continue-to-label
3157 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3158 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3160 (defun js2-print-label (n i)
3161 (insert (js2-make-pad i)
3162 (js2-label-node-name n)
3165 (cl-defstruct (js2-labeled-stmt-node
3168 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3169 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3170 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3173 "AST node for a statement with one or more labels.
3174 Multiple labels for a statement are collapsed into the labels field."
3175 labels ; Lisp list of `js2-label-node'
3176 stmt) ; the statement these labels are for
3178 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3179 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3181 (defun js2-get-label-by-name (lbl-stmt name)
3182 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3183 Returns nil if no such label is in the list."
3184 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3186 (while (and label-list (not result))
3187 (if (string= (js2-label-node-name (car label-list)) name)
3188 (setq result (car label-list))
3189 (setq label-list (cdr label-list))))
3192 (defun js2-visit-labeled-stmt (n v)
3193 (dolist (label (js2-labeled-stmt-node-labels n))
3194 (js2-visit-ast label v))
3195 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3197 (defun js2-print-labeled-stmt (n i)
3198 (dolist (label (js2-labeled-stmt-node-labels n))
3199 (js2-print-ast label i))
3200 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3202 (defun js2-labeled-stmt-node-contains (node label)
3203 "Return t if NODE contains LABEL in its label set.
3204 NODE is a `js2-labels-node'. LABEL is an identifier."
3205 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3206 if (string= label (js2-label-node-name nl))
3208 finally return nil))
3210 (defsubst js2-labeled-stmt-node-add-label (node label)
3211 "Add a `js2-label-node' to the label set for this statement."
3212 (setf (js2-labeled-stmt-node-labels node)
3213 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3215 (cl-defstruct (js2-jump-node
3218 "Abstract supertype of break and continue nodes."
3219 label ; `js2-name-node' for location of label identifier, if present
3220 target) ; target js2-labels-node or loop/switch statement
3222 (defun js2-visit-jump-node (n v)
3223 ;; We don't visit the target, since it's a back-link.
3224 (js2-visit-ast (js2-jump-node-label n) v))
3226 (cl-defstruct (js2-break-node
3227 (:include js2-jump-node)
3229 (:constructor make-js2-break-node (&key (type js2-BREAK)
3232 "AST node for a break statement.
3233 The label field is a `js2-name-node', possibly nil, for the named label
3234 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3235 is the target of the break - a label node or enclosing loop/switch statement.")
3237 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3238 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3240 (defun js2-print-break-node (n i)
3241 (insert (js2-make-pad i) "break")
3242 (when (js2-break-node-label n)
3244 (js2-print-ast (js2-break-node-label n) 0))
3247 (cl-defstruct (js2-continue-node
3248 (:include js2-jump-node)
3250 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3253 "AST node for a continue statement.
3254 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3255 It is nil if continue specifies no label. The target field is the jump target:
3256 a `js2-label-node' or the innermost enclosing loop.")
3258 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3259 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3261 (defun js2-print-continue-node (n i)
3262 (insert (js2-make-pad i) "continue")
3263 (when (js2-continue-node-label n)
3265 (js2-print-ast (js2-continue-node-label n) 0))
3268 (cl-defstruct (js2-function-node
3269 (:include js2-script-node)
3271 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3275 (form 'FUNCTION_STATEMENT)
3281 "AST node for a function declaration.
3282 The `params' field is a Lisp list of nodes. Each node is either a simple
3283 `js2-name-node', or if it's a destructuring-assignment parameter, a
3284 `js2-array-node' or `js2-object-node'."
3285 ftype ; FUNCTION, GETTER or SETTER
3286 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3287 name ; function name (a `js2-name-node', or nil if anonymous)
3288 params ; a Lisp list of destructuring forms or simple name nodes
3289 rest-p ; if t, the last parameter is rest parameter
3290 body ; a `js2-block-node' or expression node (1.8 only)
3291 lp ; position of arg-list open-paren, or nil if omitted
3292 rp ; position of arg-list close-paren, or nil if omitted
3293 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3294 needs-activation ; t if we need an activation object for this frame
3295 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3296 member-expr) ; nonstandard Ecma extension from Rhino
3298 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3299 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3301 (defun js2-visit-function-node (n v)
3302 (js2-visit-ast (js2-function-node-name n) v)
3303 (dolist (p (js2-function-node-params n))
3304 (js2-visit-ast p v))
3305 (js2-visit-ast (js2-function-node-body n) v))
3307 (defun js2-print-function-node (n i)
3308 (let* ((pad (js2-make-pad i))
3309 (getter (js2-node-get-prop n 'GETTER_SETTER))
3310 (name (or (js2-function-node-name n)
3311 (js2-function-node-member-expr n)))
3312 (params (js2-function-node-params n))
3313 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3314 (rest-p (js2-function-node-rest-p n))
3315 (body (js2-function-node-body n))
3316 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3317 (unless (or getter arrow)
3318 (insert pad "function")
3319 (when (eq (js2-function-node-generator-type n) 'STAR)
3323 (js2-print-ast name 0))
3325 (cl-loop with len = (length params)
3329 (when (and rest-p (= count len))
3331 (js2-print-ast param 0)
3338 ;; TODO: fix this to be smarter about indenting, etc.
3341 (if (js2-block-node-p body)
3342 (js2-print-body body (1+ i))
3343 (js2-print-ast body 0))
3348 (defun js2-function-name (node)
3349 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3350 (and (js2-function-node-name node)
3351 (js2-name-node-name (js2-function-node-name node))))
3353 ;; Having this be an expression node makes it more flexible.
3354 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3355 ;; that work better if you assume it's an expression. Whenever we have
3356 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3357 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3358 (cl-defstruct (js2-var-decl-node
3361 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3362 (pos (js2-current-token-beg))
3365 "AST node for a variable declaration list (VAR, CONST or LET).
3366 The node bounds differ depending on the declaration type. For VAR or
3367 CONST declarations, the bounds include the var/const keyword. For LET
3368 declarations, the node begins at the position of the first child."
3369 kids ; a Lisp list of `js2-var-init-node' structs.
3370 decl-type) ; js2-VAR, js2-CONST or js2-LET
3372 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3373 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3375 (defun js2-visit-var-decl (n v)
3376 (dolist (kid (js2-var-decl-node-kids n))
3377 (js2-visit-ast kid v)))
3379 (defun js2-print-var-decl (n i)
3380 (let ((pad (js2-make-pad i))
3381 (tt (js2-var-decl-node-decl-type n)))
3384 ((= tt js2-VAR) "var ")
3385 ((= tt js2-LET) "let ")
3386 ((= tt js2-CONST) "const ")
3388 (error "malformed var-decl node"))))
3389 (cl-loop with kids = (js2-var-decl-node-kids n)
3390 with len = (length kids)
3394 (js2-print-ast kid 0)
3398 (cl-defstruct (js2-var-init-node
3401 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3405 "AST node for a variable declaration.
3406 The type field will be js2-CONST for a const decl."
3407 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3408 initializer) ; initializer expression, a `js2-node'
3410 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3411 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3413 (defun js2-visit-var-init-node (n v)
3414 (js2-visit-ast (js2-var-init-node-target n) v)
3415 (js2-visit-ast (js2-var-init-node-initializer n) v))
3417 (defun js2-print-var-init-node (n i)
3418 (let ((pad (js2-make-pad i))
3419 (name (js2-var-init-node-target n))
3420 (init (js2-var-init-node-initializer n)))
3422 (js2-print-ast name 0)
3425 (js2-print-ast init 0))))
3427 (cl-defstruct (js2-cond-node
3430 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3437 "AST node for the ternary operator"
3441 q-pos ; buffer position of ?
3442 c-pos) ; buffer position of :
3444 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3445 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3447 (defun js2-visit-cond-node (n v)
3448 (js2-visit-ast (js2-cond-node-test-expr n) v)
3449 (js2-visit-ast (js2-cond-node-true-expr n) v)
3450 (js2-visit-ast (js2-cond-node-false-expr n) v))
3452 (defun js2-print-cond-node (n i)
3453 (let ((pad (js2-make-pad i)))
3455 (js2-print-ast (js2-cond-node-test-expr n) 0)
3457 (js2-print-ast (js2-cond-node-true-expr n) 0)
3459 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3461 (cl-defstruct (js2-infix-node
3464 (:constructor make-js2-infix-node (&key type
3468 "Represents infix expressions.
3469 Includes assignment ops like `|=', and the comma operator.
3470 The type field inherited from `js2-node' holds the operator."
3471 op-pos ; buffer position where operator begins
3472 left ; any `js2-node'
3473 right) ; any `js2-node'
3475 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3476 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3478 (defun js2-visit-infix-node (n v)
3479 (js2-visit-ast (js2-infix-node-left n) v)
3480 (js2-visit-ast (js2-infix-node-right n) v))
3482 (defconst js2-operator-tokens
3483 (let ((table (make-hash-table :test 'eq))
3485 (list (cons js2-IN "in")
3486 (cons js2-TYPEOF "typeof")
3487 (cons js2-INSTANCEOF "instanceof")
3488 (cons js2-DELPROP "delete")
3489 (cons js2-COMMA ",")
3490 (cons js2-COLON ":")
3495 (cons js2-BITOR "|")
3496 (cons js2-BITXOR "^")
3497 (cons js2-BITAND "&")
3506 (cons js2-URSH ">>>")
3507 (cons js2-ADD "+") ; infix plus
3508 (cons js2-SUB "-") ; infix minus
3513 (cons js2-BITNOT "~")
3514 (cons js2-POS "+") ; unary plus
3515 (cons js2-NEG "-") ; unary minus
3516 (cons js2-TRIPLEDOT "...")
3517 (cons js2-SHEQ "===") ; shallow equality
3518 (cons js2-SHNE "!==") ; shallow inequality
3519 (cons js2-ASSIGN "=")
3520 (cons js2-ASSIGN_BITOR "|=")
3521 (cons js2-ASSIGN_BITXOR "^=")
3522 (cons js2-ASSIGN_BITAND "&=")
3523 (cons js2-ASSIGN_LSH "<<=")
3524 (cons js2-ASSIGN_RSH ">>=")
3525 (cons js2-ASSIGN_URSH ">>>=")
3526 (cons js2-ASSIGN_ADD "+=")
3527 (cons js2-ASSIGN_SUB "-=")
3528 (cons js2-ASSIGN_MUL "*=")
3529 (cons js2-ASSIGN_DIV "/=")
3530 (cons js2-ASSIGN_MOD "%="))))
3531 (cl-loop for (k . v) in tokens do
3532 (puthash k v table))
3535 (defun js2-print-infix-node (n i)
3536 (let* ((tt (js2-node-type n))
3537 (op (gethash tt js2-operator-tokens)))
3539 (error "unrecognized infix operator %s" (js2-node-type n)))
3540 (insert (js2-make-pad i))
3541 (js2-print-ast (js2-infix-node-left n) 0)
3542 (unless (= tt js2-COMMA)
3546 (js2-print-ast (js2-infix-node-right n) 0)))
3548 (cl-defstruct (js2-assign-node
3549 (:include js2-infix-node)
3551 (:constructor make-js2-assign-node (&key type
3555 "Represents any assignment.
3556 The type field holds the actual assignment operator.")
3558 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3559 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3561 (cl-defstruct (js2-unary-node
3564 (:constructor make-js2-unary-node (&key type ; required
3567 "AST node type for unary operator nodes.
3568 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3569 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3570 property is added if the operator follows the operand."
3571 operand) ; a `js2-node' expression
3573 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3574 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3576 (defun js2-visit-unary-node (n v)
3577 (js2-visit-ast (js2-unary-node-operand n) v))
3579 (defun js2-print-unary-node (n i)
3580 (let* ((tt (js2-node-type n))
3581 (op (gethash tt js2-operator-tokens))
3582 (postfix (js2-node-get-prop n 'postfix)))
3584 (error "unrecognized unary operator %s" tt))
3585 (insert (js2-make-pad i))
3588 (if (or (= tt js2-TYPEOF)
3591 (js2-print-ast (js2-unary-node-operand n) 0)
3595 (cl-defstruct (js2-let-node
3596 (:include js2-scope)
3598 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3599 (pos (js2-current-token-beg))
3602 "AST node for a let expression or a let statement.
3603 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3604 vars ; a `js2-var-decl-node'
3605 body ; a `js2-node' representing the expression or body block
3609 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3610 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3612 (defun js2-visit-let-node (n v)
3613 (js2-visit-ast (js2-let-node-vars n) v)
3614 (js2-visit-ast (js2-let-node-body n) v))
3616 (defun js2-print-let-node (n i)
3617 (insert (js2-make-pad i) "let (")
3619 (js2-print-ast (js2-let-node-vars n) 0)
3620 (delete-region p (+ p 4)))
3622 (js2-print-ast (js2-let-node-body n) i))
3624 (cl-defstruct (js2-keyword-node
3627 (:constructor make-js2-keyword-node (&key type
3628 (pos (js2-current-token-beg))
3629 (len (- js2-ts-cursor pos)))))
3630 "AST node representing a literal keyword such as `null'.
3631 Used for `null', `this', `true', `false' and `debugger'.
3632 The node type is set to js2-NULL, js2-THIS, etc.")
3634 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3635 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3637 (defun js2-print-keyword-node (n i)
3638 (insert (js2-make-pad i)
3639 (let ((tt (js2-node-type n)))
3641 ((= tt js2-THIS) "this")
3642 ((= tt js2-SUPER) "super")
3643 ((= tt js2-NULL) "null")
3644 ((= tt js2-TRUE) "true")
3645 ((= tt js2-FALSE) "false")
3646 ((= tt js2-DEBUGGER) "debugger")
3647 (t (error "Invalid keyword literal type: %d" tt))))))
3649 (defsubst js2-this-or-super-node-p (node)
3650 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3651 (let ((type (js2-node-type node)))
3652 (or (eq type js2-THIS) (eq type js2-SUPER))))
3654 (cl-defstruct (js2-new-node
3657 (:constructor make-js2-new-node (&key (type js2-NEW)
3658 (pos (js2-current-token-beg))
3662 "AST node for new-expression such as new Foo()."
3663 target ; an identifier or reference
3664 args ; a Lisp list of argument nodes
3665 lp ; position of left-paren, nil if omitted
3666 rp ; position of right-paren, nil if omitted
3667 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3669 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3670 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3672 (defun js2-visit-new-node (n v)
3673 (js2-visit-ast (js2-new-node-target n) v)
3674 (dolist (arg (js2-new-node-args n))
3675 (js2-visit-ast arg v))
3676 (js2-visit-ast (js2-new-node-initializer n) v))
3678 (defun js2-print-new-node (n i)
3679 (insert (js2-make-pad i) "new ")
3680 (js2-print-ast (js2-new-node-target n))
3682 (js2-print-list (js2-new-node-args n))
3684 (when (js2-new-node-initializer n)
3686 (js2-print-ast (js2-new-node-initializer n))))
3688 (cl-defstruct (js2-name-node
3691 (:constructor make-js2-name-node (&key (type js2-NAME)
3692 (pos (js2-current-token-beg))
3693 (len (- js2-ts-cursor
3694 (js2-current-token-beg)))
3695 (name (js2-current-token-string)))))
3696 "AST node for a JavaScript identifier"
3698 scope) ; a `js2-scope' (optional, used for codegen)
3700 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3701 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3703 (defun js2-print-name-node (n i)
3704 (insert (js2-make-pad i)
3705 (js2-name-node-name n)))
3707 (defsubst js2-name-node-length (node)
3708 "Return identifier length of NODE, a `js2-name-node'.
3709 Returns 0 if NODE is nil or its identifier field is nil."
3711 (length (js2-name-node-name node))
3714 (cl-defstruct (js2-number-node
3717 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3718 (pos (js2-current-token-beg))
3719 (len (- js2-ts-cursor
3720 (js2-current-token-beg)))
3721 (value (js2-current-token-string))
3722 (num-value (js2-token-number
3723 (js2-current-token))))))
3724 "AST node for a number literal."
3725 value ; the original string, e.g. "6.02e23"
3726 num-value) ; the parsed number value
3728 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3729 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3731 (defun js2-print-number-node (n i)
3732 (insert (js2-make-pad i)
3733 (number-to-string (js2-number-node-num-value n))))
3735 (cl-defstruct (js2-regexp-node
3738 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3739 (pos (js2-current-token-beg))
3740 (len (- js2-ts-cursor
3741 (js2-current-token-beg)))
3743 "AST node for a regular expression literal."
3744 value ; the regexp string, without // delimiters
3745 flags) ; a string of flags, e.g. `mi'.
3747 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3748 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3750 (defun js2-print-regexp (n i)
3751 (insert (js2-make-pad i)
3753 (js2-regexp-node-value n)
3755 (if (js2-regexp-node-flags n)
3756 (insert (js2-regexp-node-flags n))))
3758 (cl-defstruct (js2-string-node
3761 (:constructor make-js2-string-node (&key (type js2-STRING)
3762 (pos (js2-current-token-beg))
3763 (len (- js2-ts-cursor
3764 (js2-current-token-beg)))
3765 (value (js2-current-token-string)))))
3767 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3768 You can tell the quote type by looking at the first character."
3769 value) ; the characters of the string, including the quotes
3771 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3772 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3774 (defun js2-print-string-node (n i)
3775 (insert (js2-make-pad i)
3776 (js2-node-string n)))
3778 (cl-defstruct (js2-template-node
3781 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3784 kids) ; `js2-string-node' is used for string segments, other nodes
3785 ; for substitutions inside.
3787 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3788 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3790 (defun js2-visit-template (n callback)
3791 (dolist (kid (js2-template-node-kids n))
3792 (js2-visit-ast kid callback)))
3794 (defun js2-print-template (n i)
3795 (insert (js2-make-pad i))
3796 (dolist (kid (js2-template-node-kids n))
3797 (if (js2-string-node-p kid)
3798 (insert (js2-node-string kid))
3799 (js2-print-ast kid))))
3801 (cl-defstruct (js2-tagged-template-node
3804 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3805 beg len tag template)))
3806 "Tagged template literal."
3807 tag ; `js2-node' with the tag expression.
3808 template) ; `js2-template-node' with the template.
3810 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3811 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3813 (defun js2-visit-tagged-template (n callback)
3814 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3815 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3817 (defun js2-print-tagged-template (n i)
3818 (insert (js2-make-pad i))
3819 (js2-print-ast (js2-tagged-template-node-tag n))
3820 (js2-print-ast (js2-tagged-template-node-template n)))
3822 (cl-defstruct (js2-array-node
3825 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3828 "AST node for an array literal."
3829 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3831 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3832 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3834 (defun js2-visit-array-node (n v)
3835 (dolist (e (js2-array-node-elems n))
3836 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3838 (defun js2-print-array-node (n i)
3839 (insert (js2-make-pad i) "[")
3840 (let ((elems (js2-array-node-elems n)))
3841 (js2-print-list elems)
3842 (when (and elems (null (car (last elems))))
3846 (cl-defstruct (js2-class-node
3849 (:constructor make-js2-class-node (&key (type js2-CLASS)
3851 (form 'CLASS_STATEMENT)
3853 extends len elems)))
3854 "AST node for an class expression.
3855 `elems' is a list of `js2-object-prop-node', and `extends' is an
3856 optional `js2-expr-node'"
3857 form ; CLASS_{STATEMENT|EXPRESSION}
3858 name ; class name (a `js2-node-name', or nil if anonymous)
3859 extends ; class heritage (a `js2-expr-node', or nil if none)
3862 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3863 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3865 (defun js2-visit-class-node (n v)
3866 (js2-visit-ast (js2-class-node-name n) v)
3867 (js2-visit-ast (js2-class-node-extends n) v)
3868 (dolist (e (js2-class-node-elems n))
3869 (js2-visit-ast e v)))
3871 (defun js2-print-class-node (n i)
3872 (let* ((pad (js2-make-pad i))
3873 (name (js2-class-node-name n))
3874 (extends (js2-class-node-extends n))
3875 (elems (js2-class-node-elems n)))
3876 (insert pad "class")
3879 (js2-print-ast name 0))
3881 (insert " extends ")
3882 (js2-print-ast extends))
3884 (dolist (elem elems)
3886 (if (js2-node-get-prop elem 'STATIC)
3887 (progn (insert (js2-make-pad (1+ i)) "static ")
3888 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3889 (js2-print-ast elem (1+ i))))
3890 (insert "\n" pad "}")))
3892 (cl-defstruct (js2-object-node
3895 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3899 "AST node for an object literal expression.
3900 `elems' is a list of `js2-object-prop-node'."
3903 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3904 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3906 (defun js2-visit-object-node (n v)
3907 (dolist (e (js2-object-node-elems n))
3908 (js2-visit-ast e v)))
3910 (defun js2-print-object-node (n i)
3911 (insert (js2-make-pad i) "{")
3912 (js2-print-list (js2-object-node-elems n))
3915 (cl-defstruct (js2-object-prop-node
3916 (:include js2-infix-node)
3918 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3922 "AST node for an object literal prop:value entry.
3923 The `left' field is the property: a name node, string node or number node.
3924 The `right' field is a `js2-node' representing the initializer value.
3925 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3926 and both fields have the same value.")
3928 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3929 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3931 (defun js2-print-object-prop-node (n i)
3932 (let* ((left (js2-object-prop-node-left n))
3933 (computed (not (or (js2-string-node-p left)
3934 (js2-number-node-p left)
3935 (js2-name-node-p left)))))
3936 (insert (js2-make-pad i))
3939 (js2-print-ast left 0)
3942 (if (not (js2-node-get-prop n 'SHORTHAND))
3945 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3947 (cl-defstruct (js2-getter-setter-node
3948 (:include js2-infix-node)
3950 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3953 "AST node for a getter/setter property in an object literal.
3954 The `left' field is the `js2-name-node' naming the getter/setter prop.
3955 The `right' field is always an anonymous `js2-function-node' with a node
3956 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3958 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3959 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3961 (defun js2-print-getter-setter (n i)
3962 (let ((pad (js2-make-pad i))
3963 (left (js2-getter-setter-node-left n))
3964 (right (js2-getter-setter-node-right n)))
3966 (if (/= (js2-node-type n) js2-FUNCTION)
3967 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3968 (js2-print-ast left 0)
3969 (js2-print-ast right 0)))
3971 (cl-defstruct (js2-prop-get-node
3972 (:include js2-infix-node)
3974 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3977 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3979 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3980 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3982 (defun js2-visit-prop-get-node (n v)
3983 (js2-visit-ast (js2-prop-get-node-left n) v)
3984 (js2-visit-ast (js2-prop-get-node-right n) v))
3986 (defun js2-print-prop-get-node (n i)
3987 (insert (js2-make-pad i))
3988 (js2-print-ast (js2-prop-get-node-left n) 0)
3990 (js2-print-ast (js2-prop-get-node-right n) 0))
3992 (cl-defstruct (js2-elem-get-node
3995 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3999 "AST node for an array index expression such as foo[bar]."
4000 target ; a `js2-node' - the expression preceding the "."
4001 element ; a `js2-node' - the expression in brackets
4002 lb ; position of left-bracket, nil if omitted
4003 rb) ; position of right-bracket, nil if omitted
4005 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4006 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4008 (defun js2-visit-elem-get-node (n v)
4009 (js2-visit-ast (js2-elem-get-node-target n) v)
4010 (js2-visit-ast (js2-elem-get-node-element n) v))
4012 (defun js2-print-elem-get-node (n i)
4013 (insert (js2-make-pad i))
4014 (js2-print-ast (js2-elem-get-node-target n) 0)
4016 (js2-print-ast (js2-elem-get-node-element n) 0)
4019 (cl-defstruct (js2-call-node
4022 (:constructor make-js2-call-node (&key (type js2-CALL)
4026 "AST node for a JavaScript function call."
4027 target ; a `js2-node' evaluating to the function to call
4028 args ; a Lisp list of `js2-node' arguments
4029 lp ; position of open-paren, or nil if missing
4030 rp) ; position of close-paren, or nil if missing
4032 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4033 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4035 (defun js2-visit-call-node (n v)
4036 (js2-visit-ast (js2-call-node-target n) v)
4037 (dolist (arg (js2-call-node-args n))
4038 (js2-visit-ast arg v)))
4040 (defun js2-print-call-node (n i)
4041 (insert (js2-make-pad i))
4042 (js2-print-ast (js2-call-node-target n) 0)
4044 (js2-print-list (js2-call-node-args n))
4047 (cl-defstruct (js2-yield-node
4050 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4053 "AST node for yield statement or expression."
4054 star-p ; whether it's yield*
4055 value) ; optional: value to be yielded
4057 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4058 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4060 (defun js2-visit-yield-node (n v)
4061 (js2-visit-ast (js2-yield-node-value n) v))
4063 (defun js2-print-yield-node (n i)
4064 (insert (js2-make-pad i))
4066 (when (js2-yield-node-star-p n)
4068 (when (js2-yield-node-value n)
4070 (js2-print-ast (js2-yield-node-value n) 0)))
4072 (cl-defstruct (js2-paren-node
4075 (:constructor make-js2-paren-node (&key (type js2-LP)
4078 "AST node for a parenthesized expression.
4079 In particular, used when the parens are syntactically optional,
4080 as opposed to required parens such as those enclosing an if-conditional."
4083 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4084 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4086 (defun js2-visit-paren-node (n v)
4087 (js2-visit-ast (js2-paren-node-expr n) v))
4089 (defun js2-print-paren-node (n i)
4090 (insert (js2-make-pad i))
4092 (js2-print-ast (js2-paren-node-expr n) 0)
4095 (cl-defstruct (js2-comp-node
4096 (:include js2-scope)
4098 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4103 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4104 result ; result expression (just after left-bracket)
4105 loops ; a Lisp list of `js2-comp-loop-node'
4106 filters ; a Lisp list of guard/filter expressions
4107 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4108 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4111 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4112 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4114 (defun js2-visit-comp-node (n v)
4115 (js2-visit-ast (js2-comp-node-result n) v)
4116 (dolist (l (js2-comp-node-loops n))
4117 (js2-visit-ast l v))
4118 (dolist (f (js2-comp-node-filters n))
4119 (js2-visit-ast f v)))
4121 (defun js2-print-comp-node (n i)
4122 (let ((pad (js2-make-pad i))
4123 (result (js2-comp-node-result n))
4124 (loops (js2-comp-node-loops n))
4125 (filters (js2-comp-node-filters n))
4126 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4127 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4128 (insert pad (if gen-p "(" "["))
4130 (js2-print-ast result 0))
4146 (js2-print-ast result 0))
4147 (insert (if gen-p ")" "]"))))
4149 (cl-defstruct (js2-comp-loop-node
4150 (:include js2-for-in-node)
4152 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4160 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4162 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4163 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4165 (defun js2-visit-comp-loop (n v)
4166 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4167 (js2-visit-ast (js2-comp-loop-node-object n) v))
4169 (defun js2-print-comp-loop (n _i)
4171 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4173 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4174 (insert (if (js2-comp-loop-node-forof-p n)
4176 (js2-print-ast (js2-comp-loop-node-object n) 0)
4179 (cl-defstruct (js2-empty-expr-node
4182 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4183 (pos (js2-current-token-beg))
4185 "AST node for an empty expression.")
4187 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4188 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4190 (cl-defstruct (js2-xml-node
4191 (:include js2-block-node)
4193 (:constructor make-js2-xml-node (&key (type js2-XML)
4194 (pos (js2-current-token-beg))
4196 "AST node for initial parse of E4X literals.
4197 The kids field is a list of XML fragments, each a `js2-string-node' or
4198 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4200 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4201 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4203 (defun js2-print-xml-node (n i)
4204 (dolist (kid (js2-xml-node-kids n))
4205 (js2-print-ast kid i)))
4207 (cl-defstruct (js2-xml-js-expr-node
4208 (:include js2-xml-node)
4210 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4213 "AST node for an embedded JavaScript {expression} in an E4X literal.
4214 The start and end fields correspond to the curly-braces."
4215 expr) ; a `js2-expr-node' of some sort
4217 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4218 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4220 (defun js2-visit-xml-js-expr (n v)
4221 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4223 (defun js2-print-xml-js-expr (n i)
4224 (insert (js2-make-pad i))
4226 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4229 (cl-defstruct (js2-xml-dot-query-node
4230 (:include js2-infix-node)
4232 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4236 "AST node for an E4X foo.(bar) filter expression.
4237 Note that the left-paren is automatically the character immediately
4238 following the dot (.) in the operator. No whitespace is permitted
4239 between the dot and the lp by the scanner."
4242 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4243 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4245 (defun js2-print-xml-dot-query (n i)
4246 (insert (js2-make-pad i))
4247 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4249 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4252 (cl-defstruct (js2-xml-ref-node
4254 (:constructor nil)) ; abstract
4255 "Base type for E4X XML attribute-access or property-get expressions.
4256 Such expressions can take a variety of forms. The general syntax has
4259 - (optional) an @ (specifying an attribute access)
4260 - (optional) a namespace (a `js2-name-node') and double-colon
4261 - (required) either a `js2-name-node' or a bracketed [expression]
4263 The property-name expressions (examples: ns::name, @name) are
4264 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4265 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4267 This node type (or more specifically, its subclasses) will sometimes
4268 be the right-hand child of a `js2-prop-get-node' or a
4269 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4270 The `js2-xml-ref-node' may also be a standalone primary expression with
4271 no explicit target, which is valid in certain expression contexts such as
4273 company..employee.(@id < 100)
4275 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4276 expression whose parent is a `js2-xml-dot-query-node'."
4281 (defsubst js2-xml-ref-node-attr-access-p (node)
4282 "Return non-nil if this expression began with an @-token."
4283 (and (numberp (js2-xml-ref-node-at-pos node))
4284 (cl-plusp (js2-xml-ref-node-at-pos node))))
4286 (cl-defstruct (js2-xml-prop-ref-node
4287 (:include js2-xml-ref-node)
4289 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4290 (pos (js2-current-token-beg))
4294 "AST node for an E4X XML [expr] property-ref expression.
4295 The JavaScript syntax is an optional @, an optional ns::, and a name.
4297 [ '@' ] [ name '::' ] name
4299 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4300 @ns::*, @*::attr, @*::*, and @*.
4302 The node starts at the @ token, if present. Otherwise it starts at the
4303 namespace name. The node bounds extend through the closing right-bracket,
4304 or if it is missing due to a syntax error, through the end of the index
4308 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4309 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4311 (defun js2-visit-xml-prop-ref-node (n v)
4312 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4313 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4315 (defun js2-print-xml-prop-ref-node (n i)
4316 (insert (js2-make-pad i))
4317 (if (js2-xml-ref-node-attr-access-p n)
4319 (when (js2-xml-prop-ref-node-namespace n)
4320 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4322 (if (js2-xml-prop-ref-node-propname n)
4323 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4325 (cl-defstruct (js2-xml-elem-ref-node
4326 (:include js2-xml-ref-node)
4328 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4329 (pos (js2-current-token-beg))
4333 "AST node for an E4X XML [expr] member-ref expression.
4336 [ '@' ] [ name '::' ] '[' expr ']'
4338 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4340 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4341 is not a legal E4X XML element-ref expression, since it's already used
4342 for standard JavaScript element-get array indexing. Hence, a
4343 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4344 non-nil namespace node, or both.
4346 The node starts at the @ token, if present. Otherwise it starts
4347 at the namespace name. The node bounds extend through the closing
4348 right-bracket, or if it is missing due to a syntax error, through the
4349 end of the index expression."
4350 expr ; the bracketed index expression
4354 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4355 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4357 (defun js2-visit-xml-elem-ref-node (n v)
4358 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4359 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4361 (defun js2-print-xml-elem-ref-node (n i)
4362 (insert (js2-make-pad i))
4363 (if (js2-xml-ref-node-attr-access-p n)
4365 (when (js2-xml-elem-ref-node-namespace n)
4366 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4369 (if (js2-xml-elem-ref-node-expr n)
4370 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4373 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4375 (cl-defstruct (js2-xml-start-tag-node
4376 (:include js2-xml-node)
4378 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4382 "AST node for an XML start-tag. Not currently used.
4383 The `kids' field is a Lisp list of child content nodes."
4384 name ; a `js2-xml-name-node'
4385 attrs ; a Lisp list of `js2-xml-attr-node'
4386 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4388 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4389 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4391 (defun js2-visit-xml-start-tag (n v)
4392 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4393 (dolist (attr (js2-xml-start-tag-node-attrs n))
4394 (js2-visit-ast attr v))
4395 (js2-visit-block n v))
4397 (defun js2-print-xml-start-tag (n i)
4398 (insert (js2-make-pad i) "<")
4399 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4400 (when (js2-xml-start-tag-node-attrs n)
4402 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4405 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4406 ;; and add the end-tag to the kids list of the parent as well.
4407 (cl-defstruct (js2-xml-end-tag-node
4408 (:include js2-xml-node)
4410 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4413 "AST node for an XML end-tag. Not currently used."
4414 name) ; a `js2-xml-name-node'
4416 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4417 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4419 (defun js2-visit-xml-end-tag (n v)
4420 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4422 (defun js2-print-xml-end-tag (n i)
4423 (insert (js2-make-pad i))
4425 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4428 (cl-defstruct (js2-xml-name-node
4429 (:include js2-xml-node)
4431 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4433 len namespace kids)))
4434 "AST node for an E4X XML name. Not currently used.
4435 Any XML name can be qualified with a namespace, hence the namespace field.
4436 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4437 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4438 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4439 namespace) ; a `js2-string-node'
4441 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4442 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4444 (defun js2-visit-xml-name-node (n v)
4445 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4447 (defun js2-print-xml-name-node (n i)
4448 (insert (js2-make-pad i))
4449 (when (js2-xml-name-node-namespace n)
4450 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4452 (dolist (kid (js2-xml-name-node-kids n))
4453 (js2-print-ast kid 0)))
4455 (cl-defstruct (js2-xml-pi-node
4456 (:include js2-xml-node)
4458 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4461 "AST node for an E4X XML processing instruction. Not currently used."
4462 name ; a `js2-xml-name-node'
4463 attrs) ; a list of `js2-xml-attr-node'
4465 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4466 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4468 (defun js2-visit-xml-pi-node (n v)
4469 (js2-visit-ast (js2-xml-pi-node-name n) v)
4470 (dolist (attr (js2-xml-pi-node-attrs n))
4471 (js2-visit-ast attr v)))
4473 (defun js2-print-xml-pi-node (n i)
4474 (insert (js2-make-pad i) "<?")
4475 (js2-print-ast (js2-xml-pi-node-name n))
4476 (when (js2-xml-pi-node-attrs n)
4478 (js2-print-list (js2-xml-pi-node-attrs n)))
4481 (cl-defstruct (js2-xml-cdata-node
4482 (:include js2-xml-node)
4484 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4487 "AST node for a CDATA escape section. Not currently used."
4488 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4490 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4491 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4493 (defun js2-visit-xml-cdata-node (n v)
4494 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4496 (defun js2-print-xml-cdata-node (n i)
4497 (insert (js2-make-pad i))
4498 (js2-print-ast (js2-xml-cdata-node-content n)))
4500 (cl-defstruct (js2-xml-attr-node
4501 (:include js2-xml-node)
4503 (:constructor make-js2-attr-node (&key (type js2-XML)
4506 eq-pos quote-type)))
4507 "AST node representing a foo='bar' XML attribute value. Not yet used."
4508 name ; a `js2-xml-name-node'
4509 value ; a `js2-xml-name-node'
4510 eq-pos ; buffer position of "=" sign
4511 quote-type) ; 'single or 'double
4513 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4514 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4516 (defun js2-visit-xml-attr-node (n v)
4517 (js2-visit-ast (js2-xml-attr-node-name n) v)
4518 (js2-visit-ast (js2-xml-attr-node-value n) v))
4520 (defun js2-print-xml-attr-node (n i)
4521 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4524 (insert (js2-make-pad i))
4525 (js2-print-ast (js2-xml-attr-node-name n) 0)
4527 (js2-print-ast (js2-xml-attr-node-value n) 0)
4530 (cl-defstruct (js2-xml-text-node
4531 (:include js2-xml-node)
4533 (:constructor make-js2-text-node (&key (type js2-XML)
4536 "AST node for an E4X XML text node. Not currently used."
4537 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4539 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4540 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4542 (defun js2-visit-xml-text-node (n v)
4543 (js2-visit-ast (js2-xml-text-node-content n) v))
4545 (defun js2-print-xml-text-node (n i)
4546 (insert (js2-make-pad i))
4547 (dolist (kid (js2-xml-text-node-content n))
4548 (js2-print-ast kid)))
4550 (cl-defstruct (js2-xml-comment-node
4551 (:include js2-xml-node)
4553 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4556 "AST node for E4X XML comment. Not currently used.")
4558 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4559 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4561 (defun js2-print-xml-comment (n i)
4562 (insert (js2-make-pad i)
4563 (js2-node-string n)))
4567 (defsubst js2-node-line (n)
4568 "Fetch the source line number at the start of node N.
4569 This is O(n) in the length of the source buffer; use prudently."
4570 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4572 (defsubst js2-block-node-kid (n i)
4573 "Return child I of node N, or nil if there aren't that many."
4574 (nth i (js2-block-node-kids n)))
4576 (defsubst js2-block-node-first (n)
4577 "Return first child of block node N, or nil if there is none."
4578 (cl-first (js2-block-node-kids n)))
4580 (defun js2-node-root (n)
4581 "Return the root of the AST containing N.
4582 If N has no parent pointer, returns N."
4583 (let ((parent (js2-node-parent n)))
4585 (js2-node-root parent)
4588 (defsubst js2-node-short-name (n)
4589 "Return the short name of node N as a string, e.g. `js2-if-node'."
4590 (substring (symbol-name (aref n 0))
4591 (length "cl-struct-")))
4593 (defun js2-node-child-list (node)
4594 "Return the child list for NODE, a Lisp list of nodes.
4595 Works for block nodes, array nodes, obj literals, funarg lists,
4596 var decls and try nodes (for catch clauses). Note that you should call
4597 `js2-block-node-kids' on the function body for the body statements.
4598 Returns nil for zero-length child lists or unsupported nodes."
4600 ((js2-function-node-p node)
4601 (js2-function-node-params node))
4602 ((js2-block-node-p node)
4603 (js2-block-node-kids node))
4604 ((js2-try-node-p node)
4605 (js2-try-node-catch-clauses node))
4606 ((js2-array-node-p node)
4607 (js2-array-node-elems node))
4608 ((js2-object-node-p node)
4609 (js2-object-node-elems node))
4610 ((js2-call-node-p node)
4611 (js2-call-node-args node))
4612 ((js2-new-node-p node)
4613 (js2-new-node-args node))
4614 ((js2-var-decl-node-p node)
4615 (js2-var-decl-node-kids node))
4619 (defun js2-node-set-child-list (node kids)
4620 "Set the child list for NODE to KIDS."
4622 ((js2-function-node-p node)
4623 (setf (js2-function-node-params node) kids))
4624 ((js2-block-node-p node)
4625 (setf (js2-block-node-kids node) kids))
4626 ((js2-try-node-p node)
4627 (setf (js2-try-node-catch-clauses node) kids))
4628 ((js2-array-node-p node)
4629 (setf (js2-array-node-elems node) kids))
4630 ((js2-object-node-p node)
4631 (setf (js2-object-node-elems node) kids))
4632 ((js2-call-node-p node)
4633 (setf (js2-call-node-args node) kids))
4634 ((js2-new-node-p node)
4635 (setf (js2-new-node-args node) kids))
4636 ((js2-var-decl-node-p node)
4637 (setf (js2-var-decl-node-kids node) kids))
4639 (error "Unsupported node type: %s" (js2-node-short-name node))))
4642 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4643 (defconst js2-paren-expr-nodes
4644 '(cl-struct-js2-comp-loop-node
4645 cl-struct-js2-comp-node
4646 cl-struct-js2-call-node
4647 cl-struct-js2-catch-node
4648 cl-struct-js2-do-node
4649 cl-struct-js2-elem-get-node
4650 cl-struct-js2-for-in-node
4651 cl-struct-js2-for-node
4652 cl-struct-js2-function-node
4653 cl-struct-js2-if-node
4654 cl-struct-js2-let-node
4655 cl-struct-js2-new-node
4656 cl-struct-js2-paren-node
4657 cl-struct-js2-switch-node
4658 cl-struct-js2-while-node
4659 cl-struct-js2-with-node
4660 cl-struct-js2-xml-dot-query-node)
4661 "Node types that can have a parenthesized child expression.
4662 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4664 (defsubst js2-paren-expr-node-p (node)
4665 "Return t for nodes that typically have a parenthesized child expression.
4666 Useful for computing the indentation anchors for arg-lists and conditions.
4667 Note that it may return a false positive, for instance when NODE is
4668 a `js2-new-node' and there are no arguments or parentheses."
4669 (memq (aref node 0) js2-paren-expr-nodes))
4671 ;; Fake polymorphism... yech.
4672 (defun js2-node-lp (node)
4673 "Return relative left-paren position for NODE, if applicable.
4674 For `js2-elem-get-node' structs, returns left-bracket position.
4675 Note that the position may be nil in the case of a parse error."
4677 ((js2-elem-get-node-p node)
4678 (js2-elem-get-node-lb node))
4679 ((js2-loop-node-p node)
4680 (js2-loop-node-lp node))
4681 ((js2-function-node-p node)
4682 (js2-function-node-lp node))
4683 ((js2-if-node-p node)
4684 (js2-if-node-lp node))
4685 ((js2-new-node-p node)
4686 (js2-new-node-lp node))
4687 ((js2-call-node-p node)
4688 (js2-call-node-lp node))
4689 ((js2-paren-node-p node)
4691 ((js2-switch-node-p node)
4692 (js2-switch-node-lp node))
4693 ((js2-catch-node-p node)
4694 (js2-catch-node-lp node))
4695 ((js2-let-node-p node)
4696 (js2-let-node-lp node))
4697 ((js2-comp-node-p node)
4699 ((js2-with-node-p node)
4700 (js2-with-node-lp node))
4701 ((js2-xml-dot-query-node-p node)
4702 (1+ (js2-infix-node-op-pos node)))
4704 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4706 ;; Fake polymorphism... blech.
4707 (defun js2-node-rp (node)
4708 "Return relative right-paren position for NODE, if applicable.
4709 For `js2-elem-get-node' structs, returns right-bracket position.
4710 Note that the position may be nil in the case of a parse error."
4712 ((js2-elem-get-node-p node)
4713 (js2-elem-get-node-rb node))
4714 ((js2-loop-node-p node)
4715 (js2-loop-node-rp node))
4716 ((js2-function-node-p node)
4717 (js2-function-node-rp node))
4718 ((js2-if-node-p node)
4719 (js2-if-node-rp node))
4720 ((js2-new-node-p node)
4721 (js2-new-node-rp node))
4722 ((js2-call-node-p node)
4723 (js2-call-node-rp node))
4724 ((js2-paren-node-p node)
4725 (1- (js2-node-len node)))
4726 ((js2-switch-node-p node)
4727 (js2-switch-node-rp node))
4728 ((js2-catch-node-p node)
4729 (js2-catch-node-rp node))
4730 ((js2-let-node-p node)
4731 (js2-let-node-rp node))
4732 ((js2-comp-node-p node)
4733 (1- (js2-node-len node)))
4734 ((js2-with-node-p node)
4735 (js2-with-node-rp node))
4736 ((js2-xml-dot-query-node-p node)
4737 (1+ (js2-xml-dot-query-node-rp node)))
4739 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4741 (defsubst js2-node-first-child (node)
4742 "Return the first element of `js2-node-child-list' for NODE."
4743 (car (js2-node-child-list node)))
4745 (defsubst js2-node-last-child (node)
4746 "Return the last element of `js2-node-last-child' for NODE."
4747 (car (last (js2-node-child-list node))))
4749 (defun js2-node-prev-sibling (node)
4750 "Return the previous statement in parent.
4751 Works for parents supported by `js2-node-child-list'.
4752 Returns nil if NODE is not in the parent, or PARENT is
4753 not a supported node, or if NODE is the first child."
4754 (let* ((p (js2-node-parent node))
4755 (kids (js2-node-child-list p))
4758 (not (eq node (cadr kids))))
4759 (setq kids (cdr kids)
4763 (defun js2-node-next-sibling (node)
4764 "Return the next statement in parent block.
4765 Returns nil if NODE is not in the block, or PARENT is not
4766 a block node, or if NODE is the last statement."
4767 (let* ((p (js2-node-parent node))
4768 (kids (js2-node-child-list p)))
4770 (not (eq node (car kids))))
4771 (setq kids (cdr kids)))
4774 (defun js2-node-find-child-before (pos parent &optional after)
4775 "Find the last child that starts before POS in parent.
4776 If AFTER is non-nil, returns first child starting after POS.
4777 POS is an absolute buffer position. PARENT is any node
4778 supported by `js2-node-child-list'.
4779 Returns nil if no applicable child is found."
4780 (let ((kids (if (js2-function-node-p parent)
4781 (js2-block-node-kids (js2-function-node-body parent))
4782 (js2-node-child-list parent)))
4783 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4784 (js2-function-node-body parent)
4788 (setq fn (if after '>= '<))
4789 (while (and kids continue)
4790 (setq kid (car kids))
4791 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4793 continue (not after))
4794 (setq continue after))
4795 (setq kids (cdr kids)))
4798 (defun js2-node-find-child-after (pos parent)
4799 "Find first child that starts after POS in parent.
4800 POS is an absolute buffer position. PARENT is any node
4801 supported by `js2-node-child-list'.
4802 Returns nil if no applicable child is found."
4803 (js2-node-find-child-before pos parent 'after))
4805 (defun js2-node-replace-child (pos parent new-node)
4806 "Replace node at index POS in PARENT with NEW-NODE.
4807 Only works for parents supported by `js2-node-child-list'."
4808 (let ((kids (js2-node-child-list parent))
4811 (setq kids (cdr kids)
4813 (setcar kids new-node)
4814 (js2-node-add-children parent new-node)))
4816 (defun js2-node-buffer (n)
4817 "Return the buffer associated with AST N.
4818 Returns nil if the buffer is not set as a property on the root
4819 node, or if parent links were not recorded during parsing."
4820 (let ((root (js2-node-root n)))
4822 (js2-ast-root-p root)
4823 (js2-ast-root-buffer root))))
4825 (defun js2-block-node-push (n kid)
4826 "Push js2-node KID onto the end of js2-block-node N's child list.
4827 KID is always added to the -end- of the kids list.
4828 Function also calls `js2-node-add-children' to add the parent link."
4829 (let ((kids (js2-node-child-list n)))
4831 (setcdr kids (nconc (cdr kids) (list kid)))
4832 (js2-node-set-child-list n (list kid)))
4833 (js2-node-add-children n kid)))
4835 (defun js2-node-string (node)
4836 (with-current-buffer (or (js2-node-buffer node)
4837 (error "No buffer available for node %s" node))
4838 (let ((pos (js2-node-abs-pos node)))
4839 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4841 ;; Container for storing the node we're looking for in a traversal.
4842 (js2-deflocal js2-discovered-node nil)
4844 ;; Keep track of absolute node position during traversals.
4845 (js2-deflocal js2-visitor-offset nil)
4847 (js2-deflocal js2-node-search-point nil)
4849 (when js2-mode-dev-mode-p
4850 (defun js2-find-node-at-point ()
4852 (let ((node (js2-node-at-point)))
4853 (message "%s" (or node "No node found at point"))))
4854 (defun js2-node-name-at-point ()
4856 (let ((node (js2-node-at-point)))
4857 (message "%s" (if node
4858 (js2-node-short-name node)
4859 "No node found at point.")))))
4861 (defun js2-node-at-point (&optional pos skip-comments)
4862 "Return AST node at POS, a buffer position, defaulting to current point.
4863 The `js2-mode-ast' variable must be set to the current parse tree.
4864 Signals an error if the AST (`js2-mode-ast') is nil.
4865 Always returns a node - if it can't find one, it returns the root.
4866 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4867 (let ((ast js2-mode-ast)
4870 (error "No JavaScript AST available"))
4871 ;; Look through comments first, since they may be inside nodes that
4872 ;; would otherwise report a match.
4873 (setq pos (or pos (point))
4874 result (if (> pos (js2-node-abs-end ast))
4876 (if (not skip-comments)
4877 (js2-comment-at-point pos))))
4879 (setq js2-discovered-node nil
4880 js2-visitor-offset 0
4881 js2-node-search-point pos)
4883 (catch 'js2-visit-done
4884 (js2-visit-ast ast #'js2-node-at-point-visitor))
4885 (setq js2-visitor-offset nil
4886 js2-node-search-point nil))
4887 (setq result js2-discovered-node))
4888 ;; may have found a comment beyond end of last child node,
4889 ;; since visiting the ast-root looks at the comment-list last.
4890 (if (and skip-comments
4891 (js2-comment-node-p result))
4893 (or result js2-mode-ast)))
4895 (defun js2-node-at-point-visitor (node end-p)
4896 (let ((rel-pos (js2-node-pos node))
4899 (point js2-node-search-point))
4902 ;; this evaluates to a non-nil return value, even if it's zero
4903 (cl-decf js2-visitor-offset rel-pos))
4904 ;; we already looked for comments before visiting, and don't want them now
4905 ((js2-comment-node-p node)
4908 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4909 ;; we only want to use the node if the point is before
4910 ;; the last character position in the node, so we decrement
4911 ;; the absolute end by 1.
4912 abs-end (+ abs-pos (js2-node-len node) -1))
4914 ;; If this node starts after search-point, stop the search.
4916 (throw 'js2-visit-done nil))
4917 ;; If this node ends before the search-point, don't check kids.
4921 ;; Otherwise point is within this node, possibly in a child.
4922 (setq js2-discovered-node node)
4923 t)))))) ; keep processing kids to look for more specific match
4925 (defsubst js2-block-comment-p (node)
4926 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4927 (and (js2-comment-node-p node)
4928 (memq (js2-comment-node-format node) '(jsdoc block))))
4930 ;; TODO: put the comments in a vector and binary-search them instead
4931 (defun js2-comment-at-point (&optional pos)
4932 "Look through scanned comment nodes for one containing POS.
4933 POS is a buffer position that defaults to current point.
4934 Function returns nil if POS was not in any comment node."
4935 (let ((ast js2-mode-ast)
4936 (x (or pos (point)))
4939 (error "No JavaScript AST available"))
4941 ;; Comments are stored in lexical order.
4942 (dolist (comment (js2-ast-root-comments ast) nil)
4943 (setq beg (js2-node-abs-pos comment)
4944 end (+ beg (js2-node-len comment)))
4947 (throw 'done comment))))))
4949 (defun js2-mode-find-parent-fn (node)
4950 "Find function enclosing NODE.
4951 Returns nil if NODE is not inside a function."
4952 (setq node (js2-node-parent node))
4953 (while (and node (not (js2-function-node-p node)))
4954 (setq node (js2-node-parent node)))
4955 (and (js2-function-node-p node) node))
4957 (defun js2-mode-find-enclosing-fn (node)
4958 "Find function or root enclosing NODE."
4959 (if (js2-ast-root-p node)
4961 (setq node (js2-node-parent node))
4962 (while (not (or (js2-ast-root-p node)
4963 (js2-function-node-p node)))
4964 (setq node (js2-node-parent node)))
4967 (defun js2-mode-find-enclosing-node (beg end)
4968 "Find node fully enclosing BEG and END."
4969 (let ((node (js2-node-at-point beg))
4973 (if (or (js2-ast-root-p node)
4975 (<= (setq pos (js2-node-abs-pos node)) beg)
4976 (>= (+ pos (js2-node-len node)) end)))
4978 (setq node (js2-node-parent node))))
4981 (defun js2-node-parent-script-or-fn (node)
4982 "Find script or function immediately enclosing NODE.
4983 If NODE is the ast-root, returns nil."
4984 (if (js2-ast-root-p node)
4986 (setq node (js2-node-parent node))
4987 (while (and node (not (or (js2-function-node-p node)
4988 (js2-script-node-p node))))
4989 (setq node (js2-node-parent node)))
4992 (defun js2-node-is-descendant (node ancestor)
4993 "Return t if NODE is a descendant of ANCESTOR."
4995 (not (eq node ancestor)))
4996 (setq node (js2-node-parent node)))
4999 ;;; visitor infrastructure
5001 (defun js2-visit-none (_node _callback)
5002 "Visitor for AST node that have no node children."
5005 (defun js2-print-none (_node _indent)
5006 "Visitor for AST node with no printed representation.")
5008 (defun js2-print-body (node indent)
5009 "Print a statement, or a block without braces."
5010 (if (js2-block-node-p node)
5011 (dolist (kid (js2-block-node-kids node))
5012 (js2-print-ast kid indent))
5013 (js2-print-ast node indent)))
5015 (defun js2-print-list (args &optional delimiter)
5016 (cl-loop with len = (length args)
5020 (when arg (js2-print-ast arg 0))
5022 (insert (or delimiter ", ")))))
5024 (defun js2-print-tree (ast)
5025 "Prints an AST to the current buffer.
5026 Makes `js2-ast-parent-nodes' available to the printer functions."
5027 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5028 (js2-print-ast ast)))
5030 (defun js2-print-ast (node &optional indent)
5031 "Helper function for printing AST nodes.
5032 Requires `js2-ast-parent-nodes' to be non-nil.
5033 You should use `js2-print-tree' instead of this function."
5034 (let ((printer (get (aref node 0) 'js2-printer))
5036 ;; TODO: wedge comments in here somewhere
5038 (funcall printer node i))))
5040 (defconst js2-side-effecting-tokens
5041 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5042 (dolist (tt (list js2-ASSIGN
5112 (if js2-instanceof-has-side-effects
5113 (aset tokens js2-INSTANCEOF t))
5116 (defun js2-node-has-side-effects (node)
5117 "Return t if NODE has side effects."
5118 (when node ; makes it easier to handle malformed expressions
5119 (let ((tt (js2-node-type node)))
5121 ;; This doubtless needs some work, since EXPR_VOID is used
5122 ;; in several ways in Rhino and I may not have caught them all.
5123 ;; I'll wait for people to notice incorrect warnings.
5124 ((and (= tt js2-EXPR_VOID)
5125 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5126 (let ((expr (js2-expr-stmt-node-expr node)))
5127 (or (js2-node-has-side-effects expr)
5128 (when (js2-string-node-p expr)
5129 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5131 (js2-node-has-side-effects (js2-infix-node-right node)))
5134 (or (js2-node-has-side-effects (js2-infix-node-right node))
5135 (js2-node-has-side-effects (js2-infix-node-left node))))
5137 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5138 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5139 ((js2-paren-node-p node)
5140 (js2-node-has-side-effects (js2-paren-node-expr node)))
5141 ((= tt js2-ERROR) ; avoid cascaded error messages
5144 (aref js2-side-effecting-tokens tt))))))
5146 (defconst js2-stmt-node-types
5150 js2-DEFAULT ; e4x "default xml namespace" statement
5164 "Node types that only appear in statement contexts.
5165 The list does not include nodes that always appear as the child
5166 of another specific statement type, such as switch-cases,
5167 catch and finally blocks, and else-clauses. The list also excludes
5168 nodes like yield, let and var, which may appear in either expression
5169 or statement context, and in the latter context always have a
5170 `js2-expr-stmt-node' parent. Finally, the list does not include
5171 functions or scripts, which are treated separately from statements
5172 by the JavaScript parser and runtime.")
5174 (defun js2-stmt-node-p (node)
5175 "Heuristic for figuring out if NODE is a statement.
5176 Some node types can appear in either an expression context or a
5177 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5178 For these node types in a statement context, the parent will be a
5179 `js2-expr-stmt-node'.
5180 Functions aren't included in the check."
5181 (memq (js2-node-type node) js2-stmt-node-types))
5183 (defun js2-mode-find-first-stmt (node)
5184 "Search upward starting from NODE looking for a statement.
5185 For purposes of this function, a `js2-function-node' counts."
5186 (while (not (or (js2-stmt-node-p node)
5187 (js2-function-node-p node)))
5188 (setq node (js2-node-parent node)))
5191 (defun js2-node-parent-stmt (node)
5192 "Return the node's first ancestor that is a statement.
5193 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5194 appearing in a statement context will have a parent that is a
5195 `js2-expr-stmt-node' that will be returned by this function."
5196 (let ((parent (js2-node-parent node)))
5197 (if (or (null parent)
5198 (js2-stmt-node-p parent)
5199 (and (js2-function-node-p parent)
5200 (not (eq (js2-function-node-form parent)
5201 'FUNCTION_EXPRESSION))))
5203 (js2-node-parent-stmt parent))))
5205 ;; In the Mozilla Rhino sources, Roshan James writes:
5206 ;; Does consistent-return analysis on the function body when strict mode is
5209 ;; function (x) { return (x+1) }
5213 ;; function (x) { if (x < 0) return (x+1); }
5215 ;; is not because the function can potentially return a value when the
5216 ;; condition is satisfied and if not, the function does not explicitly
5219 ;; This extends to checking mismatches such as "return" and "return <value>"
5220 ;; used in the same function. Warnings are not emitted if inconsistent
5221 ;; returns exist in code that can be statically shown to be unreachable.
5223 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5225 ;; emits no warning. However if the loop had a break statement, then a
5226 ;; warning would be emitted.
5228 ;; The consistency analysis looks at control structures such as loops, ifs,
5229 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5230 ;; warns the user about an inconsistent set of termination possibilities.
5232 ;; These flags enumerate the possible ways a statement/function can
5233 ;; terminate. These flags are used by endCheck() and by the Parser to
5234 ;; detect inconsistent return usage.
5236 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5237 ;; able to execute (example: throw, continue)
5239 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5240 ;; next one. Statement such as return dont. A compound statement may have
5241 ;; some branch that drops off control to the next statement.
5243 ;; END_RETURNS indicates that the statement can return with no value.
5244 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5246 ;; A compound statement such as
5250 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5252 (defconst js2-END_UNREACHED 0)
5253 (defconst js2-END_DROPS_OFF 1)
5254 (defconst js2-END_RETURNS 2)
5255 (defconst js2-END_RETURNS_VALUE 4)
5256 (defconst js2-END_YIELDS 8)
5258 (defun js2-has-consistent-return-usage (node)
5259 "Check that every return usage in a function body is consistent.
5260 Returns t if the function satisfies strict mode requirement."
5261 (let ((n (js2-end-check node)))
5262 ;; either it doesn't return a value in any branch...
5263 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5264 ;; or it returns a value (or is unreached) at every branch
5265 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5269 (defun js2-end-check-if (node)
5270 "Ensure that return usage in then/else blocks is consistent.
5271 If there is no else block, then the return statement can fall through.
5272 Returns logical OR of END_* flags"
5273 (let ((th (js2-if-node-then-part node))
5274 (el (js2-if-node-else-part node)))
5277 (logior (js2-end-check th) (if el
5279 js2-END_DROPS_OFF)))))
5281 (defun js2-end-check-switch (node)
5282 "Consistency of return statements is checked between the case statements.
5283 If there is no default, then the switch can fall through. If there is a
5284 default, we check to see if all code paths in the default return or if
5285 there is a code path that can fall through.
5286 Returns logical OR of END_* flags."
5287 (let ((rv js2-END_UNREACHED)
5289 ;; examine the cases
5291 (dolist (c (js2-switch-node-cases node))
5292 (if (js2-case-node-expr c)
5293 (js2-set-flag rv (js2-end-check-block c))
5294 (setq default-case c)
5295 (throw 'break nil))))
5296 ;; we don't care how the cases drop into each other
5297 (js2-clear-flag rv js2-END_DROPS_OFF)
5298 ;; examine the default
5299 (js2-set-flag rv (if default-case
5300 (js2-end-check default-case)
5304 (defun js2-end-check-try (node)
5305 "If the block has a finally, return consistency is checked in the
5306 finally block. If all code paths in the finally return, then the
5307 returns in the try-catch blocks don't matter. If there is a code path
5308 that does not return or if there is no finally block, the returns
5309 of the try and catch blocks are checked for mismatch.
5310 Returns logical OR of END_* flags."
5311 (let ((finally (js2-try-node-finally-block node))
5313 ;; check the finally if it exists
5314 (setq rv (if finally
5315 (js2-end-check (js2-finally-node-body finally))
5317 ;; If the finally block always returns, then none of the returns
5318 ;; in the try or catch blocks matter.
5319 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5320 (js2-clear-flag rv js2-END_DROPS_OFF)
5321 ;; examine the try block
5322 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5323 ;; check each catch block
5324 (dolist (cb (js2-try-node-catch-clauses node))
5325 (js2-set-flag rv (js2-end-check cb))))
5328 (defun js2-end-check-loop (node)
5329 "Return statement in the loop body must be consistent.
5330 The default assumption for any kind of a loop is that it will eventually
5331 terminate. The only exception is a loop with a constant true condition.
5332 Code that follows such a loop is examined only if one can determine
5333 statically that there is a break out of the loop.
5335 for(... ; ... ; ...) {}
5340 Returns logical OR of END_* flags."
5341 (let ((rv (js2-end-check (js2-loop-node-body node)))
5343 ((js2-while-node-p node)
5344 (js2-while-node-condition node))
5345 ((js2-do-node-p node)
5346 (js2-do-node-condition node))
5347 ((js2-for-node-p node)
5348 (js2-for-node-condition node)))))
5350 ;; check to see if the loop condition is always true
5352 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5353 (js2-clear-flag rv js2-END_DROPS_OFF))
5355 ;; look for effect of breaks
5356 (js2-set-flag rv (js2-node-get-prop node
5361 (defun js2-end-check-block (node)
5362 "A general block of code is examined statement by statement.
5363 If any statement (even a compound one) returns in all branches, then
5364 subsequent statements are not examined.
5365 Returns logical OR of END_* flags."
5366 (let* ((rv js2-END_DROPS_OFF)
5367 (kids (js2-block-node-kids node))
5369 ;; Check each statment. If the statement can continue onto the next
5370 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5371 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5372 (js2-clear-flag rv js2-END_DROPS_OFF)
5373 (js2-set-flag rv (js2-end-check n))
5374 (setq kids (cdr kids)
5378 (defun js2-end-check-label (node)
5379 "A labeled statement implies that there may be a break to the label.
5380 The function processes the labeled statement and then checks the
5381 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5383 Returns logical OR of END_* flags."
5384 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5385 (logior rv (js2-node-get-prop node
5387 js2-END_UNREACHED))))
5389 (defun js2-end-check-break (node)
5390 "When a break is encountered annotate the statement being broken
5391 out of by setting its CONTROL_BLOCK_PROP property.
5392 Returns logical OR of END_* flags."
5393 (and (js2-break-node-target node)
5394 (js2-node-set-prop (js2-break-node-target node)
5399 (defun js2-end-check (node)
5400 "Examine the body of a function, doing a basic reachability analysis.
5401 Returns a combination of flags END_* flags that indicate
5402 how the function execution can terminate. These constitute only the
5403 pessimistic set of termination conditions. It is possible that at
5404 runtime certain code paths will never be actually taken. Hence this
5405 analysis will flag errors in cases where there may not be errors.
5406 Returns logical OR of END_* flags"
5409 ((js2-break-node-p node)
5410 (js2-end-check-break node))
5411 ((js2-expr-stmt-node-p node)
5412 (if (setq kid (js2-expr-stmt-node-expr node))
5415 ((or (js2-continue-node-p node)
5416 (js2-throw-node-p node))
5418 ((js2-return-node-p node)
5419 (if (setq kid (js2-return-node-retval node))
5420 js2-END_RETURNS_VALUE
5422 ((js2-loop-node-p node)
5423 (js2-end-check-loop node))
5424 ((js2-switch-node-p node)
5425 (js2-end-check-switch node))
5426 ((js2-labeled-stmt-node-p node)
5427 (js2-end-check-label node))
5428 ((js2-if-node-p node)
5429 (js2-end-check-if node))
5430 ((js2-try-node-p node)
5431 (js2-end-check-try node))
5432 ((js2-block-node-p node)
5433 (if (null (js2-block-node-kids node))
5435 (js2-end-check-block node)))
5436 ((js2-yield-node-p node)
5439 js2-END_DROPS_OFF))))
5441 (defun js2-always-defined-boolean-p (node)
5442 "Check if NODE always evaluates to true or false in boolean context.
5443 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5445 (let ((tt (js2-node-type node))
5448 ((or (= tt js2-FALSE) (= tt js2-NULL))
5453 (setq num (js2-number-node-num-value node))
5454 (if (and (not (eq num 0.0e+NaN))
5461 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5462 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5464 (defvar js2-tokens nil
5465 "List of all defined token names.") ; initialized in `js2-token-names'
5467 (defconst js2-token-names
5468 (let* ((names (make-vector js2-num-tokens -1))
5469 (case-fold-search nil) ; only match js2-UPPER_CASE
5470 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5471 (cl-loop for sym in syms
5474 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5476 (aset names (symbol-value sym) ; code, e.g. 152
5478 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5479 (push sym js2-tokens)))
5481 "Vector mapping int values to token string names, sans `js2-' prefix.")
5483 (defun js2-tt-name (tok)
5484 "Return a string name for TOK, a token symbol or code.
5485 Signals an error if it's not a recognized token."
5488 (setq code (symbol-value tok)))
5491 (if (and (numberp code)
5492 (not (cl-minusp code))
5493 (< code js2-num-tokens))
5494 (aref js2-token-names code)
5495 (error "Invalid token: %s" code)))))
5497 (defsubst js2-tt-sym (tok)
5498 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5499 (intern (js2-tt-name tok)))
5501 (defconst js2-token-codes
5502 (let ((table (make-hash-table :test 'eq :size 256)))
5503 (cl-loop for name across js2-token-names
5504 for sym = (intern (concat "js2-" (upcase name)))
5506 (puthash sym (symbol-value sym) table))
5507 ;; clean up a few that are "wrong" in Rhino's token codes
5508 (puthash 'js2-DELETE js2-DELPROP table)
5510 "Hashtable mapping token type symbols to their bytecodes.")
5512 (defsubst js2-tt-code (sym)
5513 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5514 (or (gethash sym js2-token-codes)
5515 (error "Invalid token symbol: %s " sym))) ; signal code bug
5517 (defun js2-report-scan-error (msg &optional no-throw beg len)
5518 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5519 (js2-report-error msg nil
5520 (or beg (js2-current-token-beg))
5521 (or len (js2-current-token-len)))
5523 (throw 'return js2-ERROR)))
5525 (defun js2-set-string-from-buffer (token)
5526 "Set `string' and `end' slots for TOKEN, return the string."
5527 (setf (js2-token-end token) js2-ts-cursor
5528 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5530 ;; TODO: could potentially avoid a lot of consing by allocating a
5531 ;; char buffer the way Rhino does.
5532 (defsubst js2-add-to-string (c)
5533 (push c js2-ts-string-buffer))
5535 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5536 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5537 ;; any other character: when it's not part of the current token, we
5538 ;; unget it, allowing it to be read again by the following call.
5539 (defsubst js2-unget-char ()
5540 (cl-decf js2-ts-cursor))
5542 ;; Rhino distinguishes \r and \n line endings. We don't need to
5543 ;; because we only scan from Emacs buffers, which always use \n.
5544 (defun js2-get-char ()
5545 "Read and return the next character from the input buffer.
5546 Increments `js2-ts-lineno' if the return value is a newline char.
5547 Updates `js2-ts-cursor' to the point after the returned char.
5548 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5549 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5551 ;; check for end of buffer
5552 (if (>= js2-ts-cursor (point-max))
5553 (setq js2-ts-hit-eof t
5554 js2-ts-cursor (1+ js2-ts-cursor)
5555 c js2-EOF_CHAR) ; return value
5556 ;; otherwise read next char
5557 (setq c (char-before (cl-incf js2-ts-cursor)))
5558 ;; if we read a newline, update counters
5560 (setq js2-ts-line-start js2-ts-cursor
5561 js2-ts-lineno (1+ js2-ts-lineno)))
5562 ;; TODO: skip over format characters
5565 (defun js2-read-unicode-escape ()
5566 "Read a \\uNNNN sequence from the input.
5567 Assumes the ?\ and ?u have already been read.
5568 Returns the unicode character, or nil if it wasn't a valid character.
5569 Doesn't change the values of any scanner variables."
5570 ;; I really wish I knew a better way to do this, but I can't
5571 ;; find the Emacs function that takes a 16-bit int and converts
5572 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5573 ;; Have to first check that it's 4 hex characters or it may stop
5576 (let ((s (buffer-substring-no-properties js2-ts-cursor
5577 (+ 4 js2-ts-cursor))))
5578 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5579 (read (concat "?\\u" s))))))
5581 (defun js2-match-char (test)
5582 "Consume and return next character if it matches TEST, a character.
5583 Returns nil and consumes nothing if TEST is not the next character."
5584 (let ((c (js2-get-char)))
5590 (defun js2-peek-char ()
5595 (defun js2-identifier-start-p (c)
5596 "Is C a valid start to an ES5 Identifier?
5597 See http://es5.github.io/#x7.6"
5600 (memq (get-char-code-property c 'general-category)
5602 '(Lu Ll Lt Lm Lo Nl))))
5604 (defun js2-identifier-part-p (c)
5605 "Is C a valid part of an ES5 Identifier?
5606 See http://es5.github.io/#x7.6"
5608 (memq c '(?$ ?_ ?\u200c ?\u200d))
5609 (memq (get-char-code-property c 'general-category)
5616 ;; Connector Punctuation
5619 (defun js2-alpha-p (c)
5620 (cond ((and (<= ?A c) (<= c ?Z)) t)
5621 ((and (<= ?a c) (<= c ?z)) t)
5624 (defsubst js2-digit-p (c)
5625 (and (<= ?0 c) (<= c ?9)))
5627 (defun js2-js-space-p (c)
5629 (memq c '(#x20 #x9 #xB #xC #xD))
5632 ;; TODO: change this nil to check for Unicode space character
5635 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5637 (defun js2-skip-line ()
5638 "Skip to end of line."
5639 (while (not (memq (js2-get-char) js2-eol-chars)))
5641 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5643 (defun js2-init-scanner (&optional buf line)
5644 "Create token stream for BUF starting on LINE.
5645 BUF defaults to `current-buffer' and LINE defaults to 1.
5647 A buffer can only have one scanner active at a time, which yields
5648 dramatically simpler code than using a defstruct. If you need to
5649 have simultaneous scanners in a buffer, copy the regions to scan
5651 (with-current-buffer (or buf (current-buffer))
5652 (setq js2-ts-dirty-line nil
5655 js2-ts-lineno (or line 1)
5656 js2-ts-line-end-char -1
5657 js2-ts-cursor (point-min)
5658 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5659 js2-ti-tokens-cursor 0
5661 js2-ts-is-xml-attribute nil
5662 js2-ts-xml-is-tag-content nil
5663 js2-ts-xml-open-tags-count 0
5664 js2-ts-string-buffer nil)))
5666 ;; This function uses the cached op, string and number fields in
5667 ;; TokenStream; if getToken has been called since the passed token
5668 ;; was scanned, the op or string printed may be incorrect.
5669 (defun js2-token-to-string (token)
5670 ;; Not sure where this function is used in Rhino. Not tested.
5671 (if (not js2-debug-print-trees)
5673 (let ((name (js2-tt-name token)))
5675 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5676 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5677 (concat name " `" (js2-current-token-string) "'"))
5678 ((eq token js2-NUMBER)
5679 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5683 (defconst js2-keywords
5685 case catch class const continue
5686 debugger default delete do
5688 false finally for function
5689 if in instanceof import
5694 this throw true try typeof
5699 ;; Token names aren't exactly the same as the keywords, unfortunately.
5700 ;; E.g. delete is js2-DELPROP.
5701 (defconst js2-kwd-tokens
5702 (let ((table (make-vector js2-num-tokens nil))
5705 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5706 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5708 js2-ELSE js2-EXTENDS js2-EXPORT
5709 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5710 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5714 js2-STATIC js2-SUPER js2-SWITCH
5715 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5720 (aset table i 'font-lock-keyword-face))
5721 (aset table js2-STRING 'font-lock-string-face)
5722 (aset table js2-REGEXP 'font-lock-string-face)
5723 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5724 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5725 (aset table js2-COMMENT 'font-lock-comment-face)
5726 (aset table js2-THIS 'font-lock-builtin-face)
5727 (aset table js2-SUPER 'font-lock-builtin-face)
5728 (aset table js2-VOID 'font-lock-constant-face)
5729 (aset table js2-NULL 'font-lock-constant-face)
5730 (aset table js2-TRUE 'font-lock-constant-face)
5731 (aset table js2-FALSE 'font-lock-constant-face)
5732 (aset table js2-NOT 'font-lock-negation-char-face)
5734 "Vector whose values are non-nil for tokens that are keywords.
5735 The values are default faces to use for highlighting the keywords.")
5737 ;; FIXME: Support strict mode-only future reserved words, after we know
5738 ;; which parts scopes are in strict mode, and which are not.
5739 (defconst js2-reserved-words '(class enum export extends import super)
5740 "Future reserved keywords in ECMAScript 5.1.")
5742 (defconst js2-keyword-names
5743 (let ((table (make-hash-table :test 'equal)))
5744 (cl-loop for k in js2-keywords
5746 (symbol-name k) ; instanceof
5747 (intern (concat "js2-"
5748 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5751 "JavaScript keywords by name, mapped to their symbols.")
5753 (defconst js2-reserved-word-names
5754 (let ((table (make-hash-table :test 'equal)))
5755 (cl-loop for k in js2-reserved-words
5757 (puthash (symbol-name k) 'js2-RESERVED table))
5759 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5761 (defun js2-collect-string (buf)
5762 "Convert BUF, a list of chars, to a string.
5763 Reverses BUF before converting."
5765 (apply #'string (nreverse buf))
5768 (defun js2-string-to-keyword (s)
5769 "Return token for S, a string, if S is a keyword or reserved word.
5770 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5771 (or (gethash s js2-keyword-names)
5772 (gethash s js2-reserved-word-names)))
5774 (defsubst js2-ts-set-char-token-bounds (token)
5775 "Used when next token is one character."
5776 (setf (js2-token-beg token) (1- js2-ts-cursor)
5777 (js2-token-end token) js2-ts-cursor))
5779 (defsubst js2-ts-return (token type)
5780 "Update the `end' and `type' slots of TOKEN,
5781 then throw `return' with value TYPE."
5782 (setf (js2-token-end token) js2-ts-cursor
5783 (js2-token-type token) type)
5784 (throw 'return type))
5786 (defun js2-x-digit-to-int (c accumulator)
5787 "Build up a hex number.
5788 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5789 corresponding number. Otherwise return -1."
5792 ;; Use 0..9 < A..Z < a..z
5797 (throw 'check nil)))
5800 (cl-decf c (- ?A 10))
5801 (throw 'check nil)))
5804 (cl-decf c (- ?a 10))
5805 (throw 'check nil))))
5807 (logior c (lsh accumulator 4))))
5809 (defun js2-get-token (&optional modifier)
5810 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5811 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5814 This function will not return a newline (js2-EOL) - instead, it
5815 gobbles newlines until it finds a non-newline token. Call
5816 `js2-peek-token-or-eol' when you care about newlines.
5818 This function will also not return a js2-COMMENT. Instead, it
5819 records comments found in `js2-scanned-comments'. If the token
5820 returned by this function immediately follows a jsdoc comment,
5821 the token is flagged as such."
5822 (if (zerop js2-ti-lookahead)
5823 (js2-get-token-internal modifier)
5824 (cl-decf js2-ti-lookahead)
5825 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5826 (let ((tt (js2-current-token-type)))
5827 (cl-assert (not (= tt js2-EOL)))
5830 (defun js2-unget-token ()
5831 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5832 (cl-incf js2-ti-lookahead)
5833 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5835 (defun js2-get-token-internal (modifier)
5836 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5837 (tt (js2-token-type token))
5841 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5845 (when js2-record-comments
5846 (js2-record-comment token)))
5847 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5848 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5849 tt (js2-token-type token)))
5852 (setf (js2-token-follows-eol-p token) t))
5854 ;; perform lexical fontification as soon as token is scanned
5855 (when js2-parse-ide-mode
5858 (js2-record-face 'js2-error token))
5859 ((setq face (aref js2-kwd-tokens tt))
5860 (js2-record-face face token))
5861 ((and (= tt js2-NAME)
5862 (equal (js2-token-string token) "undefined"))
5863 (js2-record-face 'font-lock-constant-face token))))
5866 (defsubst js2-string-to-number (str base)
5867 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5869 (string-to-number str base)
5870 (overflow-error -1)))
5872 (defun js2-get-token-internal-1 (modifier)
5873 "Return next JavaScript token type, an int such as js2-RETURN.
5874 During operation, creates an instance of `js2-token' struct, sets
5875 its relevant fields and puts it into `js2-ti-tokens'."
5876 (let (identifier-start
5877 is-unicode-escape-start c
5878 contains-escape escape-val str result base
5879 quote-char look-for-slash continue tt
5880 (token (js2-new-token 0)))
5884 (when (eq modifier 'TEMPLATE_TAIL)
5885 (setf (js2-token-beg token) (1- js2-ts-cursor))
5886 (throw 'return (js2-get-string-or-template-token ?` token)))
5888 ;; Eat whitespace, possibly sensitive to newlines.
5891 (setq c (js2-get-char))
5893 ((eq c js2-EOF_CHAR)
5895 (js2-ts-set-char-token-bounds token)
5896 (throw 'return js2-EOF))
5898 (js2-ts-set-char-token-bounds token)
5899 (setq js2-ts-dirty-line nil)
5900 (throw 'return js2-EOL))
5901 ((not (js2-js-space-p c))
5902 (if (/= c ?-) ; in case end of HTML comment
5903 (setq js2-ts-dirty-line t))
5904 (setq continue nil))))
5905 ;; Assume the token will be 1 char - fixed up below.
5906 (js2-ts-set-char-token-bounds token)
5908 (throw 'return js2-XMLATTR))
5909 ;; identifier/keyword/instanceof?
5910 ;; watch out for starting with a <backslash>
5913 (setq c (js2-get-char))
5915 (setq identifier-start t
5916 is-unicode-escape-start t
5917 js2-ts-string-buffer nil)
5918 (setq identifier-start nil)
5922 (when (setq identifier-start (js2-identifier-start-p c))
5923 (setq js2-ts-string-buffer nil)
5924 (js2-add-to-string c))))
5925 (when identifier-start
5926 (setq contains-escape is-unicode-escape-start)
5929 (if is-unicode-escape-start
5930 ;; strictly speaking we should probably push-back
5931 ;; all the bad characters if the <backslash>uXXXX
5932 ;; sequence is malformed. But since there isn't a
5933 ;; correct context(is there?) for a bad Unicode
5934 ;; escape sequence in an identifier, we can report
5939 (setq c (js2-get-char)
5940 escape-val (js2-x-digit-to-int c escape-val))
5941 ;; Next check takes care of c < 0 and bad escape
5942 (if (cl-minusp escape-val)
5943 (throw 'break nil)))
5944 (if (cl-minusp escape-val)
5945 (js2-report-scan-error "msg.invalid.escape" t))
5946 (js2-add-to-string escape-val)
5947 (setq is-unicode-escape-start nil))
5948 (setq c (js2-get-char))
5951 (setq c (js2-get-char))
5953 (setq is-unicode-escape-start t
5955 (js2-report-scan-error "msg.illegal.character" t)))
5957 (if (or (eq c js2-EOF_CHAR)
5958 (not (js2-identifier-part-p c)))
5960 (js2-add-to-string c))))))
5962 (setf str (js2-collect-string js2-ts-string-buffer)
5963 (js2-token-end token) js2-ts-cursor)
5964 ;; FIXME: Invalid in ES5 and ES6, see
5965 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5966 ;; Probably should just drop this conditional.
5967 (unless contains-escape
5968 ;; OPT we shouldn't have to make a string (object!) to
5969 ;; check if it's a keyword.
5970 ;; Return the corresponding token if it's a keyword
5971 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5972 (setq result (js2-string-to-keyword str)))
5973 (if (and (< js2-language-version 170)
5974 (memq result '(js2-LET js2-YIELD)))
5975 ;; LET and YIELD are tokens only in 1.7 and later
5976 (setq result 'js2-NAME))
5977 (when (eq result 'js2-RESERVED)
5978 (setf (js2-token-string token) str))
5979 (throw 'return (js2-tt-code result))))
5980 ;; If we want to intern these as Rhino does, just use (intern str)
5981 (setf (js2-token-string token) str)
5982 (throw 'return js2-NAME)) ; end identifier/kwd check
5984 (when (or (js2-digit-p c)
5985 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5986 (setq js2-ts-string-buffer nil
5989 (setq c (js2-get-char))
5991 ((or (eq c ?x) (eq c ?X))
5993 (setq c (js2-get-char)))
5994 ((and (or (eq c ?b) (eq c ?B))
5995 (>= js2-language-version 200))
5997 (setq c (js2-get-char)))
5998 ((and (or (eq c ?o) (eq c ?O))
5999 (>= js2-language-version 200))
6001 (setq c (js2-get-char)))
6003 (setq base 'maybe-8))
6005 (js2-add-to-string ?0))))
6008 (if (> 0 (js2-x-digit-to-int c 0))
6009 (js2-report-scan-error "msg.missing.hex.digits")
6010 (while (<= 0 (js2-x-digit-to-int c 0))
6011 (js2-add-to-string c)
6012 (setq c (js2-get-char)))))
6014 (if (not (memq c '(?0 ?1)))
6015 (js2-report-scan-error "msg.missing.binary.digits")
6016 (while (memq c '(?0 ?1))
6017 (js2-add-to-string c)
6018 (setq c (js2-get-char)))))
6020 (if (or (> ?0 c) (< ?7 c))
6021 (js2-report-scan-error "msg.missing.octal.digits")
6022 (while (and (<= ?0 c) (>= ?7 c))
6023 (js2-add-to-string c)
6024 (setq c (js2-get-char)))))
6026 (while (and (<= ?0 c) (<= c ?9))
6027 ;; We permit 08 and 09 as decimal numbers, which
6028 ;; makes our behavior a superset of the ECMA
6029 ;; numeric grammar. We might not always be so
6030 ;; permissive, so we warn about it.
6031 (when (and (eq base 'maybe-8) (>= c ?8))
6032 (js2-report-warning "msg.bad.octal.literal"
6033 (if (eq c ?8) "8" "9"))
6035 (js2-add-to-string c)
6036 (setq c (js2-get-char)))
6037 (when (eq base 'maybe-8)
6039 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6042 (js2-add-to-string c)
6043 (setq c (js2-get-char))
6044 while (js2-digit-p c)))
6045 (when (memq c '(?e ?E))
6046 (js2-add-to-string c)
6047 (setq c (js2-get-char))
6048 (when (memq c '(?+ ?-))
6049 (js2-add-to-string c)
6050 (setq c (js2-get-char)))
6051 (unless (js2-digit-p c)
6052 (js2-report-scan-error "msg.missing.exponent" t))
6054 (js2-add-to-string c)
6055 (setq c (js2-get-char))
6056 while (js2-digit-p c))))
6058 (let ((str (js2-set-string-from-buffer token)))
6059 (setf (js2-token-number token)
6060 (js2-string-to-number str base)))
6061 (throw 'return js2-NUMBER))
6063 (when (or (memq c '(?\" ?\'))
6064 (and (>= js2-language-version 200)
6067 (js2-get-string-or-template-token c token)))
6068 (js2-ts-return token
6071 (throw 'return js2-SEMI))
6073 (throw 'return js2-LB))
6075 (throw 'return js2-RB))
6077 (throw 'return js2-LC))
6079 (throw 'return js2-RC))
6081 (throw 'return js2-LP))
6083 (throw 'return js2-RP))
6085 (throw 'return js2-COMMA))
6087 (throw 'return js2-HOOK))
6089 (if (js2-match-char ?:)
6091 (throw 'return js2-COLON)))
6093 (if (js2-match-char ?.)
6094 (if (js2-match-char ?.)
6095 js2-TRIPLEDOT js2-DOTDOT)
6096 (if (js2-match-char ?\()
6098 (throw 'return js2-DOT))))
6100 (if (js2-match-char ?|)
6101 (throw 'return js2-OR)
6102 (if (js2-match-char ?=)
6104 (throw 'return js2-BITOR))))
6106 (if (js2-match-char ?=)
6108 (throw 'return js2-BITXOR)))
6110 (if (js2-match-char ?&)
6111 (throw 'return js2-AND)
6112 (if (js2-match-char ?=)
6114 (throw 'return js2-BITAND))))
6116 (if (js2-match-char ?=)
6117 (if (js2-match-char ?=)
6119 (throw 'return js2-EQ))
6120 (if (js2-match-char ?>)
6121 (js2-ts-return token js2-ARROW)
6122 (throw 'return js2-ASSIGN))))
6124 (if (js2-match-char ?=)
6125 (if (js2-match-char ?=)
6128 (throw 'return js2-NOT)))
6130 ;; NB:treat HTML begin-comment as comment-till-eol
6131 (when (js2-match-char ?!)
6132 (when (js2-match-char ?-)
6133 (when (js2-match-char ?-)
6135 (setf (js2-token-comment-type (js2-current-token)) 'html)
6136 (throw 'return js2-COMMENT)))
6138 (if (js2-match-char ?<)
6139 (if (js2-match-char ?=)
6142 (if (js2-match-char ?=)
6144 (throw 'return js2-LT))))
6146 (if (js2-match-char ?>)
6147 (if (js2-match-char ?>)
6148 (if (js2-match-char ?=)
6151 (if (js2-match-char ?=)
6154 (if (js2-match-char ?=)
6156 (throw 'return js2-GT))))
6158 (if (js2-match-char ?=)
6160 (throw 'return js2-MUL)))
6162 ;; is it a // comment?
6163 (when (js2-match-char ?/)
6164 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6166 (setf (js2-token-comment-type token) 'line)
6167 ;; include newline so highlighting goes to end of window
6168 (cl-incf (js2-token-end token))
6169 (throw 'return js2-COMMENT))
6170 ;; is it a /* comment?
6171 (when (js2-match-char ?*)
6172 (setf look-for-slash nil
6173 (js2-token-beg token) (- js2-ts-cursor 2)
6174 (js2-token-comment-type token)
6175 (if (js2-match-char ?*)
6177 (setq look-for-slash t)
6181 (setq c (js2-get-char))
6183 ((eq c js2-EOF_CHAR)
6184 (setf (js2-token-end token) (1- js2-ts-cursor))
6185 (js2-report-error "msg.unterminated.comment")
6186 (throw 'return js2-COMMENT))
6188 (setq look-for-slash t))
6191 (js2-ts-return token js2-COMMENT)))
6193 (setf look-for-slash nil
6194 (js2-token-end token) js2-ts-cursor)))))
6195 (if (js2-match-char ?=)
6197 (throw 'return js2-DIV)))
6199 (when js2-skip-preprocessor-directives
6201 (setf (js2-token-comment-type token) 'preprocessor
6202 (js2-token-end token) js2-ts-cursor)
6203 (throw 'return js2-COMMENT))
6204 (throw 'return js2-ERROR))
6206 (if (js2-match-char ?=)
6208 (throw 'return js2-MOD)))
6210 (throw 'return js2-BITNOT))
6212 (if (js2-match-char ?=)
6214 (if (js2-match-char ?+)
6216 (throw 'return js2-ADD))))
6219 ((js2-match-char ?=)
6220 (setq c js2-ASSIGN_SUB))
6221 ((js2-match-char ?-)
6222 (unless js2-ts-dirty-line
6223 ;; treat HTML end-comment after possible whitespace
6224 ;; after line start as comment-until-eol
6225 (when (js2-match-char ?>)
6227 (setf (js2-token-comment-type (js2-current-token)) 'html)
6228 (throw 'return js2-COMMENT)))
6232 (setq js2-ts-dirty-line t)
6235 (js2-report-scan-error "msg.illegal.character")))))))
6236 (setf (js2-token-type token) tt)
6239 (defun js2-get-string-or-template-token (quote-char token)
6240 ;; We attempt to accumulate a string the fast way, by
6241 ;; building it directly out of the reader. But if there
6242 ;; are any escaped characters in the string, we revert to
6243 ;; building it out of a string buffer.
6244 (let ((c (js2-get-char))
6245 js2-ts-string-buffer
6246 nc c1 val escape-val)
6248 (while (/= c quote-char)
6250 (when (eq c js2-EOF_CHAR)
6252 (js2-report-error "msg.unterminated.string.lit")
6254 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6256 (js2-report-error "msg.unterminated.string.lit")
6259 ;; We've hit an escaped character
6260 (setq c (js2-get-char))
6269 (setq c1 (js2-read-unicode-escape))
6270 (if js2-parse-ide-mode
6273 ;; just copy the string in IDE-mode
6274 (js2-add-to-string ?\\)
6275 (js2-add-to-string ?u)
6277 (js2-add-to-string (js2-get-char)))
6278 (setq c (js2-get-char))) ; added at end of loop
6279 ;; flag it as an invalid escape
6280 (js2-report-warning "msg.invalid.escape"
6281 nil (- js2-ts-cursor 2) 6))
6282 ;; Get 4 hex digits; if the u escape is not
6283 ;; followed by 4 hex digits, use 'u' + the
6284 ;; literal character sequence that follows.
6285 (js2-add-to-string ?u)
6288 (setq c (js2-get-char)
6289 escape-val (js2-x-digit-to-int c escape-val))
6290 (if (cl-minusp escape-val)
6291 (throw 'continue nil))
6292 (js2-add-to-string c))
6293 ;; prepare for replace of stored 'u' sequence by escape value
6294 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6297 ;; Get 2 hex digits, defaulting to 'x'+literal
6298 ;; sequence, as above.
6299 (setq c (js2-get-char)
6300 escape-val (js2-x-digit-to-int c 0))
6301 (if (cl-minusp escape-val)
6303 (js2-add-to-string ?x)
6304 (throw 'continue nil))
6307 escape-val (js2-x-digit-to-int c escape-val))
6308 (if (cl-minusp escape-val)
6310 (js2-add-to-string ?x)
6311 (js2-add-to-string c1)
6312 (throw 'continue nil))
6314 (setq c escape-val))))
6316 ;; Remove line terminator after escape to follow
6317 ;; SpiderMonkey and C/C++
6318 (setq c (js2-get-char))
6319 (throw 'continue nil))
6321 (when (and (<= ?0 c) (< c ?8))
6324 (when (and (<= ?0 c) (< c ?8))
6325 (setq val (- (+ (* 8 val) c) ?0)
6327 (when (and (<= ?0 c)
6330 ;; c is 3rd char of octal sequence only
6331 ;; if the resulting val <= 0377
6332 (setq val (- (+ (* 8 val) c) ?0)
6336 (when (and (eq quote-char ?`) (eq c ?$))
6337 (when (eq (setq nc (js2-get-char)) ?\{)
6340 (js2-add-to-string c)
6341 (setq c (js2-get-char)))))
6342 (js2-set-string-from-buffer token)
6343 (if (not (eq quote-char ?`))
6345 (if (and (eq c ?$) (eq nc ?\{))
6347 js2-NO_SUBS_TEMPLATE))))
6349 (defun js2-read-regexp (start-tt)
6350 "Called by parser when it gets / or /= in literal context."
6352 in-class ; inside a '[' .. ']' character-class
6355 (token (js2-new-token 0)))
6356 (setq js2-ts-string-buffer nil)
6357 (if (eq start-tt js2-ASSIGN_DIV)
6359 (js2-add-to-string ?=)
6360 (if (not (eq start-tt js2-DIV))
6361 (error "failed assertion")))
6362 (while (and (not err)
6363 (or (/= (setq c (js2-get-char)) ?/)
6368 (setf (js2-token-end token) (1- js2-ts-cursor)
6370 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6371 (js2-report-error "msg.unterminated.re.lit"))
6374 (js2-add-to-string c)
6375 (setq c (js2-get-char)))
6379 (setq in-class nil)))
6380 (js2-add-to-string c))))
6384 ((js2-match-char ?g)
6386 ((js2-match-char ?i)
6388 ((js2-match-char ?m)
6390 ((and (js2-match-char ?u)
6391 (>= js2-language-version 200))
6393 ((and (js2-match-char ?y)
6394 (>= js2-language-version 200))
6397 (setq continue nil))))
6398 (if (js2-alpha-p (js2-peek-char))
6399 (js2-report-scan-error "msg.invalid.re.flag" t
6401 (js2-set-string-from-buffer token))
6402 (js2-collect-string flags)))
6404 (defun js2-get-first-xml-token ()
6405 (setq js2-ts-xml-open-tags-count 0
6406 js2-ts-is-xml-attribute nil
6407 js2-ts-xml-is-tag-content nil)
6409 (js2-get-next-xml-token))
6411 (defun js2-xml-discard-string (token)
6412 "Throw away the string in progress and flag an XML parse error."
6413 (setf js2-ts-string-buffer nil
6414 (js2-token-string token) nil)
6415 (js2-report-scan-error "msg.XML.bad.form" t))
6417 (defun js2-get-next-xml-token ()
6418 (setq js2-ts-string-buffer nil) ; for recording the XML
6419 (let ((token (js2-new-token 0))
6424 (setq c (js2-get-char))
6427 (throw 'return js2-ERROR))
6428 (js2-ts-xml-is-tag-content
6431 (js2-add-to-string c)
6432 (setq js2-ts-xml-is-tag-content nil
6433 js2-ts-is-xml-attribute nil))
6435 (js2-add-to-string c)
6436 (when (eq ?> (js2-peek-char))
6437 (setq c (js2-get-char))
6438 (js2-add-to-string c)
6439 (setq js2-ts-xml-is-tag-content nil)
6440 (cl-decf js2-ts-xml-open-tags-count)))
6443 (js2-set-string-from-buffer token)
6444 (throw 'return js2-XML))
6446 (js2-add-to-string c)
6447 (unless (js2-read-quoted-string c token)
6448 (throw 'return js2-ERROR)))
6450 (js2-add-to-string c)
6451 (setq js2-ts-is-xml-attribute t))
6453 (js2-add-to-string c))
6455 (js2-add-to-string c)
6456 (setq js2-ts-is-xml-attribute nil)))
6457 (when (and (not js2-ts-xml-is-tag-content)
6458 (zerop js2-ts-xml-open-tags-count))
6459 (js2-set-string-from-buffer token)
6460 (throw 'return js2-XMLEND)))
6462 ;; else not tag content
6465 (js2-add-to-string c)
6466 (setq c (js2-peek-char))
6469 (setq c (js2-get-char)) ;; skip !
6470 (js2-add-to-string c)
6471 (setq c (js2-peek-char))
6474 (setq c (js2-get-char)) ;; skip -
6475 (js2-add-to-string c)
6478 (js2-add-to-string c)
6479 (unless (js2-read-xml-comment token)
6480 (throw 'return js2-ERROR)))
6481 (js2-xml-discard-string token)
6482 (throw 'return js2-ERROR)))
6484 (setq c (js2-get-char)) ;; skip [
6485 (js2-add-to-string c)
6486 (if (and (= (js2-get-char) ?C)
6487 (= (js2-get-char) ?D)
6488 (= (js2-get-char) ?A)
6489 (= (js2-get-char) ?T)
6490 (= (js2-get-char) ?A)
6491 (= (js2-get-char) ?\[))
6493 (js2-add-to-string ?C)
6494 (js2-add-to-string ?D)
6495 (js2-add-to-string ?A)
6496 (js2-add-to-string ?T)
6497 (js2-add-to-string ?A)
6498 (js2-add-to-string ?\[)
6499 (unless (js2-read-cdata token)
6500 (throw 'return js2-ERROR)))
6501 (js2-xml-discard-string token)
6502 (throw 'return js2-ERROR)))
6504 (unless (js2-read-entity token)
6505 (throw 'return js2-ERROR))))
6506 ;; Allow bare CDATA section, e.g.:
6507 ;; let xml = <![CDATA[ foo bar baz ]]>;
6508 (when (zerop js2-ts-xml-open-tags-count)
6509 (throw 'return js2-XMLEND)))
6511 (setq c (js2-get-char)) ;; skip ?
6512 (js2-add-to-string c)
6513 (unless (js2-read-PI token)
6514 (throw 'return js2-ERROR)))
6517 (setq c (js2-get-char)) ;; skip /
6518 (js2-add-to-string c)
6519 (when (zerop js2-ts-xml-open-tags-count)
6520 (js2-xml-discard-string token)
6521 (throw 'return js2-ERROR))
6522 (setq js2-ts-xml-is-tag-content t)
6523 (cl-decf js2-ts-xml-open-tags-count))
6526 (setq js2-ts-xml-is-tag-content t)
6527 (cl-incf js2-ts-xml-open-tags-count))))
6530 (js2-set-string-from-buffer token)
6531 (throw 'return js2-XML))
6533 (js2-add-to-string c))))))))
6534 (setf (js2-token-end token) js2-ts-cursor)
6535 (setf (js2-token-type token) result)
6538 (defun js2-read-quoted-string (quote token)
6541 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6542 (js2-add-to-string c)
6545 (js2-xml-discard-string token) ;; throw away string in progress
6548 (defun js2-read-xml-comment (token)
6549 (let ((c (js2-get-char)))
6551 (while (/= c js2-EOF_CHAR)
6553 (js2-add-to-string c)
6554 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6555 (setq c (js2-get-char))
6556 (js2-add-to-string c)
6557 (if (eq (js2-peek-char) ?>)
6559 (setq c (js2-get-char)) ;; skip >
6560 (js2-add-to-string c)
6562 (throw 'continue nil)))
6563 (setq c (js2-get-char))))
6564 (js2-xml-discard-string token)
6567 (defun js2-read-cdata (token)
6568 (let ((c (js2-get-char)))
6570 (while (/= c js2-EOF_CHAR)
6572 (js2-add-to-string c)
6573 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6574 (setq c (js2-get-char))
6575 (js2-add-to-string c)
6576 (if (eq (js2-peek-char) ?>)
6578 (setq c (js2-get-char)) ;; Skip >
6579 (js2-add-to-string c)
6581 (throw 'continue nil)))
6582 (setq c (js2-get-char))))
6583 (js2-xml-discard-string token)
6586 (defun js2-read-entity (token)
6590 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6591 (js2-add-to-string c)
6594 (cl-incf decl-tags))
6597 (if (zerop decl-tags)
6598 (throw 'return t)))))
6599 (js2-xml-discard-string token)
6602 (defun js2-read-PI (token)
6603 "Scan an XML processing instruction."
6606 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6607 (js2-add-to-string c)
6608 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6609 (setq c (js2-get-char)) ;; Skip >
6610 (js2-add-to-string c)
6612 (js2-xml-discard-string token)
6617 (defun js2-set-face (beg end face &optional record)
6618 "Fontify a region. If RECORD is non-nil, record for later."
6619 (when (cl-plusp js2-highlight-level)
6620 (setq beg (min (point-max) beg)
6621 beg (max (point-min) beg)
6622 end (min (point-max) end)
6623 end (max (point-min) end))
6625 (push (list beg end face) js2-mode-fontifications)
6626 (put-text-property beg end 'font-lock-face face))))
6628 (defsubst js2-clear-face (beg end)
6629 (remove-text-properties beg end '(font-lock-face nil
6634 (defconst js2-ecma-global-props
6637 '("Infinity" "NaN" "undefined" "arguments") t)
6639 "Value properties of the Ecma-262 Global Object.
6640 Shown at or above `js2-highlight-level' 2.")
6642 ;; might want to add the name "arguments" to this list?
6643 (defconst js2-ecma-object-props
6646 '("prototype" "__proto__" "__parent__") t)
6648 "Value properties of the Ecma-262 Object constructor.
6649 Shown at or above `js2-highlight-level' 2.")
6651 (defconst js2-ecma-global-funcs
6655 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6656 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6658 "Function properties of the Ecma-262 Global object.
6659 Shown at or above `js2-highlight-level' 2.")
6661 (defconst js2-ecma-number-props
6663 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6665 "POSITIVE_INFINITY") t)
6667 "Properties of the Ecma-262 Number constructor.
6668 Shown at or above `js2-highlight-level' 2.")
6670 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6671 "Properties of the Ecma-262 Date constructor.
6672 Shown at or above `js2-highlight-level' 2.")
6674 (defconst js2-ecma-math-props
6677 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6680 "Properties of the Ecma-262 Math object.
6681 Shown at or above `js2-highlight-level' 2.")
6683 (defconst js2-ecma-math-funcs
6686 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6687 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6689 "Function properties of the Ecma-262 Math object.
6690 Shown at or above `js2-highlight-level' 2.")
6692 (defconst js2-ecma-function-props
6696 '(;; properties of the Object prototype object
6697 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6698 "toLocaleString" "toString" "valueOf"
6699 ;; properties of the Function prototype object
6701 ;; properties of the Array prototype object
6702 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6704 ;; properties of the String prototype object
6705 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6706 "localeCompare" "match" "replace" "search" "split" "substring"
6707 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6709 ;; properties of the Number prototype object
6710 "toExponential" "toFixed" "toPrecision"
6711 ;; properties of the Date prototype object
6712 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6713 "getMinutes" "getMonth" "getSeconds" "getTime"
6714 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6715 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6716 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6717 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6718 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6719 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6720 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6721 "toTimeString" "toUTCString"
6722 ;; properties of the RegExp prototype object
6724 ;; properties of the JSON prototype object
6726 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6727 "toSource" "__defineGetter__" "__defineSetter__"
6728 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6729 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6732 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6733 Shown at or above `js2-highlight-level' 3.")
6735 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6736 (let ((target-name (and target
6737 (js2-name-node-p target)
6738 (js2-name-node-name target)))
6739 (prop-name (if prop (js2-name-node-name prop)))
6740 (level2 (>= js2-highlight-level 2))
6741 (level3 (>= js2-highlight-level 3)))
6748 ((and level3 (string-match js2-ecma-function-props prop-name))
6749 'font-lock-builtin-face)
6750 ((and target-name prop)
6752 ((string= target-name "Date")
6753 (if (string-match js2-ecma-date-props prop-name)
6754 'font-lock-builtin-face))
6755 ((string= target-name "Math")
6756 (if (string-match js2-ecma-math-funcs prop-name)
6757 'font-lock-builtin-face))))))
6759 (if (string-match js2-ecma-global-funcs prop-name)
6760 'font-lock-builtin-face)))
6764 ((string= target-name "Number")
6765 (if (string-match js2-ecma-number-props prop-name)
6766 'font-lock-constant-face))
6767 ((string= target-name "Math")
6768 (if (string-match js2-ecma-math-props prop-name)
6769 'font-lock-constant-face))))
6771 (if (string-match js2-ecma-object-props prop-name)
6772 'font-lock-constant-face))))))
6774 (let ((pos (+ (js2-node-pos parent) ; absolute
6775 (js2-node-pos prop)))) ; relative
6777 (+ pos (js2-node-len prop))
6780 (defun js2-parse-highlight-member-expr-node (node)
6781 "Perform syntax highlighting of EcmaScript built-in properties.
6782 The variable `js2-highlight-level' governs this highighting."
6783 (let (face target prop name pos end parent call-p callee)
6785 ;; case 1: simple name, e.g. foo
6786 ((js2-name-node-p node)
6787 (setq name (js2-name-node-name node))
6788 ;; possible for name to be nil in rare cases - saw it when
6789 ;; running js2-mode on an elisp buffer. Might as well try to
6790 ;; make it so js2-mode never barfs.
6792 (setq face (if (string-match js2-ecma-global-props name)
6793 'font-lock-constant-face))
6795 (setq pos (js2-node-pos node)
6796 end (+ pos (js2-node-len node)))
6797 (js2-set-face pos end face 'record))))
6798 ;; case 2: property access or function call
6799 ((or (js2-prop-get-node-p node)
6800 ;; highlight function call if expr is a prop-get node
6801 ;; or a plain name (i.e. unqualified function call)
6802 (and (setq call-p (js2-call-node-p node))
6803 (setq callee (js2-call-node-target node)) ; separate setq!
6804 (or (js2-prop-get-node-p callee)
6805 (js2-name-node-p callee))))
6807 node (if call-p callee node))
6808 (if (and call-p (js2-name-node-p callee))
6810 (setq target (js2-prop-get-node-left node)
6811 prop (js2-prop-get-node-right node)))
6813 ((js2-name-node-p prop)
6814 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6815 (js2-parse-highlight-prop-get parent target prop call-p))
6816 ((js2-name-node-p target)
6817 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6818 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6820 (defun js2-parse-highlight-member-expr-fn-name (expr)
6821 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6822 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6823 We currently only handle the case where the last component is a prop-get
6824 of a simple name. Called before EXPR has a parent node."
6826 (name (and (js2-prop-get-node-p expr)
6827 (js2-prop-get-node-right expr))))
6828 (when (js2-name-node-p name)
6829 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6830 (js2-node-pos name)))
6831 (+ pos (js2-node-len name))
6832 'font-lock-function-name-face
6835 ;; source: http://jsdoc.sourceforge.net/
6836 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6837 ;; allows type specifications, and needs work before entering the wild.
6839 (defconst js2-jsdoc-param-tag-regexp
6840 (concat "^\\s-*\\*+\\s-*\\(@"
6841 "\\(?:param\\|argument\\)"
6843 "\\s-*\\({[^}]+}\\)?" ; optional type
6844 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6846 "Matches jsdoc tags with optional type and optional param name.")
6848 (defconst js2-jsdoc-typed-tag-regexp
6849 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6863 "\\)\\)\\s-*\\({[^}]+}\\)?")
6864 "Matches jsdoc tags with optional type.")
6866 (defconst js2-jsdoc-arg-tag-regexp
6867 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6890 "\\)\\)\\s-+\\([^ \t]+\\)")
6891 "Matches jsdoc tags with a single argument.")
6893 (defconst js2-jsdoc-empty-tag-regexp
6894 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6934 "Matches empty jsdoc tags.")
6936 (defconst js2-jsdoc-link-tag-regexp
6937 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6938 "Matches a jsdoc link or code tag.")
6940 (defconst js2-jsdoc-see-tag-regexp
6941 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6942 "Matches a jsdoc @see tag.")
6944 (defconst js2-jsdoc-html-tag-regexp
6945 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6946 "Matches a simple (no attributes) html start- or end-tag.")
6948 (defun js2-jsdoc-highlight-helper ()
6949 (js2-set-face (match-beginning 1)
6952 (if (match-beginning 2)
6954 (goto-char (match-beginning 2))
6955 (= (char-after) ?{))
6956 (js2-set-face (1+ (match-beginning 2))
6959 (js2-set-face (match-beginning 2)
6962 (if (match-beginning 3)
6963 (js2-set-face (match-beginning 3)
6967 (defun js2-highlight-jsdoc (ast)
6968 "Highlight doc comment tags."
6969 (let ((comments (js2-ast-root-comments ast))
6972 (dolist (node comments)
6973 (when (eq (js2-comment-node-format node) 'jsdoc)
6974 (setq beg (js2-node-abs-pos node)
6975 end (+ beg (js2-node-len node)))
6977 (narrow-to-region beg end)
6978 (dolist (re (list js2-jsdoc-param-tag-regexp
6979 js2-jsdoc-typed-tag-regexp
6980 js2-jsdoc-arg-tag-regexp
6981 js2-jsdoc-link-tag-regexp
6982 js2-jsdoc-see-tag-regexp
6983 js2-jsdoc-empty-tag-regexp))
6985 (while (re-search-forward re nil t)
6986 (js2-jsdoc-highlight-helper)))
6987 ;; simple highlighting for html tags
6989 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6990 (js2-set-face (match-beginning 1)
6992 'js2-jsdoc-html-tag-delimiter)
6993 (js2-set-face (match-beginning 2)
6995 'js2-jsdoc-html-tag-name)
6996 (js2-set-face (match-beginning 3)
6998 'js2-jsdoc-html-tag-delimiter))))))))
7000 (defun js2-highlight-assign-targets (_node left right)
7001 "Highlight function properties and external variables."
7003 ;; highlight vars and props assigned function values
7004 (when (or (js2-function-node-p right)
7005 (js2-class-node-p right))
7007 ;; var foo = function() {...}
7008 ((js2-name-node-p left)
7010 ;; foo.bar.baz = function() {...}
7011 ((and (js2-prop-get-node-p left)
7012 (js2-name-node-p (js2-prop-get-node-right left)))
7013 (setq name (js2-prop-get-node-right left))))
7015 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7016 (+ leftpos (js2-node-len name))
7017 'font-lock-function-name-face
7020 (defun js2-record-name-node (node)
7021 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7022 later. NODE must be a name node."
7023 (let ((leftpos (js2-node-abs-pos node)))
7024 (push (list node js2-current-scope
7026 (+ leftpos (js2-node-len node)))
7027 js2-recorded-identifiers)))
7029 (defun js2-highlight-undeclared-vars ()
7030 "After entire parse is finished, look for undeclared variable references.
7031 We have to wait until entire buffer is parsed, since JavaScript permits var
7032 decls to occur after they're used.
7034 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7035 it is considered declared."
7037 (dolist (entry js2-recorded-identifiers)
7038 (cl-destructuring-bind (name-node scope pos end) entry
7039 (setq name (js2-name-node-name name-node))
7040 (unless (or (member name js2-global-externs)
7041 (member name js2-default-externs)
7042 (member name js2-additional-externs)
7043 (js2-get-defining-scope scope name pos))
7044 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7045 'js2-external-variable))))
7046 (setq js2-recorded-identifiers nil)))
7048 (defun js2-set-default-externs ()
7049 "Set the value of `js2-default-externs' based on the various
7050 `js2-include-?-externs' variables."
7051 (setq js2-default-externs
7052 (append js2-ecma-262-externs
7053 (if js2-include-browser-externs js2-browser-externs)
7054 (if (and js2-include-browser-externs
7055 (>= js2-language-version 200)) js2-harmony-externs)
7056 (if js2-include-rhino-externs js2-rhino-externs)
7057 (if js2-include-node-externs js2-node-externs)
7058 (if (or js2-include-browser-externs js2-include-node-externs)
7059 js2-typed-array-externs))))
7061 (defun js2-apply-jslint-globals ()
7062 (setq js2-additional-externs
7063 (nconc (js2-get-jslint-globals)
7064 js2-additional-externs)))
7066 (defun js2-get-jslint-globals ()
7067 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7068 when (and (eq 'block (js2-comment-node-format node))
7070 (goto-char (js2-node-abs-pos node))
7071 (looking-at "/\\*global ")))
7072 append (js2-get-jslint-globals-in
7074 (js2-node-abs-end node))))
7076 (defun js2-get-jslint-globals-in (beg end)
7080 (while (re-search-forward js2-mode-identifier-re end t)
7081 (let ((match (match-string 0)))
7082 (unless (member match '("true" "false"))
7083 (push match res)))))
7088 ;; We currently only support imenu, but eventually should support speedbar and
7089 ;; possibly other browsing mechanisms.
7091 ;; The basic strategy is to identify function assignment targets of the form
7092 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7093 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7094 ;; for imenu after parsing is finished.
7096 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7097 ;; JavaScript, and the general problem is undecidable. However, several forms
7098 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7101 ;; function foo() -- function declaration
7102 ;; foo = function() -- function expression assigned to variable
7103 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7104 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7105 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7106 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7107 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7108 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7109 ;; function foo() {function bar() {...}} -- nested function
7110 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7112 ;; This list boils down to a few forms that can be combined recursively.
7113 ;; Top-level named function declarations include both the left-hand (name)
7114 ;; and the right-hand (function value) expressions needed to produce an imenu
7115 ;; entry. The other "right-hand" forms we need to look for are:
7116 ;; - functions declared as props/getters/setters in object literals
7117 ;; - nested named function declarations
7118 ;; The "left-hand" expressions that functions can be assigned to include:
7119 ;; - local/global variables
7120 ;; - nested property-get expressions like a.b.c.d
7121 ;; - element gets like foo[10] or foo['bar'] where the index
7122 ;; expression can be trivially converted to a property name. They
7123 ;; effectively then become property gets.
7125 ;; All the different definition types are canonicalized into the form
7126 ;; foo.bar.baz = position-of-function-keyword
7128 ;; We need to build a trie-like structure for imenu. As an example,
7129 ;; consider the following JavaScript code:
7131 ;; a = function() {...} // function at position 5
7132 ;; b = function() {...} // function at position 25
7133 ;; foo = function() {...} // function at position 100
7134 ;; foo.bar = function() {...} // function at position 200
7135 ;; foo.bar.baz = function() {...} // function at position 300
7136 ;; foo.bar.zab = function() {...} // function at position 400
7138 ;; During parsing we accumulate an entry for each definition in
7139 ;; the variable `js2-imenu-recorder', like so:
7145 ;; (fn foo bar baz 300)
7146 ;; (fn foo bar zab 400))
7148 ;; Where 'fn' is the respective function node.
7149 ;; After parsing these entries are merged into this alist-trie:
7153 ;; (foo (<definition> . 3)
7154 ;; (bar (<definition> . 6)
7158 ;; Note the wacky need for a <definition> name. The token can be anything
7159 ;; that isn't a valid JavaScript identifier, because you might make foo
7160 ;; a function and then start setting properties on it that are also functions.
7162 (defun js2-prop-node-name (node)
7163 "Return the name of a node that may be a property-get/property-name.
7164 If NODE is not a valid name-node, string-node or integral number-node,
7165 returns nil. Otherwise returns the string name/value of the node."
7167 ((js2-name-node-p node)
7168 (js2-name-node-name node))
7169 ((js2-string-node-p node)
7170 (js2-string-node-value node))
7171 ((and (js2-number-node-p node)
7172 (string-match "^[0-9]+$" (js2-number-node-value node)))
7173 (js2-number-node-value node))
7174 ((eq (js2-node-type node) js2-THIS)
7176 ((eq (js2-node-type node) js2-SUPER)
7179 (defun js2-node-qname-component (node)
7180 "Return the name of this node, if it contributes to a qname.
7181 Returns nil if the node doesn't contribute."
7183 (or (js2-prop-node-name node)
7184 (if (and (js2-function-node-p node)
7185 (js2-function-node-name node))
7186 (js2-name-node-name (js2-function-node-name node))))))
7188 (defun js2-record-imenu-entry (fn-node qname pos)
7189 "Add an entry to `js2-imenu-recorder'.
7190 FN-NODE should be the current item's function node.
7192 Associate FN-NODE with its QNAME for later lookup.
7193 This is used in postprocessing the chain list. For each chain, we find
7194 the parent function, look up its qname, then prepend a copy of it to the chain."
7195 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7196 (unless js2-imenu-function-map
7197 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7198 (puthash fn-node qname js2-imenu-function-map))
7200 (defun js2-record-imenu-functions (node &optional var)
7201 "Record function definitions for imenu.
7202 NODE is a function node or an object literal.
7203 VAR, if non-nil, is the expression that NODE is being assigned to.
7204 When passed arguments of wrong type, does nothing."
7205 (when js2-parse-ide-mode
7206 (let ((fun-p (js2-function-node-p node))
7209 ;; non-anonymous function declaration?
7212 (setq fname-node (js2-function-node-name node)))
7213 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7214 ;; for remaining forms, compute left-side tree branch first
7215 ((and var (setq qname (js2-compute-nested-prop-get var)))
7217 ;; foo.bar.baz = function
7219 (js2-record-imenu-entry node qname (js2-node-pos node)))
7220 ;; foo.bar.baz = object-literal
7221 ;; look for nested functions: {a: {b: function() {...} }}
7222 ((js2-object-node-p node)
7223 ;; Node position here is still absolute, since the parser
7224 ;; passes the assignment target and value expressions
7225 ;; to us before they are added as children of the assignment node.
7226 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7228 (defun js2-compute-nested-prop-get (node)
7229 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7230 component nodes as a list. Otherwise return nil. Element-gets are treated
7231 as property-gets if the index expression is a string, or a positive integer."
7232 (let (left right head)
7234 ((or (js2-name-node-p node)
7235 (js2-this-or-super-node-p node))
7237 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7238 ((js2-prop-get-node-p node) ; foo.bar
7239 (setq left (js2-prop-get-node-left node)
7240 right (js2-prop-get-node-right node))
7241 (if (setq head (js2-compute-nested-prop-get left))
7242 (nconc head (list right))))
7243 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7244 (setq left (js2-elem-get-node-target node)
7245 right (js2-elem-get-node-element node))
7246 (if (or (js2-string-node-p right) ; ['bar']
7247 (and (js2-number-node-p right) ; [10]
7248 (string-match "^[0-9]+$"
7249 (js2-number-node-value right))))
7250 (if (setq head (js2-compute-nested-prop-get left))
7251 (nconc head (list right))))))))
7253 (defun js2-record-object-literal (node qname pos)
7254 "Recursively process an object literal looking for functions.
7255 NODE is an object literal that is the right-hand child of an assignment
7256 expression. QNAME is a list of nodes representing the assignment target,
7257 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7258 POS is the absolute position of the node.
7259 We do a depth-first traversal of NODE. For any functions we find,
7260 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7262 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7263 (let ((left (js2-infix-node-left e))
7264 ;; Element positions are relative to the parent position.
7265 (pos (+ pos (js2-node-pos e))))
7267 ;; foo: function() {...}
7268 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7269 (when (js2-prop-node-name left)
7270 ;; As a policy decision, we record the position of the property,
7271 ;; not the position of the `function' keyword, since the property
7272 ;; is effectively the name of the function.
7273 (js2-record-imenu-entry right (append qname (list left)) pos)))
7274 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7275 ((js2-object-node-p right)
7276 (js2-record-object-literal right
7277 (append qname (list (js2-infix-node-left e)))
7278 (+ pos (js2-node-pos right)))))))))
7280 (defun js2-node-top-level-decl-p (node)
7281 "Return t if NODE's name is defined in the top-level scope.
7282 Also returns t if NODE's name is not defined in any scope, since it implies
7283 that it's an external variable, which must also be in the top-level scope."
7284 (let* ((name (js2-prop-node-name node))
7285 (this-scope (js2-node-get-enclosing-scope node))
7288 ((js2-this-or-super-node-p node)
7292 ((setq defining-scope (js2-get-defining-scope this-scope name))
7293 (js2-ast-root-p defining-scope))
7296 (defun js2-wrapper-function-p (node)
7297 "Return t if NODE is a function expression that's immediately invoked.
7298 NODE must be `js2-function-node'."
7299 (let ((parent (js2-node-parent node)))
7301 ;; function(){...}();
7302 (and (js2-call-node-p parent)
7303 (eq node (js2-call-node-target parent)))
7304 (and (js2-paren-node-p parent)
7305 ;; (function(){...})();
7306 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7307 ;; (function(){...}).call(this);
7308 (and (js2-prop-get-node-p parent)
7309 (member (js2-name-node-name (js2-prop-get-node-right parent))
7311 (js2-call-node-p (js2-node-parent parent))))))))
7313 (defun js2-browse-postprocess-chains ()
7314 "Modify function-declaration name chains after parsing finishes.
7315 Some of the information is only available after the parse tree is complete.
7316 For instance, processing a nested scope requires a parent function node."
7317 (let (result fn parent-qname p elem)
7318 (dolist (entry js2-imenu-recorder)
7319 ;; function node goes first
7320 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7321 ;; Examine head's defining scope:
7322 ;; Pre-processed chain, or top-level/external, keep as-is.
7323 (if (or (stringp head) (js2-node-top-level-decl-p head))
7325 (when (js2-this-or-super-node-p head)
7326 (setq chain (cdr chain))) ; discard this-node
7327 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7328 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7329 (when (eq parent-qname 'not-found)
7330 ;; anonymous function expressions are not recorded
7331 ;; during the parse, so we need to handle this case here
7333 (if (js2-wrapper-function-p fn)
7334 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7335 (if (js2-ast-root-p grandparent)
7337 (gethash grandparent js2-imenu-function-map 'skip)))
7339 (puthash fn parent-qname js2-imenu-function-map))
7340 (if (eq parent-qname 'skip)
7341 ;; We don't show it, let's record that fact.
7342 (remhash current-fn js2-imenu-function-map)
7343 ;; Prepend parent fn qname to this chain.
7344 (let ((qname (append parent-qname chain)))
7345 (puthash current-fn (butlast qname) js2-imenu-function-map)
7346 (push qname result)))))))
7347 ;; Collect chains obtained by third-party code.
7348 (let (js2-imenu-recorder)
7349 (run-hooks 'js2-build-imenu-callbacks)
7350 (dolist (entry js2-imenu-recorder)
7351 (push (cdr entry) result)))
7352 ;; Finally replace each node in each chain with its name.
7353 (dolist (chain result)
7356 (if (js2-node-p (setq elem (car p)))
7357 (setcar p (js2-node-qname-component elem)))
7361 ;; Merge name chains into a trie-like tree structure of nested lists.
7362 ;; To simplify construction of the trie, we first build it out using the rule
7363 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7364 ;; [key, num-or-list]. The second element can be a number; if so, this key
7365 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7366 ;; associated with the key at this level.) Otherwise the second element is
7367 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7368 ;; a simple recursive formulation.
7370 ;; js2-mode is building the data structure for imenu. The imenu documentation
7371 ;; claims that it's the structure above, but in practice it wants the children
7372 ;; at the same list level as the key for that level, which is how I've drawn
7373 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7374 ;; list wrapper around the children at each level.
7376 ;; A completed nested imenu-alist entry looks like this:
7378 ;; ("<definition>" . 7)
7383 ;; In particular, the documentation for `imenu--index-alist' says that
7384 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7385 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7387 (defun js2-treeify (lst)
7388 "Convert (a b c d) to (a ((b ((c d)))))."
7389 (if (null (cddr lst)) ; list length <= 2
7391 (list (car lst) (list (js2-treeify (cdr lst))))))
7393 (defun js2-build-alist-trie (chains trie)
7394 "Merge declaration name chains into a trie-like alist structure for imenu.
7395 CHAINS is the qname chain list produced during parsing. TRIE is a
7396 list of elements built up so far."
7397 (let (head tail pos branch kids)
7398 (dolist (chain chains)
7399 (setq head (car chain)
7401 pos (if (numberp (car tail)) (car tail))
7402 branch (js2-find-if (lambda (n)
7403 (string= (car n) head))
7405 kids (cl-second branch))
7407 ;; case 1: this key isn't in the trie yet
7410 (setcdr (last trie) (list (js2-treeify chain)))
7411 (setq trie (list (js2-treeify chain)))))
7412 ;; case 2: key is present with a single number entry: replace w/ list
7413 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7414 ;; ("<definition>" 20)))
7416 (setcar (cdr branch)
7417 (list (list "<definition-1>" kids)
7419 (list "<definition-2>" pos)
7420 (js2-treeify tail)))))
7421 ;; case 3: key is there (with kids), and we're a number entry
7425 (list (format "<definition-%d>"
7426 (1+ (cl-loop for kid in kids
7427 count (eq ?< (aref (car kid) 0)))))
7429 ;; case 4: key is there with kids, need to merge in our chain
7431 (js2-build-alist-trie (list tail) kids))))
7434 (defun js2-flatten-trie (trie)
7435 "Convert TRIE to imenu-format.
7436 Recurses through nodes, and for each one whose second element is a list,
7437 appends the list's flattened elements to the current element. Also
7438 changes the tails into conses. For instance, this pre-flattened trie
7450 Note that the root of the trie has no key, just a list of chains.
7451 This is also true for the value of any key with multiple children,
7452 e.g. key 'c' in the example above."
7455 (mapcar #'js2-flatten-trie trie))
7457 (if (numberp (cl-second trie))
7458 (cons (car trie) (cl-second trie))
7459 ;; else pop list and append its kids
7460 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7462 (defun js2-build-imenu-index ()
7463 "Turn `js2-imenu-recorder' into an imenu data structure."
7464 (when (eq js2-imenu-recorder 'empty)
7465 (setq js2-imenu-recorder nil))
7466 (let* ((chains (js2-browse-postprocess-chains))
7467 (result (js2-build-alist-trie chains nil)))
7468 (js2-flatten-trie result)))
7470 (defun js2-test-print-chains (chains)
7471 "Print a list of qname chains.
7472 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7473 i.e. one or more nodes, and an integer position as the list tail."
7474 (mapconcat (lambda (chain)
7476 (mapconcat (lambda (elem)
7477 (if (js2-node-p elem)
7478 (or (js2-node-qname-component elem)
7480 (number-to-string elem)))
7489 (defconst js2-version "1.8.5"
7490 "Version of JavaScript supported.")
7492 (defun js2-record-face (face &optional token)
7493 "Record a style run of FACE for TOKEN or the current token."
7494 (unless token (setq token (js2-current-token)))
7495 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7497 (defsubst js2-node-end (n)
7498 "Computes the absolute end of node N.
7499 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7500 is only true until the node is added to its parent; i.e., while parsing."
7504 (defun js2-record-comment (token)
7505 "Record a comment in `js2-scanned-comments'."
7506 (let ((ct (js2-token-comment-type token))
7507 (beg (js2-token-beg token))
7508 (end (js2-token-end token)))
7509 (push (make-js2-comment-node :len (- end beg)
7511 js2-scanned-comments)
7512 (when js2-parse-ide-mode
7513 (js2-record-face (if (eq ct 'jsdoc)
7515 'font-lock-comment-face)
7517 (when (memq ct '(html preprocessor))
7518 ;; Tell cc-engine the bounds of the comment.
7519 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7521 (defun js2-peek-token ()
7522 "Return the next token type without consuming it.
7523 If `js2-ti-lookahead' is positive, return the type of next token
7524 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7525 (if (not (zerop js2-ti-lookahead))
7527 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7528 (let ((tt (js2-get-token-internal nil)))
7532 (defalias 'js2-next-token 'js2-get-token)
7534 (defun js2-match-token (match &optional dont-unget)
7535 "Get next token and return t if it matches MATCH, a bytecode.
7536 Returns nil and consumes nothing if MATCH is not the next token."
7537 (if (/= (js2-get-token) match)
7538 (ignore (unless dont-unget (js2-unget-token)))
7541 (defun js2-match-contextual-kwd (name)
7542 "Consume and return t if next token is `js2-NAME', and its
7543 string is NAME. Returns nil and keeps current token otherwise."
7544 (if (or (/= (js2-get-token) js2-NAME)
7545 (not (string= (js2-current-token-string) name)))
7549 (js2-record-face 'font-lock-keyword-face)
7552 (defun js2-get-prop-name-token ()
7553 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7555 (defun js2-match-prop-name ()
7556 "Consume token and return t if next token is a valid property name.
7557 If `js2-language-version' is >= 180, a keyword or reserved word
7558 is considered valid name as well."
7559 (if (eq js2-NAME (js2-get-prop-name-token))
7564 (defun js2-must-match-prop-name (msg-id &optional pos len)
7565 (if (js2-match-prop-name)
7567 (js2-report-error msg-id nil pos len)
7570 (defun js2-peek-token-or-eol ()
7571 "Return js2-EOL if the next token immediately follows a newline.
7572 Else returns the next token. Used in situations where we don't
7573 consider certain token types valid if they are preceded by a newline.
7574 One example is the postfix ++ or -- operator, which has to be on the
7575 same line as its operand."
7576 (let ((tt (js2-get-token))
7577 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7583 (defun js2-must-match (token msg-id &optional pos len)
7584 "Match next token to token code TOKEN, or record a syntax error.
7585 MSG-ID is the error message to report if the match fails.
7586 Returns t on match, nil if no match."
7587 (if (js2-match-token token t)
7589 (js2-report-error msg-id nil pos len)
7593 (defun js2-must-match-name (msg-id)
7594 (if (js2-match-token js2-NAME t)
7596 (if (eq (js2-current-token-type) js2-RESERVED)
7597 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7598 (js2-report-error msg-id)
7602 (defsubst js2-inside-function ()
7603 (cl-plusp js2-nesting-of-function))
7605 (defun js2-set-requires-activation ()
7606 (if (js2-function-node-p js2-current-script-or-fn)
7607 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7609 (defun js2-check-activation-name (name _token)
7610 (when (js2-inside-function)
7611 ;; skip language-version 1.2 check from Rhino
7612 (if (or (string= "arguments" name)
7613 (and js2-compiler-activation-names ; only used in codegen
7614 (gethash name js2-compiler-activation-names)))
7615 (js2-set-requires-activation))))
7617 (defun js2-set-is-generator ()
7618 (let ((fn-node js2-current-script-or-fn))
7619 (when (and (js2-function-node-p fn-node)
7620 (not (js2-function-node-generator-type fn-node)))
7621 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7623 (defun js2-must-have-xml ()
7624 (unless js2-compiler-xml-available
7625 (js2-report-error "msg.XML.not.available")))
7627 (defun js2-push-scope (scope)
7628 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7629 (cl-assert (js2-scope-p scope))
7630 (cl-assert (null (js2-scope-parent-scope scope)))
7631 (cl-assert (not (eq js2-current-scope scope)))
7632 (setf (js2-scope-parent-scope scope) js2-current-scope
7633 js2-current-scope scope))
7635 (defsubst js2-pop-scope ()
7636 (setq js2-current-scope
7637 (js2-scope-parent-scope js2-current-scope)))
7639 (defun js2-enter-loop (loop-node)
7640 (push loop-node js2-loop-set)
7641 (push loop-node js2-loop-and-switch-set)
7642 (js2-push-scope loop-node)
7643 ;; Tell the current labeled statement (if any) its statement,
7644 ;; and set the jump target of the first label to the loop.
7645 ;; These are used in `js2-parse-continue' to verify that the
7646 ;; continue target is an actual labeled loop. (And for codegen.)
7647 (when js2-labeled-stmt
7648 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7649 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7650 js2-labeled-stmt))) loop-node)))
7652 (defun js2-exit-loop ()
7654 (pop js2-loop-and-switch-set)
7657 (defsubst js2-enter-switch (switch-node)
7658 (push switch-node js2-loop-and-switch-set))
7660 (defsubst js2-exit-switch ()
7661 (pop js2-loop-and-switch-set))
7663 (defun js2-parse (&optional buf cb)
7664 "Tell the js2 parser to parse a region of JavaScript.
7666 BUF is a buffer or buffer name containing the code to parse.
7667 Call `narrow-to-region' first to parse only part of the buffer.
7669 The returned AST root node is given some additional properties:
7670 `node-count' - total number of nodes in the AST
7671 `buffer' - BUF. The buffer it refers to may change or be killed,
7672 so the value is not necessarily reliable.
7674 An optional callback CB can be specified to report parsing
7675 progress. If `(functionp CB)' returns t, it will be called with
7676 the current line number once before parsing begins, then again
7677 each time the lexer reaches a new line number.
7679 CB can also be a list of the form `(symbol cb ...)' to specify
7680 multiple callbacks with different criteria. Each symbol is a
7681 criterion keyword, and the following element is the callback to
7684 :line - called whenever the line number changes
7685 :token - called for each new token consumed
7687 The list of criteria could be extended to include entering or
7688 leaving a statement, an expression, or a function definition."
7689 (if (and cb (not (functionp cb)))
7690 (error "criteria callbacks not yet implemented"))
7691 (let ((inhibit-point-motion-hooks t)
7692 (js2-compiler-xml-available (>= js2-language-version 160))
7693 ;; This is a recursive-descent parser, so give it a big stack.
7694 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7695 (max-specpdl-size (max max-specpdl-size 3000))
7696 (case-fold-search nil)
7698 (with-current-buffer (or buf (current-buffer))
7699 (setq js2-scanned-comments nil
7700 js2-parsed-errors nil
7701 js2-parsed-warnings nil
7702 js2-imenu-recorder nil
7703 js2-imenu-function-map nil
7706 (setq ast (js2-do-parse))
7707 (unless js2-ts-hit-eof
7708 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7709 (setf (js2-ast-root-errors ast) js2-parsed-errors
7710 (js2-ast-root-warnings ast) js2-parsed-warnings)
7711 ;; if we didn't find any declarations, put a dummy in this list so we
7712 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7713 (unless js2-imenu-recorder
7714 (setq js2-imenu-recorder 'empty))
7715 (run-hooks 'js2-parse-finished-hook)
7718 ;; Corresponds to Rhino's Parser.parse() method.
7719 (defun js2-do-parse ()
7720 "Parse current buffer starting from current point.
7721 Scanner should be initialized."
7722 (let ((pos js2-ts-cursor)
7723 (end js2-ts-cursor) ; in case file is empty
7725 ;; initialize buffer-local parsing vars
7726 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7727 js2-current-script-or-fn root
7728 js2-current-scope root
7729 js2-nesting-of-function 0
7730 js2-labeled-stmt nil
7731 js2-recorded-identifiers nil) ; for js2-highlight
7732 (while (/= (setq tt (js2-get-token)) js2-EOF)
7733 (if (= tt js2-FUNCTION)
7735 (setq n (if js2-called-by-compile-function
7736 (js2-parse-function-expr)
7737 (js2-parse-function-stmt))))
7738 ;; not a function - parse a statement
7740 (setq n (js2-parse-statement)))
7741 ;; add function or statement to script
7742 (setq end (js2-node-end n))
7743 (js2-block-node-push root n))
7744 ;; add comments to root in lexical order
7745 (when js2-scanned-comments
7746 ;; if we find a comment beyond end of normal kids, use its end
7747 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7748 (dolist (comment js2-scanned-comments)
7749 (push comment (js2-ast-root-comments root))
7750 (js2-node-add-children root comment)))
7751 (setf (js2-node-len root) (- end pos))
7752 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7753 ;; Give extensions a chance to muck with things before highlighting starts.
7754 (let ((js2-additional-externs js2-additional-externs))
7756 (run-hooks 'js2-post-parse-callbacks))
7757 (js2-highlight-undeclared-vars))
7760 (defun js2-parse-function-closure-body (fn-node)
7761 "Parse a JavaScript 1.8 function closure body."
7762 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7764 (js2-report-error "msg.no.brace.body" nil
7765 (js2-node-pos fn-node)
7766 (- js2-ts-cursor (js2-node-pos fn-node)))
7767 (js2-node-add-children fn-node
7768 (setf (js2-function-node-body fn-node)
7769 (js2-parse-expr t))))))
7771 (defun js2-parse-function-body (fn-node)
7772 (js2-must-match js2-LC "msg.no.brace.body"
7773 (js2-node-pos fn-node)
7774 (- js2-ts-cursor (js2-node-pos fn-node)))
7775 (let ((pos (js2-current-token-beg)) ; LC position
7776 (pn (make-js2-block-node)) ; starts at LC position
7779 (cl-incf js2-nesting-of-function)
7781 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7784 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7785 (js2-parse-statement)
7787 (js2-parse-function-stmt))))
7788 (cl-decf js2-nesting-of-function))
7789 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7790 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7791 (setq end (js2-current-token-end)))
7792 (setf (js2-node-pos pn) pos
7793 (js2-node-len pn) (- end pos))
7794 (setf (js2-function-node-body fn-node) pn)
7795 (js2-node-add-children fn-node pn)
7798 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7799 "Declare and fontify destructuring parameters inside NODE.
7800 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7802 ((js2-name-node-p node)
7804 (js2-define-symbol decl-type (js2-name-node-name node)
7805 node ignore-not-in-block)
7807 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7808 (+ leftpos (js2-node-len node))
7810 ((js2-object-node-p node)
7811 (dolist (elem (js2-object-node-elems node))
7812 (js2-define-destruct-symbols
7813 ;; In abbreviated destructuring {a, b}, right == left.
7814 (js2-object-prop-node-right elem)
7815 decl-type face ignore-not-in-block)))
7816 ((js2-array-node-p node)
7817 (dolist (elem (js2-array-node-elems node))
7819 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7820 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7821 (js2-node-len node)))))
7823 (defun js2-parse-function-params (function-type fn-node pos)
7824 (if (js2-match-token js2-RP)
7825 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7826 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7827 (eq (js2-current-token-type) js2-NAME)))
7828 params param default-found rest-param-at)
7829 (when paren-free-arrow
7831 (cl-loop for tt = (js2-peek-token)
7834 ;; destructuring param
7835 ((and (not paren-free-arrow)
7836 (or (= tt js2-LB) (= tt js2-LC)))
7839 (js2-report-error "msg.no.default.after.default.param"))
7840 (setq param (js2-parse-destruct-primary-expr))
7841 (js2-define-destruct-symbols param
7843 'js2-function-param)
7844 (push param params))
7847 (when (and (>= js2-language-version 200)
7848 (not paren-free-arrow)
7849 (js2-match-token js2-TRIPLEDOT)
7850 (not rest-param-at))
7851 ;; to report errors if there are more parameters
7852 (setq rest-param-at (length params)))
7853 (js2-must-match-name "msg.no.parm")
7854 (js2-record-face 'js2-function-param)
7855 (setq param (js2-create-name-node))
7856 (js2-define-symbol js2-LP (js2-current-token-string) param)
7857 ;; default parameter value
7858 (when (or (and default-found
7860 (js2-must-match js2-ASSIGN
7861 "msg.no.default.after.default.param"
7862 (js2-node-pos param)
7863 (js2-node-len param)))
7864 (and (>= js2-language-version 200)
7865 (js2-match-token js2-ASSIGN)))
7866 (cl-assert (not paren-free-arrow))
7867 (let* ((pos (js2-node-pos param))
7868 (tt (js2-current-token-type))
7869 (op-pos (- (js2-current-token-beg) pos))
7871 (right (js2-parse-assign-expr))
7872 (len (- (js2-node-end right) pos)))
7873 (setq param (make-js2-assign-node
7874 :type tt :pos pos :len len :op-pos op-pos
7875 :left left :right right)
7877 (js2-node-add-children param left right)))
7878 (push param params)))
7879 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7880 (js2-report-error "msg.param.after.rest" nil
7881 (js2-node-pos param) (js2-node-len param)))
7883 (js2-match-token js2-COMMA))
7884 (when (and (not paren-free-arrow)
7885 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7886 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7888 (setf (js2-function-node-rest-p fn-node) t))
7890 (js2-node-add-children fn-node p)
7891 (push p (js2-function-node-params fn-node))))))
7893 (defun js2-check-inconsistent-return-warning (fn-node name)
7894 "Possibly show inconsistent-return warning.
7895 Last token scanned is the close-curly for the function body."
7896 (when (and js2-mode-show-strict-warnings
7897 js2-strict-inconsistent-return-warning
7898 (not (js2-has-consistent-return-usage
7899 (js2-function-node-body fn-node))))
7900 ;; Have it extend from close-curly to bol or beginning of block.
7901 (let ((pos (save-excursion
7902 (goto-char (js2-current-token-end))
7903 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7905 (end (js2-current-token-end)))
7906 (if (cl-plusp (js2-name-node-length name))
7907 (js2-add-strict-warning "msg.no.return.value"
7908 (js2-name-node-name name) pos end)
7909 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7911 (defun js2-parse-function-stmt ()
7912 (let ((pos (js2-current-token-beg))
7913 (star-p (js2-match-token js2-MUL)))
7914 (js2-must-match-name "msg.unnamed.function.stmt")
7915 (let ((name (js2-create-name-node t))
7918 ((js2-match-token js2-LP)
7919 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7920 (js2-allow-member-expr-as-function-name
7921 (setq member-expr (js2-parse-member-expr-tail nil name))
7922 (js2-parse-highlight-member-expr-fn-name member-expr)
7923 (js2-must-match js2-LP "msg.no.paren.parms")
7924 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7925 (js2-function-node-member-expr pn) member-expr)
7928 (js2-report-error "msg.no.paren.parms")
7929 (make-js2-error-node))))))
7931 (defun js2-parse-function-expr ()
7932 (let ((pos (js2-current-token-beg))
7933 (star-p (js2-match-token js2-MUL))
7935 (when (js2-match-token js2-NAME)
7936 (setq name (js2-create-name-node t)))
7937 (js2-must-match js2-LP "msg.no.paren.parms")
7938 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7940 (defun js2-parse-function (function-type pos star-p &optional name)
7941 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7942 beginning of the first token (function keyword, unless it's an
7943 arrow function), NAME is js2-name-node."
7945 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7946 (setq lp (js2-current-token-beg)))
7947 (setf fn-node (make-js2-function-node :pos pos
7950 :lp (if lp (- lp pos))
7951 :generator-type (and star-p 'STAR)))
7953 (js2-set-face (js2-node-pos name) (js2-node-end name)
7954 'font-lock-function-name-face 'record)
7955 (when (and (eq function-type 'FUNCTION_STATEMENT)
7956 (cl-plusp (js2-name-node-length name)))
7957 ;; Function statements define a symbol in the enclosing scope
7958 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7959 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
7960 ;; 1. Nested functions are not affected by the dynamic scope flag
7961 ;; as dynamic scope is already a parent of their scope.
7962 ;; 2. Functions defined under the with statement also immune to
7963 ;; this setup, in which case dynamic scope is ignored in favor
7964 ;; of the with object.
7965 (setf (js2-function-node-ignore-dynamic fn-node) t))
7966 ;; dynamically bind all the per-function variables
7967 (let ((js2-current-script-or-fn fn-node)
7968 (js2-current-scope fn-node)
7969 (js2-nesting-of-with 0)
7973 js2-loop-and-switch-set)
7974 (js2-parse-function-params function-type fn-node pos)
7975 (when (eq function-type 'FUNCTION_ARROW)
7976 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7977 (if (and (>= js2-language-version 180)
7978 (/= (js2-peek-token) js2-LC))
7979 (js2-parse-function-closure-body fn-node)
7980 (js2-parse-function-body fn-node))
7981 (js2-check-inconsistent-return-warning fn-node name)
7984 (js2-node-add-children fn-node name)
7985 ;; Function expressions define a name only in the body of the
7986 ;; function, and only if not hidden by a parameter name
7987 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7988 (null (js2-scope-get-symbol js2-current-scope
7989 (js2-name-node-name name))))
7990 (js2-define-symbol js2-FUNCTION
7991 (js2-name-node-name name)
7993 (when (eq function-type 'FUNCTION_STATEMENT)
7994 (js2-record-imenu-functions fn-node))))
7996 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7997 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7998 ;; We wait until after parsing the function to set its parent scope,
7999 ;; since `js2-define-symbol' needs the defining-scope check to stop
8000 ;; at the function boundary when checking for redeclarations.
8001 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8004 (defun js2-parse-statements (&optional parent)
8005 "Parse a statement list. Last token consumed must be js2-LC.
8007 PARENT can be a `js2-block-node', in which case the statements are
8008 appended to PARENT. Otherwise a new `js2-block-node' is created
8011 This function does not match the closing js2-RC: the caller
8012 matches the RC so it can provide a suitable error message if not
8013 matched. This means it's up to the caller to set the length of
8014 the node to include the closing RC. The node start pos is set to
8015 the absolute buffer start position, and the caller should fix it
8016 up to be relative to the parent node. All children of this block
8017 node are given relative start positions and correct lengths."
8018 (let ((pn (or parent (make-js2-block-node)))
8020 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8022 (js2-block-node-push pn (js2-parse-statement)))
8025 (defun js2-parse-statement ()
8027 ;; coarse-grained user-interrupt check - needs work
8028 (and js2-parse-interruptable-p
8029 (zerop (% (cl-incf js2-parse-stmt-count)
8030 js2-statements-per-pause))
8032 (throw 'interrupted t))
8033 (setq pn (js2-statement-helper))
8034 ;; no-side-effects warning check
8035 (unless (js2-node-has-side-effects pn)
8036 (setq end (js2-node-end pn))
8039 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8040 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8043 ;; These correspond to the switch cases in Parser.statementHelper
8044 (defconst js2-parsers
8045 (let ((parsers (make-vector js2-num-tokens
8046 #'js2-parse-expr-stmt)))
8047 (aset parsers js2-BREAK #'js2-parse-break)
8048 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8049 (aset parsers js2-CONST #'js2-parse-const-var)
8050 (aset parsers js2-CONTINUE #'js2-parse-continue)
8051 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8052 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8053 (aset parsers js2-DO #'js2-parse-do)
8054 (aset parsers js2-EXPORT #'js2-parse-export)
8055 (aset parsers js2-FOR #'js2-parse-for)
8056 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8057 (aset parsers js2-IF #'js2-parse-if)
8058 (aset parsers js2-IMPORT #'js2-parse-import)
8059 (aset parsers js2-LC #'js2-parse-block)
8060 (aset parsers js2-LET #'js2-parse-let-stmt)
8061 (aset parsers js2-NAME #'js2-parse-name-or-label)
8062 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8063 (aset parsers js2-SEMI #'js2-parse-semi)
8064 (aset parsers js2-SWITCH #'js2-parse-switch)
8065 (aset parsers js2-THROW #'js2-parse-throw)
8066 (aset parsers js2-TRY #'js2-parse-try)
8067 (aset parsers js2-VAR #'js2-parse-const-var)
8068 (aset parsers js2-WHILE #'js2-parse-while)
8069 (aset parsers js2-WITH #'js2-parse-with)
8070 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8072 "A vector mapping token types to parser functions.")
8074 (defun js2-parse-warn-missing-semi (beg end)
8075 (and js2-mode-show-strict-warnings
8076 js2-strict-missing-semi-warning
8077 (js2-add-strict-warning
8078 "msg.missing.semi" nil
8079 ;; back up to beginning of statement or line
8080 (max beg (save-excursion
8085 (defconst js2-no-semi-insertion
8098 "List of tokens that don't do automatic semicolon insertion.")
8100 (defconst js2-autoinsert-semi-and-warn
8101 (list js2-ERROR js2-EOF js2-RC))
8103 (defun js2-statement-helper ()
8104 (let* ((tt (js2-get-token))
8106 (parser (if (= tt js2-ERROR)
8108 (aref js2-parsers tt)))
8110 ;; If the statement is set, then it's been told its label by now.
8111 (and js2-labeled-stmt
8112 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8113 (setq js2-labeled-stmt nil))
8114 (setq pn (funcall parser))
8115 ;; Don't do auto semi insertion for certain statement types.
8116 (unless (or (memq first-tt js2-no-semi-insertion)
8117 (js2-labeled-stmt-node-p pn))
8118 (js2-auto-insert-semicolon pn))
8121 (defun js2-auto-insert-semicolon (pn)
8122 (let* ((tt (js2-get-token))
8123 (pos (js2-node-pos pn)))
8126 ;; extend the node bounds to include the semicolon.
8127 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8128 ((memq tt js2-autoinsert-semi-and-warn)
8129 (js2-unget-token) ; Not ';', do not consume.
8131 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8133 (if (not (js2-token-follows-eol-p (js2-current-token)))
8134 ;; Report error if no EOL or autoinsert ';' otherwise
8135 (js2-report-error "msg.no.semi.stmt")
8136 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8137 (js2-unget-token) ; Not ';', do not consume.
8140 (defun js2-parse-condition ()
8141 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8142 The parens are discarded and the expression node is returned.
8143 The `pos' field of the return value is set to an absolute position
8144 that must be fixed up by the caller.
8145 Return value is a list (EXPR LP RP), with absolute paren positions."
8147 (if (js2-must-match js2-LP "msg.no.paren.cond")
8148 (setq lp (js2-current-token-beg)))
8149 (setq pn (js2-parse-expr))
8150 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8151 (setq rp (js2-current-token-beg)))
8152 ;; Report strict warning on code like "if (a = 7) ..."
8153 (if (and js2-strict-cond-assign-warning
8154 (js2-assign-node-p pn))
8155 (js2-add-strict-warning "msg.equal.as.assign" nil
8157 (+ (js2-node-pos pn)
8158 (js2-node-len pn))))
8161 (defun js2-parse-if ()
8162 "Parser for if-statement. Last matched token must be js2-IF."
8163 (let ((pos (js2-current-token-beg))
8164 cond if-true if-false else-pos end pn)
8165 (setq cond (js2-parse-condition)
8166 if-true (js2-parse-statement)
8167 if-false (if (js2-match-token js2-ELSE)
8169 (setq else-pos (- (js2-current-token-beg) pos))
8170 (js2-parse-statement)))
8171 end (js2-node-end (or if-false if-true))
8172 pn (make-js2-if-node :pos pos
8174 :condition (car cond)
8178 :lp (js2-relpos (cl-second cond) pos)
8179 :rp (js2-relpos (cl-third cond) pos)))
8180 (js2-node-add-children pn (car cond) if-true if-false)
8183 (defun js2-parse-import ()
8184 "Parse import statement. The current token must be js2-IMPORT."
8185 (unless (js2-ast-root-p js2-current-scope)
8186 (js2-report-error "msg.mod.import.decl.at.top.level"))
8187 (let ((beg (js2-current-token-beg)))
8188 (cond ((js2-match-token js2-STRING)
8189 (make-js2-import-node
8191 :len (- (js2-current-token-end) beg)
8192 :module-id (js2-current-token-string)))
8194 (let* ((import-clause (js2-parse-import-clause))
8195 (from-clause (and import-clause (js2-parse-from-clause)))
8196 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8197 (node (make-js2-import-node
8199 :len (- (js2-current-token-end) beg)
8200 :import import-clause
8202 :module-id module-id)))
8204 (js2-node-add-children node import-clause))
8206 (js2-node-add-children node from-clause))
8209 (defun js2-parse-import-clause ()
8210 "Parse the bindings in an import statement.
8211 This can take many forms:
8213 ImportedDefaultBinding -> 'foo'
8214 NameSpaceImport -> '* as lib'
8215 NamedImports -> '{foo as bar, bang}'
8216 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8217 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8219 Try to match namespace imports and named imports first because nothing can
8220 come after them. If it is an imported default binding, then it could have named
8221 imports or a namespace import that follows it.
8223 (let* ((beg (js2-current-token-beg))
8224 (clause (make-js2-import-clause-node
8228 ((js2-match-token js2-MUL)
8229 (let ((ns-import (js2-parse-namespace-import)))
8231 (let ((name-node (js2-namespace-import-node-name ns-import)))
8233 js2-LET (js2-name-node-name name-node) name-node t)))
8234 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8235 (push ns-import children)))
8236 ((js2-match-token js2-LC)
8237 (let ((imports (js2-parse-export-bindings t)))
8238 (setf (js2-import-clause-node-named-imports clause) imports)
8239 (dolist (import imports)
8240 (push import children)
8241 (let ((name-node (js2-export-binding-node-local-name import)))
8244 js2-LET (js2-name-node-name name-node) name-node t))))))
8245 ((= (js2-peek-token) js2-NAME)
8246 (let ((binding (js2-maybe-parse-export-binding)))
8247 (let ((node-name (js2-export-binding-node-local-name binding)))
8248 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8249 (setf (js2-import-clause-node-default-binding clause) binding)
8250 (push binding children))
8251 (when (js2-match-token js2-COMMA)
8253 ((js2-match-token js2-MUL)
8254 (let ((ns-import (js2-parse-namespace-import)))
8255 (let ((name-node (js2-namespace-import-node-name ns-import)))
8257 js2-LET (js2-name-node-name name-node) name-node t))
8258 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8259 (push ns-import children)))
8260 ((js2-match-token js2-LC)
8261 (let ((imports (js2-parse-export-bindings t)))
8262 (setf (js2-import-clause-node-named-imports clause) imports)
8263 (dolist (import imports)
8264 (push import children)
8265 (let ((name-node (js2-export-binding-node-local-name import)))
8268 js2-LET (js2-name-node-name name-node) name-node t))))))
8269 (t (js2-report-error "msg.syntax")))))
8270 (t (js2-report-error "msg.mod.declaration.after.import")))
8271 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8272 (apply #'js2-node-add-children clause children)
8275 (defun js2-parse-namespace-import ()
8276 "Parse a namespace import expression such as '* as bar'.
8277 The current token must be js2-MUL."
8278 (let ((beg (js2-current-token-beg)))
8279 (when (js2-must-match js2-NAME "msg.syntax")
8280 (if (equal "as" (js2-current-token-string))
8281 (when (js2-must-match-prop-name "msg.syntax")
8282 (let ((node (make-js2-namespace-import-node
8284 :len (- (js2-current-token-end) beg)
8285 :name (make-js2-name-node
8286 :pos (js2-current-token-beg)
8287 :len (js2-current-token-end)
8288 :name (js2-current-token-string)))))
8289 (js2-node-add-children node (js2-namespace-import-node-name node))
8292 (js2-report-error "msg.syntax")))))
8295 (defun js2-parse-from-clause ()
8296 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8297 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8298 (let ((beg (js2-current-token-beg)))
8299 (if (equal "from" (js2-current-token-string))
8301 ((js2-match-token js2-STRING)
8302 (make-js2-from-clause-node
8304 :len (- (js2-current-token-end) beg)
8305 :module-id (js2-current-token-string)
8307 ((js2-match-token js2-THIS)
8308 (when (js2-must-match-name "msg.mod.spec.after.from")
8309 (if (equal "module" (js2-current-token-string))
8310 (make-js2-from-clause-node
8312 :len (- (js2-current-token-end) beg)
8317 (js2-report-error "msg.mod.spec.after.from")
8319 (t (js2-report-error "msg.mod.spec.after.from") nil))
8321 (js2-report-error "msg.mod.from.after.import.spec.set")
8324 (defun js2-parse-export-bindings (&optional import-p)
8325 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8326 {foo as bar, baz as bang}. The current token must be
8327 js2-LC. Return a lisp list of js2-export-binding-node"
8328 (let ((bindings (list)))
8330 (let ((binding (js2-maybe-parse-export-binding)))
8332 (push binding bindings))
8333 (js2-match-token js2-COMMA)))
8334 (when (js2-must-match js2-RC (if import-p
8335 "msg.mod.rc.after.import.spec.list"
8336 "msg.mod.rc.after.export.spec.list"))
8337 (reverse bindings))))
8339 (defun js2-maybe-parse-export-binding ()
8340 "Attempt to parse a binding expression found inside an import/export statement.
8341 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8342 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8343 js2-export-binding-node and consume all the tokens. If it does not match, it
8344 consumes no tokens."
8345 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8346 (beg (js2-current-token-beg))
8347 (extern-name-len (js2-current-token-len))
8348 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8349 (aref js2-kwd-tokens (js2-current-token-type)))))
8351 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8352 (if (and as (equal "as" (js2-current-token-string)))
8355 (and (js2-match-token js2-DEFAULT) "default")
8356 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8358 (let ((node (make-js2-export-binding-node
8360 :len (- (js2-current-token-end) beg)
8361 :local-name (make-js2-name-node
8363 :pos (js2-current-token-beg)
8364 :len (js2-current-token-len))
8365 :extern-name (make-js2-name-node
8368 :len extern-name-len))))
8369 (js2-node-add-children
8371 (js2-export-binding-node-local-name node)
8372 (js2-export-binding-node-extern-name node))
8376 (when as (js2-unget-token))
8377 (let* ((name-node (make-js2-name-node
8378 :name (js2-current-token-string)
8379 :pos (js2-current-token-beg)
8380 :len (js2-current-token-len)))
8381 (node (make-js2-export-binding-node
8382 :pos (js2-current-token-beg)
8383 :len (js2-current-token-len)
8384 :local-name name-node
8385 :extern-name name-node)))
8386 (when is-reserved-name
8387 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8388 (js2-node-add-children node name-node)
8392 (defun js2-parse-switch ()
8393 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8394 (let ((pos (js2-current-token-beg))
8395 tt pn discriminant has-default case-expr case-node
8396 case-pos cases stmt lp)
8397 (if (js2-must-match js2-LP "msg.no.paren.switch")
8398 (setq lp (js2-current-token-beg)))
8399 (setq discriminant (js2-parse-expr)
8400 pn (make-js2-switch-node :discriminant discriminant
8402 :lp (js2-relpos lp pos)))
8403 (js2-node-add-children pn discriminant)
8404 (js2-enter-switch pn)
8407 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8408 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8409 (js2-must-match js2-LC "msg.no.brace.switch")
8412 (setq tt (js2-next-token)
8413 case-pos (js2-current-token-beg))
8416 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8417 (throw 'break nil)) ; done
8419 (setq case-expr (js2-parse-expr))
8420 (js2-must-match js2-COLON "msg.no.colon.case"))
8423 (js2-report-error "msg.double.switch.default"))
8426 (js2-must-match js2-COLON "msg.no.colon.case"))
8428 (js2-report-error "msg.bad.switch")
8429 (throw 'break nil)))
8430 (setq case-node (make-js2-case-node :pos case-pos
8431 :len (- (js2-current-token-end) case-pos)
8433 (js2-node-add-children case-node case-expr)
8434 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8438 (setf stmt (js2-parse-statement)
8439 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8440 (js2-block-node-push case-node stmt))
8441 (push case-node cases)))
8442 ;; add cases last, as pushing reverses the order to be correct
8444 (js2-node-add-children pn kid)
8445 (push kid (js2-switch-node-cases pn)))
8447 (js2-exit-switch))))
8449 (defun js2-parse-while ()
8450 "Parser for while-statement. Last matched token must be js2-WHILE."
8451 (let ((pos (js2-current-token-beg))
8452 (pn (make-js2-while-node))
8457 (setf cond (js2-parse-condition)
8458 (js2-while-node-condition pn) (car cond)
8459 body (js2-parse-statement)
8460 (js2-while-node-body pn) body
8461 (js2-node-len pn) (- (js2-node-end body) pos)
8462 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8463 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8464 (js2-node-add-children pn body (car cond)))
8468 (defun js2-parse-do ()
8469 "Parser for do-statement. Last matched token must be js2-DO."
8470 (let ((pos (js2-current-token-beg))
8471 (pn (make-js2-do-node))
8476 (setq body (js2-parse-statement))
8477 (js2-must-match js2-WHILE "msg.no.while.do")
8478 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8479 cond (js2-parse-condition)
8480 (js2-do-node-condition pn) (car cond)
8481 (js2-do-node-body pn) body
8483 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8484 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8485 (js2-node-add-children pn (car cond) body))
8487 ;; Always auto-insert semicolon to follow SpiderMonkey:
8488 ;; It is required by ECMAScript but is ignored by the rest of
8489 ;; world; see bug 238945
8490 (if (js2-match-token js2-SEMI)
8491 (setq end js2-ts-cursor))
8492 (setf (js2-node-len pn) (- end pos))
8495 (defun js2-parse-export ()
8496 "Parse an export statement.
8497 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8498 expressions should only be either hoistable expressions (function or generator)
8499 or assignment expressions, but there is no checking to enforce that and so it
8500 will parse without error a small subset of
8501 invalid export statements."
8502 (unless (js2-ast-root-p js2-current-scope)
8503 (js2-report-error "msg.mod.export.decl.at.top.level"))
8504 (let ((beg (js2-current-token-beg))
8506 exports-list from-clause declaration default)
8508 ((js2-match-token js2-MUL)
8509 (setq from-clause (js2-parse-from-clause))
8511 (push from-clause children)))
8512 ((js2-match-token js2-LC)
8513 (setq exports-list (js2-parse-export-bindings))
8515 (dolist (export exports-list)
8516 (push export children)))
8517 (when (js2-match-token js2-NAME)
8518 (if (equal "from" (js2-current-token-string))
8521 (setq from-clause (js2-parse-from-clause)))
8522 (js2-unget-token))))
8523 ((js2-match-token js2-DEFAULT)
8524 (setq default (js2-parse-expr)))
8525 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8526 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8528 (setq declaration (js2-parse-expr))))
8530 (push from-clause children))
8532 (push declaration children))
8534 (push default children))
8535 (let ((node (make-js2-export-node
8537 :len (- (js2-current-token-end) beg)
8538 :exports-list exports-list
8539 :from-clause from-clause
8540 :declaration declaration
8542 (apply #'js2-node-add-children node children)
8545 (defun js2-parse-for ()
8546 "Parse a for, for-in or for each-in statement.
8547 Last matched token must be js2-FOR."
8548 (let ((for-pos (js2-current-token-beg))
8549 pn is-for-each is-for-in-or-of is-for-of
8550 in-pos each-pos tmp-pos
8551 init ; Node init is also foo in 'foo in object'.
8552 cond ; Node cond is also object in 'foo in object'.
8553 incr ; 3rd section of for-loop initializer.
8555 ;; See if this is a for each () instead of just a for ()
8556 (when (js2-match-token js2-NAME)
8557 (if (string= "each" (js2-current-token-string))
8560 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8561 (js2-record-face 'font-lock-keyword-face))
8562 (js2-report-error "msg.no.paren.for")))
8563 (if (js2-must-match js2-LP "msg.no.paren.for")
8564 (setq lp (- (js2-current-token-beg) for-pos)))
8565 (setq tt (js2-get-token))
8566 ;; 'for' makes local scope
8567 (js2-push-scope (make-js2-scope))
8569 ;; parse init clause
8570 (let ((js2-in-for-init t)) ; set as dynamic variable
8574 (setq init (make-js2-empty-expr-node)))
8575 ((or (= tt js2-VAR) (= tt js2-LET))
8576 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8579 (setq init (js2-parse-expr)))))
8580 (if (or (js2-match-token js2-IN)
8581 (and (>= js2-language-version 200)
8582 (js2-match-contextual-kwd "of")
8583 (setq is-for-of t)))
8584 (setq is-for-in-or-of t
8585 in-pos (- (js2-current-token-beg) for-pos)
8586 ;; scope of iteration target object is not the scope we've created above.
8587 ;; stash current scope temporary.
8588 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8589 (js2-parse-expr))) ; object over which we're iterating
8590 ;; else ordinary for loop - parse cond and incr
8591 (js2-must-match js2-SEMI "msg.no.semi.for")
8592 (setq cond (if (= (js2-peek-token) js2-SEMI)
8593 (make-js2-empty-expr-node) ; no loop condition
8595 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8596 (setq tmp-pos (js2-current-token-end)
8597 incr (if (= (js2-peek-token) js2-RP)
8598 (make-js2-empty-expr-node :pos tmp-pos)
8600 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8601 (setq rp (- (js2-current-token-beg) for-pos)))
8602 (if (not is-for-in-or-of)
8603 (setq pn (make-js2-for-node :init init
8608 ;; cond could be null if 'in obj' got eaten by the init node.
8609 (if (js2-infix-node-p init)
8610 ;; it was (foo in bar) instead of (var foo in bar)
8611 (setq cond (js2-infix-node-right init)
8612 init (js2-infix-node-left init))
8613 (if (and (js2-var-decl-node-p init)
8614 (> (length (js2-var-decl-node-kids init)) 1))
8615 (js2-report-error "msg.mult.index")))
8616 (setq pn (make-js2-for-in-node :iterator init
8619 :foreach-p is-for-each
8627 ;; We have to parse the body -after- creating the loop node,
8628 ;; so that the loop node appears in the js2-loop-set, allowing
8629 ;; break/continue statements to find the enclosing loop.
8630 (setf body (js2-parse-statement)
8631 (js2-loop-node-body pn) body
8632 (js2-node-pos pn) for-pos
8633 (js2-node-len pn) (- (js2-node-end body) for-pos))
8634 (js2-node-add-children pn init cond incr body))
8640 (defun js2-parse-try ()
8641 "Parse a try statement. Last matched token must be js2-TRY."
8642 (let ((try-pos (js2-current-token-beg))
8649 (if (/= (js2-peek-token) js2-LC)
8650 (js2-report-error "msg.no.brace.try"))
8651 (setq try-block (js2-parse-statement)
8652 try-end (js2-node-end try-block)
8653 peek (js2-peek-token))
8656 (while (js2-match-token js2-CATCH)
8657 (let* ((catch-pos (js2-current-token-beg))
8658 (catch-node (make-js2-catch-node :pos catch-pos))
8663 (if saw-default-catch
8664 (js2-report-error "msg.catch.unreachable"))
8665 (if (js2-must-match js2-LP "msg.no.paren.catch")
8666 (setq lp (- (js2-current-token-beg) catch-pos)))
8667 (js2-push-scope catch-node)
8668 (let ((tt (js2-peek-token)))
8670 ;; Destructuring pattern:
8671 ;; catch ({ message, file }) { ... }
8672 ((or (= tt js2-LB) (= tt js2-LC))
8674 (setq param (js2-parse-destruct-primary-expr))
8675 (js2-define-destruct-symbols param js2-LET nil))
8678 (js2-must-match-name "msg.bad.catchcond")
8679 (setq param (js2-create-name-node))
8680 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8682 (if (js2-match-token js2-IF)
8683 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8684 catch-cond (js2-parse-expr))
8685 (setq saw-default-catch t))
8686 (if (js2-must-match js2-RP "msg.bad.catchcond")
8687 (setq rp (- (js2-current-token-beg) catch-pos)))
8688 (js2-must-match js2-LC "msg.no.brace.catchblock")
8689 (js2-parse-statements catch-node)
8690 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8691 (setq try-end (js2-current-token-end)))
8693 (setf (js2-node-len catch-node) (- try-end catch-pos)
8694 (js2-catch-node-param catch-node) param
8695 (js2-catch-node-guard-expr catch-node) catch-cond
8696 (js2-catch-node-guard-kwd catch-node) guard-kwd
8697 (js2-catch-node-lp catch-node) lp
8698 (js2-catch-node-rp catch-node) rp)
8699 (js2-node-add-children catch-node param catch-cond)
8700 (push catch-node catch-blocks))))
8701 ((/= peek js2-FINALLY)
8702 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8703 (js2-node-pos try-block)
8704 (- (setq try-end (js2-node-end try-block))
8705 (js2-node-pos try-block)))))
8706 (when (js2-match-token js2-FINALLY)
8707 (let ((finally-pos (js2-current-token-beg))
8708 (block (js2-parse-statement)))
8709 (setq try-end (js2-node-end block)
8710 finally-block (make-js2-finally-node :pos finally-pos
8711 :len (- try-end finally-pos)
8713 (js2-node-add-children finally-block block)))
8714 (let ((pn (make-js2-try-node :pos try-pos
8715 :len (- try-end try-pos)
8716 :try-block try-block
8717 :finally-block finally-block)))
8718 (js2-node-add-children pn try-block finally-block)
8719 ;; Push them onto the try-node, which reverses and corrects their order.
8720 (dolist (cb catch-blocks)
8721 (js2-node-add-children pn cb)
8722 (push cb (js2-try-node-catch-clauses pn)))
8725 (defun js2-parse-throw ()
8726 "Parser for throw-statement. Last matched token must be js2-THROW."
8727 (let ((pos (js2-current-token-beg))
8729 (if (= (js2-peek-token-or-eol) js2-EOL)
8730 ;; ECMAScript does not allow new lines before throw expression,
8732 (js2-report-error "msg.bad.throw.eol"))
8733 (setq expr (js2-parse-expr)
8734 pn (make-js2-throw-node :pos pos
8735 :len (- (js2-node-end expr) pos)
8737 (js2-node-add-children pn expr)
8740 (defun js2-match-jump-label-name (label-name)
8741 "If break/continue specified a label, return that label's labeled stmt.
8742 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8743 does not match an existing label, reports an error and returns nil."
8744 (let ((bundle (cdr (assoc label-name js2-label-set))))
8746 (js2-report-error "msg.undef.label"))
8749 (defun js2-parse-break ()
8750 "Parser for break-statement. Last matched token must be js2-BREAK."
8751 (let ((pos (js2-current-token-beg))
8752 (end (js2-current-token-end))
8753 break-target ; statement to break from
8754 break-label ; in "break foo", name-node representing the foo
8755 labels ; matching labeled statement to break to
8757 (when (eq (js2-peek-token-or-eol) js2-NAME)
8759 (setq break-label (js2-create-name-node)
8760 end (js2-node-end break-label)
8761 ;; matchJumpLabelName only matches if there is one
8762 labels (js2-match-jump-label-name (js2-current-token-string))
8763 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8764 (unless (or break-target break-label)
8765 ;; no break target specified - try for innermost enclosing loop/switch
8766 (if (null js2-loop-and-switch-set)
8768 (js2-report-error "msg.bad.break" nil pos (length "break")))
8769 (setq break-target (car js2-loop-and-switch-set))))
8770 (setq pn (make-js2-break-node :pos pos
8773 :target break-target))
8774 (js2-node-add-children pn break-label) ; but not break-target
8777 (defun js2-parse-continue ()
8778 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8779 (let ((pos (js2-current-token-beg))
8780 (end (js2-current-token-end))
8781 label ; optional user-specified label, a `js2-name-node'
8782 labels ; current matching labeled stmt, if any
8783 target ; the `js2-loop-node' target of this continue stmt
8785 (when (= (js2-peek-token-or-eol) js2-NAME)
8787 (setq label (js2-create-name-node)
8788 end (js2-node-end label)
8789 ;; matchJumpLabelName only matches if there is one
8790 labels (js2-match-jump-label-name (js2-current-token-string))))
8792 ((null labels) ; no current label to go to
8793 (if (null js2-loop-set) ; no loop to continue to
8794 (js2-report-error "msg.continue.outside" nil pos
8795 (length "continue"))
8796 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8798 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8799 (setq target (js2-labeled-stmt-node-stmt labels))
8800 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8801 (setq pn (make-js2-continue-node :pos pos
8805 (js2-node-add-children pn label) ; but not target - it's not our child
8808 (defun js2-parse-with ()
8809 "Parser for with-statement. Last matched token must be js2-WITH."
8810 (let ((pos (js2-current-token-beg))
8812 (if (js2-must-match js2-LP "msg.no.paren.with")
8813 (setq lp (js2-current-token-beg)))
8814 (setq obj (js2-parse-expr))
8815 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8816 (setq rp (js2-current-token-beg)))
8817 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8818 (setq body (js2-parse-statement)))
8819 (setq pn (make-js2-with-node :pos pos
8820 :len (- (js2-node-end body) pos)
8823 :lp (js2-relpos lp pos)
8824 :rp (js2-relpos rp pos)))
8825 (js2-node-add-children pn obj body)
8828 (defun js2-parse-const-var ()
8829 "Parser for var- or const-statement.
8830 Last matched token must be js2-CONST or js2-VAR."
8831 (let ((tt (js2-current-token-type))
8832 (pos (js2-current-token-beg))
8834 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8835 pn (make-js2-expr-stmt-node :pos pos
8836 :len (- (js2-node-end expr) pos)
8838 (js2-node-add-children pn expr)
8841 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8842 (let ((pn (make-js2-expr-stmt-node :pos pos
8843 :len (js2-node-len expr)
8844 :type (if (js2-inside-function)
8849 (js2-node-add-children pn expr))
8852 (defun js2-parse-let-stmt ()
8853 "Parser for let-statement. Last matched token must be js2-LET."
8854 (let ((pos (js2-current-token-beg))
8856 (if (= (js2-peek-token) js2-LP)
8857 ;; let expression in statement context
8858 (setq expr (js2-parse-let pos 'statement)
8859 pn (js2-wrap-with-expr-stmt pos expr t))
8860 ;; else we're looking at a statement like let x=6, y=7;
8861 (setf expr (js2-parse-variables js2-LET pos)
8862 pn (js2-wrap-with-expr-stmt pos expr t)
8863 (js2-node-type pn) js2-EXPR_RESULT))
8866 (defun js2-parse-ret-yield ()
8867 (js2-parse-return-or-yield (js2-current-token-type) nil))
8869 (defconst js2-parse-return-stmt-enders
8870 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8872 (defsubst js2-now-all-set (before after mask)
8873 "Return whether or not the bits in the mask have changed to all set.
8874 BEFORE is bits before change, AFTER is bits after change, and MASK is
8875 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8877 (and (/= (logand before mask) mask)
8878 (= (logand after mask) mask)))
8880 (defun js2-parse-return-or-yield (tt expr-context)
8881 (let* ((pos (js2-current-token-beg))
8882 (end (js2-current-token-end))
8883 (before js2-end-flags)
8884 (inside-function (js2-inside-function))
8885 (gen-type (and inside-function (js2-function-node-generator-type
8886 js2-current-script-or-fn)))
8887 e ret name yield-star-p)
8888 (unless inside-function
8889 (js2-report-error (if (eq tt js2-RETURN)
8892 (when (and inside-function
8894 (js2-match-token js2-MUL))
8895 (setq yield-star-p t))
8896 ;; This is ugly, but we don't want to require a semicolon.
8897 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8898 (setq e (js2-parse-expr)
8899 end (js2-node-end e)))
8902 (js2-set-flag js2-end-flags (if (null e)
8904 js2-end-returns-value))
8905 (setq ret (make-js2-return-node :pos pos
8908 (js2-node-add-children ret e)
8909 ;; See if we need a strict mode warning.
8910 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8911 ;; more thorough and accurate than this before/after flag check.
8912 ;; E.g. if there's a finally-block that always returns, we shouldn't
8913 ;; show a warning generated by inconsistent returns in the catch blocks.
8914 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8915 ;; so we know which returns/yields to highlight, and we should get rid of
8916 ;; all the checking in `js2-parse-return-or-yield'.
8917 (if (and js2-strict-inconsistent-return-warning
8918 (js2-now-all-set before js2-end-flags
8919 (logior js2-end-returns js2-end-returns-value)))
8920 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8921 ((eq gen-type 'COMPREHENSION)
8922 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8923 ;; like SpiderMonkey does.
8924 (js2-report-error "msg.syntax" nil pos 5))
8926 (setq ret (make-js2-yield-node :pos pos
8929 :star-p yield-star-p))
8930 (js2-node-add-children ret e)
8931 (unless expr-context
8933 ret (js2-wrap-with-expr-stmt pos e t))
8934 (js2-set-requires-activation)
8935 (js2-set-is-generator))))
8936 ;; see if we are mixing yields and value returns.
8937 (when (and inside-function
8938 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8939 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8941 (setq name (js2-function-name js2-current-script-or-fn))
8942 (if (zerop (length name))
8943 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8944 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8947 (defun js2-parse-debugger ()
8948 (make-js2-keyword-node :type js2-DEBUGGER))
8950 (defun js2-parse-block ()
8951 "Parser for a curly-delimited statement block.
8952 Last token matched must be `js2-LC'."
8953 (let ((pos (js2-current-token-beg))
8954 (pn (make-js2-scope)))
8958 (js2-parse-statements pn)
8959 (js2-must-match js2-RC "msg.no.brace.block")
8960 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8964 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8965 (defun js2-parse-semi ()
8966 "Parse a statement or handle an error.
8967 Current token type is `js2-SEMI' or `js2-ERROR'."
8968 (let ((tt (js2-current-token-type)) pos len)
8969 (if (eq tt js2-SEMI)
8970 (make-js2-empty-expr-node :len 1)
8971 (setq pos (js2-current-token-beg)
8972 len (- (js2-current-token-end) pos))
8973 (js2-report-error "msg.syntax" nil pos len)
8974 (make-js2-error-node :pos pos :len len))))
8976 (defun js2-parse-default-xml-namespace ()
8977 "Parse a `default xml namespace = <expr>' e4x statement."
8978 (let ((pos (js2-current-token-beg))
8981 (js2-set-requires-activation)
8982 (setq len (- js2-ts-cursor pos))
8983 (unless (and (js2-match-token js2-NAME)
8984 (string= (js2-current-token-string) "xml"))
8985 (js2-report-error "msg.bad.namespace" nil pos len))
8986 (unless (and (js2-match-token js2-NAME)
8987 (string= (js2-current-token-string) "namespace"))
8988 (js2-report-error "msg.bad.namespace" nil pos len))
8989 (unless (js2-match-token js2-ASSIGN)
8990 (js2-report-error "msg.bad.namespace" nil pos len))
8991 (setq expr (js2-parse-expr)
8992 end (js2-node-end expr)
8993 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8997 (js2-node-add-children unary expr)
8998 (make-js2-expr-stmt-node :pos pos
9002 (defun js2-record-label (label bundle)
9003 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9005 (let ((name (js2-label-node-name label))
9008 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9009 ;; flag both labels if possible when used in editing mode
9010 (if (and js2-parse-ide-mode
9011 (setq dup (js2-get-label-by-name labeled-stmt name)))
9012 (js2-report-error "msg.dup.label" nil
9013 (js2-node-abs-pos dup) (js2-node-len dup)))
9014 (js2-report-error "msg.dup.label" nil
9015 (js2-node-pos label) (js2-node-len label)))
9016 (js2-labeled-stmt-node-add-label bundle label)
9017 (js2-node-add-children bundle label)
9018 ;; Add one reference to the bundle per label in `js2-label-set'
9019 (push (cons name bundle) js2-label-set)))
9021 (defun js2-parse-name-or-label ()
9022 "Parser for identifier or label. Last token matched must be js2-NAME.
9023 Called when we found a name in a statement context. If it's a label, we gather
9024 up any following labels and the next non-label statement into a
9025 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9026 expression and return it wrapped in a `js2-expr-stmt-node'."
9027 (let ((pos (js2-current-token-beg))
9030 ;; set check for label and call down to `js2-parse-primary-expr'
9031 (setq expr (js2-maybe-parse-label))
9033 ;; Parse the non-label expression and wrap with expression stmt.
9034 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9035 ;; else parsed a label
9036 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9037 (js2-record-label expr bundle)
9038 ;; look for more labels
9039 (while (and continue (= (js2-get-token) js2-NAME))
9040 (if (setq expr (js2-maybe-parse-label))
9041 (js2-record-label expr bundle)
9042 (setq expr (js2-parse-expr)
9043 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9045 (js2-auto-insert-semicolon stmt)))
9046 ;; no more labels; now parse the labeled statement
9049 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9051 (setq stmt (js2-statement-helper))))
9052 ;; remove the labels for this statement from the global set
9053 (dolist (label (js2-labeled-stmt-node-labels bundle))
9054 (setq js2-label-set (remove label js2-label-set))))
9055 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9056 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9057 (js2-node-add-children bundle stmt)
9060 (defun js2-maybe-parse-label ()
9061 (cl-assert (= (js2-current-token-type) js2-NAME))
9063 (next-tt (js2-get-token))
9064 (label-end (js2-current-token-end)))
9065 ;; Do not consume colon, it is used as unwind indicator
9066 ;; to return to statementHelper.
9068 (if (= next-tt js2-COLON)
9070 (setq label-pos (js2-current-token-beg))
9071 (make-js2-label-node :pos label-pos
9072 :len (- label-end label-pos)
9073 :name (js2-current-token-string))
9074 (js2-set-face label-pos
9076 'font-lock-variable-name-face 'record))
9077 ;; Backtrack from the name token, too.
9081 (defun js2-parse-expr-stmt ()
9082 "Default parser in statement context, if no recognized statement found."
9083 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9086 (js2-parse-expr)) t))
9088 (defun js2-parse-variables (decl-type pos)
9089 "Parse a comma-separated list of variable declarations.
9090 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9092 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9093 For 'var' or 'const', the keyword should be the token last scanned.
9095 POS is the position where the node should start. It's sometimes the
9096 var/const/let keyword, and other times the beginning of the first token
9097 in the first variable declaration.
9099 Returns the parsed `js2-var-decl-node' expression node."
9100 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9102 destructuring kid-pos tt init name end nbeg nend vi
9105 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9106 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9107 ;; var {a, b} = baz;
9109 (setq destructuring nil
9112 kid-pos (js2-current-token-beg)
9113 end (js2-current-token-end)
9115 (if (or (= tt js2-LB) (= tt js2-LC))
9116 ;; Destructuring assignment, e.g., var [a, b] = ...
9117 (setq destructuring (js2-parse-destruct-primary-expr)
9118 end (js2-node-end destructuring))
9119 ;; Simple variable name
9121 (when (js2-must-match-name "msg.bad.var")
9122 (setq name (js2-create-name-node)
9123 nbeg (js2-current-token-beg)
9124 nend (js2-current-token-end)
9126 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9127 (when (js2-match-token js2-ASSIGN)
9128 (setq init (js2-parse-assign-expr)
9129 end (js2-node-end init))
9130 (js2-record-imenu-functions init name))
9132 (js2-set-face nbeg nend (if (js2-function-node-p init)
9133 'font-lock-function-name-face
9134 'font-lock-variable-name-face)
9136 (setq vi (make-js2-var-init-node :pos kid-pos
9137 :len (- end kid-pos)
9141 (if (and (null init) (not js2-in-for-init))
9142 (js2-report-error "msg.destruct.assign.no.init"))
9143 (js2-define-destruct-symbols destructuring
9145 'font-lock-variable-name-face)
9146 (setf (js2-var-init-node-target vi) destructuring))
9147 (setf (js2-var-init-node-target vi) name))
9148 (setf (js2-var-init-node-initializer vi) init)
9149 (js2-node-add-children vi name destructuring init)
9150 (js2-block-node-push result vi)
9151 (unless (js2-match-token js2-COMMA)
9152 (setq continue nil)))
9153 (setf (js2-node-len result) (- end pos))
9156 (defun js2-parse-let (pos &optional stmt-p)
9157 "Parse a let expression or statement.
9158 A let-expression is of the form `let (vars) expr'.
9159 A let-statment is of the form `let (vars) {statements}'.
9160 The third form of let is a variable declaration list, handled
9161 by `js2-parse-variables'."
9162 (let ((pn (make-js2-let-node :pos pos))
9164 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9165 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9169 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9170 (if (js2-must-match js2-RP "msg.no.paren.let")
9171 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9172 (if (and stmt-p (js2-match-token js2-LC))
9175 (setf beg (js2-current-token-beg) ; position stmt at LC
9176 body (js2-parse-statements))
9177 (js2-must-match js2-RC "msg.no.curly.let")
9178 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9179 (js2-node-len pn) (- (js2-current-token-end) pos)
9180 (js2-let-node-body pn) body
9181 (js2-node-type pn) js2-LET))
9183 (setf body (js2-parse-expr)
9184 (js2-node-len pn) (- (js2-node-end body) pos)
9185 (js2-let-node-body pn) body))
9186 (setf (js2-let-node-vars pn) vars)
9187 (js2-node-add-children pn vars body))
9191 (defun js2-define-new-symbol (decl-type name node &optional scope)
9192 (js2-scope-put-symbol (or scope js2-current-scope)
9194 (make-js2-symbol decl-type name node)))
9196 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9197 "Define a symbol in the current scope.
9198 If NODE is non-nil, it is the AST node associated with the symbol."
9199 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9200 (symbol (if defining-scope
9201 (js2-scope-get-symbol defining-scope name)))
9202 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9203 (pos (if node (js2-node-abs-pos node)))
9204 (len (if node (js2-node-len node))))
9206 ((and symbol ; already defined
9207 (or (= sdt js2-CONST) ; old version is const
9208 (= decl-type js2-CONST) ; new version is const
9209 ;; two let-bound vars in this block have same name
9210 (and (= sdt js2-LET)
9211 (eq defining-scope js2-current-scope))))
9214 ((= sdt js2-CONST) "msg.const.redecl")
9215 ((= sdt js2-LET) "msg.let.redecl")
9216 ((= sdt js2-VAR) "msg.var.redecl")
9217 ((= sdt js2-FUNCTION) "msg.function.redecl")
9218 (t "msg.parm.redecl"))
9220 ((= decl-type js2-LET)
9221 (if (and (not ignore-not-in-block)
9222 (or (= (js2-node-type js2-current-scope) js2-IF)
9223 (js2-loop-node-p js2-current-scope)))
9224 (js2-report-error "msg.let.decl.not.in.block")
9225 (js2-define-new-symbol decl-type name node)))
9226 ((or (= decl-type js2-VAR)
9227 (= decl-type js2-CONST)
9228 (= decl-type js2-FUNCTION))
9230 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9231 (js2-add-strict-warning "msg.var.redecl" name)
9232 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9233 (js2-add-strict-warning "msg.var.hides.arg" name)))
9234 (js2-define-new-symbol decl-type name node
9235 js2-current-script-or-fn)))
9236 ((= decl-type js2-LP)
9238 ;; must be duplicate parameter. Second parameter hides the
9239 ;; first, so go ahead and add the second pararameter
9240 (js2-report-warning "msg.dup.parms" name))
9241 (js2-define-new-symbol decl-type name node))
9242 (t (js2-code-bug)))))
9244 (defun js2-parse-paren-expr-or-generator-comp ()
9245 (let ((px-pos (js2-current-token-beg)))
9247 ((and (>= js2-language-version 200)
9248 (js2-match-token js2-FOR))
9249 (js2-parse-generator-comp px-pos))
9250 ((and (>= js2-language-version 200)
9251 (js2-match-token js2-RP))
9252 ;; Not valid expression syntax, but this is valid in an arrow
9253 ;; function with no params: () => body.
9254 (if (eq (js2-peek-token) js2-ARROW)
9255 ;; Return whatever, it will hopefully be rewinded and
9256 ;; reparsed when we reach the =>.
9257 (make-js2-keyword-node :type js2-NULL)
9258 (js2-report-error "msg.syntax")
9259 (make-js2-error-node)))
9261 (let* ((js2-in-for-init nil)
9262 (expr (js2-parse-expr))
9263 (pn (make-js2-paren-node :pos px-pos
9265 :len (- (js2-current-token-end)
9267 (js2-node-add-children pn (js2-paren-node-expr pn))
9268 (js2-must-match js2-RP "msg.no.paren")
9271 (defun js2-parse-expr (&optional oneshot)
9272 (let* ((pn (js2-parse-assign-expr))
9273 (pos (js2-node-pos pn))
9277 (while (and (not oneshot)
9278 (js2-match-token js2-COMMA))
9279 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9280 (if (= (js2-peek-token) js2-YIELD)
9281 (js2-report-error "msg.yield.parenthesized"))
9282 (setq right (js2-parse-assign-expr)
9284 pn (make-js2-infix-node :type js2-COMMA
9286 :len (- js2-ts-cursor pos)
9290 (js2-node-add-children pn left right))
9293 (defun js2-parse-assign-expr ()
9294 (let ((tt (js2-get-token))
9295 (pos (js2-current-token-beg))
9296 pn left right op-pos
9297 ts-state recorded-identifiers parsed-errors)
9298 (if (= tt js2-YIELD)
9299 (js2-parse-return-or-yield tt t)
9300 ;; Save the tokenizer state in case we find an arrow function
9301 ;; and have to rewind.
9302 (setq ts-state (make-js2-ts-state)
9303 recorded-identifiers js2-recorded-identifiers
9304 parsed-errors js2-parsed-errors)
9305 ;; not yield - parse assignment expression
9306 (setq pn (js2-parse-cond-expr)
9309 ((and (<= js2-first-assign tt)
9310 (<= tt js2-last-assign))
9311 ;; tt express assignment (=, |=, ^=, ..., %=)
9312 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9314 (setq right (js2-parse-assign-expr)
9315 pn (make-js2-assign-node :type tt
9317 :len (- (js2-node-end right) pos)
9321 (when js2-parse-ide-mode
9322 (js2-highlight-assign-targets pn left right)
9323 (js2-record-imenu-functions right left))
9324 ;; do this last so ide checks above can use absolute positions
9325 (js2-node-add-children pn left right))
9326 ((and (= tt js2-ARROW)
9327 (>= js2-language-version 200))
9328 (js2-ts-seek ts-state)
9329 (setq js2-recorded-identifiers recorded-identifiers
9330 js2-parsed-errors parsed-errors)
9331 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9336 (defun js2-parse-cond-expr ()
9337 (let ((pos (js2-current-token-beg))
9338 (pn (js2-parse-or-expr))
9344 (when (js2-match-token js2-HOOK)
9345 (setq q-pos (- (js2-current-token-beg) pos)
9346 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9347 (js2-must-match js2-COLON "msg.no.colon.cond")
9348 (setq c-pos (- (js2-current-token-beg) pos)
9349 if-false (js2-parse-assign-expr)
9351 pn (make-js2-cond-node :pos pos
9352 :len (- (js2-node-end if-false) pos)
9353 :test-expr test-expr
9355 :false-expr if-false
9358 (js2-node-add-children pn test-expr if-true if-false))
9361 (defun js2-make-binary (type left parser)
9362 "Helper for constructing a binary-operator AST node.
9363 LEFT is the left-side-expression, already parsed, and the
9364 binary operator should have just been matched.
9365 PARSER is a function to call to parse the right operand,
9366 or a `js2-node' struct if it has already been parsed.
9367 FIXME: The latter option is unused?"
9368 (let* ((pos (js2-node-pos left))
9369 (op-pos (- (js2-current-token-beg) pos))
9370 (right (if (js2-node-p parser)
9374 (pn (make-js2-infix-node :type type
9376 :len (- (js2-node-end right) pos)
9380 (js2-node-add-children pn left right)
9383 (defun js2-parse-or-expr ()
9384 (let ((pn (js2-parse-and-expr)))
9385 (when (js2-match-token js2-OR)
9386 (setq pn (js2-make-binary js2-OR
9388 'js2-parse-or-expr)))
9391 (defun js2-parse-and-expr ()
9392 (let ((pn (js2-parse-bit-or-expr)))
9393 (when (js2-match-token js2-AND)
9394 (setq pn (js2-make-binary js2-AND
9396 'js2-parse-and-expr)))
9399 (defun js2-parse-bit-or-expr ()
9400 (let ((pn (js2-parse-bit-xor-expr)))
9401 (while (js2-match-token js2-BITOR)
9402 (setq pn (js2-make-binary js2-BITOR
9404 'js2-parse-bit-xor-expr)))
9407 (defun js2-parse-bit-xor-expr ()
9408 (let ((pn (js2-parse-bit-and-expr)))
9409 (while (js2-match-token js2-BITXOR)
9410 (setq pn (js2-make-binary js2-BITXOR
9412 'js2-parse-bit-and-expr)))
9415 (defun js2-parse-bit-and-expr ()
9416 (let ((pn (js2-parse-eq-expr)))
9417 (while (js2-match-token js2-BITAND)
9418 (setq pn (js2-make-binary js2-BITAND
9420 'js2-parse-eq-expr)))
9423 (defconst js2-parse-eq-ops
9424 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9426 (defun js2-parse-eq-expr ()
9427 (let ((pn (js2-parse-rel-expr))
9429 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9430 (setq pn (js2-make-binary tt
9432 'js2-parse-rel-expr)))
9436 (defconst js2-parse-rel-ops
9437 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9439 (defun js2-parse-rel-expr ()
9440 (let ((pn (js2-parse-shift-expr))
9444 (setq tt (js2-get-token))
9446 ((and js2-in-for-init (= tt js2-IN))
9448 (setq continue nil))
9449 ((memq tt js2-parse-rel-ops)
9450 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9453 (setq continue nil))))
9456 (defconst js2-parse-shift-ops
9457 (list js2-LSH js2-URSH js2-RSH))
9459 (defun js2-parse-shift-expr ()
9460 (let ((pn (js2-parse-add-expr))
9464 (setq tt (js2-get-token))
9465 (if (memq tt js2-parse-shift-ops)
9466 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9468 (setq continue nil)))
9471 (defun js2-parse-add-expr ()
9472 (let ((pn (js2-parse-mul-expr))
9476 (setq tt (js2-get-token))
9477 (if (or (= tt js2-ADD) (= tt js2-SUB))
9478 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9480 (setq continue nil)))
9483 (defconst js2-parse-mul-ops
9484 (list js2-MUL js2-DIV js2-MOD))
9486 (defun js2-parse-mul-expr ()
9487 (let ((pn (js2-parse-unary-expr))
9491 (setq tt (js2-get-token))
9492 (if (memq tt js2-parse-mul-ops)
9493 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9495 (setq continue nil)))
9498 (defun js2-make-unary (type parser &rest args)
9499 "Make a unary node of type TYPE.
9500 PARSER is either a node (for postfix operators) or a function to call
9501 to parse the operand (for prefix operators)."
9502 (let* ((pos (js2-current-token-beg))
9503 (postfix (js2-node-p parser))
9506 (apply parser args)))
9509 (if postfix ; e.g. i++
9510 (setq pos (js2-node-pos expr)
9511 end (js2-current-token-end))
9512 (setq end (js2-node-end expr)))
9513 (setq pn (make-js2-unary-node :type type
9517 (js2-node-add-children pn expr)
9520 (defconst js2-incrementable-node-types
9521 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9522 "Node types that can be the operand of a ++ or -- operator.")
9524 (defun js2-check-bad-inc-dec (tt beg end unary)
9525 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9526 js2-incrementable-node-types)
9527 (js2-report-error (if (= tt js2-INC)
9530 nil beg (- end beg))))
9532 (defun js2-parse-unary-expr ()
9533 (let ((tt (js2-current-token-type))
9536 ((or (= tt js2-VOID)
9541 (js2-make-unary tt 'js2-parse-unary-expr))
9544 ;; Convert to special POS token in decompiler and parse tree
9545 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9548 ;; Convert to special NEG token in decompiler and parse tree
9549 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9554 (setq beg (js2-current-token-beg)
9555 end (js2-current-token-end)
9556 expr (js2-make-unary tt 'js2-parse-member-expr t))
9557 (js2-check-bad-inc-dec tt beg end expr)))
9560 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9563 (make-js2-error-node)) ; try to continue
9565 js2-compiler-xml-available)
9566 ;; XML stream encountered in expression.
9567 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9569 (setq pn (js2-parse-member-expr t)
9570 ;; Don't look across a newline boundary for a postfix incop.
9571 tt (js2-peek-token-or-eol))
9572 (when (or (= tt js2-INC) (= tt js2-DEC))
9575 pn (js2-make-unary tt expr))
9576 (js2-node-set-prop pn 'postfix t)
9577 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9580 (defun js2-parse-xml-initializer ()
9581 "Parse an E4X XML initializer.
9582 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9583 Then I'll postprocess the result, depending on whether we're in IDE
9584 mode or codegen mode, and generate the appropriate rewritten AST.
9585 IDE mode uses a rich AST that models the XML structure. Codegen mode
9586 just concatenates everything and makes a new XML or XMLList out of it."
9587 (let ((tt (js2-get-first-xml-token))
9588 pn-xml pn expr kids expr-pos
9591 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9592 (js2-report-error "msg.syntax"))
9593 (setq pn-xml (make-js2-xml-node))
9596 (setq first-token nil)
9597 (setq tt (js2-get-next-xml-token)))
9599 ;; js2-XML means we found a {expr} in the XML stream.
9600 ;; The token string is the XML up to the left-curly.
9602 (push (make-js2-string-node :pos (js2-current-token-beg)
9603 :len (- js2-ts-cursor (js2-current-token-beg)))
9605 (js2-must-match js2-LC "msg.syntax")
9606 (setq expr-pos js2-ts-cursor
9607 expr (if (eq (js2-peek-token) js2-RC)
9608 (make-js2-empty-expr-node :pos expr-pos)
9610 (js2-must-match js2-RC "msg.syntax")
9611 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9612 :len (js2-node-len expr)
9614 (js2-node-add-children pn expr)
9616 ;; a js2-XMLEND token means we hit the final close-tag.
9618 (push (make-js2-string-node :pos (js2-current-token-beg)
9619 :len (- js2-ts-cursor (js2-current-token-beg)))
9621 (dolist (kid (nreverse kids))
9622 (js2-block-node-push pn-xml kid))
9623 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9624 (js2-node-pos pn-xml))
9627 (js2-report-error "msg.syntax")
9628 (setq continue nil))))
9632 (defun js2-parse-argument-list ()
9633 "Parse an argument list and return it as a Lisp list of nodes.
9634 Returns the list in reverse order. Consumes the right-paren token."
9636 (unless (js2-match-token js2-RP)
9638 (let ((tt (js2-get-token)))
9639 (if (= tt js2-YIELD)
9640 (js2-report-error "msg.yield.parenthesized"))
9641 (if (and (= tt js2-TRIPLEDOT)
9642 (>= js2-language-version 200))
9643 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9645 (push (js2-parse-assign-expr) result)))
9647 (js2-match-token js2-COMMA))
9648 (js2-must-match js2-RP "msg.no.paren.arg")
9651 (defun js2-parse-member-expr (&optional allow-call-syntax)
9652 (let ((tt (js2-current-token-type))
9653 pn pos target args beg end init)
9655 (setq pn (js2-parse-primary-expr))
9656 ;; parse a 'new' expression
9658 (setq pos (js2-current-token-beg)
9660 target (js2-parse-member-expr)
9661 end (js2-node-end target)
9662 pn (make-js2-new-node :pos pos
9665 (js2-highlight-function-call (js2-current-token))
9666 (js2-node-add-children pn target)
9667 (when (js2-match-token js2-LP)
9668 ;; Add the arguments to pn, if any are supplied.
9669 (setf beg pos ; start of "new" keyword
9670 pos (js2-current-token-beg)
9671 args (nreverse (js2-parse-argument-list))
9672 (js2-new-node-args pn) args
9673 end (js2-current-token-end)
9674 (js2-new-node-lp pn) (- pos beg)
9675 (js2-new-node-rp pn) (- end 1 beg))
9676 (apply #'js2-node-add-children pn args))
9677 (when (and js2-allow-rhino-new-expr-initializer
9678 (js2-match-token js2-LC))
9679 (setf init (js2-parse-object-literal)
9680 end (js2-node-end init)
9681 (js2-new-node-initializer pn) init)
9682 (js2-node-add-children pn init))
9683 (setf (js2-node-len pn) (- end beg))) ; end outer if
9684 (js2-parse-member-expr-tail allow-call-syntax pn)))
9686 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9687 "Parse a chain of property/array accesses or function calls.
9688 Includes parsing for E4X operators like `..' and `.@'.
9689 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9690 Returns an expression tree that includes PN, the parent node."
9694 (setq tt (js2-get-token))
9696 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9697 (setq pn (js2-parse-property-access tt pn)))
9698 ((= tt js2-DOTQUERY)
9699 (setq pn (js2-parse-dot-query pn)))
9701 (setq pn (js2-parse-element-get pn)))
9704 (if allow-call-syntax
9705 (setq pn (js2-parse-function-call pn))
9706 (setq continue nil)))
9707 ((= tt js2-TEMPLATE_HEAD)
9708 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9709 ((= tt js2-NO_SUBS_TEMPLATE)
9710 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9713 (setq continue nil))))
9714 (if (>= js2-highlight-level 2)
9715 (js2-parse-highlight-member-expr-node pn))
9718 (defun js2-parse-tagged-template (tag-node tpl-node)
9719 "Parse tagged template expression."
9720 (let* ((beg (js2-node-pos tag-node))
9721 (pn (make-js2-tagged-template-node :beg beg
9722 :len (- (js2-current-token-end) beg)
9724 :template tpl-node)))
9725 (js2-node-add-children pn tag-node tpl-node)
9728 (defun js2-parse-dot-query (pn)
9729 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9730 Last token parsed must be `js2-DOTQUERY'."
9731 (let ((pos (js2-node-pos pn))
9734 (js2-set-requires-activation)
9735 (setq op-pos (js2-current-token-beg)
9736 expr (js2-parse-expr)
9737 end (js2-node-end expr)
9738 pn (make-js2-xml-dot-query-node :left pn
9742 (js2-node-add-children pn
9743 (js2-xml-dot-query-node-left pn)
9744 (js2-xml-dot-query-node-right pn))
9745 (if (js2-must-match js2-RP "msg.no.paren")
9746 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9747 end (js2-current-token-end)))
9748 (setf (js2-node-len pn) (- end pos))
9751 (defun js2-parse-element-get (pn)
9752 "Parse an element-get expression, e.g. foo[bar].
9753 Last token parsed must be `js2-RB'."
9754 (let ((lb (js2-current-token-beg))
9755 (pos (js2-node-pos pn))
9757 (setq expr (js2-parse-expr))
9758 (if (js2-must-match js2-RB "msg.no.bracket.index")
9759 (setq rb (js2-current-token-beg)))
9760 (setq pn (make-js2-elem-get-node :target pn
9763 :lb (js2-relpos lb pos)
9764 :rb (js2-relpos rb pos)
9765 :len (- (js2-current-token-end) pos)))
9766 (js2-node-add-children pn
9767 (js2-elem-get-node-target pn)
9768 (js2-elem-get-node-element pn))
9771 (defun js2-highlight-function-call (token)
9772 (when (eq (js2-token-type token) js2-NAME)
9773 (js2-record-face 'js2-function-call token)))
9775 (defun js2-parse-function-call (pn)
9776 (js2-highlight-function-call (js2-current-token))
9779 (pos (js2-node-pos pn)))
9780 (setq pn (make-js2-call-node :pos pos
9782 :lp (- (js2-current-token-beg) pos)))
9783 (js2-node-add-children pn (js2-call-node-target pn))
9784 ;; Add the arguments to pn, if any are supplied.
9785 (setf args (nreverse (js2-parse-argument-list))
9786 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9787 (js2-call-node-args pn) args)
9788 (apply #'js2-node-add-children pn args)
9789 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9792 (defun js2-parse-property-access (tt pn)
9793 "Parse a property access, XML descendants access, or XML attr access."
9794 (let ((member-type-flags 0)
9795 (dot-pos (js2-current-token-beg))
9796 (dot-len (if (= tt js2-DOTDOT) 2 1))
9798 ref ; right side of . or .. operator
9800 (when (= tt js2-DOTDOT)
9802 (setq member-type-flags js2-descendants-flag))
9803 (if (not js2-compiler-xml-available)
9805 (js2-must-match-prop-name "msg.no.name.after.dot")
9806 (setq name (js2-create-name-node t js2-GETPROP)
9807 result (make-js2-prop-get-node :left pn
9808 :pos (js2-current-token-beg)
9810 :len (js2-current-token-len)))
9811 (js2-node-add-children result pn name)
9813 ;; otherwise look for XML operators
9814 (setf result (if (= tt js2-DOT)
9815 (make-js2-prop-get-node)
9816 (make-js2-infix-node :type js2-DOTDOT))
9817 (js2-node-pos result) (js2-node-pos pn)
9818 (js2-infix-node-op-pos result) dot-pos
9819 (js2-infix-node-left result) pn ; do this after setting position
9820 tt (js2-get-prop-name-token))
9822 ;; handles: name, ns::name, ns::*, ns::[expr]
9824 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9825 ;; handles: *, *::name, *::*, *::[expr]
9827 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9828 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9830 (setq result (js2-parse-attribute-access)))
9832 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9834 (setf (js2-node-len result) (- (js2-node-end ref)
9835 (js2-node-pos result))
9836 (js2-infix-node-right result) ref))
9837 (if (js2-infix-node-p result)
9838 (js2-node-add-children result
9839 (js2-infix-node-left result)
9840 (js2-infix-node-right result)))
9843 (defun js2-parse-attribute-access ()
9844 "Parse an E4X XML attribute expression.
9845 This includes expressions of the forms:
9847 @attr @ns::attr @ns::*
9849 @[expr] @*::[expr] @ns::[expr]
9851 Called if we peeked an '@' token."
9852 (let ((tt (js2-get-prop-name-token))
9853 (at-pos (js2-current-token-beg)))
9855 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9857 (js2-parse-property-name at-pos nil 0))
9858 ;; handles: @*, @*::name, @*::*, @*::[expr]
9860 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9863 (js2-parse-xml-elem-ref at-pos))
9865 (js2-report-error "msg.no.name.after.xmlAttr")
9866 ;; Avoid cascaded errors that happen if we make an error node here.
9867 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9869 (defun js2-parse-property-name (at-pos s member-type-flags)
9870 "Check if :: follows name in which case it becomes qualified name.
9872 AT-POS is a natural number if we just read an '@' token, else nil.
9873 S is the name or string that was matched: an identifier, 'throw' or '*'.
9874 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9876 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9877 operator, or the name is followed by ::. For a plain name, returns a
9878 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9879 (let ((pos (or at-pos (js2-current-token-beg)))
9881 (name (js2-create-name-node t (js2-current-token-type) s))
9884 (when (js2-match-token js2-COLONCOLON)
9886 colon-pos (js2-current-token-beg)
9887 tt (js2-get-prop-name-token))
9889 ;; handles name::name
9891 (setq name (js2-create-name-node)))
9894 (setq name (js2-create-name-node nil nil "*")))
9895 ;; handles name::[expr]
9897 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9899 (js2-report-error "msg.no.name.after.coloncolon"))))
9900 (if (and (null ns) (zerop member-type-flags))
9904 (make-js2-xml-prop-ref-node :pos pos
9905 :len (- (js2-node-end name) pos)
9907 :colon-pos colon-pos
9909 (js2-node-add-children pn name))))))
9911 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9912 "Parse the [expr] portion of an xml element reference.
9913 For instance, @[expr], @*::[expr], or ns::[expr]."
9914 (let* ((lb (js2-current-token-beg))
9915 (pos (or at-pos lb))
9917 (expr (js2-parse-expr))
9918 (end (js2-node-end expr))
9920 (if (js2-must-match js2-RB "msg.no.bracket.index")
9921 (setq rb (js2-current-token-beg)
9922 end (js2-current-token-end)))
9925 (make-js2-xml-elem-ref-node :pos pos
9927 :namespace namespace
9928 :colon-pos colon-pos
9931 :lb (js2-relpos lb pos)
9932 :rb (js2-relpos rb pos)))
9933 (js2-node-add-children pn namespace expr))))
9935 (defun js2-parse-destruct-primary-expr ()
9936 (let ((js2-is-in-destructuring t))
9937 (js2-parse-primary-expr)))
9939 (defun js2-parse-primary-expr ()
9940 "Parse a literal (leaf) expression of some sort.
9941 Includes complex literals such as functions, object-literals,
9942 array-literals, array comprehensions and regular expressions."
9943 (let (pn ; parent node (usually return value)
9945 (setq tt (js2-current-token-type))
9948 (js2-parse-class-expr))
9949 ((= tt js2-FUNCTION)
9950 (js2-parse-function-expr))
9952 (js2-parse-array-comp-or-literal))
9954 (js2-parse-object-literal))
9956 (js2-parse-let (js2-current-token-beg)))
9958 (js2-parse-paren-expr-or-generator-comp))
9961 (js2-parse-attribute-access))
9963 (js2-parse-name tt))
9965 (make-js2-number-node))
9966 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9967 (make-js2-string-node :type tt))
9968 ((= tt js2-TEMPLATE_HEAD)
9969 (js2-parse-template-literal))
9970 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9971 ;; Got / or /= which in this context means a regexp literal
9972 (let ((px-pos (js2-current-token-beg))
9973 (flags (js2-read-regexp tt))
9974 (end (js2-current-token-end)))
9976 (make-js2-regexp-node :pos px-pos
9978 :value (js2-current-token-string)
9980 (js2-set-face px-pos end 'font-lock-string-face 'record)
9981 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9982 ((or (= tt js2-NULL)
9987 (make-js2-keyword-node :type tt))
9988 ((= tt js2-TRIPLEDOT)
9989 ;; Likewise, only valid in an arrow function with a rest param.
9990 (if (and (js2-match-token js2-NAME)
9991 (js2-match-token js2-RP)
9992 (eq (js2-peek-token) js2-ARROW))
9994 (js2-unget-token) ; Put back the right paren.
9995 ;; See the previous case.
9996 (make-js2-keyword-node :type js2-NULL))
9997 (js2-report-error "msg.syntax")
9998 (make-js2-error-node)))
9999 ((= tt js2-RESERVED)
10000 (js2-report-error "msg.reserved.id")
10001 (make-js2-name-node))
10003 ;; the scanner or one of its subroutines reported the error.
10004 (make-js2-error-node))
10006 (let* ((px-pos (point-at-bol))
10007 (len (- js2-ts-cursor px-pos)))
10008 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10009 (make-js2-error-node :pos (1- js2-ts-cursor)))
10011 (js2-report-error "msg.syntax")
10012 (make-js2-error-node)))))
10014 (defun js2-parse-template-literal ()
10015 (let ((beg (js2-current-token-beg))
10016 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10017 (tt js2-TEMPLATE_HEAD))
10018 (while (eq tt js2-TEMPLATE_HEAD)
10019 (push (js2-parse-expr) kids)
10020 (js2-must-match js2-RC "msg.syntax")
10021 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10022 (push (make-js2-string-node :type tt) kids))
10023 (setq kids (nreverse kids))
10024 (let ((tpl (make-js2-template-node :beg beg
10025 :len (- (js2-current-token-end) beg)
10027 (apply #'js2-node-add-children tpl kids)
10030 (defun js2-parse-name (_tt)
10031 (let ((name (js2-current-token-string))
10033 (setq node (if js2-compiler-xml-available
10034 (js2-parse-property-name nil name 0)
10035 (js2-create-name-node 'check-activation nil name)))
10036 (if js2-highlight-external-variables
10037 (js2-record-name-node node))
10040 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10041 (js2-add-strict-warning
10043 ;; back up from comma to beginning of line or array/objlit
10045 (js2-node-pos (car elems))
10048 (goto-char comma-pos)
10049 (back-to-indentation)
10053 (defun js2-parse-array-comp-or-literal ()
10054 (let ((pos (js2-current-token-beg)))
10055 (if (and (>= js2-language-version 200)
10056 (js2-match-token js2-FOR))
10057 (js2-parse-array-comp pos)
10058 (js2-parse-array-literal pos))))
10060 (defun js2-parse-array-literal (pos)
10061 (let ((after-lb-or-comma t)
10062 after-comma tt elems pn
10064 (unless js2-is-in-destructuring
10065 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10067 (setq tt (js2-get-token))
10071 (setq after-comma (js2-current-token-end))
10072 (if (not after-lb-or-comma)
10073 (setq after-lb-or-comma t)
10077 (= tt js2-EOF)) ; prevent infinite loop
10079 (js2-report-error "msg.no.bracket.arg" nil pos))
10080 (when (and after-comma (< js2-language-version 170))
10081 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10082 pos (remove nil elems) after-comma))
10084 pn (make-js2-array-node :pos pos
10085 :len (- js2-ts-cursor pos)
10086 :elems (nreverse elems)))
10087 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10088 ;; destructuring binding
10089 (js2-is-in-destructuring
10090 (push (if (or (= tt js2-LC)
10093 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10094 (js2-parse-destruct-primary-expr)
10096 (js2-report-error "msg.bad.var")
10097 (make-js2-error-node))
10099 (setq after-lb-or-comma nil
10102 ((and (>= js2-language-version 170)
10103 (= tt js2-FOR) ; check for array comprehension
10104 (not after-lb-or-comma) ; "for" can't follow a comma
10105 elems ; must have at least 1 element
10106 (not (cdr elems))) ; but no 2nd element
10109 pn (js2-parse-legacy-array-comp (car elems) pos)))
10112 (unless after-lb-or-comma
10113 (js2-report-error "msg.no.bracket.arg"))
10114 (if (and (= tt js2-TRIPLEDOT)
10115 (>= js2-language-version 200))
10117 (push (js2-make-unary tt 'js2-parse-assign-expr)
10120 (push (js2-parse-assign-expr) elems))
10121 (setq after-lb-or-comma nil
10122 after-comma nil))))
10123 (unless js2-is-in-destructuring
10127 (defun js2-parse-legacy-array-comp (expr pos)
10128 "Parse a legacy array comprehension (JavaScript 1.7).
10129 EXPR is the first expression after the opening left-bracket.
10130 POS is the beginning of the LB token preceding EXPR.
10131 We should have just parsed the 'for' keyword before calling this function."
10132 (let ((current-scope js2-current-scope)
10133 loops first filter result)
10136 (while (js2-match-token js2-FOR)
10137 (let ((loop (make-js2-comp-loop-node)))
10138 (js2-push-scope loop)
10140 (js2-parse-comp-loop loop)))
10141 ;; First loop takes expr scope's parent.
10142 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10143 (js2-scope-parent-scope current-scope))
10144 ;; Set expr scope's parent to the last loop.
10145 (setf (js2-scope-parent-scope current-scope) (car loops))
10146 (if (/= (js2-get-token) js2-IF)
10148 (setq filter (js2-parse-condition))))
10149 (dotimes (_ (1- (length loops)))
10151 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10152 (setq result (make-js2-comp-node :pos pos
10153 :len (- js2-ts-cursor pos)
10155 :loops (nreverse loops)
10156 :filters (and filter (list (car filter)))
10157 :form 'LEGACY_ARRAY))
10158 (apply #'js2-node-add-children result expr (car filter)
10159 (js2-comp-node-loops result))
10162 (defun js2-parse-array-comp (pos)
10163 "Parse an ES6 array comprehension.
10164 POS is the beginning of the LB token.
10165 We should have just parsed the 'for' keyword before calling this function."
10166 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10167 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10170 (defun js2-parse-generator-comp (pos)
10171 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10172 (js2-current-script-or-fn
10173 (make-js2-function-node :generator-type 'COMPREHENSION))
10174 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10175 (js2-must-match js2-RP "msg.no.paren" pos)
10178 (defun js2-parse-comprehension (pos form)
10179 (let (loops filters expr result)
10183 (while (js2-match-token js2-FOR)
10184 (let ((loop (make-js2-comp-loop-node)))
10185 (js2-push-scope loop)
10187 (js2-parse-comp-loop loop)))
10188 (while (js2-match-token js2-IF)
10189 (push (car (js2-parse-condition)) filters))
10190 (setq expr (js2-parse-assign-expr)))
10193 (setq result (make-js2-comp-node :pos pos
10194 :len (- js2-ts-cursor pos)
10196 :loops (nreverse loops)
10197 :filters (nreverse filters)
10199 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10200 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10203 (defun js2-parse-comp-loop (pn &optional only-of-p)
10204 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10205 The current token should be the initial FOR.
10206 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10207 (let ((pos (js2-comp-loop-node-pos pn))
10208 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10209 (when (and (not only-of-p) (js2-match-token js2-NAME))
10210 (if (string= (js2-current-token-string) "each")
10213 each-pos (- (js2-current-token-beg) pos)) ; relative
10214 (js2-record-face 'font-lock-keyword-face))
10215 (js2-report-error "msg.no.paren.for")))
10216 (if (js2-must-match js2-LP "msg.no.paren.for")
10217 (setq lp (- (js2-current-token-beg) pos)))
10218 (setq tt (js2-peek-token))
10223 (setq iter (js2-parse-destruct-primary-expr))
10224 (js2-define-destruct-symbols iter js2-LET
10225 'font-lock-variable-name-face t))
10226 ((js2-match-token js2-NAME)
10227 (setq iter (js2-create-name-node)))
10229 (js2-report-error "msg.bad.var")))
10230 ;; Define as a let since we want the scope of the variable to
10231 ;; be restricted to the array comprehension
10232 (if (js2-name-node-p iter)
10233 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10234 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10235 (and (>= js2-language-version 200)
10236 (js2-match-contextual-kwd "of")
10238 (setq in-pos (- (js2-current-token-beg) pos))
10239 (js2-report-error "msg.in.after.for.name"))
10240 (setq obj (js2-parse-expr))
10241 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10242 (setq rp (- (js2-current-token-beg) pos)))
10243 (setf (js2-node-pos pn) pos
10244 (js2-node-len pn) (- js2-ts-cursor pos)
10245 (js2-comp-loop-node-iterator pn) iter
10246 (js2-comp-loop-node-object pn) obj
10247 (js2-comp-loop-node-in-pos pn) in-pos
10248 (js2-comp-loop-node-each-pos pn) each-pos
10249 (js2-comp-loop-node-foreach-p pn) foreach-p
10250 (js2-comp-loop-node-forof-p pn) forof-p
10251 (js2-comp-loop-node-lp pn) lp
10252 (js2-comp-loop-node-rp pn) rp)
10253 (js2-node-add-children pn iter obj)
10256 (defun js2-parse-class-stmt ()
10257 (let ((pos (js2-current-token-beg))
10258 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10259 (name (js2-create-name-node t)))
10260 (js2-set-face (js2-node-pos name) (js2-node-end name)
10261 'font-lock-function-name-face 'record)
10262 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10263 (js2-define-symbol js2-FUNCTION
10264 (js2-name-node-name name)
10268 (defun js2-parse-class-expr ()
10269 (let ((pos (js2-current-token-beg))
10271 (when (js2-match-token js2-NAME)
10272 (setq name (js2-create-name-node t)))
10273 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10275 (defun js2-parse-class (pos form name)
10276 ;; class X [extends ...] {
10277 (let (pn elems extends)
10278 (if (js2-match-token js2-EXTENDS)
10279 (if (= (js2-peek-token) js2-LC)
10280 (js2-report-error "msg.missing.extends")
10281 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10282 (setq extends (js2-parse-assign-expr))
10284 (js2-report-error "msg.bad.extends"))))
10285 (js2-must-match js2-LC "msg.no.brace.class")
10286 (setq elems (js2-parse-object-literal-elems t)
10287 pn (make-js2-class-node :pos pos
10288 :len (- js2-ts-cursor pos)
10293 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10296 (defun js2-parse-object-literal ()
10297 (let* ((pos (js2-current-token-beg))
10298 (elems (js2-parse-object-literal-elems))
10299 (result (make-js2-object-node :pos pos
10300 :len (- js2-ts-cursor pos)
10302 (apply #'js2-node-add-children result (js2-object-node-elems result))
10305 (defun js2-parse-object-literal-elems (&optional class-p)
10306 (let ((pos (js2-current-token-beg))
10309 tt elems elem after-comma)
10311 (setq static (and class-p (js2-match-token js2-STATIC))
10312 tt (js2-get-prop-name-token)
10315 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
10316 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
10317 ;; TODO(sdh): support *foo() {...}
10318 ((or (= js2-NAME tt)
10320 (setq after-comma nil
10321 elem (js2-parse-named-prop tt))
10322 (if (and (null elem)
10323 (not js2-recover-from-parse-errors))
10324 (setq continue nil)))
10325 ;; {[Symbol.iterator]: ...}
10326 ((and (= tt js2-LB)
10327 (>= js2-language-version 200))
10328 (let ((expr (js2-parse-expr)))
10329 (js2-must-match js2-RB "msg.missing.computed.rb")
10330 (setq after-comma nil
10331 elem (js2-parse-plain-property expr))))
10332 ;; {12: x} or {10.7: x}
10334 (setq after-comma nil
10335 elem (js2-parse-plain-property (make-js2-number-node))))
10336 ;; Break out of loop, and handle trailing commas.
10340 (setq continue nil)
10342 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10343 pos elems after-comma)))
10345 (js2-report-error "msg.bad.prop")
10346 (unless js2-recover-from-parse-errors
10347 (setq continue nil)))) ; end switch
10348 ;; Handle static for classes' codegen.
10350 (if elem (js2-node-set-prop elem 'STATIC t)
10351 (js2-report-error "msg.unexpected.static")))
10352 ;; Handle commas, depending on class-p.
10353 (let ((comma (js2-match-token js2-COMMA)))
10356 (js2-report-error "msg.class.unexpected.comma"))
10358 (setq after-comma (js2-current-token-end))
10359 (setq continue nil))))
10360 ;; Append any parsed element.
10361 (if elem (push elem elems))) ; end loop
10362 (js2-must-match js2-RC "msg.no.brace.prop")
10365 (defun js2-parse-named-prop (tt)
10366 "Parse a name, string, or getter/setter object property.
10367 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10368 (let ((string-prop (and (= tt js2-STRING)
10369 (make-js2-string-node)))
10371 (ppos (js2-current-token-beg))
10372 (pend (js2-current-token-end))
10373 (name (js2-create-name-node))
10374 (prop (js2-current-token-string)))
10376 ;; getter/setter prop
10377 ((and (= tt js2-NAME)
10378 (= (js2-peek-token) js2-NAME)
10379 (or (string= prop "get")
10380 (string= prop "set")))
10382 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
10383 (js2-record-face 'font-lock-function-name-face) ; for peeked name
10384 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
10385 (js2-parse-getter-setter-prop ppos name prop))
10386 ;; method definition: {f() {...}}
10387 ((and (= (js2-peek-token) js2-LP)
10388 (>= js2-language-version 200))
10389 (js2-record-face 'font-lock-function-name-face) ; name
10390 (js2-parse-getter-setter-prop ppos name ""))
10394 (setq expr (js2-parse-plain-property (or string-prop name)))
10395 (when (and (not string-prop)
10396 (not js2-is-in-destructuring)
10397 js2-highlight-external-variables
10398 (js2-node-get-prop expr 'SHORTHAND))
10399 (js2-record-name-node name))
10400 (js2-set-face ppos pend
10401 (if (js2-function-node-p
10402 (js2-object-prop-node-right expr))
10403 'font-lock-function-name-face
10404 'font-lock-variable-name-face)
10407 (defun js2-parse-plain-property (prop)
10408 "Parse a non-getter/setter property in an object literal.
10409 PROP is the node representing the property: a number, name or string."
10410 (let* ((tt (js2-get-token))
10411 (pos (js2-node-pos prop))
10414 ;; Abbreviated property, as in {foo, bar}
10415 ((and (>= js2-language-version 200)
10416 (or (= tt js2-COMMA)
10418 (not (js2-number-node-p prop)))
10420 (setq result (make-js2-object-prop-node
10424 :op-pos (js2-current-token-len)))
10425 (js2-node-add-children result prop)
10426 (js2-node-set-prop result 'SHORTHAND t)
10430 (if (= tt js2-COLON)
10431 (setq colon (- (js2-current-token-beg) pos)
10432 expr (js2-parse-assign-expr))
10433 (js2-report-error "msg.no.colon.prop")
10434 (setq expr (make-js2-error-node)))
10435 (setq result (make-js2-object-prop-node
10437 ;; don't include last consumed token in length
10438 :len (- (+ (js2-node-pos expr)
10439 (js2-node-len expr))
10444 (js2-node-add-children result prop expr)
10447 (defun js2-parse-getter-setter-prop (pos prop type-string)
10448 "Parse getter or setter property in an object literal.
10449 JavaScript syntax is:
10451 { get foo() {...}, set foo(x) {...} }
10453 and expression closure style is also supported
10455 { get foo() x, set foo(x) _x = x }
10457 POS is the start position of the `get' or `set' keyword.
10458 PROP is the `js2-name-node' representing the property name.
10459 GET-P is non-nil if the keyword was `get'."
10461 ((string= "get" type-string) js2-GET)
10462 ((string= "set" type-string) js2-SET)
10465 (fn (js2-parse-function-expr)))
10466 ;; it has to be an anonymous function, as we already parsed the name
10467 (if (/= (js2-node-type fn) js2-FUNCTION)
10468 (js2-report-error "msg.bad.prop")
10469 (if (cl-plusp (length (js2-function-name fn)))
10470 (js2-report-error "msg.bad.prop")))
10471 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10472 (setq end (js2-node-end fn)
10473 result (make-js2-getter-setter-node :type type
10478 (js2-node-add-children result prop fn)
10481 (defun js2-create-name-node (&optional check-activation-p token string)
10482 "Create a name node using the current token and, optionally, STRING.
10483 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10484 (let* ((beg (js2-current-token-beg))
10485 (tt (js2-current-token-type))
10487 (if (= js2-NAME tt)
10488 (js2-current-token-string)
10489 (js2-tt-name tt))))
10491 (setq name (make-js2-name-node :pos beg
10494 (if check-activation-p
10495 (js2-check-activation-name s (or token js2-NAME)))
10498 ;;; Indentation support
10500 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10501 ;; Karl cleverly deduces that the desired indentation level is often a
10502 ;; function of paren/bracket/brace nesting depth, which can be determined
10503 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10504 ;; then does some equally clever checks to see if we're in the context of a
10505 ;; substatement of a possibly braceless statement keyword such as if, while,
10506 ;; or finally. This approach yields pretty good results.
10508 ;; The indenter is often "wrong", however, and needs to be overridden.
10509 ;; The right long-term solution is probably to emulate (or integrate
10510 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10511 ;; parse tree from `js2-parse' is present, which is not true at the
10512 ;; moment the user is typing, computing indentation is still thousands
10513 ;; of lines of code to handle every possible syntactic edge case.
10515 ;; In the meantime, the compromise solution is that we offer a "bounce
10516 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10517 ;; current line indent among various likely guess points. This approach
10518 ;; is far from perfect, but should at least make it slightly easier to
10519 ;; move the line towards its desired indentation when manually
10520 ;; overriding Karl's heuristic nesting guesser.
10522 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10523 ;; extensions such as `let' and Array comprehensions. Major kudos to
10524 ;; Karl for coming up with the initial approach, which packs a lot of
10525 ;; punch for so little code.
10527 (defconst js2-possibly-braceless-keywords-re
10528 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10529 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10530 "try" "while" "with" "let")))
10531 "Regular expression matching keywords that are optionally
10532 followed by an opening brace.")
10534 (defconst js2-indent-operator-re
10535 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10536 (regexp-opt '("in" "instanceof") 'words))
10537 "Regular expression matching operators that affect indentation
10538 of continued expressions.")
10540 (defconst js2-declaration-keyword-re
10541 (regexp-opt '("var" "let" "const") 'words)
10542 "Regular expression matching variable declaration keywords.")
10544 (defun js2-re-search-forward-inner (regexp &optional bound count)
10545 "Auxiliary function for `js2-re-search-forward'."
10546 (let (parse saved-point)
10548 (re-search-forward regexp bound)
10549 (setq parse (if saved-point
10550 (parse-partial-sexp saved-point (point))
10551 (syntax-ppss (point))))
10552 (cond ((nth 3 parse)
10554 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10555 (save-excursion (end-of-line) (point)) t))
10559 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10560 (re-search-forward "\\*/"))
10562 (setq count (1- count))))
10563 (setq saved-point (point))))
10566 (defun js2-re-search-forward (regexp &optional bound noerror count)
10567 "Search forward but ignore strings and comments.
10568 Invokes `re-search-forward' but treats the buffer as if strings
10569 and comments have been removed."
10570 (let ((saved-point (point)))
10571 (condition-case err
10572 (cond ((null count)
10573 (js2-re-search-forward-inner regexp bound 1))
10575 (js2-re-search-backward-inner regexp bound (- count)))
10577 (js2-re-search-forward-inner regexp bound count)))
10579 (goto-char saved-point)
10581 (error (error-message-string err)))))))
10583 (defun js2-re-search-backward-inner (regexp &optional bound count)
10584 "Auxiliary function for `js2-re-search-backward'."
10587 (re-search-backward regexp bound)
10588 (setq parse (syntax-ppss (point)))
10589 (cond ((nth 3 parse)
10590 (re-search-backward
10591 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10592 (line-beginning-position) t))
10594 (goto-char (nth 8 parse)))
10596 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10597 (re-search-backward "/\\*"))
10599 (setq count (1- count))))))
10602 (defun js2-re-search-backward (regexp &optional bound noerror count)
10603 "Search backward but ignore strings and comments.
10604 Invokes `re-search-backward' but treats the buffer as if strings
10605 and comments have been removed."
10606 (let ((saved-point (point)))
10607 (condition-case err
10608 (cond ((null count)
10609 (js2-re-search-backward-inner regexp bound 1))
10611 (js2-re-search-forward-inner regexp bound (- count)))
10613 (js2-re-search-backward-inner regexp bound count)))
10615 (goto-char saved-point)
10617 (error (error-message-string err)))))))
10619 (defun js2-looking-at-operator-p ()
10620 "Return non-nil if text after point is a non-comma operator."
10621 (and (looking-at js2-indent-operator-re)
10622 (or (not (looking-at ":"))
10624 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10625 (looking-at "?"))))))
10627 (defun js2-continued-expression-p ()
10628 "Return non-nil if the current line continues an expression."
10630 (back-to-indentation)
10631 (or (js2-looking-at-operator-p)
10632 (when (catch 'found
10633 (while (and (re-search-backward "\n" nil t)
10634 (let ((state (syntax-ppss)))
10635 (when (nth 4 state)
10636 (goto-char (nth 8 state))) ;; skip comments
10637 (skip-chars-backward " \t")
10640 (throw 'found t))))))
10642 (when (js2-looking-at-operator-p)
10644 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10646 (defun js2-end-of-do-while-loop-p ()
10647 "Return non-nil if word after point is `while' of a do-while
10648 statement, else returns nil. A braceless do-while statement
10649 spanning several lines requires that the start of the loop is
10650 indented to the same column as the current line."
10653 (when (looking-at "\\s-*\\<while\\>")
10654 (if (save-excursion
10655 (skip-chars-backward "[ \t\n]*}")
10656 (looking-at "[ \t\n]*}"))
10658 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10659 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10660 (or (looking-at "\\<do\\>")
10661 (let ((saved-indent (current-indentation)))
10662 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10663 (/= (current-indentation) saved-indent)))
10664 (and (looking-at "[ \t]*\\<do\\>")
10665 (not (js2-re-search-forward
10666 "\\<while\\>" (point-at-eol) t))
10667 (= (current-indentation) saved-indent))))))))
10669 (defun js2-multiline-decl-indentation ()
10670 "Return the declaration indentation column if the current line belongs
10671 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10672 (let (forward-sexp-function ; use Lisp version
10673 at-opening-bracket)
10675 (back-to-indentation)
10676 (when (not (looking-at js2-declaration-keyword-re))
10677 (when (looking-at js2-indent-operator-re)
10678 (goto-char (match-end 0))) ; continued expressions are ok
10679 (while (and (not at-opening-bracket)
10681 (let ((pos (point)))
10684 (or (eq (char-before) ?,)
10685 (and (not (eq (char-before) ?\;))
10686 (prog2 (skip-syntax-backward ".")
10687 (looking-at js2-indent-operator-re)
10688 (js2-backward-sws))
10689 (not (eq (char-before) ?\;)))
10690 (js2-same-line pos)))))
10693 (scan-error (setq at-opening-bracket t))))
10694 (when (looking-at js2-declaration-keyword-re)
10695 (goto-char (match-end 0))
10696 (1+ (current-column)))))))
10698 (defun js2-ctrl-statement-indentation ()
10699 "Return the proper indentation of current line if it is a control statement.
10700 Returns an indentation if this line starts the body of a control
10701 statement without braces, else returns nil."
10702 (let (forward-sexp-function)
10704 (back-to-indentation)
10705 (when (and (not (js2-same-line (point-min)))
10706 (not (looking-at "{"))
10707 (js2-re-search-backward "[[:graph:]]" nil t)
10708 (not (looking-at "[{([]"))
10711 (when (= (char-before) ?\))
10712 ;; scan-sexps sometimes throws an error
10713 (ignore-errors (backward-sexp))
10714 (skip-chars-backward " \t" (point-at-bol)))
10715 (let ((pt (point)))
10716 (back-to-indentation)
10717 (when (looking-at "}[ \t]*")
10718 (goto-char (match-end 0)))
10719 (and (looking-at js2-possibly-braceless-keywords-re)
10720 (= (match-end 0) pt)
10721 (not (js2-end-of-do-while-loop-p))))))
10722 (+ (current-indentation) js2-basic-offset)))))
10724 (defun js2-indent-in-array-comp (parse-status)
10725 "Return non-nil if we think we're in an array comprehension.
10726 In particular, return the buffer position of the first `for' kwd."
10727 (let ((bracket (nth 1 parse-status))
10731 (goto-char bracket)
10732 (when (looking-at "\\[")
10735 (if (looking-at "[[{]")
10736 (let (forward-sexp-function) ; use Lisp version
10737 (forward-sexp) ; skip destructuring form
10739 (if (and (/= (char-after) ?,) ; regular array
10740 (looking-at "for"))
10741 (match-beginning 0)))
10742 ;; to skip arbitrary expressions we need the parser,
10743 ;; so we'll just guess at it.
10744 (if (and (> end (point)) ; not empty literal
10745 (re-search-forward "[^,]]* \\(for\\) " end t)
10746 ;; not inside comment or string literal
10747 (let ((state (parse-partial-sexp bracket (point))))
10748 (not (or (nth 3 state) (nth 4 state)))))
10749 (match-beginning 1))))))))
10751 (defun js2-array-comp-indentation (parse-status for-kwd)
10752 (if (js2-same-line for-kwd)
10753 ;; first continuation line
10755 (goto-char (nth 1 parse-status))
10757 (skip-chars-forward " \t")
10760 (goto-char for-kwd)
10761 (current-column))))
10763 (defun js2-proper-indentation (parse-status)
10764 "Return the proper indentation for the current line."
10766 (back-to-indentation)
10767 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10768 (at-closing-bracket (looking-at "[]})]"))
10769 (same-indent-p (or at-closing-bracket
10770 (looking-at "\\<case\\>[^:]")
10771 (and (looking-at "\\<default:")
10774 (not (memq (char-before) '(?, ?{)))))))
10775 (continued-expr-p (js2-continued-expression-p))
10776 (declaration-indent (and js2-pretty-multiline-declarations
10777 (js2-multiline-decl-indentation)))
10778 (bracket (nth 1 parse-status))
10781 ;; indent array comprehension continuation lines specially
10783 (>= js2-language-version 170)
10784 (not (js2-same-line bracket))
10785 (setq beg (js2-indent-in-array-comp parse-status))
10786 (>= (point) (save-excursion
10788 (point-at-bol)))) ; at or after first loop?
10789 (js2-array-comp-indentation parse-status beg))
10793 ((and declaration-indent continued-expr-p)
10794 (+ declaration-indent js2-basic-offset))
10796 (declaration-indent)
10799 (goto-char bracket)
10801 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10802 (when (save-excursion (skip-chars-backward " \t)")
10805 (back-to-indentation)
10806 (and (eq js2-pretty-multiline-declarations 'all)
10807 (looking-at js2-declaration-keyword-re)
10808 (goto-char (1+ (match-end 0))))
10810 (cond (same-indent-p
10813 (+ (current-column) (* 2 js2-basic-offset)))
10815 (+ (current-column) js2-basic-offset))))
10816 (if (and js2-indent-switch-body
10817 (not at-closing-bracket)
10818 (looking-at "\\_<switch\\_>"))
10819 (+ indent js2-basic-offset)
10822 (unless same-indent-p
10824 (skip-chars-forward " \t"))
10825 (current-column))))
10827 (continued-expr-p js2-basic-offset)
10831 (defun js2-lineup-comment (parse-status)
10832 "Indent a multi-line block comment continuation line."
10833 (let* ((beg (nth 8 parse-status))
10834 (first-line (js2-same-line beg))
10835 (offset (save-excursion
10837 (if (looking-at "/\\*")
10838 (+ 1 (current-column))
10841 (indent-line-to offset))))
10843 (defun js2-backward-sws ()
10844 "Move backward through whitespace and comments."
10846 (while (forward-comment -1)))
10848 (defun js2-forward-sws ()
10849 "Move forward through whitespace and comments."
10851 (while (forward-comment 1)))
10853 (defun js2-current-indent (&optional pos)
10854 "Return column of indentation on current line.
10855 If POS is non-nil, go to that point and return indentation for that line."
10859 (back-to-indentation)
10862 (defun js2-arglist-close ()
10863 "Return non-nil if we're on a line beginning with a close-paren/brace."
10865 (goto-char (point-at-bol))
10867 (looking-at "[])}]")))
10869 (defun js2-indent-looks-like-label-p ()
10870 (goto-char (point-at-bol))
10872 (looking-at (concat js2-mode-identifier-re ":")))
10874 (defun js2-indent-in-objlit-p (parse-status)
10875 "Return non-nil if this looks like an object-literal entry."
10876 (let ((start (nth 1 parse-status)))
10880 (and (zerop (forward-line -1))
10881 (not (< (point) start)) ; crossed a {} boundary
10882 (js2-indent-looks-like-label-p)))
10884 (js2-indent-looks-like-label-p)))))
10886 ;; If prev line looks like foobar({ then we're passing an object
10887 ;; literal to a function call, and people pretty much always want to
10888 ;; de-dent back to the previous line, so move the 'basic-offset'
10889 ;; position to the front.
10890 (defun js2-indent-objlit-arg-p (parse-status)
10892 (back-to-indentation)
10894 (and (eq (1- (point)) (nth 1 parse-status))
10895 (eq (char-before) ?{)
10898 (skip-chars-backward " \t")
10899 (eq (char-before) ?\()))))
10901 (defun js2-indent-case-block-p ()
10903 (back-to-indentation)
10905 (goto-char (point-at-bol))
10906 (skip-chars-forward " \t")
10907 (looking-at "case\\s-.+:")))
10909 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10910 "Cycle among alternate computed indentation positions.
10911 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10912 of the buffer to the current point. NORMAL-COL is the indentation
10913 column computed by the heuristic guesser based on current paren,
10914 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10916 (let ((cur-indent (js2-current-indent))
10917 (old-buffer-undo-list buffer-undo-list)
10918 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10919 (current-line (save-excursion
10920 (forward-line 0) ; move to bol
10921 (1+ (count-lines (point-min) (point)))))
10922 positions pos main-pos anchor arglist-cont same-indent
10923 basic-offset computed-pos)
10924 ;; temporarily don't record undo info, if user requested this
10925 (when js2-mode-indent-inhibit-undo
10926 (setq buffer-undo-list t))
10929 ;; First likely point: indent from beginning of previous code line
10930 (push (setq basic-offset
10932 (back-to-indentation)
10934 (back-to-indentation)
10939 ;; (First + epsilon) likely point: indent 2x from beginning of
10940 ;; previous code line. Google does it this way.
10941 (push (setq basic-offset
10943 (back-to-indentation)
10945 (back-to-indentation)
10947 (* 2 js2-basic-offset)))
10950 ;; Second likely point: indent from assign-expr RHS. This
10951 ;; is just a crude guess based on finding " = " on the previous
10952 ;; line containing actual code.
10953 (setq pos (save-excursion
10955 (goto-char (point-at-bol))
10956 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10958 (goto-char (match-end 1))
10959 (skip-chars-forward " \t\r\n")
10960 (current-column))))
10962 (cl-incf pos js2-basic-offset)
10963 (push pos positions))
10965 ;; Third likely point: same indent as previous line of code.
10966 ;; Make it the first likely point if we're not on an
10967 ;; arglist-close line and previous line ends in a comma, or
10968 ;; both this line and prev line look like object-literal
10970 (setq pos (save-excursion
10971 (goto-char (point-at-bol))
10973 (back-to-indentation)
10976 ;; while we're here, look for trailing comma
10977 (if (save-excursion
10978 (goto-char (point-at-eol))
10980 (eq (char-before) ?,))
10981 (setq arglist-cont (1- (point)))))))
10983 (if (and (or arglist-cont
10984 (js2-indent-in-objlit-p parse-status))
10985 (not (js2-arglist-close)))
10986 (setq same-indent pos))
10987 (push pos positions))
10989 ;; Fourth likely point: first preceding code with less indentation.
10990 ;; than the immediately preceding code line.
10991 (setq pos (save-excursion
10992 (back-to-indentation)
10994 (back-to-indentation)
10995 (setq anchor (current-column))
10996 (while (and (zerop (forward-line -1))
10998 (back-to-indentation)
11001 (setq pos (current-column))))
11002 (push pos positions)
11004 ;; nesting-heuristic position, main by default
11005 (push (setq main-pos normal-col) positions)
11007 ;; delete duplicates and sort positions list
11008 (setq positions (sort (delete-dups positions) '<))
11010 ;; comma-list continuation lines: prev line indent takes precedence
11012 (setq main-pos same-indent))
11014 ;; common special cases where we want to indent in from previous line
11015 (if (or (js2-indent-case-block-p)
11016 (js2-indent-objlit-arg-p parse-status))
11017 (setq main-pos basic-offset))
11019 ;; if bouncing backwards, reverse positions list
11021 (setq positions (reverse positions)))
11023 ;; record whether we're already sitting on one of the alternatives
11024 (setq pos (member cur-indent positions))
11027 ;; case 0: we're one one of the alternatives and this is the
11028 ;; first time they've pressed TAB on this line (best-guess).
11029 ((and js2-mode-indent-ignore-first-tab
11031 ;; first time pressing TAB on this line?
11032 (not (eq js2-mode-last-indented-line current-line)))
11034 (setq computed-pos nil))
11035 ;; case 1: only one computed position => use it
11036 ((null (cdr positions))
11037 (setq computed-pos 0))
11038 ;; case 2: not on any of the computed spots => use main spot
11040 (setq computed-pos (js2-position main-pos positions)))
11041 ;; case 3: on last position: cycle to first position
11043 (setq computed-pos 0))
11044 ;; case 4: on intermediate position: cycle to next position
11046 (setq computed-pos (js2-position (cl-second pos) positions))))
11048 ;; see if any hooks want to indent; otherwise we do it
11049 (cl-loop with result = nil
11050 for hook in js2-indent-hook
11051 while (null result)
11053 (setq result (funcall hook positions computed-pos))
11055 (unless (or result (null computed-pos))
11056 (indent-line-to (nth computed-pos positions)))))
11059 (if js2-mode-indent-inhibit-undo
11060 (setq buffer-undo-list old-buffer-undo-list))
11061 ;; see commentary for `js2-mode-last-indented-line'
11062 (setq js2-mode-last-indented-line current-line))))
11064 (defun js2-indent-bounce-backwards ()
11065 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11066 cycles between the computed indentation positions in reverse order."
11068 (js2-indent-line t))
11070 (defun js2-1-line-comment-continuation-p ()
11071 "Return t if we're in a 1-line comment continuation.
11072 If so, we don't ever want to use bounce-indent."
11076 (looking-at "\\s-*//"))
11080 (when (looking-at "\\s-*$")
11083 (looking-at "\\s-*//")))))
11085 (defun js2-indent-line (&optional bounce-backwards)
11086 "Indent the current line as JavaScript source text."
11088 (let (parse-status offset indent-col
11089 ;; Don't whine about errors/warnings when we're indenting.
11090 ;; This has to be set before calling parse-partial-sexp below.
11091 (inhibit-point-motion-hooks t))
11092 (setq parse-status (save-excursion
11093 (syntax-ppss (point-at-bol)))
11094 offset (- (point) (save-excursion
11095 (back-to-indentation)
11097 (js2-with-underscore-as-word-syntax
11098 (if (nth 4 parse-status)
11099 (js2-lineup-comment parse-status)
11100 (setq indent-col (js2-proper-indentation parse-status))
11101 ;; See comments below about `js2-mode-last-indented-line'.
11103 ;; bounce-indenting is disabled during electric-key indent.
11104 ;; It doesn't work well on first line of buffer.
11105 ((and js2-bounce-indent-p
11106 (not (js2-same-line (point-min)))
11107 (not (js2-1-line-comment-continuation-p)))
11108 (js2-bounce-indent indent-col parse-status bounce-backwards))
11109 ;; just indent to the guesser's likely spot
11110 (t (indent-line-to indent-col))))
11111 (when (cl-plusp offset)
11112 (forward-char offset)))))
11114 (defun js2-indent-region (start end)
11115 "Indent the region, but don't use bounce indenting."
11116 (let ((js2-bounce-indent-p nil)
11117 (indent-region-function nil)
11118 (after-change-functions (remq 'js2-mode-edit
11119 after-change-functions)))
11120 (indent-region start end nil) ; nil for byte-compiler
11121 (js2-mode-edit start end (- end start))))
11123 (defvar js2-minor-mode-map
11124 (let ((map (make-sparse-keymap)))
11125 (define-key map (kbd "C-c C-`") #'js2-next-error)
11126 (define-key map [mouse-1] #'js2-mode-show-node)
11128 "Keymap used when `js2-minor-mode' is active.")
11131 (define-minor-mode js2-minor-mode
11132 "Minor mode for running js2 as a background linter.
11133 This allows you to use a different major mode for JavaScript editing,
11134 such as `js-mode', while retaining the asynchronous error/warning
11135 highlighting features of `js2-mode'."
11137 :lighter " js-lint"
11139 (js2-minor-mode-enter)
11140 (js2-minor-mode-exit)))
11142 (defun js2-minor-mode-enter ()
11143 "Initialization for `js2-minor-mode'."
11144 (set (make-local-variable 'max-lisp-eval-depth)
11145 (max max-lisp-eval-depth 3000))
11146 (setq next-error-function #'js2-next-error)
11147 (js2-set-default-externs)
11148 ;; Experiment: make reparse-delay longer for longer files.
11149 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11150 (setq js2-idle-timer-delay
11151 (* js2-idle-timer-delay
11152 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11153 (setq js2-mode-buffer-dirty-p t
11154 js2-mode-parsing nil)
11155 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11156 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11157 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11158 (when js2-include-jslint-globals
11159 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11160 (run-hooks 'js2-init-hook)
11163 (defun js2-minor-mode-exit ()
11164 "Turn off `js2-minor-mode'."
11165 (setq next-error-function nil)
11166 (remove-hook 'after-change-functions #'js2-mode-edit t)
11167 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11168 (when js2-mode-node-overlay
11169 (delete-overlay js2-mode-node-overlay)
11170 (setq js2-mode-node-overlay nil))
11171 (js2-remove-overlays)
11172 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11173 (setq js2-mode-ast nil))
11175 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11176 (make-variable-buffer-local 'js2-source-buffer)
11178 (cl-defun js2-display-error-list ()
11179 "Display a navigable buffer listing parse errors/warnings."
11181 (unless (js2-have-errors-p)
11182 (message "No errors")
11183 (cl-return-from js2-display-error-list))
11184 (cl-labels ((annotate-list
11186 "Add diagnostic TYPE and line number to errs list"
11187 (mapcar (lambda (err)
11188 (list err type (line-number-at-pos (nth 1 err))))
11190 (let* ((srcbuf (current-buffer))
11191 (errbuf (get-buffer-create "*js-lint*"))
11192 (errors (annotate-list
11193 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11194 'js2-error)) ; must be a valid face name
11195 (warnings (annotate-list
11196 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11197 'js2-warning)) ; must be a valid face name
11198 (all-errs (sort (append errors warnings)
11199 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11200 (with-current-buffer errbuf
11201 (let ((inhibit-read-only t))
11203 (dolist (err all-errs)
11204 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11205 (insert-text-button
11206 (format "line %d: %s" line (js2-get-msg msg-key))
11208 'follow-link "\C-m"
11209 'action 'js2-error-buffer-jump
11210 'js2-msg (js2-get-msg msg-key)
11213 (js2-error-buffer-mode)
11214 (setq js2-source-buffer srcbuf)
11215 (pop-to-buffer errbuf)
11216 (goto-char (point-min))
11218 (js2-error-buffer-view))))))
11220 (defvar js2-error-buffer-mode-map
11221 (let ((map (make-sparse-keymap)))
11222 (define-key map "n" #'js2-error-buffer-next)
11223 (define-key map "p" #'js2-error-buffer-prev)
11224 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11225 (define-key map "o" #'js2-error-buffer-view)
11226 (define-key map "q" #'js2-error-buffer-quit)
11228 "Keymap used for js2 diagnostics buffers.")
11230 (defun js2-error-buffer-mode ()
11231 "Major mode for js2 diagnostics buffers.
11232 Selecting an error will jump it to the corresponding source-buffer error.
11233 \\{js2-error-buffer-mode-map}"
11235 (setq major-mode 'js2-error-buffer-mode
11236 mode-name "JS Lint Diagnostics")
11237 (use-local-map js2-error-buffer-mode-map)
11238 (setq truncate-lines t)
11239 (set-buffer-modified-p nil)
11240 (setq buffer-read-only t)
11241 (run-hooks 'js2-error-buffer-mode-hook))
11243 (defun js2-error-buffer-next ()
11244 "Move to next error and view it."
11246 (when (zerop (forward-line 1))
11247 (js2-error-buffer-view)))
11249 (defun js2-error-buffer-prev ()
11250 "Move to previous error and view it."
11252 (when (zerop (forward-line -1))
11253 (js2-error-buffer-view)))
11255 (defun js2-error-buffer-quit ()
11256 "Kill the current buffer."
11260 (defun js2-error-buffer-jump (&rest ignored)
11261 "Jump cursor to current error in source buffer."
11263 (when (js2-error-buffer-view)
11264 (pop-to-buffer js2-source-buffer)))
11266 (defun js2-error-buffer-view ()
11267 "Scroll source buffer to show error at current line."
11270 ((not (eq major-mode 'js2-error-buffer-mode))
11271 (message "Not in a js2 errors buffer"))
11272 ((not (buffer-live-p js2-source-buffer))
11273 (message "Source buffer has been killed"))
11274 ((not (wholenump (get-text-property (point) 'js2-pos)))
11275 (message "There does not seem to be an error here"))
11277 (let ((pos (get-text-property (point) 'js2-pos))
11278 (msg (get-text-property (point) 'js2-msg)))
11279 (save-selected-window
11280 (pop-to-buffer js2-source-buffer)
11285 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11286 ;; FIXME: Should derive from js-mode.
11287 "Major mode for editing JavaScript code."
11288 ;; Used by comment-region; don't change it.
11289 (set (make-local-variable 'comment-start) "//")
11290 (set (make-local-variable 'comment-end) "")
11291 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11292 (set (make-local-variable 'max-lisp-eval-depth)
11293 (max max-lisp-eval-depth 3000))
11294 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11295 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11296 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11297 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11298 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11299 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11300 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11301 ;; for characters inside regexp literals.
11302 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11303 ;; this is necessary to make `show-paren-function' work properly
11304 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11305 ;; needed for M-x rgrep, among other things
11306 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11308 (set (make-local-variable 'electric-indent-chars)
11309 (append "{}()[]:;,*." electric-indent-chars))
11310 (set (make-local-variable 'electric-layout-rules)
11311 '((?\; . after) (?\{ . after) (?\} . before)))
11313 ;; some variables needed by cc-engine for paragraph-fill, etc.
11314 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11315 c-comment-start-regexp "/[*/]\\|\\s|"
11316 c-line-comment-starter "//"
11317 c-paragraph-start js2-paragraph-start
11318 c-paragraph-separate "$"
11319 c-syntactic-ws-start js2-syntactic-ws-start
11320 c-syntactic-ws-end js2-syntactic-ws-end
11321 c-syntactic-eol js2-syntactic-eol)
11323 (let ((c-buffer-is-cc-mode t))
11324 ;; Copied from `js-mode'. Also see Bug#6071.
11325 (make-local-variable 'paragraph-start)
11326 (make-local-variable 'paragraph-separate)
11327 (make-local-variable 'paragraph-ignore-fill-prefix)
11328 (make-local-variable 'adaptive-fill-mode)
11329 (make-local-variable 'adaptive-fill-regexp)
11330 (c-setup-paragraph-variables))
11332 (setq font-lock-defaults '(nil t))
11334 ;; Experiment: make reparse-delay longer for longer files.
11335 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11336 (setq js2-idle-timer-delay
11337 (* js2-idle-timer-delay
11338 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11340 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11341 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11342 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11343 (setq next-error-function #'js2-next-error)
11344 (imenu-add-to-menubar (concat "IM-" mode-name))
11345 (add-to-invisibility-spec '(js2-outline . t))
11346 (set (make-local-variable 'line-move-ignore-invisible) t)
11347 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11349 (setq js2-mode-functions-hidden nil
11350 js2-mode-comments-hidden nil
11351 js2-mode-buffer-dirty-p t
11352 js2-mode-parsing nil)
11354 (js2-set-default-externs)
11356 (when js2-include-jslint-globals
11357 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11359 (run-hooks 'js2-init-hook)
11363 (defun js2-mode-exit ()
11364 "Exit `js2-mode' and clean up."
11366 (when js2-mode-node-overlay
11367 (delete-overlay js2-mode-node-overlay)
11368 (setq js2-mode-node-overlay nil))
11369 (js2-remove-overlays)
11370 (setq js2-mode-ast nil)
11371 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11372 (remove-from-invisibility-spec '(js2-outline . t))
11373 (js2-mode-show-all)
11374 (with-silent-modifications
11375 (js2-clear-face (point-min) (point-max))))
11377 (defun js2-mode-reset-timer ()
11378 "Cancel any existing parse timer and schedule a new one."
11379 (if js2-mode-parse-timer
11380 (cancel-timer js2-mode-parse-timer))
11381 (setq js2-mode-parsing nil)
11382 (let ((timer (timer-create)))
11383 (setq js2-mode-parse-timer timer)
11384 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11385 (timer-set-idle-time timer js2-idle-timer-delay)
11386 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11387 (timer-activate-when-idle timer nil)))
11389 (defun js2-mode-idle-reparse (buffer)
11390 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11391 it to be reparsed when the buffer is selected."
11392 (cond ((eq buffer (current-buffer))
11394 ((buffer-live-p buffer)
11395 ;; reparse when the buffer is selected again
11396 (with-current-buffer buffer
11397 (add-hook 'window-configuration-change-hook
11398 #'js2-mode-idle-reparse-inner
11401 (defun js2-mode-idle-reparse-inner ()
11402 (remove-hook 'window-configuration-change-hook
11403 #'js2-mode-idle-reparse-inner
11407 (defun js2-mode-edit (_beg _end _len)
11408 "Schedule a new parse after buffer is edited.
11409 Buffer edit spans from BEG to END and is of length LEN."
11410 (setq js2-mode-buffer-dirty-p t)
11411 (js2-mode-hide-overlay)
11412 (js2-mode-reset-timer))
11414 (defun js2-minor-mode-edit (_beg _end _len)
11415 "Callback for buffer edits in `js2-mode'.
11416 Schedules a new parse after buffer is edited.
11417 Buffer edit spans from BEG to END and is of length LEN."
11418 (setq js2-mode-buffer-dirty-p t)
11419 (js2-mode-hide-overlay)
11420 (js2-mode-reset-timer))
11422 (defun js2-reparse (&optional force)
11423 "Re-parse current buffer after user finishes some data entry.
11424 If we get any user input while parsing, including cursor motion,
11425 we discard the parse and reschedule it. If FORCE is nil, then the
11426 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11429 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11430 (unless js2-mode-parsing
11431 (setq js2-mode-parsing t)
11433 (when (or js2-mode-buffer-dirty-p force)
11434 (js2-remove-overlays)
11435 (setq js2-mode-buffer-dirty-p nil
11436 js2-mode-fontifications nil
11437 js2-mode-deferred-properties nil)
11438 (if js2-mode-verbose-parse-p
11439 (message "parsing..."))
11442 (setq interrupted-p
11443 (catch 'interrupted
11445 (with-silent-modifications
11446 ;; if parsing is interrupted, comments and regex
11447 ;; literals stay ignored by `parse-partial-sexp'
11448 (remove-text-properties (point-min) (point-max)
11450 (js2-mode-apply-deferred-properties)
11451 (js2-mode-remove-suppressed-warnings)
11452 (js2-mode-show-warnings)
11453 (js2-mode-show-errors)
11454 (if (>= js2-highlight-level 1)
11455 (js2-highlight-jsdoc js2-mode-ast)))
11459 ;; unfinished parse => try again
11460 (setq js2-mode-buffer-dirty-p t)
11461 (js2-mode-reset-timer))
11462 (if js2-mode-verbose-parse-p
11463 (message "Parse time: %s" time))))
11464 (setq js2-mode-parsing nil)
11465 (unless interrupted-p
11466 (setq js2-mode-parse-timer nil))))))
11468 (defun js2-mode-show-node (event)
11469 "Debugging aid: highlight selected AST node on mouse click."
11471 (mouse-set-point event)
11472 (setq deactivate-mark t)
11473 (when js2-mode-show-overlay
11474 (let ((node (js2-node-at-point))
11477 (message "No node found at location %s" (point))
11478 (setq beg (js2-node-abs-pos node)
11479 end (+ beg (js2-node-len node)))
11480 (if js2-mode-node-overlay
11481 (move-overlay js2-mode-node-overlay beg end)
11482 (setq js2-mode-node-overlay (make-overlay beg end))
11483 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11484 (with-silent-modifications
11485 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
11486 (message "%s, parent: %s"
11487 (js2-node-short-name node)
11488 (if (js2-node-parent node)
11489 (js2-node-short-name (js2-node-parent node))
11492 (defun js2-mode-hide-overlay (&optional _p1 p2)
11493 "Remove the debugging overlay when the point moves.
11494 P1 and P2 are the old and new values of point, respectively."
11495 (when js2-mode-node-overlay
11496 (let ((beg (overlay-start js2-mode-node-overlay))
11497 (end (overlay-end js2-mode-node-overlay)))
11498 ;; Sometimes we're called spuriously.
11502 (with-silent-modifications
11503 (remove-text-properties beg end '(point-left nil)))
11504 (delete-overlay js2-mode-node-overlay)
11505 (setq js2-mode-node-overlay nil)))))
11507 (defun js2-mode-reset ()
11508 "Debugging helper: reset everything."
11513 (defun js2-mode-show-warn-or-err (e face)
11514 "Highlight a warning or error E with FACE.
11515 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11516 The last element is optional. When present, use instead of FACE."
11517 (let* ((key (cl-first e))
11518 (beg (cl-second e))
11519 (end (+ beg (cl-third e)))
11520 ;; Don't inadvertently go out of bounds.
11521 (beg (max (point-min) (min beg (point-max))))
11522 (end (max (point-min) (min end (point-max))))
11523 (ovl (make-overlay beg end)))
11524 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11525 (overlay-put ovl 'js2-error t)
11526 (put-text-property beg end 'help-echo (js2-get-msg key))
11527 (put-text-property beg end 'point-entered #'js2-echo-error)))
11529 (defun js2-remove-overlays ()
11530 "Remove overlays from buffer that have a `js2-error' property."
11531 (let ((beg (point-min))
11534 (dolist (o (overlays-in beg end))
11535 (when (overlay-get o 'js2-error)
11536 (delete-overlay o))))))
11538 (defun js2-error-at-point (&optional pos)
11539 "Return non-nil if there's an error overlay at POS.
11540 Defaults to point."
11541 (cl-loop with pos = (or pos (point))
11542 for o in (overlays-at pos)
11543 thereis (overlay-get o 'js2-error)))
11545 (defun js2-mode-apply-deferred-properties ()
11546 "Apply fontifications and other text properties recorded during parsing."
11547 (when (cl-plusp js2-highlight-level)
11548 ;; We defer clearing faces as long as possible to eliminate flashing.
11549 (js2-clear-face (point-min) (point-max))
11550 ;; Have to reverse the recorded fontifications list so that errors
11551 ;; and warnings overwrite the normal fontifications.
11552 (dolist (f (nreverse js2-mode-fontifications))
11553 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11554 (setq js2-mode-fontifications nil))
11555 (dolist (p js2-mode-deferred-properties)
11556 (apply #'put-text-property p))
11557 (setq js2-mode-deferred-properties nil))
11559 (defun js2-mode-show-errors ()
11560 "Highlight syntax errors."
11561 (when js2-mode-show-parse-errors
11562 (dolist (e (js2-ast-root-errors js2-mode-ast))
11563 (js2-mode-show-warn-or-err e 'js2-error))))
11565 (defun js2-mode-remove-suppressed-warnings ()
11566 "Take suppressed warnings out of the AST warnings list.
11567 This ensures that the counts and `next-error' are correct."
11568 (setf (js2-ast-root-warnings js2-mode-ast)
11571 (let ((key (caar e)))
11573 (and (not js2-strict-trailing-comma-warning)
11574 (string-match "trailing\\.comma" key))
11575 (and (not js2-strict-cond-assign-warning)
11576 (string= key "msg.equal.as.assign"))
11577 (and js2-missing-semi-one-line-override
11578 (string= key "msg.missing.semi")
11579 (let* ((beg (cl-second e))
11580 (node (js2-node-at-point beg))
11581 (fn (js2-mode-find-parent-fn node))
11582 (body (and fn (js2-function-node-body fn)))
11583 (lc (and body (js2-node-abs-pos body)))
11584 (rc (and lc (+ lc (js2-node-len body)))))
11589 (and (js2-same-line lc)
11590 (js2-same-line rc))))))))))
11591 (js2-ast-root-warnings js2-mode-ast))))
11593 (defun js2-mode-show-warnings ()
11594 "Highlight strict-mode warnings."
11595 (when js2-mode-show-strict-warnings
11596 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11597 (js2-mode-show-warn-or-err e 'js2-warning))))
11599 (defun js2-echo-error (_old-point new-point)
11600 "Called by point-motion hooks."
11601 (let ((msg (get-text-property new-point 'help-echo)))
11602 (when (and (stringp msg)
11603 (not (active-minibuffer-window))
11604 (not (current-message)))
11607 (defalias 'js2-echo-help #'js2-echo-error)
11609 (defun js2-line-break (&optional _soft)
11610 "Break line at point and indent, continuing comment if within one.
11611 If inside a string, and `js2-concat-multiline-strings' is not
11612 nil, turn it into concatenation."
11614 (let ((parse-status (syntax-ppss)))
11616 ;; Check if we're inside a string.
11617 ((nth 3 parse-status)
11618 (if js2-concat-multiline-strings
11619 (js2-mode-split-string parse-status)
11621 ;; Check if inside a block comment.
11622 ((nth 4 parse-status)
11623 (js2-mode-extend-comment (nth 8 parse-status)))
11625 (newline-and-indent)))))
11627 (defun js2-mode-split-string (parse-status)
11628 "Turn a newline in mid-string into a string concatenation.
11629 PARSE-STATUS is as documented in `parse-partial-sexp'."
11630 (let* ((quote-char (nth 3 parse-status))
11631 (at-eol (eq js2-concat-multiline-strings 'eol)))
11632 (insert quote-char)
11633 (insert (if at-eol " +\n" "\n"))
11637 (insert quote-char)
11639 (insert quote-char)
11640 (backward-char 1))))
11642 (defun js2-mode-extend-comment (start-pos)
11643 "Indent the line and, when inside a comment block, add comment prefix."
11644 (let (star single col first-line needs-close)
11646 (back-to-indentation)
11647 (when (< (point) start-pos)
11648 (goto-char start-pos))
11650 ((looking-at "\\*[^/]")
11652 col (current-column)))
11653 ((looking-at "/\\*")
11656 col (1+ (current-column))))
11659 col (current-column)))))
11660 ;; Heuristic for whether we need to close the comment:
11661 ;; if we've got a parse error here, assume it's an unterminated
11665 (eq (get-text-property (1- (point)) 'point-entered)
11667 ;; The heuristic above doesn't work well when we're
11668 ;; creating a comment and there's another one downstream,
11669 ;; as our parser thinks this one ends at the end of the
11670 ;; next one. (You can have a /* inside a js block comment.)
11671 ;; So just close it if the next non-ws char isn't a *.
11675 (skip-chars-forward " \t\r\n")
11676 (not (eq (char-after) ?*))))))
11677 (delete-horizontal-space)
11683 (if (and first-line needs-close)
11690 (and (zerop (forward-line 1))
11691 (looking-at "\\s-*//"))))
11694 ;; Don't need to extend the comment after all.
11695 (js2-indent-line)))
11697 (defun js2-beginning-of-line ()
11698 "Toggle point between bol and first non-whitespace char in line.
11699 Also moves past comment delimiters when inside comments."
11704 (back-to-indentation))
11706 (skip-chars-forward "/ \t"))
11707 ((and (eq (char-after) ?*)
11708 (setq node (js2-comment-at-point))
11709 (memq (js2-comment-node-format node) '(jsdoc block))
11711 (skip-chars-backward " \t")
11713 (skip-chars-forward "\* \t"))
11715 (goto-char (point-at-bol))))))
11717 (defun js2-end-of-line ()
11718 "Toggle point between eol and last non-whitespace char in line."
11721 (skip-chars-backward " \t")
11722 (goto-char (point-at-eol))))
11724 (defun js2-mode-wait-for-parse (callback)
11725 "Invoke CALLBACK when parsing is finished.
11726 If parsing is already finished, calls CALLBACK immediately."
11727 (if (not js2-mode-buffer-dirty-p)
11729 (push callback js2-mode-pending-parse-callbacks)
11730 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11732 (defun js2-mode-parse-finished ()
11733 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11734 ;; We can't let errors propagate up, since it prevents the
11735 ;; `js2-parse' method from completing normally and returning
11736 ;; the ast, which makes things mysteriously not work right.
11738 (dolist (cb js2-mode-pending-parse-callbacks)
11739 (condition-case err
11741 (error (message "%s" err))))
11742 (setq js2-mode-pending-parse-callbacks nil)))
11744 (defun js2-mode-flag-region (from to flag)
11745 "Hide or show text from FROM to TO, according to FLAG.
11746 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11747 Returns the created overlay if FLAG is non-nil."
11748 (remove-overlays from to 'invisible 'js2-outline)
11750 (let ((o (make-overlay from to)))
11751 (overlay-put o 'invisible 'js2-outline)
11752 (overlay-put o 'isearch-open-invisible
11753 'js2-isearch-open-invisible)
11756 ;; Function to be set as an outline-isearch-open-invisible' property
11757 ;; to the overlay that makes the outline invisible (see
11758 ;; `js2-mode-flag-region').
11759 (defun js2-isearch-open-invisible (_overlay)
11760 ;; We rely on the fact that isearch places point on the matched text.
11761 (js2-mode-show-element))
11763 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11764 "Return cons cell of bounds of folding overlay at POS.
11765 Returns nil if not found."
11766 (let ((overlays (overlays-at (or pos (point))))
11768 (while (and overlays
11770 (if (overlay-get (car overlays) 'invisible)
11771 (setq o (car overlays))
11772 (setq overlays (cdr overlays))))
11774 (cons (overlay-start o) (overlay-end o)))))
11776 (defun js2-mode-function-at-point (&optional pos)
11777 "Return the innermost function node enclosing current point.
11778 Returns nil if point is not in a function."
11779 (let ((node (js2-node-at-point pos)))
11780 (while (and node (not (js2-function-node-p node)))
11781 (setq node (js2-node-parent node)))
11782 (if (js2-function-node-p node)
11785 (defun js2-mode-toggle-element ()
11786 "Hide or show the foldable element at the point."
11788 (let (comment fn pos)
11791 ;; /* ... */ comment?
11792 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11793 (if (js2-mode-invisible-overlay-bounds
11794 (setq pos (+ 3 (js2-node-abs-pos comment))))
11797 (js2-mode-show-element))
11798 (js2-mode-hide-element)))
11801 (back-to-indentation)
11802 (looking-at js2-mode-//-comment-re))
11803 (js2-mode-toggle-//-comment))
11805 ((setq fn (js2-mode-function-at-point))
11806 (setq pos (and (js2-function-node-body fn)
11807 (js2-node-abs-pos (js2-function-node-body fn))))
11808 (goto-char (1+ pos))
11809 (if (js2-mode-invisible-overlay-bounds)
11810 (js2-mode-show-element)
11811 (js2-mode-hide-element)))
11813 (message "Nothing at point to hide or show"))))))
11815 (defun js2-mode-hide-element ()
11816 "Fold/hide contents of a block, showing ellipses.
11817 Show the hidden text with \\[js2-mode-show-element]."
11819 (if js2-mode-buffer-dirty-p
11820 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11821 (let (node body beg end)
11823 ((js2-mode-invisible-overlay-bounds)
11824 (message "already hidden"))
11826 (setq node (js2-node-at-point))
11828 ((js2-block-comment-p node)
11829 (js2-mode-hide-comment node))
11831 (while (and node (not (js2-function-node-p node)))
11832 (setq node (js2-node-parent node)))
11834 (setq body (js2-function-node-body node)))
11836 (setq beg (js2-node-abs-pos body)
11837 end (+ beg (js2-node-len body)))
11838 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11839 (message "No collapsable element found at point"))))))))
11841 (defun js2-mode-show-element ()
11842 "Show the hidden element at current point."
11844 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11846 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11847 (message "Nothing to un-hide"))))
11849 (defun js2-mode-show-all ()
11850 "Show all of the text in the buffer."
11852 (js2-mode-flag-region (point-min) (point-max) nil))
11854 (defun js2-mode-toggle-hide-functions ()
11856 (if js2-mode-functions-hidden
11857 (js2-mode-show-functions)
11858 (js2-mode-hide-functions)))
11860 (defun js2-mode-hide-functions ()
11861 "Hides all non-nested function bodies in the buffer.
11862 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11863 to open an individual entry."
11865 (if js2-mode-buffer-dirty-p
11866 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11867 (if (null js2-mode-ast)
11868 (message "Oops - parsing failed")
11869 (setq js2-mode-functions-hidden t)
11870 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11872 (defun js2-mode-function-hider (n endp)
11874 (let ((tt (js2-node-type n))
11877 ((and (= tt js2-FUNCTION)
11878 (setq body (js2-function-node-body n)))
11879 (setq beg (js2-node-abs-pos body)
11880 end (+ beg (js2-node-len body)))
11881 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11882 nil) ; don't process children of function
11884 t))))) ; keep processing other AST nodes
11886 (defun js2-mode-show-functions ()
11887 "Un-hide any folded function bodies in the buffer."
11889 (setq js2-mode-functions-hidden nil)
11891 (goto-char (point-min))
11892 (while (/= (goto-char (next-overlay-change (point)))
11894 (dolist (o (overlays-at (point)))
11895 (when (and (overlay-get o 'invisible)
11896 (not (overlay-get o 'comment)))
11897 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11899 (defun js2-mode-hide-comment (n)
11900 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11903 (beg (+ (js2-node-abs-pos n) head))
11904 (end (- (+ beg (js2-node-len n)) head 2))
11905 (o (js2-mode-flag-region beg end 'hide)))
11906 (overlay-put o 'comment t)))
11908 (defun js2-mode-toggle-hide-comments ()
11909 "Folds all block comments in the buffer.
11910 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11911 to open an individual entry."
11913 (if js2-mode-comments-hidden
11914 (js2-mode-show-comments)
11915 (js2-mode-hide-comments)))
11917 (defun js2-mode-hide-comments ()
11919 (if js2-mode-buffer-dirty-p
11920 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11921 (if (null js2-mode-ast)
11922 (message "Oops - parsing failed")
11923 (setq js2-mode-comments-hidden t)
11924 (dolist (n (js2-ast-root-comments js2-mode-ast))
11925 (when (js2-block-comment-p n)
11926 (js2-mode-hide-comment n)))
11927 (js2-mode-hide-//-comments)))
11929 (defun js2-mode-extend-//-comment (direction)
11930 "Find start or end of a block of similar //-comment lines.
11931 DIRECTION is -1 to look back, 1 to look forward.
11932 INDENT is the indentation level to match.
11933 Returns the end-of-line position of the furthest adjacent
11934 //-comment line with the same indentation as the current line.
11935 If there is no such matching line, returns current end of line."
11936 (let ((pos (point-at-eol))
11937 (indent (current-indentation)))
11939 (while (and (zerop (forward-line direction))
11940 (looking-at js2-mode-//-comment-re)
11941 (eq indent (length (match-string 1))))
11942 (setq pos (point-at-eol)))
11945 (defun js2-mode-hide-//-comments ()
11946 "Fold adjacent 1-line comments, showing only snippet of first one."
11949 (goto-char (point-min))
11950 (while (re-search-forward js2-mode-//-comment-re nil t)
11952 end (js2-mode-extend-//-comment 1))
11953 (unless (eq beg end)
11954 (overlay-put (js2-mode-flag-region beg end 'hide)
11957 (forward-char 1)))))
11959 (defun js2-mode-toggle-//-comment ()
11960 "Fold or un-fold any multi-line //-comment at point.
11961 Caller should have determined that this line starts with a //-comment."
11962 (let* ((beg (point-at-eol))
11966 (if (js2-mode-invisible-overlay-bounds)
11967 (js2-mode-show-element)
11968 ;; else hide the comment
11969 (setq beg (js2-mode-extend-//-comment -1)
11970 end (js2-mode-extend-//-comment 1))
11971 (unless (eq beg end)
11972 (overlay-put (js2-mode-flag-region beg end 'hide)
11975 (defun js2-mode-show-comments ()
11976 "Un-hide any hidden comments, leaving other hidden elements alone."
11978 (setq js2-mode-comments-hidden nil)
11980 (goto-char (point-min))
11981 (while (/= (goto-char (next-overlay-change (point)))
11983 (dolist (o (overlays-at (point)))
11984 (when (overlay-get o 'comment)
11985 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11987 (defun js2-mode-display-warnings-and-errors ()
11988 "Turn on display of warnings and errors."
11990 (setq js2-mode-show-parse-errors t
11991 js2-mode-show-strict-warnings t)
11992 (js2-reparse 'force))
11994 (defun js2-mode-hide-warnings-and-errors ()
11995 "Turn off display of warnings and errors."
11997 (setq js2-mode-show-parse-errors nil
11998 js2-mode-show-strict-warnings nil)
11999 (js2-reparse 'force))
12001 (defun js2-mode-toggle-warnings-and-errors ()
12002 "Toggle the display of warnings and errors.
12003 Some users don't like having warnings/errors reported while they type."
12005 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12006 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12007 (if (called-interactively-p 'any)
12008 (message "warnings and errors %s"
12009 (if js2-mode-show-parse-errors
12012 (js2-reparse 'force))
12014 (defun js2-mode-customize ()
12016 (customize-group 'js2-mode))
12018 (defun js2-mode-forward-sexp (&optional arg)
12019 "Move forward across one statement or balanced expression.
12020 With ARG, do it that many times. Negative arg -N means
12021 move backward across N balanced expressions."
12023 (setq arg (or arg 1))
12025 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12027 (let (forward-sexp-function
12028 node (start (point)) pos lp rp child)
12031 ;; could probably make this better for some cases:
12032 ;; - if in statement block (e.g. function body), go to parent
12033 ;; - infix exprs like (foo in bar) - maybe go to beginning
12034 ;; of infix expr if in the right-side expression?
12035 ((and arg (cl-minusp arg))
12036 (dotimes (_ (- arg))
12038 (forward-char -1) ; Enter the node we backed up to.
12039 (when (setq node (js2-node-at-point (point) t))
12040 (setq pos (js2-node-abs-pos node))
12041 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12042 (setq lp (car parens)
12044 (when (and lp (> start lp))
12045 (if (and rp (<= start rp))
12046 ;; Between parens, check if there's a child node we can jump.
12047 (when (setq child (js2-node-closest-child node (point) lp t))
12048 (setq pos (js2-node-abs-pos child)))
12049 ;; Before both parens.
12051 (let ((state (parse-partial-sexp start pos)))
12052 (goto-char (if (not (zerop (car state)))
12053 ;; Stumble at the unbalanced paren if < 0, or
12054 ;; jump a bit further if > 0.
12055 (scan-sexps start -1)
12057 (unless pos (goto-char (point-min)))))
12062 (when (setq node (js2-node-at-point (point) t))
12063 (setq pos (js2-node-abs-pos node))
12064 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12065 (setq lp (car parens)
12068 (when (and rp (<= start rp))
12070 (when (setq child (js2-node-closest-child node (point) rp))
12071 (setq pos (js2-node-abs-end child)))
12072 (setq pos (1+ rp))))
12073 ;; No parens or child nodes, looks for the end of the curren node.
12074 (cl-incf pos (js2-node-len
12075 (if (js2-expr-stmt-node-p (js2-node-parent node))
12076 ;; Stop after the semicolon.
12077 (js2-node-parent node)
12079 (let ((state (save-excursion (parse-partial-sexp start pos))))
12080 (goto-char (if (not (zerop (car state)))
12081 (scan-sexps start 1)
12083 (unless pos (goto-char (point-max)))))))))
12085 (defun js2-mode-forward-sexp-parens (node abs-pos)
12086 "Return a cons cell with positions of main parens in NODE."
12088 ((or (js2-array-node-p node)
12089 (js2-object-node-p node)
12090 (js2-comp-node-p node)
12091 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12092 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12093 ((js2-paren-expr-node-p node)
12094 (let ((lp (js2-node-lp node))
12095 (rp (js2-node-rp node)))
12096 (cons (when lp (+ abs-pos lp))
12097 (when rp (+ abs-pos rp)))))))
12099 (defun js2-node-closest-child (parent point limit &optional before)
12100 (let* ((parent-pos (js2-node-abs-pos parent))
12101 (rpoint (- point parent-pos))
12102 (rlimit (- limit parent-pos))
12103 (min (min rpoint rlimit))
12104 (max (max rpoint rlimit))
12109 (lambda (node _end-p)
12110 (if (eq node parent)
12112 (let ((pos (js2-node-pos node)) ;; Both relative values.
12113 (end (+ (js2-node-pos node) (js2-node-len node))))
12114 (when (and (>= pos min) (<= end max)
12115 (if before (< pos rpoint) (> end rpoint)))
12117 (when (> end rpoint)
12118 (throw 'done nil)))
12122 (defun js2-errors ()
12123 "Return a list of errors found."
12125 (js2-ast-root-errors js2-mode-ast)))
12127 (defun js2-warnings ()
12128 "Return a list of warnings found."
12130 (js2-ast-root-warnings js2-mode-ast)))
12132 (defun js2-have-errors-p ()
12133 "Return non-nil if any parse errors or warnings were found."
12134 (or (js2-errors) (js2-warnings)))
12136 (defun js2-errors-and-warnings ()
12137 "Return a copy of the concatenated errors and warnings lists.
12138 They are appended: first the errors, then the warnings.
12139 Entries are of the form (MSG BEG END)."
12141 (append (js2-ast-root-errors js2-mode-ast)
12142 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12144 (defun js2-next-error (&optional arg reset)
12145 "Move to next parse error.
12146 Typically invoked via \\[next-error].
12147 ARG is the number of errors, forward or backward, to move.
12148 RESET means start over from the beginning."
12150 (if (not (or (js2-errors) (js2-warnings)))
12151 (message "No errors")
12153 (goto-char (point-min)))
12154 (let* ((errs (js2-errors-and-warnings))
12158 (backward (cl-minusp count))
12159 (sorter (if backward '> '<))
12160 (stopper (if backward '< '>))
12161 (count (abs count))
12163 ;; Sort by start position.
12164 (setq errs (sort errs (lambda (e1 e2)
12165 (funcall sorter (cl-second e1) (cl-second e2))))
12167 ;; Find nth error with pos > start.
12168 (while (and errs continue)
12169 (when (funcall stopper (cl-cadar errs) start)
12170 (setq err (car errs))
12171 (if (zerop (cl-decf count))
12172 (setq continue nil)))
12173 (setq errs (cdr errs)))
12174 ;; Clear for `js2-echo-error'.
12177 (goto-char (cl-second err))
12178 ;; Wrap around to first error.
12179 (goto-char (cl-second (car all-errs)))
12180 ;; If we were already on it, echo msg again.
12181 (if (= (point) start)
12182 (js2-echo-error (point) (point)))))))
12184 (defun js2-down-mouse-3 ()
12185 "Make right-click move the point to the click location.
12186 This makes right-click context menu operations a bit more intuitive.
12187 The point will not move if the region is active, however, to avoid
12188 destroying the region selection."
12190 (when (and js2-move-point-on-right-click
12192 (let ((e last-input-event))
12194 (goto-char (cl-cadadr e))))))
12196 (defun js2-mode-create-imenu-index ()
12197 "Return an alist for `imenu--index-alist'."
12198 ;; This is built up in `js2-parse-record-imenu' during parsing.
12200 ;; if we have an ast but no recorder, they're requesting a rescan
12201 (unless js2-imenu-recorder
12202 (js2-reparse 'force))
12204 (js2-build-imenu-index)
12205 (setq js2-imenu-recorder nil
12206 js2-imenu-function-map nil))))
12208 (defun js2-mode-find-tag ()
12209 "Replacement for `find-tag-default'.
12210 `find-tag-default' returns a ridiculous answer inside comments."
12212 (js2-with-underscore-as-word-syntax
12214 (if (and (not (looking-at "[[:alnum:]_$]"))
12215 (looking-back "[[:alnum:]_$]"))
12216 (setq beg (progn (forward-word -1) (point))
12217 end (progn (forward-word 1) (point)))
12218 (setq beg (progn (forward-word 1) (point))
12219 end (progn (forward-word -1) (point))))
12220 (replace-regexp-in-string
12222 (buffer-substring-no-properties beg end))))))
12224 (defun js2-mode-forward-sibling ()
12225 "Move to the end of the sibling following point in parent.
12226 Returns non-nil if successful, or nil if there was no following sibling."
12227 (let* ((node (js2-node-at-point))
12228 (parent (js2-mode-find-enclosing-fn node))
12230 (when (setq sib (js2-node-find-child-after (point) parent))
12231 (goto-char (+ (js2-node-abs-pos sib)
12232 (js2-node-len sib))))))
12234 (defun js2-mode-backward-sibling ()
12235 "Move to the beginning of the sibling node preceding point in parent.
12236 Parent is defined as the enclosing script or function."
12237 (let* ((node (js2-node-at-point))
12238 (parent (js2-mode-find-enclosing-fn node))
12240 (when (setq sib (js2-node-find-child-before (point) parent))
12241 (goto-char (js2-node-abs-pos sib)))))
12243 (defun js2-beginning-of-defun (&optional arg)
12244 "Go to line on which current function starts, and return t on success.
12245 If we're not in a function or already at the beginning of one, go
12246 to beginning of previous script-level element.
12247 With ARG N, do that N times. If N is negative, move forward."
12248 (setq arg (or arg 1))
12250 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12252 ((js2-function-node-p parent)
12253 (goto-char (js2-node-abs-pos parent)))
12255 (js2-mode-backward-sibling)))
12257 (js2-beginning-of-defun (1- arg))
12259 (when (js2-end-of-defun)
12260 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12262 (defun js2-end-of-defun ()
12263 "Go to the char after the last position of the current function
12264 or script-level element."
12265 (let* ((node (js2-node-at-point))
12266 (parent (or (and (js2-function-node-p node) node)
12267 (js2-node-parent-script-or-fn node)))
12269 (unless (js2-function-node-p parent)
12270 ;; Use current script-level node, or, if none, the next one.
12271 (setq script (or parent node)
12272 parent (js2-node-find-child-before (point) script))
12273 (when (or (null parent)
12274 (>= (point) (+ (js2-node-abs-pos parent)
12275 (js2-node-len parent))))
12276 (setq parent (js2-node-find-child-after (point) script))))
12278 (goto-char (+ (js2-node-abs-pos parent)
12279 (js2-node-len parent))))))
12281 (defun js2-mark-defun (&optional allow-extend)
12282 "Put mark at end of this function, point at beginning.
12283 The function marked is the one that contains point.
12285 Interactively, if this command is repeated,
12286 or (in Transient Mark mode) if the mark is active,
12287 it marks the next defun after the ones already marked."
12290 (when (and allow-extend
12291 (or (and (eq last-command this-command) (mark t))
12292 (and transient-mark-mode mark-active)))
12293 (let ((sib (save-excursion
12295 (if (js2-mode-forward-sibling)
12301 ;; no more siblings - try extending to enclosing node
12302 (goto-char (mark t)))))
12303 (when (not extended)
12304 (let ((node (js2-node-at-point (point) t)) ; skip comments
12305 ast fn stmt parent beg end)
12306 (when (js2-ast-root-p node)
12308 node (or (js2-node-find-child-after (point) node)
12309 (js2-node-find-child-before (point) node))))
12310 ;; only mark whole buffer if we can't find any children
12313 (if (js2-function-node-p node)
12315 (setq fn (js2-mode-find-enclosing-fn node)
12316 stmt (if (or (null fn)
12317 (js2-ast-root-p fn))
12318 (js2-mode-find-first-stmt node))
12319 parent (or stmt fn)))
12320 (setq beg (js2-node-abs-pos parent)
12321 end (+ beg (js2-node-len parent)))
12324 (exchange-point-and-mark)))))
12326 (defun js2-narrow-to-defun ()
12327 "Narrow to the function enclosing point."
12329 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12330 (fn (if (js2-script-node-p node)
12332 (js2-mode-find-enclosing-fn node)))
12333 (beg (js2-node-abs-pos fn)))
12334 (unless (js2-ast-root-p fn)
12335 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12337 (provide 'js2-mode)
12339 ;;; js2-mode.el ends here