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-SUPER 165)
654 (defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
655 (defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
656 (defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
658 (defconst js2-num-tokens (1+ js2-TAGGED_TEMPLATE))
660 (defconst js2-debug-print-trees nil)
662 ;; Rhino accepts any string or stream as input. Emacs character
663 ;; processing works best in buffers, so we'll assume the input is a
664 ;; buffer. JavaScript strings can be copied into temp buffers before
667 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
668 ;; They're the Emacs equivalent of instance variables, more or less.
670 (js2-deflocal js2-ts-dirty-line nil
671 "Token stream buffer-local variable.
672 Indicates stuff other than whitespace since start of line.")
674 (js2-deflocal js2-ts-hit-eof nil
675 "Token stream buffer-local variable.")
678 (js2-deflocal js2-ts-line-start 0
679 "Token stream buffer-local variable.")
681 (js2-deflocal js2-ts-lineno 1
682 "Token stream buffer-local variable.")
685 (js2-deflocal js2-ts-line-end-char -1
686 "Token stream buffer-local variable.")
688 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
689 "Token stream buffer-local variable.
690 Current scan position.")
693 (js2-deflocal js2-ts-is-xml-attribute nil
694 "Token stream buffer-local variable.")
696 (js2-deflocal js2-ts-xml-is-tag-content nil
697 "Token stream buffer-local variable.")
699 (js2-deflocal js2-ts-xml-open-tags-count 0
700 "Token stream buffer-local variable.")
702 (js2-deflocal js2-ts-string-buffer nil
703 "Token stream buffer-local variable.
704 List of chars built up while scanning various tokens.")
706 (cl-defstruct (js2-token
708 (:constructor make-js2-token (beg)))
709 "Value returned from the token stream."
719 ;; Have to call `js2-init-scanner' to initialize the values.
720 (js2-deflocal js2-ti-tokens nil)
721 (js2-deflocal js2-ti-tokens-cursor nil)
722 (js2-deflocal js2-ti-lookahead nil)
724 (cl-defstruct (js2-ts-state
725 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
726 (cursor js2-ts-cursor)
727 (tokens (copy-sequence js2-ti-tokens))
728 (tokens-cursor js2-ti-tokens-cursor)
729 (lookahead js2-ti-lookahead))))
738 (js2-deflocal js2-parsed-errors nil
739 "List of errors produced during scanning/parsing.")
741 (js2-deflocal js2-parsed-warnings nil
742 "List of warnings produced during scanning/parsing.")
744 (js2-deflocal js2-recover-from-parse-errors t
745 "Non-nil to continue parsing after a syntax error.
747 In recovery mode, the AST will be built in full, and any error
748 nodes will be flagged with appropriate error information. If
749 this flag is nil, a syntax error will result in an error being
752 The variable is automatically buffer-local, because different
753 modes that use the parser will need different settings.")
755 (js2-deflocal js2-parse-hook nil
756 "List of callbacks for receiving parsing progress.")
758 (defvar js2-parse-finished-hook nil
759 "List of callbacks to notify when parsing finishes.
760 Not called if parsing was interrupted.")
762 (js2-deflocal js2-is-eval-code nil
763 "True if we're evaluating code in a string.
764 If non-nil, the tokenizer will record the token text, and the AST nodes
765 will record their source text. Off by default for IDE modes, since the
766 text is available in the buffer.")
768 (defvar js2-parse-ide-mode t
769 "Non-nil if the parser is being used for `js2-mode'.
770 If non-nil, the parser will set text properties for fontification
771 and the syntax table. The value should be nil when using the
772 parser as a frontend to an interpreter or byte compiler.")
774 ;;; Parser instance variables (buffer-local vars for js2-parse)
776 (defconst js2-ti-after-eol (lsh 1 16)
777 "Flag: first token of the source line.")
779 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
781 (js2-deflocal js2-compiler-generate-debug-info t)
782 (js2-deflocal js2-compiler-use-dynamic-scope nil)
783 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
784 (js2-deflocal js2-compiler-xml-available t)
785 (js2-deflocal js2-compiler-optimization-level 0)
786 (js2-deflocal js2-compiler-generating-source t)
787 (js2-deflocal js2-compiler-strict-mode nil)
788 (js2-deflocal js2-compiler-report-warning-as-error nil)
789 (js2-deflocal js2-compiler-generate-observer-count nil)
790 (js2-deflocal js2-compiler-activation-names nil)
794 ;; There's a compileFunction method in Context.java - may need it.
795 (js2-deflocal js2-called-by-compile-function nil
796 "True if `js2-parse' was called by `js2-compile-function'.
797 Will only be used when we finish implementing the interpreter.")
799 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
801 ;; SKIP: node factory - we're going to just call functions directly,
802 ;; and eventually go to a unified AST format.
804 (js2-deflocal js2-nesting-of-function 0)
806 (js2-deflocal js2-recorded-identifiers nil
807 "Tracks identifiers found during parsing.")
809 (js2-deflocal js2-is-in-destructuring nil
810 "True while parsing destructuring expression.")
812 (defcustom js2-global-externs nil
813 "A list of any extern names you'd like to consider always declared.
814 This list is global and is used by all `js2-mode' files.
815 You can create buffer-local externs list using `js2-additional-externs'.
817 There is also a buffer-local variable `js2-default-externs',
818 which is initialized by default to include the Ecma-262 externs
819 and the standard browser externs. The three lists are all
820 checked during highlighting."
824 (js2-deflocal js2-default-externs nil
825 "Default external declarations.
827 These are currently only used for highlighting undeclared variables,
828 which only worries about top-level (unqualified) references.
829 As js2-mode's processing improves, we will flesh out this list.
831 The initial value is set to `js2-ecma-262-externs', unless some
832 of the `js2-include-?-externs' variables are set to t, in which
833 case the browser, Rhino and/or Node.js externs are also included.
835 See `js2-additional-externs' for more information.")
837 (defcustom js2-include-browser-externs t
838 "Non-nil to include browser externs in the master externs list.
839 If you work on JavaScript files that are not intended for browsers,
840 such as Mozilla Rhino server-side JavaScript, set this to nil.
841 See `js2-additional-externs' for more information about externs."
845 (defcustom js2-include-rhino-externs nil
846 "Non-nil to include Mozilla Rhino externs in the master externs list.
847 See `js2-additional-externs' for more information about externs."
851 (defcustom js2-include-node-externs nil
852 "Non-nil to include Node.js externs in the master externs list.
853 See `js2-additional-externs' for more information about externs."
857 (js2-deflocal js2-additional-externs nil
858 "A buffer-local list of additional external declarations.
859 It is used to decide whether variables are considered undeclared
860 for purposes of highlighting.
862 Each entry is a Lisp string. The string should be the fully qualified
863 name of an external entity. All externs should be added to this list,
864 so that as js2-mode's processing improves it can take advantage of them.
866 You may want to declare your externs in three ways.
867 First, you can add externs that are valid for all your JavaScript files.
868 You should probably do this by adding them to `js2-global-externs', which
869 is a global list used for all js2-mode files.
871 Next, you can add a function to `js2-init-hook' that adds additional
872 externs appropriate for the specific file, perhaps based on its path.
873 These should go in `js2-additional-externs', which is buffer-local.
875 Third, you can use JSLint's global declaration, as long as
876 `js2-include-jslint-globals' is non-nil, which see.
878 Finally, you can add a function to `js2-post-parse-callbacks',
879 which is called after parsing completes, and `js2-mode-ast' is bound to
880 the root of the parse tree. At this stage you can set up an AST
881 node visitor using `js2-visit-ast' and examine the parse tree
882 for specific import patterns that may imply the existence of
883 other externs, possibly tied to your build system. These should also
884 be added to `js2-additional-externs'.
886 Your post-parse callback may of course also use the simpler and
887 faster (but perhaps less robust) approach of simply scanning the
888 buffer text for your imports, using regular expressions.")
891 ;; SKIP: encoded-source
893 ;;; The following variables are per-function and should be saved/restored
894 ;;; during function parsing...
896 (js2-deflocal js2-current-script-or-fn nil)
897 (js2-deflocal js2-current-scope nil)
898 (js2-deflocal js2-nesting-of-with 0)
899 (js2-deflocal js2-label-set nil
900 "An alist mapping label names to nodes.")
902 (js2-deflocal js2-loop-set nil)
903 (js2-deflocal js2-loop-and-switch-set nil)
904 (js2-deflocal js2-has-return-value nil)
905 (js2-deflocal js2-end-flags 0)
907 ;;; ...end of per function variables
909 ;; These flags enumerate the possible ways a statement/function can
910 ;; terminate. These flags are used by endCheck() and by the Parser to
911 ;; detect inconsistent return usage.
913 ;; END_UNREACHED is reserved for code paths that are assumed to always be
914 ;; able to execute (example: throw, continue)
916 ;; END_DROPS_OFF indicates if the statement can transfer control to the
917 ;; next one. Statement such as return dont. A compound statement may have
918 ;; some branch that drops off control to the next statement.
920 ;; END_RETURNS indicates that the statement can return (without arguments)
921 ;; END_RETURNS_VALUE indicates that the statement can return a value.
923 ;; A compound statement such as
927 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
929 (defconst js2-end-unreached #x0)
930 (defconst js2-end-drops-off #x1)
931 (defconst js2-end-returns #x2)
932 (defconst js2-end-returns-value #x4)
934 ;; Rhino awkwardly passes a statementLabel parameter to the
935 ;; statementHelper() function, the main statement parser, which
936 ;; is then used by quite a few of the sub-parsers. We just make
937 ;; it a buffer-local variable and make sure it's cleaned up properly.
938 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
940 ;; Similarly, Rhino passes an inForInit boolean through about half
941 ;; the expression parsers. We use a dynamically-scoped variable,
942 ;; which makes it easier to funcall the parsers individually without
943 ;; worrying about whether they take the parameter or not.
944 (js2-deflocal js2-in-for-init nil)
945 (js2-deflocal js2-temp-name-counter 0)
946 (js2-deflocal js2-parse-stmt-count 0)
948 (defsubst js2-get-next-temp-name ()
949 (format "$%d" (cl-incf js2-temp-name-counter)))
951 (defvar js2-parse-interruptable-p t
952 "Set this to nil to force parse to continue until finished.
953 This will mostly be useful for interpreters.")
955 (defvar js2-statements-per-pause 50
956 "Pause after this many statements to check for user input.
957 If user input is pending, stop the parse and discard the tree.
958 This makes for a smoother user experience for large files.
959 You may have to wait a second or two before the highlighting
960 and error-reporting appear, but you can always type ahead if
961 you wish. This appears to be more or less how Eclipse, IntelliJ
962 and other editors work.")
964 (js2-deflocal js2-record-comments t
965 "Instructs the scanner to record comments in `js2-scanned-comments'.")
967 (js2-deflocal js2-scanned-comments nil
968 "List of all comments from the current parse.")
970 (defcustom js2-mode-indent-inhibit-undo nil
971 "Non-nil to disable collection of Undo information when indenting lines.
972 Some users have requested this behavior. It's nil by default because
973 other Emacs modes don't work this way."
977 (defcustom js2-mode-indent-ignore-first-tab nil
978 "If non-nil, ignore first TAB keypress if we look indented properly.
979 It's fairly common for users to navigate to an already-indented line
980 and press TAB for reassurance that it's been indented. For this class
981 of users, we want the first TAB press on a line to be ignored if the
982 line is already indented to one of the precomputed alternatives.
984 This behavior is only partly implemented. If you TAB-indent a line,
985 navigate to another line, and then navigate back, it fails to clear
986 the last-indented variable, so it thinks you've already hit TAB once,
987 and performs the indent. A full solution would involve getting on the
988 point-motion hooks for the entire buffer. If we come across another
989 use cases that requires watching point motion, I'll consider doing it.
991 If you set this variable to nil, then the TAB key will always change
992 the indentation of the current line, if more than one alternative
993 indentation spot exists."
997 (defvar js2-indent-hook nil
998 "A hook for user-defined indentation rules.
1000 Functions on this hook should expect two arguments: (LIST INDEX)
1001 The LIST argument is the list of computed indentation points for
1002 the current line. INDEX is the list index of the indentation point
1003 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1004 indent function is not going to change the current line indentation.
1006 If a hook function on this list returns a non-nil value, then
1007 `js2-bounce-indent' assumes the hook function has performed its own
1008 indentation, and will do nothing. If all hook functions on the list
1009 return nil, then `js2-bounce-indent' will use its computed indentation
1010 and reindent the line.
1012 When hook functions on this hook list are called, the variable
1013 `js2-mode-ast' may or may not be set, depending on whether the
1014 parse tree is available. If the variable is nil, you can pass a
1015 callback to `js2-mode-wait-for-parse', and your callback will be
1016 called after the new parse tree is built. This can take some time
1019 (defface js2-warning
1020 `((((class color) (background light))
1021 (:underline "orange"))
1022 (((class color) (background dark))
1023 (:underline "orange"))
1025 "Face for JavaScript warnings."
1029 `((((class color) (background light))
1030 (:foreground "red"))
1031 (((class color) (background dark))
1032 (:foreground "red"))
1033 (t (:foreground "red")))
1034 "Face for JavaScript errors."
1037 (defface js2-jsdoc-tag
1038 '((t :foreground "SlateGray"))
1039 "Face used to highlight @whatever tags in jsdoc comments."
1042 (defface js2-jsdoc-type
1043 '((t :foreground "SteelBlue"))
1044 "Face used to highlight {FooBar} types in jsdoc comments."
1047 (defface js2-jsdoc-value
1048 '((t :foreground "PeachPuff3"))
1049 "Face used to highlight tag values in jsdoc comments."
1052 (defface js2-function-param
1053 '((t :foreground "SeaGreen"))
1054 "Face used to highlight function parameters in javascript."
1057 (defface js2-function-call
1058 '((t :inherit default))
1059 "Face used to highlight function name in calls."
1062 (defface js2-instance-member
1063 '((t :foreground "DarkOrchid"))
1064 "Face used to highlight instance variables in javascript.
1065 Not currently used."
1068 (defface js2-private-member
1069 '((t :foreground "PeachPuff3"))
1070 "Face used to highlight calls to private methods in javascript.
1071 Not currently used."
1074 (defface js2-private-function-call
1075 '((t :foreground "goldenrod"))
1076 "Face used to highlight calls to private functions in javascript.
1077 Not currently used."
1080 (defface js2-jsdoc-html-tag-name
1081 '((((class color) (min-colors 88) (background light))
1082 (:foreground "rosybrown"))
1083 (((class color) (min-colors 8) (background dark))
1084 (:foreground "yellow"))
1085 (((class color) (min-colors 8) (background light))
1086 (:foreground "magenta")))
1087 "Face used to highlight jsdoc html tag names"
1090 (defface js2-jsdoc-html-tag-delimiter
1091 '((((class color) (min-colors 88) (background light))
1092 (:foreground "dark khaki"))
1093 (((class color) (min-colors 8) (background dark))
1094 (:foreground "green"))
1095 (((class color) (min-colors 8) (background light))
1096 (:foreground "green")))
1097 "Face used to highlight brackets in jsdoc html tags."
1100 (defface js2-external-variable
1101 '((t :foreground "orange"))
1102 "Face used to highlight undeclared variable identifiers.")
1104 (defcustom js2-init-hook nil
1105 "List of functions to be called after `js2-mode' or
1106 `js2-minor-mode' has initialized all variables, before parsing
1107 the buffer for the first time."
1110 :version "20130608")
1112 (defcustom js2-post-parse-callbacks nil
1113 "List of callback functions invoked after parsing finishes.
1114 Currently, the main use for this function is to add synthetic
1115 declarations to `js2-recorded-identifiers', which see."
1119 (defcustom js2-build-imenu-callbacks nil
1120 "List of functions called during Imenu index generation.
1121 It's a good place to add additional entries to it, using
1122 `js2-record-imenu-entry'."
1126 (defcustom js2-highlight-external-variables t
1127 "Non-nil to highlight undeclared variable identifiers.
1128 An undeclared variable is any variable not declared with var or let
1129 in the current scope or any lexically enclosing scope. If you use
1130 such a variable, then you are either expecting it to originate from
1131 another file, or you've got a potential bug."
1135 (defcustom js2-include-jslint-globals t
1136 "Non-nil to include the identifiers from JSLint global
1137 declaration (see http://www.jslint.com/lint.html#global) in the
1138 buffer-local externs list. See `js2-additional-externs' for more
1143 (defvar js2-mode-map
1144 (let ((map (make-sparse-keymap)))
1145 (define-key map [mouse-1] #'js2-mode-show-node)
1146 (define-key map (kbd "M-j") #'js2-line-break)
1147 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1148 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1149 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1150 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1151 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1152 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1153 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1154 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1155 (when js2-bounce-indent-p
1156 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1158 (define-key map [menu-bar javascript]
1159 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1161 (define-key map [menu-bar javascript customize-js2-mode]
1162 '(menu-item "Customize js2-mode" js2-mode-customize
1163 :help "Customize the behavior of this mode"))
1165 (define-key map [menu-bar javascript js2-force-refresh]
1166 '(menu-item "Force buffer refresh" js2-mode-reset
1167 :help "Re-parse the buffer from scratch"))
1169 (define-key map [menu-bar javascript separator-2]
1172 (define-key map [menu-bar javascript next-error]
1173 '(menu-item "Next warning or error" next-error
1174 :enabled (and js2-mode-ast
1175 (or (js2-ast-root-errors js2-mode-ast)
1176 (js2-ast-root-warnings js2-mode-ast)))
1177 :help "Move to next warning or error"))
1179 (define-key map [menu-bar javascript display-errors]
1180 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1181 :visible (not js2-mode-show-parse-errors)
1182 :help "Turn on display of warnings and errors"))
1184 (define-key map [menu-bar javascript hide-errors]
1185 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1186 :visible js2-mode-show-parse-errors
1187 :help "Turn off display of warnings and errors"))
1189 (define-key map [menu-bar javascript separator-1]
1192 (define-key map [menu-bar javascript js2-toggle-function]
1193 '(menu-item "Show/collapse element" js2-mode-toggle-element
1194 :help "Hide or show function body or comment"))
1196 (define-key map [menu-bar javascript show-comments]
1197 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1198 :visible js2-mode-comments-hidden
1199 :help "Expand all hidden block comments"))
1201 (define-key map [menu-bar javascript hide-comments]
1202 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1203 :visible (not js2-mode-comments-hidden)
1204 :help "Show block comments as /*...*/"))
1206 (define-key map [menu-bar javascript show-all-functions]
1207 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1208 :visible js2-mode-functions-hidden
1209 :help "Expand all hidden function bodies"))
1211 (define-key map [menu-bar javascript hide-all-functions]
1212 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1213 :visible (not js2-mode-functions-hidden)
1214 :help "Show {...} for all top-level function bodies"))
1217 "Keymap used in `js2-mode' buffers.")
1219 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1221 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1222 "Matches a //-comment line. Must be first non-whitespace on line.
1223 First match-group is the leading whitespace.")
1225 (defvar js2-mode-hook nil)
1227 (js2-deflocal js2-mode-ast nil "Private variable.")
1228 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1229 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1230 (js2-deflocal js2-mode-parsing nil "Private variable.")
1231 (js2-deflocal js2-mode-node-overlay nil)
1233 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1234 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1236 (js2-deflocal js2-mode-fontifications nil "Private variable")
1237 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1238 (js2-deflocal js2-imenu-recorder nil "Private variable")
1239 (js2-deflocal js2-imenu-function-map nil "Private variable")
1241 (defvar js2-paragraph-start
1242 "\\(@[[:alpha:]]+\\>\\|$\\)")
1244 ;; Note that we also set a 'c-in-sws text property in html comments,
1245 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1246 (defvar js2-syntactic-ws-start
1247 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1249 (defvar js2-syntactic-ws-end
1250 "\\s \\|[\n\r/]\\|\\s!")
1252 (defvar js2-syntactic-eol
1253 (concat "\\s *\\(/\\*[^*\n\r]*"
1254 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1256 "\\(//\\|/\\*[^*\n\r]*"
1257 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1259 "Copied from `java-mode'. Needed for some cc-engine functions.")
1261 (defvar js2-comment-prefix-regexp
1264 (defvar js2-comment-start-skip
1265 "\\(//+\\|/\\*+\\)\\s *")
1267 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1268 "Non-nil to emit status messages during parsing.")
1270 (defvar js2-mode-functions-hidden nil "Private variable.")
1271 (defvar js2-mode-comments-hidden nil "Private variable.")
1273 (defvar js2-mode-syntax-table
1274 (let ((table (make-syntax-table)))
1275 (c-populate-syntax-table table)
1277 "Syntax table used in `js2-mode' buffers.")
1279 (defvar js2-mode-abbrev-table nil
1280 "Abbrev table in use in `js2-mode' buffers.")
1281 (define-abbrev-table 'js2-mode-abbrev-table ())
1283 (defvar js2-mode-pending-parse-callbacks nil
1284 "List of functions waiting to be notified that parse is finished.")
1286 (defvar js2-mode-last-indented-line -1)
1288 ;;; Localizable error and warning messages
1290 ;; Messages are copied from Rhino's Messages.properties.
1291 ;; Many of the Java-specific messages have been elided.
1292 ;; Add any js2-specific ones at the end, so we can keep
1293 ;; this file synced with changes to Rhino's.
1295 (defvar js2-message-table
1296 (make-hash-table :test 'equal :size 250)
1297 "Contains localized messages for `js2-mode'.")
1299 ;; TODO(stevey): construct this table at compile-time.
1300 (defmacro js2-msg (key &rest strings)
1301 `(puthash ,key (concat ,@strings)
1304 (defun js2-get-msg (msg-key)
1305 "Look up a localized message.
1306 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1307 the correct number of ARGS must be provided."
1308 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1309 (args (if (listp msg-key) (cdr msg-key)))
1310 (msg (gethash key js2-message-table)))
1312 (apply #'format msg args)
1313 key))) ; default to showing the key
1315 (js2-msg "msg.dup.parms"
1316 "Duplicate parameter name '%s'.")
1318 (js2-msg "msg.too.big.jump"
1319 "Program too complex: jump offset too big.")
1321 (js2-msg "msg.too.big.index"
1322 "Program too complex: internal index exceeds 64K limit.")
1324 (js2-msg "msg.while.compiling.fn"
1325 "Encountered code generation error while compiling function '%s': %s")
1327 (js2-msg "msg.while.compiling.script"
1328 "Encountered code generation error while compiling script: %s")
1331 (js2-msg "msg.ctor.not.found"
1332 "Constructor for '%s' not found.")
1334 (js2-msg "msg.not.ctor"
1335 "'%s' is not a constructor.")
1338 (js2-msg "msg.varargs.ctor"
1339 "Method or constructor '%s' must be static "
1340 "with the signature (Context cx, Object[] args, "
1341 "Function ctorObj, boolean inNewExpr) "
1342 "to define a variable arguments constructor.")
1344 (js2-msg "msg.varargs.fun"
1345 "Method '%s' must be static with the signature "
1346 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1347 "to define a variable arguments function.")
1349 (js2-msg "msg.incompat.call"
1350 "Method '%s' called on incompatible object.")
1352 (js2-msg "msg.bad.parms"
1353 "Unsupported parameter type '%s' in method '%s'.")
1355 (js2-msg "msg.bad.method.return"
1356 "Unsupported return type '%s' in method '%s'.")
1358 (js2-msg "msg.bad.ctor.return"
1359 "Construction of objects of type '%s' is not supported.")
1361 (js2-msg "msg.no.overload"
1362 "Method '%s' occurs multiple times in class '%s'.")
1364 (js2-msg "msg.method.not.found"
1365 "Method '%s' not found in '%s'.")
1369 (js2-msg "msg.bad.for.in.lhs"
1370 "Invalid left-hand side of for..in loop.")
1372 (js2-msg "msg.mult.index"
1373 "Only one variable allowed in for..in loop.")
1375 (js2-msg "msg.bad.for.in.destruct"
1376 "Left hand side of for..in loop must be an array of "
1377 "length 2 to accept key/value pair.")
1379 (js2-msg "msg.cant.convert"
1380 "Can't convert to type '%s'.")
1382 (js2-msg "msg.bad.assign.left"
1383 "Invalid assignment left-hand side.")
1385 (js2-msg "msg.bad.decr"
1386 "Invalid decrement operand.")
1388 (js2-msg "msg.bad.incr"
1389 "Invalid increment operand.")
1391 (js2-msg "msg.bad.yield"
1392 "yield must be in a function.")
1394 (js2-msg "msg.yield.parenthesized"
1395 "yield expression must be parenthesized.")
1398 (js2-msg "msg.cant.call.indirect"
1399 "Function '%s' must be called directly, and not by way of a "
1400 "function of another name.")
1402 (js2-msg "msg.eval.nonstring"
1403 "Calling eval() with anything other than a primitive "
1404 "string value will simply return the value. "
1405 "Is this what you intended?")
1407 (js2-msg "msg.eval.nonstring.strict"
1408 "Calling eval() with anything other than a primitive "
1409 "string value is not allowed in strict mode.")
1411 (js2-msg "msg.bad.destruct.op"
1412 "Invalid destructuring assignment operator")
1415 (js2-msg "msg.only.from.new"
1416 "'%s' may only be invoked from a `new' expression.")
1418 (js2-msg "msg.deprec.ctor"
1419 "The '%s' constructor is deprecated.")
1422 (js2-msg "msg.no.function.ref.found"
1423 "no source found to decompile function reference %s")
1425 (js2-msg "msg.arg.isnt.array"
1426 "second argument to Function.prototype.apply must be an array")
1429 (js2-msg "msg.bad.esc.mask"
1430 "invalid string escape mask")
1433 (js2-msg "msg.bad.quant"
1434 "Invalid quantifier %s")
1436 (js2-msg "msg.overlarge.backref"
1437 "Overly large back reference %s")
1439 (js2-msg "msg.overlarge.min"
1440 "Overly large minimum %s")
1442 (js2-msg "msg.overlarge.max"
1443 "Overly large maximum %s")
1445 (js2-msg "msg.zero.quant"
1446 "Zero quantifier %s")
1448 (js2-msg "msg.max.lt.min"
1449 "Maximum %s less than minimum")
1451 (js2-msg "msg.unterm.quant"
1452 "Unterminated quantifier %s")
1454 (js2-msg "msg.unterm.paren"
1455 "Unterminated parenthetical %s")
1457 (js2-msg "msg.unterm.class"
1458 "Unterminated character class %s")
1460 (js2-msg "msg.bad.range"
1461 "Invalid range in character class.")
1463 (js2-msg "msg.trail.backslash"
1464 "Trailing \\ in regular expression.")
1466 (js2-msg "msg.re.unmatched.right.paren"
1467 "unmatched ) in regular expression.")
1469 (js2-msg "msg.no.regexp"
1470 "Regular expressions are not available.")
1472 (js2-msg "msg.bad.backref"
1473 "back-reference exceeds number of capturing parentheses.")
1475 (js2-msg "msg.bad.regexp.compile"
1476 "Only one argument may be specified if the first "
1477 "argument to RegExp.prototype.compile is a RegExp object.")
1480 (js2-msg "msg.got.syntax.errors"
1481 "Compilation produced %s syntax errors.")
1483 (js2-msg "msg.var.redecl"
1484 "TypeError: redeclaration of var %s.")
1486 (js2-msg "msg.const.redecl"
1487 "TypeError: redeclaration of const %s.")
1489 (js2-msg "msg.let.redecl"
1490 "TypeError: redeclaration of variable %s.")
1492 (js2-msg "msg.parm.redecl"
1493 "TypeError: redeclaration of formal parameter %s.")
1495 (js2-msg "msg.fn.redecl"
1496 "TypeError: redeclaration of function %s.")
1498 (js2-msg "msg.let.decl.not.in.block"
1499 "SyntaxError: let declaration not directly within block")
1501 (js2-msg "msg.mod.import.decl.at.top.level"
1502 "SyntaxError: import declarations may only appear at the top level")
1504 (js2-msg "msg.mod.as.after.reserved.word"
1505 "SyntaxError: missing keyword 'as' after reserved word %s")
1507 (js2-msg "msg.mod.rc.after.import.spec.list"
1508 "SyntaxError: missing '}' after module specifier list")
1510 (js2-msg "msg.mod.from.after.import.spec.set"
1511 "SyntaxError: missing keyword 'from' after import specifier set")
1513 (js2-msg "msg.mod.declaration.after.import"
1514 "SyntaxError: missing declaration after 'import' keyword")
1516 (js2-msg "msg.mod.spec.after.from"
1517 "SyntaxError: missing module specifier after 'from' keyword")
1519 (js2-msg "msg.mod.export.decl.at.top.level"
1520 "SyntaxError: export declarations may only appear at top level")
1522 (js2-msg "msg.mod.rc.after.export.spec.list"
1523 "SyntaxError: missing '}' after export specifier list")
1526 (js2-msg "msg.dup.label"
1529 (js2-msg "msg.undef.label"
1532 (js2-msg "msg.bad.break"
1533 "unlabelled break must be inside loop or switch")
1535 (js2-msg "msg.continue.outside"
1536 "continue must be inside loop")
1538 (js2-msg "msg.continue.nonloop"
1539 "continue can only use labels of iteration statements")
1541 (js2-msg "msg.bad.throw.eol"
1542 "Line terminator is not allowed between the throw "
1543 "keyword and throw expression.")
1545 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1546 "function statement requires a name")
1548 (js2-msg "msg.no.paren.parms"
1549 "missing ( before function parameters.")
1551 (js2-msg "msg.no.parm"
1552 "missing formal parameter")
1554 (js2-msg "msg.no.paren.after.parms"
1555 "missing ) after formal parameters")
1557 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1558 "parameter without default follows parameter with default")
1560 (js2-msg "msg.param.after.rest" ; added by js2-mode
1561 "parameter after rest parameter")
1563 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1564 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1566 (js2-msg "msg.no.brace.body"
1567 "missing '{' before function body")
1569 (js2-msg "msg.no.brace.after.body"
1570 "missing } after function body")
1572 (js2-msg "msg.no.paren.cond"
1573 "missing ( before condition")
1575 (js2-msg "msg.no.paren.after.cond"
1576 "missing ) after condition")
1578 (js2-msg "msg.no.semi.stmt"
1579 "missing ; before statement")
1581 (js2-msg "msg.missing.semi"
1582 "missing ; after statement")
1584 (js2-msg "msg.no.name.after.dot"
1585 "missing name after . operator")
1587 (js2-msg "msg.no.name.after.coloncolon"
1588 "missing name after :: operator")
1590 (js2-msg "msg.no.name.after.dotdot"
1591 "missing name after .. operator")
1593 (js2-msg "msg.no.name.after.xmlAttr"
1594 "missing name after .@")
1596 (js2-msg "msg.no.bracket.index"
1597 "missing ] in index expression")
1599 (js2-msg "msg.no.paren.switch"
1600 "missing ( before switch expression")
1602 (js2-msg "msg.no.paren.after.switch"
1603 "missing ) after switch expression")
1605 (js2-msg "msg.no.brace.switch"
1606 "missing '{' before switch body")
1608 (js2-msg "msg.bad.switch"
1609 "invalid switch statement")
1611 (js2-msg "msg.no.colon.case"
1612 "missing : after case expression")
1614 (js2-msg "msg.double.switch.default"
1615 "double default label in the switch statement")
1617 (js2-msg "msg.no.while.do"
1618 "missing while after do-loop body")
1620 (js2-msg "msg.no.paren.for"
1621 "missing ( after for")
1623 (js2-msg "msg.no.semi.for"
1624 "missing ; after for-loop initializer")
1626 (js2-msg "msg.no.semi.for.cond"
1627 "missing ; after for-loop condition")
1629 (js2-msg "msg.in.after.for.name"
1630 "missing in or of after for")
1632 (js2-msg "msg.no.paren.for.ctrl"
1633 "missing ) after for-loop control")
1635 (js2-msg "msg.no.paren.with"
1636 "missing ( before with-statement object")
1638 (js2-msg "msg.no.paren.after.with"
1639 "missing ) after with-statement object")
1641 (js2-msg "msg.no.paren.after.let"
1642 "missing ( after let")
1644 (js2-msg "msg.no.paren.let"
1645 "missing ) after variable list")
1647 (js2-msg "msg.no.curly.let"
1648 "missing } after let statement")
1650 (js2-msg "msg.bad.return"
1653 (js2-msg "msg.no.brace.block"
1654 "missing } in compound statement")
1656 (js2-msg "msg.bad.label"
1659 (js2-msg "msg.bad.var"
1660 "missing variable name")
1662 (js2-msg "msg.bad.var.init"
1663 "invalid variable initialization")
1665 (js2-msg "msg.no.colon.cond"
1666 "missing : in conditional expression")
1668 (js2-msg "msg.no.paren.arg"
1669 "missing ) after argument list")
1671 (js2-msg "msg.no.bracket.arg"
1672 "missing ] after element list")
1674 (js2-msg "msg.bad.prop"
1675 "invalid property id")
1677 (js2-msg "msg.no.colon.prop"
1678 "missing : after property id")
1680 (js2-msg "msg.no.brace.prop"
1681 "missing } after property list")
1683 (js2-msg "msg.no.paren"
1684 "missing ) in parenthetical")
1686 (js2-msg "msg.reserved.id"
1687 "'%s' is a reserved identifier")
1689 (js2-msg "msg.no.paren.catch"
1690 "missing ( before catch-block condition")
1692 (js2-msg "msg.bad.catchcond"
1693 "invalid catch block condition")
1695 (js2-msg "msg.catch.unreachable"
1696 "any catch clauses following an unqualified catch are unreachable")
1698 (js2-msg "msg.no.brace.try"
1699 "missing '{' before try block")
1701 (js2-msg "msg.no.brace.catchblock"
1702 "missing '{' before catch-block body")
1704 (js2-msg "msg.try.no.catchfinally"
1705 "'try' without 'catch' or 'finally'")
1707 (js2-msg "msg.no.return.value"
1708 "function %s does not always return a value")
1710 (js2-msg "msg.anon.no.return.value"
1711 "anonymous function does not always return a value")
1713 (js2-msg "msg.return.inconsistent"
1714 "return statement is inconsistent with previous usage")
1716 (js2-msg "msg.generator.returns"
1717 "TypeError: legacy generator function '%s' returns a value")
1719 (js2-msg "msg.anon.generator.returns"
1720 "TypeError: anonymous legacy generator function returns a value")
1722 (js2-msg "msg.syntax"
1725 (js2-msg "msg.unexpected.eof"
1726 "Unexpected end of file")
1728 (js2-msg "msg.XML.bad.form"
1729 "illegally formed XML syntax")
1731 (js2-msg "msg.XML.not.available"
1732 "XML runtime not available")
1734 (js2-msg "msg.too.deep.parser.recursion"
1735 "Too deep recursion while parsing")
1737 (js2-msg "msg.no.side.effects"
1738 "Code has no side effects")
1740 (js2-msg "msg.extra.trailing.comma"
1741 "Trailing comma is not supported in some browsers")
1743 (js2-msg "msg.array.trailing.comma"
1744 "Trailing comma yields different behavior across browsers")
1746 (js2-msg "msg.equal.as.assign"
1747 (concat "Test for equality (==) mistyped as assignment (=)?"
1748 " (parenthesize to suppress warning)"))
1750 (js2-msg "msg.var.hides.arg"
1751 "Variable %s hides argument")
1753 (js2-msg "msg.destruct.assign.no.init"
1754 "Missing = in destructuring declaration")
1757 (js2-msg "msg.no.properties"
1758 "%s has no properties.")
1760 (js2-msg "msg.invalid.iterator"
1761 "Invalid iterator value")
1763 (js2-msg "msg.iterator.primitive"
1764 "__iterator__ returned a primitive value")
1766 (js2-msg "msg.assn.create.strict"
1767 "Assignment to undeclared variable %s")
1769 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1770 "Undeclared variable or function '%s'")
1772 (js2-msg "msg.ref.undefined.prop"
1773 "Reference to undefined property '%s'")
1775 (js2-msg "msg.prop.not.found"
1776 "Property %s not found.")
1778 (js2-msg "msg.invalid.type"
1779 "Invalid JavaScript value of type %s")
1781 (js2-msg "msg.primitive.expected"
1782 "Primitive type expected (had %s instead)")
1784 (js2-msg "msg.namespace.expected"
1785 "Namespace object expected to left of :: (found %s instead)")
1787 (js2-msg "msg.null.to.object"
1788 "Cannot convert null to an object.")
1790 (js2-msg "msg.undef.to.object"
1791 "Cannot convert undefined to an object.")
1793 (js2-msg "msg.cyclic.value"
1794 "Cyclic %s value not allowed.")
1796 (js2-msg "msg.is.not.defined"
1797 "'%s' is not defined.")
1799 (js2-msg "msg.undef.prop.read"
1800 "Cannot read property '%s' from %s")
1802 (js2-msg "msg.undef.prop.write"
1803 "Cannot set property '%s' of %s to '%s'")
1805 (js2-msg "msg.undef.prop.delete"
1806 "Cannot delete property '%s' of %s")
1808 (js2-msg "msg.undef.method.call"
1809 "Cannot call method '%s' of %s")
1811 (js2-msg "msg.undef.with"
1812 "Cannot apply 'with' to %s")
1814 (js2-msg "msg.isnt.function"
1815 "%s is not a function, it is %s.")
1817 (js2-msg "msg.isnt.function.in"
1818 "Cannot call property %s in object %s. "
1819 "It is not a function, it is '%s'.")
1821 (js2-msg "msg.function.not.found"
1822 "Cannot find function %s.")
1824 (js2-msg "msg.function.not.found.in"
1825 "Cannot find function %s in object %s.")
1827 (js2-msg "msg.isnt.xml.object"
1828 "%s is not an xml object.")
1830 (js2-msg "msg.no.ref.to.get"
1831 "%s is not a reference to read reference value.")
1833 (js2-msg "msg.no.ref.to.set"
1834 "%s is not a reference to set reference value to %s.")
1836 (js2-msg "msg.no.ref.from.function"
1837 "Function %s can not be used as the left-hand "
1838 "side of assignment or as an operand of ++ or -- operator.")
1840 (js2-msg "msg.bad.default.value"
1841 "Object's getDefaultValue() method returned an object.")
1843 (js2-msg "msg.instanceof.not.object"
1844 "Can't use instanceof on a non-object.")
1846 (js2-msg "msg.instanceof.bad.prototype"
1847 "'prototype' property of %s is not an object.")
1849 (js2-msg "msg.bad.radix"
1850 "illegal radix %s.")
1853 (js2-msg "msg.default.value"
1854 "Cannot find default value for object.")
1856 (js2-msg "msg.zero.arg.ctor"
1857 "Cannot load class '%s' which has no zero-parameter constructor.")
1859 (js2-msg "msg.ctor.multiple.parms"
1860 "Can't define constructor or class %s since more than "
1861 "one constructor has multiple parameters.")
1863 (js2-msg "msg.extend.scriptable"
1864 "%s must extend ScriptableObject in order to define property %s.")
1866 (js2-msg "msg.bad.getter.parms"
1867 "In order to define a property, getter %s must have zero "
1868 "parameters or a single ScriptableObject parameter.")
1870 (js2-msg "msg.obj.getter.parms"
1871 "Expected static or delegated getter %s to take "
1872 "a ScriptableObject parameter.")
1874 (js2-msg "msg.getter.static"
1875 "Getter and setter must both be static or neither be static.")
1877 (js2-msg "msg.setter.return"
1878 "Setter must have void return type: %s")
1880 (js2-msg "msg.setter2.parms"
1881 "Two-parameter setter must take a ScriptableObject as "
1882 "its first parameter.")
1884 (js2-msg "msg.setter1.parms"
1885 "Expected single parameter setter for %s")
1887 (js2-msg "msg.setter2.expected"
1888 "Expected static or delegated setter %s to take two parameters.")
1890 (js2-msg "msg.setter.parms"
1891 "Expected either one or two parameters for setter.")
1893 (js2-msg "msg.setter.bad.type"
1894 "Unsupported parameter type '%s' in setter '%s'.")
1896 (js2-msg "msg.add.sealed"
1897 "Cannot add a property to a sealed object: %s.")
1899 (js2-msg "msg.remove.sealed"
1900 "Cannot remove a property from a sealed object: %s.")
1902 (js2-msg "msg.modify.sealed"
1903 "Cannot modify a property of a sealed object: %s.")
1905 (js2-msg "msg.modify.readonly"
1906 "Cannot modify readonly property: %s.")
1909 (js2-msg "msg.missing.exponent"
1912 (js2-msg "msg.caught.nfe"
1913 "number format error")
1915 (js2-msg "msg.unterminated.string.lit"
1916 "unterminated string literal")
1918 (js2-msg "msg.unterminated.comment"
1919 "unterminated comment")
1921 (js2-msg "msg.unterminated.re.lit"
1922 "unterminated regular expression literal")
1924 (js2-msg "msg.invalid.re.flag"
1925 "invalid flag after regular expression")
1927 (js2-msg "msg.no.re.input.for"
1930 (js2-msg "msg.illegal.character"
1931 "illegal character")
1933 (js2-msg "msg.invalid.escape"
1934 "invalid Unicode escape sequence")
1936 (js2-msg "msg.bad.namespace"
1937 "not a valid default namespace statement. "
1938 "Syntax is: default xml namespace = EXPRESSION;")
1940 ;; TokensStream warnings
1941 (js2-msg "msg.bad.octal.literal"
1942 "illegal octal literal digit %s; "
1943 "interpreting it as a decimal digit")
1945 (js2-msg "msg.missing.hex.digits"
1946 "missing hexadecimal digits after '0x'")
1948 (js2-msg "msg.missing.binary.digits"
1949 "missing binary digits after '0b'")
1951 (js2-msg "msg.missing.octal.digits"
1952 "missing octal digits after '0o'")
1954 (js2-msg "msg.script.is.not.constructor"
1955 "Script objects are not constructors.")
1958 (js2-msg "msg.arraylength.bad"
1959 "Inappropriate array length.")
1962 (js2-msg "msg.arraylength.too.big"
1963 "Array length %s exceeds supported capacity limit.")
1966 (js2-msg "msg.bad.uri"
1967 "Malformed URI sequence.")
1970 (js2-msg "msg.bad.precision"
1971 "Precision %s out of range.")
1974 (js2-msg "msg.send.newborn"
1975 "Attempt to send value to newborn generator")
1977 (js2-msg "msg.already.exec.gen"
1978 "Already executing generator")
1980 (js2-msg "msg.StopIteration.invalid"
1981 "StopIteration may not be changed to an arbitrary object.")
1984 (js2-msg "msg.yield.closing"
1985 "Yield from closing generator")
1988 (js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
1989 "class statement requires a name")
1991 (js2-msg "msg.class.unexpected.comma" ; added by js2-mode
1992 "unexpected ',' between class properties")
1994 (js2-msg "msg.unexpected.static" ; added by js2-mode
1995 "unexpected 'static'")
1997 (js2-msg "msg.missing.extends" ; added by js2-mode
1998 "name is required after extends")
2000 (js2-msg "msg.no.brace.class" ; added by js2-mode
2001 "missing '{' before class body")
2003 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
2004 "missing ']' after computed property expression")
2008 (defconst js2-ti-max-lookahead 2)
2009 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
2011 (defun js2-new-token (offset)
2012 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
2013 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
2014 (aset js2-ti-tokens js2-ti-tokens-cursor token)
2017 (defsubst js2-current-token ()
2018 (aref js2-ti-tokens js2-ti-tokens-cursor))
2020 (defsubst js2-current-token-string ()
2021 (js2-token-string (js2-current-token)))
2023 (defsubst js2-current-token-type ()
2024 (js2-token-type (js2-current-token)))
2026 (defsubst js2-current-token-beg ()
2027 (js2-token-beg (js2-current-token)))
2029 (defsubst js2-current-token-end ()
2030 (js2-token-end (js2-current-token)))
2032 (defun js2-current-token-len ()
2033 (let ((token (js2-current-token)))
2034 (- (js2-token-end token)
2035 (js2-token-beg token))))
2037 (defun js2-ts-seek (state)
2038 (setq js2-ts-lineno (js2-ts-state-lineno state)
2039 js2-ts-cursor (js2-ts-state-cursor state)
2040 js2-ti-tokens (js2-ts-state-tokens state)
2041 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2042 js2-ti-lookahead (js2-ts-state-lookahead state)))
2046 (defun js2-delete-if (predicate list)
2047 "Remove all items satisfying PREDICATE in LIST."
2048 (cl-loop for item in list
2049 if (not (funcall predicate item))
2052 (defun js2-position (element list)
2053 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2054 Returns nil if element is not found in the list."
2057 (while (and list (not found))
2058 (if (eq element (car list))
2060 (setq count (1+ count)
2064 (defun js2-find-if (predicate list)
2065 "Find first item satisfying PREDICATE in LIST."
2067 (while (and list (not result))
2068 (if (funcall predicate (car list))
2069 (setq result (car list)))
2070 (setq list (cdr list)))
2073 (defmacro js2-time (form)
2074 "Evaluate FORM, discard result, and return elapsed time in sec."
2076 (let ((beg (make-symbol "--js2-time-beg--")))
2077 `(let ((,beg (current-time)))
2079 (/ (truncate (* (- (float-time (current-time))
2084 (defsubst js2-same-line (pos)
2085 "Return t if POS is on the same line as current point."
2086 (and (>= pos (point-at-bol))
2087 (<= pos (point-at-eol))))
2089 (defun js2-code-bug ()
2090 "Signal an error when we encounter an unexpected code path."
2091 (error "failed assertion"))
2093 (defsubst js2-record-text-property (beg end prop value)
2094 "Record a text property to set when parsing finishes."
2095 (push (list beg end prop value) js2-mode-deferred-properties))
2097 ;; I'd like to associate errors with nodes, but for now the
2098 ;; easiest thing to do is get the context info from the last token.
2099 (defun js2-record-parse-error (msg &optional arg pos len)
2100 (push (list (list msg arg)
2101 (or pos (js2-current-token-beg))
2102 (or len (js2-current-token-len)))
2105 (defun js2-report-error (msg &optional msg-arg pos len)
2106 "Signal a syntax error or record a parse error."
2107 (if js2-recover-from-parse-errors
2108 (js2-record-parse-error msg msg-arg pos len)
2109 (signal 'js2-syntax-error
2113 (goto-char js2-ts-cursor)
2117 (defun js2-report-warning (msg &optional msg-arg pos len face)
2118 (if js2-compiler-report-warning-as-error
2119 (js2-report-error msg msg-arg pos len)
2120 (push (list (list msg msg-arg)
2121 (or pos (js2-current-token-beg))
2122 (or len (js2-current-token-len))
2124 js2-parsed-warnings)))
2126 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2127 (if js2-compiler-strict-mode
2128 (js2-report-warning msg-id msg-arg beg
2129 (and beg end (- end beg)))))
2131 (put 'js2-syntax-error 'error-conditions
2132 '(error syntax-error js2-syntax-error))
2133 (put 'js2-syntax-error 'error-message "Syntax error")
2135 (put 'js2-parse-error 'error-conditions
2136 '(error parse-error js2-parse-error))
2137 (put 'js2-parse-error 'error-message "Parse error")
2139 (defmacro js2-clear-flag (flags flag)
2140 `(setq ,flags (logand ,flags (lognot ,flag))))
2142 (defmacro js2-set-flag (flags flag)
2143 "Logical-or FLAG into FLAGS."
2144 `(setq ,flags (logior ,flags ,flag)))
2146 (defsubst js2-flag-set-p (flags flag)
2147 (/= 0 (logand flags flag)))
2149 (defsubst js2-flag-not-set-p (flags flag)
2150 (zerop (logand flags flag)))
2152 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2153 "Evaluate BODY with the _ character set to be word-syntax."
2154 (declare (indent 0) (debug t))
2155 (let ((old-syntax (make-symbol "old-syntax")))
2156 `(let ((,old-syntax (string (char-syntax ?_))))
2159 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2161 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2163 ;;; AST struct and function definitions
2165 ;; flags for ast node property 'member-type (used for e4x operators)
2166 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2167 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2168 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2170 (defsubst js2-relpos (pos anchor)
2171 "Convert POS to be relative to ANCHOR.
2172 If POS is nil, returns nil."
2173 (and pos (- pos anchor)))
2175 (defun js2-make-pad (indent)
2178 (make-string (* indent js2-basic-offset) ? )))
2180 (defun js2-visit-ast (node callback)
2181 "Visit every node in ast NODE with visitor CALLBACK.
2183 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2184 called twice: once to visit the node, and again after all the node's
2185 children have been processed. The END-P argument is nil on the first
2186 call and non-nil on the second call. The return value of the callback
2187 affects the traversal: if non-nil, the children of NODE are processed.
2188 If the callback returns nil, or if the node has no children, then the
2189 callback is called immediately with a non-nil END-P argument.
2191 The node traversal is approximately lexical-order, although there
2192 are currently no guarantees around this."
2194 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2196 (when (funcall callback node nil)
2199 ((eq vfunc 'js2-visit-none)
2200 nil) ; don't even bother calling it
2201 ;; Each AST node type has to define a `js2-visitor' function
2202 ;; that takes a node and a callback, and calls `js2-visit-ast'
2203 ;; on each child of the node.
2205 (funcall vfunc node callback))
2207 (error "%s does not define a visitor-traversal function"
2209 ;; call the end-visit
2210 (funcall callback node t))))
2212 (cl-defstruct (js2-node
2213 (:constructor nil)) ; abstract
2214 "Base AST node type."
2215 (type -1) ; token type
2216 (pos -1) ; start position of this AST node in parsed input
2217 (len 1) ; num characters spanned by the node
2218 props ; optional node property list (an alist)
2219 parent) ; link to parent node; null for root
2221 (defsubst js2-node-get-prop (node prop &optional default)
2222 (or (cadr (assoc prop (js2-node-props node))) default))
2224 (defsubst js2-node-set-prop (node prop value)
2225 (setf (js2-node-props node)
2226 (cons (list prop value) (js2-node-props node))))
2228 (defun js2-fixup-starts (n nodes)
2229 "Adjust the start positions of NODES to be relative to N.
2230 Any node in the list may be nil, for convenience."
2231 (dolist (node nodes)
2233 (setf (js2-node-pos node) (- (js2-node-pos node)
2234 (js2-node-pos n))))))
2236 (defun js2-node-add-children (parent &rest nodes)
2237 "Set parent node of NODES to PARENT, and return PARENT.
2238 Does nothing if we're not recording parent links.
2239 If any given node in NODES is nil, doesn't record that link."
2240 (js2-fixup-starts parent nodes)
2241 (dolist (node nodes)
2243 (setf (js2-node-parent node) parent))))
2245 ;; Non-recursive since it's called a frightening number of times.
2246 (defun js2-node-abs-pos (n)
2247 (let ((pos (js2-node-pos n)))
2248 (while (setq n (js2-node-parent n))
2249 (setq pos (+ pos (js2-node-pos n))))
2252 (defsubst js2-node-abs-end (n)
2253 "Return absolute buffer position of end of N."
2254 (+ (js2-node-abs-pos n) (js2-node-len n)))
2256 ;; It's important to make sure block nodes have a Lisp list for the
2257 ;; child nodes, to limit printing recursion depth in an AST that
2258 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2259 ;; a sufficiently large vector tree.
2261 (cl-defstruct (js2-block-node
2264 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2265 (pos (js2-current-token-beg))
2269 "A block of statements."
2270 kids) ; a Lisp list of the child statement nodes
2272 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2273 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2275 (defun js2-visit-block (ast callback)
2276 "Visit the `js2-block-node' children of AST."
2277 (dolist (kid (js2-block-node-kids ast))
2278 (js2-visit-ast kid callback)))
2280 (defun js2-print-block (n i)
2281 (let ((pad (js2-make-pad i)))
2283 (dolist (kid (js2-block-node-kids n))
2284 (js2-print-ast kid (1+ i)))
2287 (cl-defstruct (js2-scope
2288 (:include js2-block-node)
2290 (:constructor make-js2-scope (&key (type js2-BLOCK)
2291 (pos (js2-current-token-beg))
2294 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2295 ;; I don't have one of those handy, so I'll use an alist for now.
2296 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2297 ;; and is much lighter-weight to construct (both CPU and mem).
2298 ;; The keys are interned strings (symbols) for faster lookup.
2299 ;; Should switch to hybrid alist/hashtable eventually.
2300 symbol-table ; an alist of (symbol . js2-symbol)
2301 parent-scope ; a `js2-scope'
2302 top) ; top-level `js2-scope' (script/function)
2304 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2305 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2307 (defun js2-node-get-enclosing-scope (node)
2308 "Return the innermost `js2-scope' node surrounding NODE.
2309 Returns nil if there is no enclosing scope node."
2310 (let ((parent (js2-node-parent node)))
2311 (while (not (js2-scope-p parent))
2312 (setq parent (js2-node-parent parent)))
2315 (defun js2-get-defining-scope (scope name &optional point)
2316 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2317 Returns `js2-scope' in which NAME is defined, or nil if not found.
2319 If POINT is non-nil, and if the found declaration type is
2320 `js2-LET', also check that the declaration node is before POINT."
2321 (let ((sym (if (symbolp name)
2326 (while (and scope continue)
2328 (let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
2331 (not (eq js2-LET (js2-symbol-decl-type entry)))
2333 (js2-node-abs-pos (js2-symbol-ast-node entry))))))
2334 (and (eq sym 'arguments)
2335 (js2-function-node-p scope)))
2338 (setq scope (js2-scope-parent-scope scope))))
2341 (defun js2-scope-get-symbol (scope name)
2342 "Return symbol table entry for NAME in SCOPE.
2343 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2344 (and (js2-scope-symbol-table scope)
2345 (cdr (assq (if (symbolp name)
2348 (js2-scope-symbol-table scope)))))
2350 (defun js2-scope-put-symbol (scope name symbol)
2351 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2352 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2353 (let* ((table (js2-scope-symbol-table scope))
2354 (sym (if (symbolp name) name (intern name)))
2355 (entry (assq sym table)))
2357 (setcdr entry symbol)
2358 (push (cons sym symbol)
2359 (js2-scope-symbol-table scope)))))
2361 (cl-defstruct (js2-symbol
2363 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2364 "A symbol table entry."
2365 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2366 ;; js2-LET, or js2-CONST
2369 ast-node) ; a `js2-node'
2371 (cl-defstruct (js2-error-node
2373 (:constructor nil) ; silence emacs21 byte-compiler
2374 (:constructor make-js2-error-node (&key (type js2-ERROR)
2375 (pos (js2-current-token-beg))
2377 "AST node representing a parse error.")
2379 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2380 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2382 (cl-defstruct (js2-script-node
2383 (:include js2-scope)
2385 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2386 (pos (js2-current-token-beg))
2388 ;; FIXME: What are those?
2391 functions ; Lisp list of nested functions
2392 regexps ; Lisp list of (string . flags)
2393 symbols ; alist (every symbol gets unique index)
2395 var-names ; vector of string names
2396 consts ; bool-vector matching var-decls
2397 (temp-number 0)) ; for generating temp variables
2399 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2400 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2402 (defun js2-print-script (node indent)
2403 (dolist (kid (js2-block-node-kids node))
2404 (js2-print-ast kid indent)))
2406 (cl-defstruct (js2-ast-root
2407 (:include js2-script-node)
2409 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2410 (pos (js2-current-token-beg))
2413 "The root node of a js2 AST."
2414 buffer ; the source buffer from which the code was parsed
2415 comments ; a Lisp list of comments, ordered by start position
2416 errors ; a Lisp list of errors found during parsing
2417 warnings ; a Lisp list of warnings found during parsing
2418 node-count) ; number of nodes in the tree, including the root
2420 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2421 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2423 (defun js2-visit-ast-root (ast callback)
2424 (dolist (kid (js2-ast-root-kids ast))
2425 (js2-visit-ast kid callback))
2426 (dolist (comment (js2-ast-root-comments ast))
2427 (js2-visit-ast comment callback)))
2429 (cl-defstruct (js2-comment-node
2432 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2433 (pos (js2-current-token-beg))
2436 format) ; 'line, 'block, 'jsdoc or 'html
2438 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2439 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2441 (defun js2-print-comment (n i)
2442 ;; We really ought to link end-of-line comments to their nodes.
2443 ;; Or maybe we could add a new comment type, 'endline.
2444 (insert (js2-make-pad i)
2445 (js2-node-string n)))
2447 (cl-defstruct (js2-expr-stmt-node
2450 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2454 "An expression statement."
2457 (defsubst js2-expr-stmt-node-set-has-result (node)
2458 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2459 (setf (js2-node-type node) js2-EXPR_RESULT))
2461 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2462 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2464 (defun js2-visit-expr-stmt-node (n v)
2465 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2467 (defun js2-print-expr-stmt-node (n indent)
2468 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2471 (cl-defstruct (js2-loop-node
2472 (:include js2-scope)
2474 "Abstract supertype of loop nodes."
2475 body ; a `js2-block-node'
2476 lp ; position of left-paren, nil if omitted
2477 rp) ; position of right-paren, nil if omitted
2479 (cl-defstruct (js2-do-node
2480 (:include js2-loop-node)
2482 (:constructor make-js2-do-node (&key (type js2-DO)
2483 (pos (js2-current-token-beg))
2490 "AST node for do-loop."
2491 condition ; while (expression)
2492 while-pos) ; buffer position of 'while' keyword
2494 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2495 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2497 (defun js2-visit-do-node (n v)
2498 (js2-visit-ast (js2-do-node-body n) v)
2499 (js2-visit-ast (js2-do-node-condition n) v))
2501 (defun js2-print-do-node (n i)
2502 (let ((pad (js2-make-pad i)))
2503 (insert pad "do {\n")
2504 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2505 (js2-print-ast kid (1+ i)))
2506 (insert pad "} while (")
2507 (js2-print-ast (js2-do-node-condition n) 0)
2510 (cl-defstruct (js2-export-node
2513 (:constructor make-js2-export-node (&key (type js2-EXPORT)
2514 (pos) (js2-current-token-beg)
2520 "AST node for an export statement. There are many things that can be exported,
2521 so many of its properties will be nil.
2523 exports-list ; lisp list of js2-export-binding-node to export
2524 from-clause ; js2-from-clause-node for re-exporting symbols from another module
2525 declaration ; js2-var-decl-node (var, let, const) or js2-class-node
2526 default) ; js2-function-node or js2-assign-node
2528 (put 'cl-struct-js2-export-node 'js2-visitor 'js2-visit-export-node)
2529 (put 'cl-struct-js2-export-node 'js2-printer 'js2-print-export-node)
2531 (defun js2-visit-export-node (n v)
2532 (let ((exports-list (js2-export-node-exports-list n))
2533 (from (js2-export-node-from-clause n))
2534 (declaration (js2-export-node-declaration n))
2535 (default (js2-export-node-default n)))
2537 (dolist (export exports-list)
2538 (js2-visit-ast export v)))
2540 (js2-visit-ast from v))
2542 (js2-visit-ast declaration v))
2544 (js2-visit-ast default v))))
2546 (defun js2-print-export-node (n i)
2547 (let ((pad (js2-make-pad i))
2548 (exports-list (js2-export-node-exports-list n))
2549 (from (js2-export-node-from-clause n))
2550 (declaration (js2-export-node-declaration n))
2551 (default (js2-export-node-default n)))
2552 (insert pad "export ")
2556 (js2-print-ast default i))
2558 (js2-print-ast declaration i))
2559 ((and exports-list from)
2560 (js2-print-named-imports exports-list)
2562 (js2-print-from-clause from))
2565 (js2-print-from-clause from))
2567 (js2-print-named-imports exports-list)))
2570 (cl-defstruct (js2-while-node
2571 (:include js2-loop-node)
2573 (:constructor make-js2-while-node (&key (type js2-WHILE)
2574 (pos (js2-current-token-beg))
2578 "AST node for while-loop."
2579 condition) ; while-condition
2581 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2582 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2584 (defun js2-visit-while-node (n v)
2585 (js2-visit-ast (js2-while-node-condition n) v)
2586 (js2-visit-ast (js2-while-node-body n) v))
2588 (defun js2-print-while-node (n i)
2589 (let ((pad (js2-make-pad i)))
2590 (insert pad "while (")
2591 (js2-print-ast (js2-while-node-condition n) 0)
2593 (js2-print-body (js2-while-node-body n) (1+ i))
2594 (insert pad "}\n")))
2596 (cl-defstruct (js2-for-node
2597 (:include js2-loop-node)
2599 (:constructor make-js2-for-node (&key (type js2-FOR)
2604 "AST node for a C-style for-loop."
2605 init ; initialization expression
2606 condition ; loop condition
2607 update) ; update clause
2609 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2610 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2612 (defun js2-visit-for-node (n v)
2613 (js2-visit-ast (js2-for-node-init n) v)
2614 (js2-visit-ast (js2-for-node-condition n) v)
2615 (js2-visit-ast (js2-for-node-update n) v)
2616 (js2-visit-ast (js2-for-node-body n) v))
2618 (defun js2-print-for-node (n i)
2619 (let ((pad (js2-make-pad i)))
2620 (insert pad "for (")
2621 (js2-print-ast (js2-for-node-init n) 0)
2623 (js2-print-ast (js2-for-node-condition n) 0)
2625 (js2-print-ast (js2-for-node-update n) 0)
2627 (js2-print-body (js2-for-node-body n) (1+ i))
2628 (insert pad "}\n")))
2630 (cl-defstruct (js2-for-in-node
2631 (:include js2-loop-node)
2633 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2642 "AST node for a for..in loop."
2643 iterator ; [var] foo in ...
2644 object ; object over which we're iterating
2645 in-pos ; buffer position of 'in' keyword
2646 each-pos ; buffer position of 'each' keyword, if foreach-p
2647 foreach-p ; t if it's a for-each loop
2648 forof-p) ; t if it's a for-of loop
2650 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2651 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2653 (defun js2-visit-for-in-node (n v)
2654 (js2-visit-ast (js2-for-in-node-iterator n) v)
2655 (js2-visit-ast (js2-for-in-node-object n) v)
2656 (js2-visit-ast (js2-for-in-node-body n) v))
2658 (defun js2-print-for-in-node (n i)
2659 (let ((pad (js2-make-pad i))
2660 (foreach (js2-for-in-node-foreach-p n))
2661 (forof (js2-for-in-node-forof-p n)))
2666 (js2-print-ast (js2-for-in-node-iterator n) 0)
2667 (insert (if forof " of " " in "))
2668 (js2-print-ast (js2-for-in-node-object n) 0)
2670 (js2-print-body (js2-for-in-node-body n) (1+ i))
2671 (insert pad "}\n")))
2673 (cl-defstruct (js2-return-node
2676 (:constructor make-js2-return-node (&key (type js2-RETURN)
2680 "AST node for a return statement."
2681 retval) ; expression to return, or 'undefined
2683 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2684 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2686 (defun js2-visit-return-node (n v)
2687 (js2-visit-ast (js2-return-node-retval n) v))
2689 (defun js2-print-return-node (n i)
2690 (insert (js2-make-pad i) "return")
2691 (when (js2-return-node-retval n)
2693 (js2-print-ast (js2-return-node-retval n) 0))
2696 (cl-defstruct (js2-if-node
2699 (:constructor make-js2-if-node (&key (type js2-IF)
2706 "AST node for an if-statement."
2707 condition ; expression
2708 then-part ; statement or block
2709 else-pos ; optional buffer position of 'else' keyword
2710 else-part ; optional statement or block
2711 lp ; position of left-paren, nil if omitted
2712 rp) ; position of right-paren, nil if omitted
2714 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2715 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2717 (defun js2-visit-if-node (n v)
2718 (js2-visit-ast (js2-if-node-condition n) v)
2719 (js2-visit-ast (js2-if-node-then-part n) v)
2720 (js2-visit-ast (js2-if-node-else-part n) v))
2722 (defun js2-print-if-node (n i)
2723 (let ((pad (js2-make-pad i))
2724 (then-part (js2-if-node-then-part n))
2725 (else-part (js2-if-node-else-part n)))
2727 (js2-print-ast (js2-if-node-condition n) 0)
2729 (js2-print-body then-part (1+ i))
2734 ((js2-if-node-p else-part)
2736 (js2-print-body else-part i))
2738 (insert " else {\n")
2739 (js2-print-body else-part (1+ i))
2740 (insert pad "}\n")))))
2742 (cl-defstruct (js2-export-binding-node
2745 (:constructor make-js2-export-binding-node (&key (type -1)
2750 "AST node for an external symbol binding.
2751 It contains a local-name node which is the name of the value in the
2752 current scope, and extern-name which is the name of the value in the
2753 imported or exported scope. By default these are the same, but if the
2754 name is aliased as in {foo as bar}, it would have an extern-name node
2755 containing 'foo' and a local-name node containing 'bar'."
2756 local-name ; js2-name-node with the variable name in this scope
2757 extern-name) ; js2-name-node with the value name in the exporting module
2759 (put 'cl-struct-js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
2760 (put 'cl-struct-js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
2762 (defun js2-visit-extern-binding (n v)
2763 "Visit an extern binding node. First visit the local-name, and, if
2764 different, visit the extern-name."
2765 (let ((local-name (js2-export-binding-node-local-name n))
2766 (extern-name (js2-export-binding-node-extern-name n)))
2768 (js2-visit-ast local-name v))
2769 (when (not (equal local-name extern-name))
2770 (js2-visit-ast extern-name v))))
2772 (defun js2-print-extern-binding (n i)
2773 "Print a representation of a single extern binding. E.g. 'foo' or
2775 (let ((local-name (js2-export-binding-node-local-name n))
2776 (extern-name (js2-export-binding-node-extern-name n)))
2777 (insert (js2-name-node-name extern-name))
2778 (when (not (equal local-name extern-name))
2780 (insert (js2-name-node-name local-name)))))
2783 (cl-defstruct (js2-import-node
2786 (:constructor make-js2-import-node (&key (type js2-IMPORT)
2787 (pos (js2-current-token-beg))
2792 "AST node for an import statement. It follows the form
2794 import ModuleSpecifier;
2795 import ImportClause FromClause;"
2796 import ; js2-import-clause-node specifying which names are to imported.
2797 from ; js2-from-clause-node indicating the module from which to import.
2798 module-id) ; module-id of the import. E.g. 'src/mylib'.
2800 (put 'cl-struct-js2-import-node 'js2-printer 'js2-print-import)
2801 (put 'cl-struct-js2-import-node 'js2-visitor 'js2-visit-import)
2803 (defun js2-visit-import (n v)
2804 (let ((import-clause (js2-import-node-import n))
2805 (from-clause (js2-import-node-from n)))
2807 (js2-visit-ast import-clause v))
2809 (js2-visit-ast from-clause v))))
2811 (defun js2-print-import (n i)
2812 "Prints a representation of the import node"
2813 (let ((pad (js2-make-pad i))
2814 (import-clause (js2-import-node-import n))
2815 (from-clause (js2-import-node-from n))
2816 (module-id (js2-import-node-module-id n)))
2817 (insert pad "import ")
2820 (js2-print-import-clause import-clause)
2822 (js2-print-from-clause from-clause))
2828 (cl-defstruct (js2-import-clause-node
2831 (:constructor make-js2-import-clause-node (&key (type -1)
2837 "AST node corresponding to the import clause of an import statement. This is
2838 the portion of the import that bindings names from the external context to the
2840 namespace-import ; js2-namespace-import-node. E.g. '* as lib'
2841 named-imports ; lisp list of js2-export-binding-node for all named imports.
2842 default-binding) ; js2-export-binding-node for the default import binding
2844 (put 'cl-struct-js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
2845 (put 'cl-struct-js2-import-clause-node 'js2-printer 'js2-print-import-clause)
2847 (defun js2-visit-import-clause (n v)
2848 (let ((ns-import (js2-import-clause-node-namespace-import n))
2849 (named-imports (js2-import-clause-node-named-imports n))
2850 (default (js2-import-clause-node-default-binding n)))
2852 (js2-visit-ast ns-import v))
2854 (dolist (import named-imports)
2855 (js2-visit-ast import v)))
2857 (js2-visit-ast default v))))
2859 (defun js2-print-import-clause (n)
2860 (let ((ns-import (js2-import-clause-node-namespace-import n))
2861 (named-imports (js2-import-clause-node-named-imports n))
2862 (default (js2-import-clause-node-default-binding n)))
2864 ((and default ns-import)
2865 (js2-print-ast default)
2867 (js2-print-namespace-import ns-import))
2868 ((and default named-imports)
2869 (js2-print-ast default)
2871 (js2-print-named-imports named-imports))
2873 (js2-print-ast default))
2875 (js2-print-namespace-import ns-import))
2877 (js2-print-named-imports named-imports)))))
2879 (defun js2-print-namespace-import (node)
2881 (insert (js2-name-node-name (js2-namespace-import-node-name node))))
2883 (defun js2-print-named-imports (imports)
2885 (let ((len (length imports))
2888 (js2-print-extern-binding (nth n imports) 0)
2889 (unless (= n (- len 1))
2894 (cl-defstruct (js2-namespace-import-node
2897 (:constructor make-js2-namespace-import-node (&key (type -1)
2901 "AST node for a complete namespace import.
2902 E.g. the '* as lib' expression in:
2904 import * as lib from 'src/lib'
2906 It contains a single name node referring to the bound name."
2907 name) ; js2-name-node of the bound name.
2909 (defun js2-visit-namespace-import (n v)
2910 (js2-visit-ast (js2-namespace-import-node-name n) v))
2912 (put 'cl-struct-js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
2913 (put 'cl-struct-js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
2915 (cl-defstruct (js2-from-clause-node
2918 (:constructor make-js2-from-clause-node (&key (type js2-NAME)
2923 "AST node for the from clause in an import or export statement.
2924 E.g. from 'my/module'. It can refere to either an external module, or to the
2925 modules metadata itself."
2926 module-id ; string containing the module specifier.
2927 metadata-p) ; true if this clause refers to the module's metadata
2929 (put 'cl-struct-js2-from-clause-node 'js2-visitor 'js2-visit-none)
2930 (put 'cl-struct-js2-from-clause-node 'js2-printer 'js2-print-from-clause)
2932 (defun js2-print-from-clause (n)
2934 (if (js2-from-clause-node-metadata-p n)
2935 (insert "this module")
2937 (insert (js2-from-clause-node-module-id n))
2940 (cl-defstruct (js2-try-node
2943 (:constructor make-js2-try-node (&key (type js2-TRY)
2949 "AST node for a try-statement."
2951 catch-clauses ; a Lisp list of `js2-catch-node'
2952 finally-block) ; a `js2-finally-node'
2954 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2955 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2957 (defun js2-visit-try-node (n v)
2958 (js2-visit-ast (js2-try-node-try-block n) v)
2959 (dolist (clause (js2-try-node-catch-clauses n))
2960 (js2-visit-ast clause v))
2961 (js2-visit-ast (js2-try-node-finally-block n) v))
2963 (defun js2-print-try-node (n i)
2964 (let ((pad (js2-make-pad i))
2965 (catches (js2-try-node-catch-clauses n))
2966 (finally (js2-try-node-finally-block n)))
2967 (insert pad "try {\n")
2968 (js2-print-body (js2-try-node-try-block n) (1+ i))
2971 (dolist (catch catches)
2972 (js2-print-ast catch i)))
2974 (js2-print-ast finally i)
2977 (cl-defstruct (js2-catch-node
2978 (:include js2-scope)
2980 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2987 "AST node for a catch clause."
2988 param ; destructuring form or simple name node
2989 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2990 guard-expr ; catch condition, a `js2-node'
2991 lp ; buffer position of left-paren, nil if omitted
2992 rp) ; buffer position of right-paren, nil if omitted
2994 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2995 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2997 (defun js2-visit-catch-node (n v)
2998 (js2-visit-ast (js2-catch-node-param n) v)
2999 (when (js2-catch-node-guard-kwd n)
3000 (js2-visit-ast (js2-catch-node-guard-expr n) v))
3001 (js2-visit-block n v))
3003 (defun js2-print-catch-node (n i)
3004 (let ((pad (js2-make-pad i))
3005 (guard-kwd (js2-catch-node-guard-kwd n))
3006 (guard-expr (js2-catch-node-guard-expr n)))
3008 (js2-print-ast (js2-catch-node-param n) 0)
3011 (js2-print-ast guard-expr 0))
3013 (js2-print-body n (1+ i))
3016 (cl-defstruct (js2-finally-node
3019 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
3022 "AST node for a finally clause."
3023 body) ; a `js2-node', often but not always a block node
3025 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
3026 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
3028 (defun js2-visit-finally-node (n v)
3029 (js2-visit-ast (js2-finally-node-body n) v))
3031 (defun js2-print-finally-node (n i)
3032 (let ((pad (js2-make-pad i)))
3033 (insert " finally {\n")
3034 (js2-print-body (js2-finally-node-body n) (1+ i))
3035 (insert pad "}\n")))
3037 (cl-defstruct (js2-switch-node
3040 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
3046 "AST node for a switch statement."
3047 discriminant ; a `js2-node' (switch expression)
3048 cases ; a Lisp list of `js2-case-node'
3049 lp ; position of open-paren for discriminant, nil if omitted
3050 rp) ; position of close-paren for discriminant, nil if omitted
3052 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
3053 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
3055 (defun js2-visit-switch-node (n v)
3056 (js2-visit-ast (js2-switch-node-discriminant n) v)
3057 (dolist (c (js2-switch-node-cases n))
3058 (js2-visit-ast c v)))
3060 (defun js2-print-switch-node (n i)
3061 (let ((pad (js2-make-pad i))
3062 (cases (js2-switch-node-cases n)))
3063 (insert pad "switch (")
3064 (js2-print-ast (js2-switch-node-discriminant n) 0)
3066 (dolist (case cases)
3067 (js2-print-ast case i))
3068 (insert pad "}\n")))
3070 (cl-defstruct (js2-case-node
3071 (:include js2-block-node)
3073 (:constructor make-js2-case-node (&key (type js2-CASE)
3076 "AST node for a case clause of a switch statement."
3077 expr) ; the case expression (nil for default)
3079 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
3080 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
3082 (defun js2-visit-case-node (n v)
3083 (js2-visit-ast (js2-case-node-expr n) v)
3084 (js2-visit-block n v))
3086 (defun js2-print-case-node (n i)
3087 (let ((pad (js2-make-pad i))
3088 (expr (js2-case-node-expr n)))
3091 (insert "default:\n")
3093 (js2-print-ast expr 0)
3095 (dolist (kid (js2-case-node-kids n))
3096 (js2-print-ast kid (1+ i)))))
3098 (cl-defstruct (js2-throw-node
3101 (:constructor make-js2-throw-node (&key (type js2-THROW)
3104 "AST node for a throw statement."
3105 expr) ; the expression to throw
3107 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
3108 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
3110 (defun js2-visit-throw-node (n v)
3111 (js2-visit-ast (js2-throw-node-expr n) v))
3113 (defun js2-print-throw-node (n i)
3114 (insert (js2-make-pad i) "throw ")
3115 (js2-print-ast (js2-throw-node-expr n) 0)
3118 (cl-defstruct (js2-with-node
3121 (:constructor make-js2-with-node (&key (type js2-WITH)
3125 "AST node for a with-statement."
3128 lp ; buffer position of left-paren around object, nil if omitted
3129 rp) ; buffer position of right-paren around object, nil if omitted
3131 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
3132 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
3134 (defun js2-visit-with-node (n v)
3135 (js2-visit-ast (js2-with-node-object n) v)
3136 (js2-visit-ast (js2-with-node-body n) v))
3138 (defun js2-print-with-node (n i)
3139 (let ((pad (js2-make-pad i)))
3140 (insert pad "with (")
3141 (js2-print-ast (js2-with-node-object n) 0)
3143 (js2-print-body (js2-with-node-body n) (1+ i))
3144 (insert pad "}\n")))
3146 (cl-defstruct (js2-label-node
3149 (:constructor make-js2-label-node (&key (type js2-LABEL)
3152 "AST node for a statement label or case label."
3154 loop) ; for validating and code-generating continue-to-label
3156 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
3157 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
3159 (defun js2-print-label (n i)
3160 (insert (js2-make-pad i)
3161 (js2-label-node-name n)
3164 (cl-defstruct (js2-labeled-stmt-node
3167 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
3168 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
3169 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
3172 "AST node for a statement with one or more labels.
3173 Multiple labels for a statement are collapsed into the labels field."
3174 labels ; Lisp list of `js2-label-node'
3175 stmt) ; the statement these labels are for
3177 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
3178 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
3180 (defun js2-get-label-by-name (lbl-stmt name)
3181 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
3182 Returns nil if no such label is in the list."
3183 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
3185 (while (and label-list (not result))
3186 (if (string= (js2-label-node-name (car label-list)) name)
3187 (setq result (car label-list))
3188 (setq label-list (cdr label-list))))
3191 (defun js2-visit-labeled-stmt (n v)
3192 (dolist (label (js2-labeled-stmt-node-labels n))
3193 (js2-visit-ast label v))
3194 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
3196 (defun js2-print-labeled-stmt (n i)
3197 (dolist (label (js2-labeled-stmt-node-labels n))
3198 (js2-print-ast label i))
3199 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
3201 (defun js2-labeled-stmt-node-contains (node label)
3202 "Return t if NODE contains LABEL in its label set.
3203 NODE is a `js2-labels-node'. LABEL is an identifier."
3204 (cl-loop for nl in (js2-labeled-stmt-node-labels node)
3205 if (string= label (js2-label-node-name nl))
3207 finally return nil))
3209 (defsubst js2-labeled-stmt-node-add-label (node label)
3210 "Add a `js2-label-node' to the label set for this statement."
3211 (setf (js2-labeled-stmt-node-labels node)
3212 (nconc (js2-labeled-stmt-node-labels node) (list label))))
3214 (cl-defstruct (js2-jump-node
3217 "Abstract supertype of break and continue nodes."
3218 label ; `js2-name-node' for location of label identifier, if present
3219 target) ; target js2-labels-node or loop/switch statement
3221 (defun js2-visit-jump-node (n v)
3222 ;; We don't visit the target, since it's a back-link.
3223 (js2-visit-ast (js2-jump-node-label n) v))
3225 (cl-defstruct (js2-break-node
3226 (:include js2-jump-node)
3228 (:constructor make-js2-break-node (&key (type js2-BREAK)
3231 "AST node for a break statement.
3232 The label field is a `js2-name-node', possibly nil, for the named label
3233 if provided. E.g. in 'break foo', it represents 'foo'. The target field
3234 is the target of the break - a label node or enclosing loop/switch statement.")
3236 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
3237 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
3239 (defun js2-print-break-node (n i)
3240 (insert (js2-make-pad i) "break")
3241 (when (js2-break-node-label n)
3243 (js2-print-ast (js2-break-node-label n) 0))
3246 (cl-defstruct (js2-continue-node
3247 (:include js2-jump-node)
3249 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3252 "AST node for a continue statement.
3253 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3254 It is nil if continue specifies no label. The target field is the jump target:
3255 a `js2-label-node' or the innermost enclosing loop.")
3257 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3258 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3260 (defun js2-print-continue-node (n i)
3261 (insert (js2-make-pad i) "continue")
3262 (when (js2-continue-node-label n)
3264 (js2-print-ast (js2-continue-node-label n) 0))
3267 (cl-defstruct (js2-function-node
3268 (:include js2-script-node)
3270 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3274 (form 'FUNCTION_STATEMENT)
3280 "AST node for a function declaration.
3281 The `params' field is a Lisp list of nodes. Each node is either a simple
3282 `js2-name-node', or if it's a destructuring-assignment parameter, a
3283 `js2-array-node' or `js2-object-node'."
3284 ftype ; FUNCTION, GETTER or SETTER
3285 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
3286 name ; function name (a `js2-name-node', or nil if anonymous)
3287 params ; a Lisp list of destructuring forms or simple name nodes
3288 rest-p ; if t, the last parameter is rest parameter
3289 body ; a `js2-block-node' or expression node (1.8 only)
3290 lp ; position of arg-list open-paren, or nil if omitted
3291 rp ; position of arg-list close-paren, or nil if omitted
3292 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3293 needs-activation ; t if we need an activation object for this frame
3294 generator-type ; STAR, LEGACY, COMPREHENSION or nil
3295 member-expr) ; nonstandard Ecma extension from Rhino
3297 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3298 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3300 (defun js2-visit-function-node (n v)
3301 (js2-visit-ast (js2-function-node-name n) v)
3302 (dolist (p (js2-function-node-params n))
3303 (js2-visit-ast p v))
3304 (js2-visit-ast (js2-function-node-body n) v))
3306 (defun js2-print-function-node (n i)
3307 (let* ((pad (js2-make-pad i))
3308 (getter (js2-node-get-prop n 'GETTER_SETTER))
3309 (name (or (js2-function-node-name n)
3310 (js2-function-node-member-expr n)))
3311 (params (js2-function-node-params n))
3312 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3313 (rest-p (js2-function-node-rest-p n))
3314 (body (js2-function-node-body n))
3315 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3316 (unless (or getter arrow)
3317 (insert pad "function")
3318 (when (eq (js2-function-node-generator-type n) 'STAR)
3322 (js2-print-ast name 0))
3324 (cl-loop with len = (length params)
3328 (when (and rest-p (= count len))
3330 (js2-print-ast param 0)
3337 ;; TODO: fix this to be smarter about indenting, etc.
3340 (if (js2-block-node-p body)
3341 (js2-print-body body (1+ i))
3342 (js2-print-ast body 0))
3347 (defun js2-function-name (node)
3348 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3349 (and (js2-function-node-name node)
3350 (js2-name-node-name (js2-function-node-name node))))
3352 ;; Having this be an expression node makes it more flexible.
3353 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3354 ;; that work better if you assume it's an expression. Whenever we have
3355 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3356 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3357 (cl-defstruct (js2-var-decl-node
3360 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3361 (pos (js2-current-token-beg))
3364 "AST node for a variable declaration list (VAR, CONST or LET).
3365 The node bounds differ depending on the declaration type. For VAR or
3366 CONST declarations, the bounds include the var/const keyword. For LET
3367 declarations, the node begins at the position of the first child."
3368 kids ; a Lisp list of `js2-var-init-node' structs.
3369 decl-type) ; js2-VAR, js2-CONST or js2-LET
3371 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3372 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3374 (defun js2-visit-var-decl (n v)
3375 (dolist (kid (js2-var-decl-node-kids n))
3376 (js2-visit-ast kid v)))
3378 (defun js2-print-var-decl (n i)
3379 (let ((pad (js2-make-pad i))
3380 (tt (js2-var-decl-node-decl-type n)))
3383 ((= tt js2-VAR) "var ")
3384 ((= tt js2-LET) "let ")
3385 ((= tt js2-CONST) "const ")
3387 (error "malformed var-decl node"))))
3388 (cl-loop with kids = (js2-var-decl-node-kids n)
3389 with len = (length kids)
3393 (js2-print-ast kid 0)
3397 (cl-defstruct (js2-var-init-node
3400 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3404 "AST node for a variable declaration.
3405 The type field will be js2-CONST for a const decl."
3406 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3407 initializer) ; initializer expression, a `js2-node'
3409 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3410 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3412 (defun js2-visit-var-init-node (n v)
3413 (js2-visit-ast (js2-var-init-node-target n) v)
3414 (js2-visit-ast (js2-var-init-node-initializer n) v))
3416 (defun js2-print-var-init-node (n i)
3417 (let ((pad (js2-make-pad i))
3418 (name (js2-var-init-node-target n))
3419 (init (js2-var-init-node-initializer n)))
3421 (js2-print-ast name 0)
3424 (js2-print-ast init 0))))
3426 (cl-defstruct (js2-cond-node
3429 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3436 "AST node for the ternary operator"
3440 q-pos ; buffer position of ?
3441 c-pos) ; buffer position of :
3443 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3444 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3446 (defun js2-visit-cond-node (n v)
3447 (js2-visit-ast (js2-cond-node-test-expr n) v)
3448 (js2-visit-ast (js2-cond-node-true-expr n) v)
3449 (js2-visit-ast (js2-cond-node-false-expr n) v))
3451 (defun js2-print-cond-node (n i)
3452 (let ((pad (js2-make-pad i)))
3454 (js2-print-ast (js2-cond-node-test-expr n) 0)
3456 (js2-print-ast (js2-cond-node-true-expr n) 0)
3458 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3460 (cl-defstruct (js2-infix-node
3463 (:constructor make-js2-infix-node (&key type
3467 "Represents infix expressions.
3468 Includes assignment ops like `|=', and the comma operator.
3469 The type field inherited from `js2-node' holds the operator."
3470 op-pos ; buffer position where operator begins
3471 left ; any `js2-node'
3472 right) ; any `js2-node'
3474 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3475 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3477 (defun js2-visit-infix-node (n v)
3478 (js2-visit-ast (js2-infix-node-left n) v)
3479 (js2-visit-ast (js2-infix-node-right n) v))
3481 (defconst js2-operator-tokens
3482 (let ((table (make-hash-table :test 'eq))
3484 (list (cons js2-IN "in")
3485 (cons js2-TYPEOF "typeof")
3486 (cons js2-INSTANCEOF "instanceof")
3487 (cons js2-DELPROP "delete")
3488 (cons js2-COMMA ",")
3489 (cons js2-COLON ":")
3494 (cons js2-BITOR "|")
3495 (cons js2-BITXOR "^")
3496 (cons js2-BITAND "&")
3505 (cons js2-URSH ">>>")
3506 (cons js2-ADD "+") ; infix plus
3507 (cons js2-SUB "-") ; infix minus
3512 (cons js2-BITNOT "~")
3513 (cons js2-POS "+") ; unary plus
3514 (cons js2-NEG "-") ; unary minus
3515 (cons js2-TRIPLEDOT "...")
3516 (cons js2-SHEQ "===") ; shallow equality
3517 (cons js2-SHNE "!==") ; shallow inequality
3518 (cons js2-ASSIGN "=")
3519 (cons js2-ASSIGN_BITOR "|=")
3520 (cons js2-ASSIGN_BITXOR "^=")
3521 (cons js2-ASSIGN_BITAND "&=")
3522 (cons js2-ASSIGN_LSH "<<=")
3523 (cons js2-ASSIGN_RSH ">>=")
3524 (cons js2-ASSIGN_URSH ">>>=")
3525 (cons js2-ASSIGN_ADD "+=")
3526 (cons js2-ASSIGN_SUB "-=")
3527 (cons js2-ASSIGN_MUL "*=")
3528 (cons js2-ASSIGN_DIV "/=")
3529 (cons js2-ASSIGN_MOD "%="))))
3530 (cl-loop for (k . v) in tokens do
3531 (puthash k v table))
3534 (defun js2-print-infix-node (n i)
3535 (let* ((tt (js2-node-type n))
3536 (op (gethash tt js2-operator-tokens)))
3538 (error "unrecognized infix operator %s" (js2-node-type n)))
3539 (insert (js2-make-pad i))
3540 (js2-print-ast (js2-infix-node-left n) 0)
3541 (unless (= tt js2-COMMA)
3545 (js2-print-ast (js2-infix-node-right n) 0)))
3547 (cl-defstruct (js2-assign-node
3548 (:include js2-infix-node)
3550 (:constructor make-js2-assign-node (&key type
3554 "Represents any assignment.
3555 The type field holds the actual assignment operator.")
3557 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3558 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3560 (cl-defstruct (js2-unary-node
3563 (:constructor make-js2-unary-node (&key type ; required
3566 "AST node type for unary operator nodes.
3567 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3568 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3569 property is added if the operator follows the operand."
3570 operand) ; a `js2-node' expression
3572 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3573 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3575 (defun js2-visit-unary-node (n v)
3576 (js2-visit-ast (js2-unary-node-operand n) v))
3578 (defun js2-print-unary-node (n i)
3579 (let* ((tt (js2-node-type n))
3580 (op (gethash tt js2-operator-tokens))
3581 (postfix (js2-node-get-prop n 'postfix)))
3583 (error "unrecognized unary operator %s" tt))
3584 (insert (js2-make-pad i))
3587 (if (or (= tt js2-TYPEOF)
3590 (js2-print-ast (js2-unary-node-operand n) 0)
3594 (cl-defstruct (js2-let-node
3595 (:include js2-scope)
3597 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3598 (pos (js2-current-token-beg))
3601 "AST node for a let expression or a let statement.
3602 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3603 vars ; a `js2-var-decl-node'
3604 body ; a `js2-node' representing the expression or body block
3608 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3609 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3611 (defun js2-visit-let-node (n v)
3612 (js2-visit-ast (js2-let-node-vars n) v)
3613 (js2-visit-ast (js2-let-node-body n) v))
3615 (defun js2-print-let-node (n i)
3616 (insert (js2-make-pad i) "let (")
3618 (js2-print-ast (js2-let-node-vars n) 0)
3619 (delete-region p (+ p 4)))
3621 (js2-print-ast (js2-let-node-body n) i))
3623 (cl-defstruct (js2-keyword-node
3626 (:constructor make-js2-keyword-node (&key type
3627 (pos (js2-current-token-beg))
3628 (len (- js2-ts-cursor pos)))))
3629 "AST node representing a literal keyword such as `null'.
3630 Used for `null', `this', `true', `false' and `debugger'.
3631 The node type is set to js2-NULL, js2-THIS, etc.")
3633 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3634 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3636 (defun js2-print-keyword-node (n i)
3637 (insert (js2-make-pad i)
3638 (let ((tt (js2-node-type n)))
3640 ((= tt js2-THIS) "this")
3641 ((= tt js2-SUPER) "super")
3642 ((= tt js2-NULL) "null")
3643 ((= tt js2-TRUE) "true")
3644 ((= tt js2-FALSE) "false")
3645 ((= tt js2-DEBUGGER) "debugger")
3646 (t (error "Invalid keyword literal type: %d" tt))))))
3648 (defsubst js2-this-or-super-node-p (node)
3649 "Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
3650 (let ((type (js2-node-type node)))
3651 (or (eq type js2-THIS) (eq type js2-SUPER))))
3653 (cl-defstruct (js2-new-node
3656 (:constructor make-js2-new-node (&key (type js2-NEW)
3657 (pos (js2-current-token-beg))
3661 "AST node for new-expression such as new Foo()."
3662 target ; an identifier or reference
3663 args ; a Lisp list of argument nodes
3664 lp ; position of left-paren, nil if omitted
3665 rp ; position of right-paren, nil if omitted
3666 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3668 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3669 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3671 (defun js2-visit-new-node (n v)
3672 (js2-visit-ast (js2-new-node-target n) v)
3673 (dolist (arg (js2-new-node-args n))
3674 (js2-visit-ast arg v))
3675 (js2-visit-ast (js2-new-node-initializer n) v))
3677 (defun js2-print-new-node (n i)
3678 (insert (js2-make-pad i) "new ")
3679 (js2-print-ast (js2-new-node-target n))
3681 (js2-print-list (js2-new-node-args n))
3683 (when (js2-new-node-initializer n)
3685 (js2-print-ast (js2-new-node-initializer n))))
3687 (cl-defstruct (js2-name-node
3690 (:constructor make-js2-name-node (&key (type js2-NAME)
3691 (pos (js2-current-token-beg))
3692 (len (- js2-ts-cursor
3693 (js2-current-token-beg)))
3694 (name (js2-current-token-string)))))
3695 "AST node for a JavaScript identifier"
3697 scope) ; a `js2-scope' (optional, used for codegen)
3699 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3700 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3702 (defun js2-print-name-node (n i)
3703 (insert (js2-make-pad i)
3704 (js2-name-node-name n)))
3706 (defsubst js2-name-node-length (node)
3707 "Return identifier length of NODE, a `js2-name-node'.
3708 Returns 0 if NODE is nil or its identifier field is nil."
3710 (length (js2-name-node-name node))
3713 (cl-defstruct (js2-number-node
3716 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3717 (pos (js2-current-token-beg))
3718 (len (- js2-ts-cursor
3719 (js2-current-token-beg)))
3720 (value (js2-current-token-string))
3721 (num-value (js2-token-number
3722 (js2-current-token))))))
3723 "AST node for a number literal."
3724 value ; the original string, e.g. "6.02e23"
3725 num-value) ; the parsed number value
3727 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3728 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3730 (defun js2-print-number-node (n i)
3731 (insert (js2-make-pad i)
3732 (number-to-string (js2-number-node-num-value n))))
3734 (cl-defstruct (js2-regexp-node
3737 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3738 (pos (js2-current-token-beg))
3739 (len (- js2-ts-cursor
3740 (js2-current-token-beg)))
3742 "AST node for a regular expression literal."
3743 value ; the regexp string, without // delimiters
3744 flags) ; a string of flags, e.g. `mi'.
3746 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3747 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3749 (defun js2-print-regexp (n i)
3750 (insert (js2-make-pad i)
3752 (js2-regexp-node-value n)
3754 (if (js2-regexp-node-flags n)
3755 (insert (js2-regexp-node-flags n))))
3757 (cl-defstruct (js2-string-node
3760 (:constructor make-js2-string-node (&key (type js2-STRING)
3761 (pos (js2-current-token-beg))
3762 (len (- js2-ts-cursor
3763 (js2-current-token-beg)))
3764 (value (js2-current-token-string)))))
3766 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3767 You can tell the quote type by looking at the first character."
3768 value) ; the characters of the string, including the quotes
3770 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3771 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3773 (defun js2-print-string-node (n i)
3774 (insert (js2-make-pad i)
3775 (js2-node-string n)))
3777 (cl-defstruct (js2-template-node
3780 (:constructor make-js2-template-node (&key (type js2-TEMPLATE_HEAD)
3783 kids) ; `js2-string-node' is used for string segments, other nodes
3784 ; for substitutions inside.
3786 (put 'cl-struct-js2-template-node 'js2-visitor 'js2-visit-template)
3787 (put 'cl-struct-js2-template-node 'js2-printer 'js2-print-template)
3789 (defun js2-visit-template (n callback)
3790 (dolist (kid (js2-template-node-kids n))
3791 (js2-visit-ast kid callback)))
3793 (defun js2-print-template (n i)
3794 (insert (js2-make-pad i))
3795 (dolist (kid (js2-template-node-kids n))
3796 (if (js2-string-node-p kid)
3797 (insert (js2-node-string kid))
3798 (js2-print-ast kid))))
3800 (cl-defstruct (js2-tagged-template-node
3803 (:constructor make-js2-tagged-template-node (&key (type js2-TAGGED_TEMPLATE)
3804 beg len tag template)))
3805 "Tagged template literal."
3806 tag ; `js2-node' with the tag expression.
3807 template) ; `js2-template-node' with the template.
3809 (put 'cl-struct-js2-tagged-template-node 'js2-visitor 'js2-visit-tagged-template)
3810 (put 'cl-struct-js2-tagged-template-node 'js2-printer 'js2-print-tagged-template)
3812 (defun js2-visit-tagged-template (n callback)
3813 (js2-visit-ast (js2-tagged-template-node-tag n) callback)
3814 (js2-visit-ast (js2-tagged-template-node-template n) callback))
3816 (defun js2-print-tagged-template (n i)
3817 (insert (js2-make-pad i))
3818 (js2-print-ast (js2-tagged-template-node-tag n))
3819 (js2-print-ast (js2-tagged-template-node-template n)))
3821 (cl-defstruct (js2-array-node
3824 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3827 "AST node for an array literal."
3828 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3830 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3831 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3833 (defun js2-visit-array-node (n v)
3834 (dolist (e (js2-array-node-elems n))
3835 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3837 (defun js2-print-array-node (n i)
3838 (insert (js2-make-pad i) "[")
3839 (let ((elems (js2-array-node-elems n)))
3840 (js2-print-list elems)
3841 (when (and elems (null (car (last elems))))
3845 (cl-defstruct (js2-class-node
3848 (:constructor make-js2-class-node (&key (type js2-CLASS)
3850 (form 'CLASS_STATEMENT)
3852 extends len elems)))
3853 "AST node for an class expression.
3854 `elems' is a list of `js2-object-prop-node', and `extends' is an
3855 optional `js2-expr-node'"
3856 form ; CLASS_{STATEMENT|EXPRESSION}
3857 name ; class name (a `js2-node-name', or nil if anonymous)
3858 extends ; class heritage (a `js2-expr-node', or nil if none)
3861 (put 'cl-struct-js2-class-node 'js2-visitor 'js2-visit-class-node)
3862 (put 'cl-struct-js2-class-node 'js2-printer 'js2-print-class-node)
3864 (defun js2-visit-class-node (n v)
3865 (js2-visit-ast (js2-class-node-name n) v)
3866 (js2-visit-ast (js2-class-node-extends n) v)
3867 (dolist (e (js2-class-node-elems n))
3868 (js2-visit-ast e v)))
3870 (defun js2-print-class-node (n i)
3871 (let* ((pad (js2-make-pad i))
3872 (name (js2-class-node-name n))
3873 (extends (js2-class-node-extends n))
3874 (elems (js2-class-node-elems n)))
3875 (insert pad "class")
3878 (js2-print-ast name 0))
3880 (insert " extends ")
3881 (js2-print-ast extends))
3883 (dolist (elem elems)
3885 (if (js2-node-get-prop elem 'STATIC)
3886 (progn (insert (js2-make-pad (1+ i)) "static ")
3887 (js2-print-ast elem 0)) ;; TODO(sdh): indentation isn't quite right
3888 (js2-print-ast elem (1+ i))))
3889 (insert "\n" pad "}")))
3891 (cl-defstruct (js2-object-node
3894 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3898 "AST node for an object literal expression.
3899 `elems' is a list of `js2-object-prop-node'."
3902 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3903 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3905 (defun js2-visit-object-node (n v)
3906 (dolist (e (js2-object-node-elems n))
3907 (js2-visit-ast e v)))
3909 (defun js2-print-object-node (n i)
3910 (insert (js2-make-pad i) "{")
3911 (js2-print-list (js2-object-node-elems n))
3914 (cl-defstruct (js2-object-prop-node
3915 (:include js2-infix-node)
3917 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3921 "AST node for an object literal prop:value entry.
3922 The `left' field is the property: a name node, string node or number node.
3923 The `right' field is a `js2-node' representing the initializer value.
3924 If the property is abbreviated, the node's `SHORTHAND' property is non-nil
3925 and both fields have the same value.")
3927 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3928 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3930 (defun js2-print-object-prop-node (n i)
3931 (let* ((left (js2-object-prop-node-left n))
3932 (computed (not (or (js2-string-node-p left)
3933 (js2-number-node-p left)
3934 (js2-name-node-p left)))))
3935 (insert (js2-make-pad i))
3938 (js2-print-ast left 0)
3941 (if (not (js2-node-get-prop n 'SHORTHAND))
3944 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3946 (cl-defstruct (js2-getter-setter-node
3947 (:include js2-infix-node)
3949 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3952 "AST node for a getter/setter property in an object literal.
3953 The `left' field is the `js2-name-node' naming the getter/setter prop.
3954 The `right' field is always an anonymous `js2-function-node' with a node
3955 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3957 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3958 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3960 (defun js2-print-getter-setter (n i)
3961 (let ((pad (js2-make-pad i))
3962 (left (js2-getter-setter-node-left n))
3963 (right (js2-getter-setter-node-right n)))
3965 (if (/= (js2-node-type n) js2-FUNCTION)
3966 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3967 (js2-print-ast left 0)
3968 (js2-print-ast right 0)))
3970 (cl-defstruct (js2-prop-get-node
3971 (:include js2-infix-node)
3973 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3976 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3978 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3979 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3981 (defun js2-visit-prop-get-node (n v)
3982 (js2-visit-ast (js2-prop-get-node-left n) v)
3983 (js2-visit-ast (js2-prop-get-node-right n) v))
3985 (defun js2-print-prop-get-node (n i)
3986 (insert (js2-make-pad i))
3987 (js2-print-ast (js2-prop-get-node-left n) 0)
3989 (js2-print-ast (js2-prop-get-node-right n) 0))
3991 (cl-defstruct (js2-elem-get-node
3994 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3998 "AST node for an array index expression such as foo[bar]."
3999 target ; a `js2-node' - the expression preceding the "."
4000 element ; a `js2-node' - the expression in brackets
4001 lb ; position of left-bracket, nil if omitted
4002 rb) ; position of right-bracket, nil if omitted
4004 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
4005 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
4007 (defun js2-visit-elem-get-node (n v)
4008 (js2-visit-ast (js2-elem-get-node-target n) v)
4009 (js2-visit-ast (js2-elem-get-node-element n) v))
4011 (defun js2-print-elem-get-node (n i)
4012 (insert (js2-make-pad i))
4013 (js2-print-ast (js2-elem-get-node-target n) 0)
4015 (js2-print-ast (js2-elem-get-node-element n) 0)
4018 (cl-defstruct (js2-call-node
4021 (:constructor make-js2-call-node (&key (type js2-CALL)
4025 "AST node for a JavaScript function call."
4026 target ; a `js2-node' evaluating to the function to call
4027 args ; a Lisp list of `js2-node' arguments
4028 lp ; position of open-paren, or nil if missing
4029 rp) ; position of close-paren, or nil if missing
4031 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
4032 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
4034 (defun js2-visit-call-node (n v)
4035 (js2-visit-ast (js2-call-node-target n) v)
4036 (dolist (arg (js2-call-node-args n))
4037 (js2-visit-ast arg v)))
4039 (defun js2-print-call-node (n i)
4040 (insert (js2-make-pad i))
4041 (js2-print-ast (js2-call-node-target n) 0)
4043 (js2-print-list (js2-call-node-args n))
4046 (cl-defstruct (js2-yield-node
4049 (:constructor make-js2-yield-node (&key (type js2-YIELD)
4052 "AST node for yield statement or expression."
4053 star-p ; whether it's yield*
4054 value) ; optional: value to be yielded
4056 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
4057 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
4059 (defun js2-visit-yield-node (n v)
4060 (js2-visit-ast (js2-yield-node-value n) v))
4062 (defun js2-print-yield-node (n i)
4063 (insert (js2-make-pad i))
4065 (when (js2-yield-node-star-p n)
4067 (when (js2-yield-node-value n)
4069 (js2-print-ast (js2-yield-node-value n) 0)))
4071 (cl-defstruct (js2-paren-node
4074 (:constructor make-js2-paren-node (&key (type js2-LP)
4077 "AST node for a parenthesized expression.
4078 In particular, used when the parens are syntactically optional,
4079 as opposed to required parens such as those enclosing an if-conditional."
4082 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
4083 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
4085 (defun js2-visit-paren-node (n v)
4086 (js2-visit-ast (js2-paren-node-expr n) v))
4088 (defun js2-print-paren-node (n i)
4089 (insert (js2-make-pad i))
4091 (js2-print-ast (js2-paren-node-expr n) 0)
4094 (cl-defstruct (js2-comp-node
4095 (:include js2-scope)
4097 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
4102 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
4103 result ; result expression (just after left-bracket)
4104 loops ; a Lisp list of `js2-comp-loop-node'
4105 filters ; a Lisp list of guard/filter expressions
4106 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
4107 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
4110 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
4111 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
4113 (defun js2-visit-comp-node (n v)
4114 (js2-visit-ast (js2-comp-node-result n) v)
4115 (dolist (l (js2-comp-node-loops n))
4116 (js2-visit-ast l v))
4117 (dolist (f (js2-comp-node-filters n))
4118 (js2-visit-ast f v)))
4120 (defun js2-print-comp-node (n i)
4121 (let ((pad (js2-make-pad i))
4122 (result (js2-comp-node-result n))
4123 (loops (js2-comp-node-loops n))
4124 (filters (js2-comp-node-filters n))
4125 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
4126 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
4127 (insert pad (if gen-p "(" "["))
4129 (js2-print-ast result 0))
4145 (js2-print-ast result 0))
4146 (insert (if gen-p ")" "]"))))
4148 (cl-defstruct (js2-comp-loop-node
4149 (:include js2-for-in-node)
4151 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
4159 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
4161 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
4162 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
4164 (defun js2-visit-comp-loop (n v)
4165 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
4166 (js2-visit-ast (js2-comp-loop-node-object n) v))
4168 (defun js2-print-comp-loop (n _i)
4170 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
4172 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
4173 (insert (if (js2-comp-loop-node-forof-p n)
4175 (js2-print-ast (js2-comp-loop-node-object n) 0)
4178 (cl-defstruct (js2-empty-expr-node
4181 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
4182 (pos (js2-current-token-beg))
4184 "AST node for an empty expression.")
4186 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
4187 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
4189 (cl-defstruct (js2-xml-node
4190 (:include js2-block-node)
4192 (:constructor make-js2-xml-node (&key (type js2-XML)
4193 (pos (js2-current-token-beg))
4195 "AST node for initial parse of E4X literals.
4196 The kids field is a list of XML fragments, each a `js2-string-node' or
4197 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
4199 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
4200 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
4202 (defun js2-print-xml-node (n i)
4203 (dolist (kid (js2-xml-node-kids n))
4204 (js2-print-ast kid i)))
4206 (cl-defstruct (js2-xml-js-expr-node
4207 (:include js2-xml-node)
4209 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
4212 "AST node for an embedded JavaScript {expression} in an E4X literal.
4213 The start and end fields correspond to the curly-braces."
4214 expr) ; a `js2-expr-node' of some sort
4216 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
4217 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
4219 (defun js2-visit-xml-js-expr (n v)
4220 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
4222 (defun js2-print-xml-js-expr (n i)
4223 (insert (js2-make-pad i))
4225 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
4228 (cl-defstruct (js2-xml-dot-query-node
4229 (:include js2-infix-node)
4231 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
4235 "AST node for an E4X foo.(bar) filter expression.
4236 Note that the left-paren is automatically the character immediately
4237 following the dot (.) in the operator. No whitespace is permitted
4238 between the dot and the lp by the scanner."
4241 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
4242 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
4244 (defun js2-print-xml-dot-query (n i)
4245 (insert (js2-make-pad i))
4246 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
4248 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
4251 (cl-defstruct (js2-xml-ref-node
4253 (:constructor nil)) ; abstract
4254 "Base type for E4X XML attribute-access or property-get expressions.
4255 Such expressions can take a variety of forms. The general syntax has
4258 - (optional) an @ (specifying an attribute access)
4259 - (optional) a namespace (a `js2-name-node') and double-colon
4260 - (required) either a `js2-name-node' or a bracketed [expression]
4262 The property-name expressions (examples: ns::name, @name) are
4263 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
4264 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
4266 This node type (or more specifically, its subclasses) will sometimes
4267 be the right-hand child of a `js2-prop-get-node' or a
4268 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
4269 The `js2-xml-ref-node' may also be a standalone primary expression with
4270 no explicit target, which is valid in certain expression contexts such as
4272 company..employee.(@id < 100)
4274 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
4275 expression whose parent is a `js2-xml-dot-query-node'."
4280 (defsubst js2-xml-ref-node-attr-access-p (node)
4281 "Return non-nil if this expression began with an @-token."
4282 (and (numberp (js2-xml-ref-node-at-pos node))
4283 (cl-plusp (js2-xml-ref-node-at-pos node))))
4285 (cl-defstruct (js2-xml-prop-ref-node
4286 (:include js2-xml-ref-node)
4288 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
4289 (pos (js2-current-token-beg))
4293 "AST node for an E4X XML [expr] property-ref expression.
4294 The JavaScript syntax is an optional @, an optional ns::, and a name.
4296 [ '@' ] [ name '::' ] name
4298 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
4299 @ns::*, @*::attr, @*::*, and @*.
4301 The node starts at the @ token, if present. Otherwise it starts at the
4302 namespace name. The node bounds extend through the closing right-bracket,
4303 or if it is missing due to a syntax error, through the end of the index
4307 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
4308 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
4310 (defun js2-visit-xml-prop-ref-node (n v)
4311 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
4312 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
4314 (defun js2-print-xml-prop-ref-node (n i)
4315 (insert (js2-make-pad i))
4316 (if (js2-xml-ref-node-attr-access-p n)
4318 (when (js2-xml-prop-ref-node-namespace n)
4319 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
4321 (if (js2-xml-prop-ref-node-propname n)
4322 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
4324 (cl-defstruct (js2-xml-elem-ref-node
4325 (:include js2-xml-ref-node)
4327 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
4328 (pos (js2-current-token-beg))
4332 "AST node for an E4X XML [expr] member-ref expression.
4335 [ '@' ] [ name '::' ] '[' expr ']'
4337 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
4339 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
4340 is not a legal E4X XML element-ref expression, since it's already used
4341 for standard JavaScript element-get array indexing. Hence, a
4342 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4343 non-nil namespace node, or both.
4345 The node starts at the @ token, if present. Otherwise it starts
4346 at the namespace name. The node bounds extend through the closing
4347 right-bracket, or if it is missing due to a syntax error, through the
4348 end of the index expression."
4349 expr ; the bracketed index expression
4353 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4354 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4356 (defun js2-visit-xml-elem-ref-node (n v)
4357 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4358 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4360 (defun js2-print-xml-elem-ref-node (n i)
4361 (insert (js2-make-pad i))
4362 (if (js2-xml-ref-node-attr-access-p n)
4364 (when (js2-xml-elem-ref-node-namespace n)
4365 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4368 (if (js2-xml-elem-ref-node-expr n)
4369 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4372 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4374 (cl-defstruct (js2-xml-start-tag-node
4375 (:include js2-xml-node)
4377 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4381 "AST node for an XML start-tag. Not currently used.
4382 The `kids' field is a Lisp list of child content nodes."
4383 name ; a `js2-xml-name-node'
4384 attrs ; a Lisp list of `js2-xml-attr-node'
4385 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4387 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4388 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4390 (defun js2-visit-xml-start-tag (n v)
4391 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4392 (dolist (attr (js2-xml-start-tag-node-attrs n))
4393 (js2-visit-ast attr v))
4394 (js2-visit-block n v))
4396 (defun js2-print-xml-start-tag (n i)
4397 (insert (js2-make-pad i) "<")
4398 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4399 (when (js2-xml-start-tag-node-attrs n)
4401 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4404 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4405 ;; and add the end-tag to the kids list of the parent as well.
4406 (cl-defstruct (js2-xml-end-tag-node
4407 (:include js2-xml-node)
4409 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4412 "AST node for an XML end-tag. Not currently used."
4413 name) ; a `js2-xml-name-node'
4415 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4416 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4418 (defun js2-visit-xml-end-tag (n v)
4419 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4421 (defun js2-print-xml-end-tag (n i)
4422 (insert (js2-make-pad i))
4424 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4427 (cl-defstruct (js2-xml-name-node
4428 (:include js2-xml-node)
4430 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4432 len namespace kids)))
4433 "AST node for an E4X XML name. Not currently used.
4434 Any XML name can be qualified with a namespace, hence the namespace field.
4435 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4436 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4437 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4438 namespace) ; a `js2-string-node'
4440 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4441 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4443 (defun js2-visit-xml-name-node (n v)
4444 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4446 (defun js2-print-xml-name-node (n i)
4447 (insert (js2-make-pad i))
4448 (when (js2-xml-name-node-namespace n)
4449 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4451 (dolist (kid (js2-xml-name-node-kids n))
4452 (js2-print-ast kid 0)))
4454 (cl-defstruct (js2-xml-pi-node
4455 (:include js2-xml-node)
4457 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4460 "AST node for an E4X XML processing instruction. Not currently used."
4461 name ; a `js2-xml-name-node'
4462 attrs) ; a list of `js2-xml-attr-node'
4464 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4465 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4467 (defun js2-visit-xml-pi-node (n v)
4468 (js2-visit-ast (js2-xml-pi-node-name n) v)
4469 (dolist (attr (js2-xml-pi-node-attrs n))
4470 (js2-visit-ast attr v)))
4472 (defun js2-print-xml-pi-node (n i)
4473 (insert (js2-make-pad i) "<?")
4474 (js2-print-ast (js2-xml-pi-node-name n))
4475 (when (js2-xml-pi-node-attrs n)
4477 (js2-print-list (js2-xml-pi-node-attrs n)))
4480 (cl-defstruct (js2-xml-cdata-node
4481 (:include js2-xml-node)
4483 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4486 "AST node for a CDATA escape section. Not currently used."
4487 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4489 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4490 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4492 (defun js2-visit-xml-cdata-node (n v)
4493 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4495 (defun js2-print-xml-cdata-node (n i)
4496 (insert (js2-make-pad i))
4497 (js2-print-ast (js2-xml-cdata-node-content n)))
4499 (cl-defstruct (js2-xml-attr-node
4500 (:include js2-xml-node)
4502 (:constructor make-js2-attr-node (&key (type js2-XML)
4505 eq-pos quote-type)))
4506 "AST node representing a foo='bar' XML attribute value. Not yet used."
4507 name ; a `js2-xml-name-node'
4508 value ; a `js2-xml-name-node'
4509 eq-pos ; buffer position of "=" sign
4510 quote-type) ; 'single or 'double
4512 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4513 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4515 (defun js2-visit-xml-attr-node (n v)
4516 (js2-visit-ast (js2-xml-attr-node-name n) v)
4517 (js2-visit-ast (js2-xml-attr-node-value n) v))
4519 (defun js2-print-xml-attr-node (n i)
4520 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4523 (insert (js2-make-pad i))
4524 (js2-print-ast (js2-xml-attr-node-name n) 0)
4526 (js2-print-ast (js2-xml-attr-node-value n) 0)
4529 (cl-defstruct (js2-xml-text-node
4530 (:include js2-xml-node)
4532 (:constructor make-js2-text-node (&key (type js2-XML)
4535 "AST node for an E4X XML text node. Not currently used."
4536 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4538 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4539 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4541 (defun js2-visit-xml-text-node (n v)
4542 (js2-visit-ast (js2-xml-text-node-content n) v))
4544 (defun js2-print-xml-text-node (n i)
4545 (insert (js2-make-pad i))
4546 (dolist (kid (js2-xml-text-node-content n))
4547 (js2-print-ast kid)))
4549 (cl-defstruct (js2-xml-comment-node
4550 (:include js2-xml-node)
4552 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4555 "AST node for E4X XML comment. Not currently used.")
4557 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4558 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4560 (defun js2-print-xml-comment (n i)
4561 (insert (js2-make-pad i)
4562 (js2-node-string n)))
4566 (defsubst js2-node-line (n)
4567 "Fetch the source line number at the start of node N.
4568 This is O(n) in the length of the source buffer; use prudently."
4569 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4571 (defsubst js2-block-node-kid (n i)
4572 "Return child I of node N, or nil if there aren't that many."
4573 (nth i (js2-block-node-kids n)))
4575 (defsubst js2-block-node-first (n)
4576 "Return first child of block node N, or nil if there is none."
4577 (cl-first (js2-block-node-kids n)))
4579 (defun js2-node-root (n)
4580 "Return the root of the AST containing N.
4581 If N has no parent pointer, returns N."
4582 (let ((parent (js2-node-parent n)))
4584 (js2-node-root parent)
4587 (defsubst js2-node-short-name (n)
4588 "Return the short name of node N as a string, e.g. `js2-if-node'."
4589 (substring (symbol-name (aref n 0))
4590 (length "cl-struct-")))
4592 (defun js2-node-child-list (node)
4593 "Return the child list for NODE, a Lisp list of nodes.
4594 Works for block nodes, array nodes, obj literals, funarg lists,
4595 var decls and try nodes (for catch clauses). Note that you should call
4596 `js2-block-node-kids' on the function body for the body statements.
4597 Returns nil for zero-length child lists or unsupported nodes."
4599 ((js2-function-node-p node)
4600 (js2-function-node-params node))
4601 ((js2-block-node-p node)
4602 (js2-block-node-kids node))
4603 ((js2-try-node-p node)
4604 (js2-try-node-catch-clauses node))
4605 ((js2-array-node-p node)
4606 (js2-array-node-elems node))
4607 ((js2-object-node-p node)
4608 (js2-object-node-elems node))
4609 ((js2-call-node-p node)
4610 (js2-call-node-args node))
4611 ((js2-new-node-p node)
4612 (js2-new-node-args node))
4613 ((js2-var-decl-node-p node)
4614 (js2-var-decl-node-kids node))
4618 (defun js2-node-set-child-list (node kids)
4619 "Set the child list for NODE to KIDS."
4621 ((js2-function-node-p node)
4622 (setf (js2-function-node-params node) kids))
4623 ((js2-block-node-p node)
4624 (setf (js2-block-node-kids node) kids))
4625 ((js2-try-node-p node)
4626 (setf (js2-try-node-catch-clauses node) kids))
4627 ((js2-array-node-p node)
4628 (setf (js2-array-node-elems node) kids))
4629 ((js2-object-node-p node)
4630 (setf (js2-object-node-elems node) kids))
4631 ((js2-call-node-p node)
4632 (setf (js2-call-node-args node) kids))
4633 ((js2-new-node-p node)
4634 (setf (js2-new-node-args node) kids))
4635 ((js2-var-decl-node-p node)
4636 (setf (js2-var-decl-node-kids node) kids))
4638 (error "Unsupported node type: %s" (js2-node-short-name node))))
4641 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4642 (defconst js2-paren-expr-nodes
4643 '(cl-struct-js2-comp-loop-node
4644 cl-struct-js2-comp-node
4645 cl-struct-js2-call-node
4646 cl-struct-js2-catch-node
4647 cl-struct-js2-do-node
4648 cl-struct-js2-elem-get-node
4649 cl-struct-js2-for-in-node
4650 cl-struct-js2-for-node
4651 cl-struct-js2-function-node
4652 cl-struct-js2-if-node
4653 cl-struct-js2-let-node
4654 cl-struct-js2-new-node
4655 cl-struct-js2-paren-node
4656 cl-struct-js2-switch-node
4657 cl-struct-js2-while-node
4658 cl-struct-js2-with-node
4659 cl-struct-js2-xml-dot-query-node)
4660 "Node types that can have a parenthesized child expression.
4661 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4663 (defsubst js2-paren-expr-node-p (node)
4664 "Return t for nodes that typically have a parenthesized child expression.
4665 Useful for computing the indentation anchors for arg-lists and conditions.
4666 Note that it may return a false positive, for instance when NODE is
4667 a `js2-new-node' and there are no arguments or parentheses."
4668 (memq (aref node 0) js2-paren-expr-nodes))
4670 ;; Fake polymorphism... yech.
4671 (defun js2-node-lp (node)
4672 "Return relative left-paren position for NODE, if applicable.
4673 For `js2-elem-get-node' structs, returns left-bracket position.
4674 Note that the position may be nil in the case of a parse error."
4676 ((js2-elem-get-node-p node)
4677 (js2-elem-get-node-lb node))
4678 ((js2-loop-node-p node)
4679 (js2-loop-node-lp node))
4680 ((js2-function-node-p node)
4681 (js2-function-node-lp node))
4682 ((js2-if-node-p node)
4683 (js2-if-node-lp node))
4684 ((js2-new-node-p node)
4685 (js2-new-node-lp node))
4686 ((js2-call-node-p node)
4687 (js2-call-node-lp node))
4688 ((js2-paren-node-p node)
4690 ((js2-switch-node-p node)
4691 (js2-switch-node-lp node))
4692 ((js2-catch-node-p node)
4693 (js2-catch-node-lp node))
4694 ((js2-let-node-p node)
4695 (js2-let-node-lp node))
4696 ((js2-comp-node-p node)
4698 ((js2-with-node-p node)
4699 (js2-with-node-lp node))
4700 ((js2-xml-dot-query-node-p node)
4701 (1+ (js2-infix-node-op-pos node)))
4703 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4705 ;; Fake polymorphism... blech.
4706 (defun js2-node-rp (node)
4707 "Return relative right-paren position for NODE, if applicable.
4708 For `js2-elem-get-node' structs, returns right-bracket position.
4709 Note that the position may be nil in the case of a parse error."
4711 ((js2-elem-get-node-p node)
4712 (js2-elem-get-node-rb node))
4713 ((js2-loop-node-p node)
4714 (js2-loop-node-rp node))
4715 ((js2-function-node-p node)
4716 (js2-function-node-rp node))
4717 ((js2-if-node-p node)
4718 (js2-if-node-rp node))
4719 ((js2-new-node-p node)
4720 (js2-new-node-rp node))
4721 ((js2-call-node-p node)
4722 (js2-call-node-rp node))
4723 ((js2-paren-node-p node)
4724 (1- (js2-node-len node)))
4725 ((js2-switch-node-p node)
4726 (js2-switch-node-rp node))
4727 ((js2-catch-node-p node)
4728 (js2-catch-node-rp node))
4729 ((js2-let-node-p node)
4730 (js2-let-node-rp node))
4731 ((js2-comp-node-p node)
4732 (1- (js2-node-len node)))
4733 ((js2-with-node-p node)
4734 (js2-with-node-rp node))
4735 ((js2-xml-dot-query-node-p node)
4736 (1+ (js2-xml-dot-query-node-rp node)))
4738 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4740 (defsubst js2-node-first-child (node)
4741 "Return the first element of `js2-node-child-list' for NODE."
4742 (car (js2-node-child-list node)))
4744 (defsubst js2-node-last-child (node)
4745 "Return the last element of `js2-node-last-child' for NODE."
4746 (car (last (js2-node-child-list node))))
4748 (defun js2-node-prev-sibling (node)
4749 "Return the previous statement in parent.
4750 Works for parents supported by `js2-node-child-list'.
4751 Returns nil if NODE is not in the parent, or PARENT is
4752 not a supported node, or if NODE is the first child."
4753 (let* ((p (js2-node-parent node))
4754 (kids (js2-node-child-list p))
4757 (not (eq node (cadr kids))))
4758 (setq kids (cdr kids)
4762 (defun js2-node-next-sibling (node)
4763 "Return the next statement in parent block.
4764 Returns nil if NODE is not in the block, or PARENT is not
4765 a block node, or if NODE is the last statement."
4766 (let* ((p (js2-node-parent node))
4767 (kids (js2-node-child-list p)))
4769 (not (eq node (car kids))))
4770 (setq kids (cdr kids)))
4773 (defun js2-node-find-child-before (pos parent &optional after)
4774 "Find the last child that starts before POS in parent.
4775 If AFTER is non-nil, returns first child starting after POS.
4776 POS is an absolute buffer position. PARENT is any node
4777 supported by `js2-node-child-list'.
4778 Returns nil if no applicable child is found."
4779 (let ((kids (if (js2-function-node-p parent)
4780 (js2-block-node-kids (js2-function-node-body parent))
4781 (js2-node-child-list parent)))
4782 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4783 (js2-function-node-body parent)
4787 (setq fn (if after '>= '<))
4788 (while (and kids continue)
4789 (setq kid (car kids))
4790 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4792 continue (not after))
4793 (setq continue after))
4794 (setq kids (cdr kids)))
4797 (defun js2-node-find-child-after (pos parent)
4798 "Find first child that starts after POS in parent.
4799 POS is an absolute buffer position. PARENT is any node
4800 supported by `js2-node-child-list'.
4801 Returns nil if no applicable child is found."
4802 (js2-node-find-child-before pos parent 'after))
4804 (defun js2-node-replace-child (pos parent new-node)
4805 "Replace node at index POS in PARENT with NEW-NODE.
4806 Only works for parents supported by `js2-node-child-list'."
4807 (let ((kids (js2-node-child-list parent))
4810 (setq kids (cdr kids)
4812 (setcar kids new-node)
4813 (js2-node-add-children parent new-node)))
4815 (defun js2-node-buffer (n)
4816 "Return the buffer associated with AST N.
4817 Returns nil if the buffer is not set as a property on the root
4818 node, or if parent links were not recorded during parsing."
4819 (let ((root (js2-node-root n)))
4821 (js2-ast-root-p root)
4822 (js2-ast-root-buffer root))))
4824 (defun js2-block-node-push (n kid)
4825 "Push js2-node KID onto the end of js2-block-node N's child list.
4826 KID is always added to the -end- of the kids list.
4827 Function also calls `js2-node-add-children' to add the parent link."
4828 (let ((kids (js2-node-child-list n)))
4830 (setcdr kids (nconc (cdr kids) (list kid)))
4831 (js2-node-set-child-list n (list kid)))
4832 (js2-node-add-children n kid)))
4834 (defun js2-node-string (node)
4835 (with-current-buffer (or (js2-node-buffer node)
4836 (error "No buffer available for node %s" node))
4837 (let ((pos (js2-node-abs-pos node)))
4838 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4840 ;; Container for storing the node we're looking for in a traversal.
4841 (js2-deflocal js2-discovered-node nil)
4843 ;; Keep track of absolute node position during traversals.
4844 (js2-deflocal js2-visitor-offset nil)
4846 (js2-deflocal js2-node-search-point nil)
4848 (when js2-mode-dev-mode-p
4849 (defun js2-find-node-at-point ()
4851 (let ((node (js2-node-at-point)))
4852 (message "%s" (or node "No node found at point"))))
4853 (defun js2-node-name-at-point ()
4855 (let ((node (js2-node-at-point)))
4856 (message "%s" (if node
4857 (js2-node-short-name node)
4858 "No node found at point.")))))
4860 (defun js2-node-at-point (&optional pos skip-comments)
4861 "Return AST node at POS, a buffer position, defaulting to current point.
4862 The `js2-mode-ast' variable must be set to the current parse tree.
4863 Signals an error if the AST (`js2-mode-ast') is nil.
4864 Always returns a node - if it can't find one, it returns the root.
4865 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4866 (let ((ast js2-mode-ast)
4869 (error "No JavaScript AST available"))
4870 ;; Look through comments first, since they may be inside nodes that
4871 ;; would otherwise report a match.
4872 (setq pos (or pos (point))
4873 result (if (> pos (js2-node-abs-end ast))
4875 (if (not skip-comments)
4876 (js2-comment-at-point pos))))
4878 (setq js2-discovered-node nil
4879 js2-visitor-offset 0
4880 js2-node-search-point pos)
4882 (catch 'js2-visit-done
4883 (js2-visit-ast ast #'js2-node-at-point-visitor))
4884 (setq js2-visitor-offset nil
4885 js2-node-search-point nil))
4886 (setq result js2-discovered-node))
4887 ;; may have found a comment beyond end of last child node,
4888 ;; since visiting the ast-root looks at the comment-list last.
4889 (if (and skip-comments
4890 (js2-comment-node-p result))
4892 (or result js2-mode-ast)))
4894 (defun js2-node-at-point-visitor (node end-p)
4895 (let ((rel-pos (js2-node-pos node))
4898 (point js2-node-search-point))
4901 ;; this evaluates to a non-nil return value, even if it's zero
4902 (cl-decf js2-visitor-offset rel-pos))
4903 ;; we already looked for comments before visiting, and don't want them now
4904 ((js2-comment-node-p node)
4907 (setq abs-pos (cl-incf js2-visitor-offset rel-pos)
4908 ;; we only want to use the node if the point is before
4909 ;; the last character position in the node, so we decrement
4910 ;; the absolute end by 1.
4911 abs-end (+ abs-pos (js2-node-len node) -1))
4913 ;; If this node starts after search-point, stop the search.
4915 (throw 'js2-visit-done nil))
4916 ;; If this node ends before the search-point, don't check kids.
4920 ;; Otherwise point is within this node, possibly in a child.
4921 (setq js2-discovered-node node)
4922 t)))))) ; keep processing kids to look for more specific match
4924 (defsubst js2-block-comment-p (node)
4925 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4926 (and (js2-comment-node-p node)
4927 (memq (js2-comment-node-format node) '(jsdoc block))))
4929 ;; TODO: put the comments in a vector and binary-search them instead
4930 (defun js2-comment-at-point (&optional pos)
4931 "Look through scanned comment nodes for one containing POS.
4932 POS is a buffer position that defaults to current point.
4933 Function returns nil if POS was not in any comment node."
4934 (let ((ast js2-mode-ast)
4935 (x (or pos (point)))
4938 (error "No JavaScript AST available"))
4940 ;; Comments are stored in lexical order.
4941 (dolist (comment (js2-ast-root-comments ast) nil)
4942 (setq beg (js2-node-abs-pos comment)
4943 end (+ beg (js2-node-len comment)))
4946 (throw 'done comment))))))
4948 (defun js2-mode-find-parent-fn (node)
4949 "Find function enclosing NODE.
4950 Returns nil if NODE is not inside a function."
4951 (setq node (js2-node-parent node))
4952 (while (and node (not (js2-function-node-p node)))
4953 (setq node (js2-node-parent node)))
4954 (and (js2-function-node-p node) node))
4956 (defun js2-mode-find-enclosing-fn (node)
4957 "Find function or root enclosing NODE."
4958 (if (js2-ast-root-p node)
4960 (setq node (js2-node-parent node))
4961 (while (not (or (js2-ast-root-p node)
4962 (js2-function-node-p node)))
4963 (setq node (js2-node-parent node)))
4966 (defun js2-mode-find-enclosing-node (beg end)
4967 "Find node fully enclosing BEG and END."
4968 (let ((node (js2-node-at-point beg))
4972 (if (or (js2-ast-root-p node)
4974 (<= (setq pos (js2-node-abs-pos node)) beg)
4975 (>= (+ pos (js2-node-len node)) end)))
4977 (setq node (js2-node-parent node))))
4980 (defun js2-node-parent-script-or-fn (node)
4981 "Find script or function immediately enclosing NODE.
4982 If NODE is the ast-root, returns nil."
4983 (if (js2-ast-root-p node)
4985 (setq node (js2-node-parent node))
4986 (while (and node (not (or (js2-function-node-p node)
4987 (js2-script-node-p node))))
4988 (setq node (js2-node-parent node)))
4991 (defun js2-node-is-descendant (node ancestor)
4992 "Return t if NODE is a descendant of ANCESTOR."
4994 (not (eq node ancestor)))
4995 (setq node (js2-node-parent node)))
4998 ;;; visitor infrastructure
5000 (defun js2-visit-none (_node _callback)
5001 "Visitor for AST node that have no node children."
5004 (defun js2-print-none (_node _indent)
5005 "Visitor for AST node with no printed representation.")
5007 (defun js2-print-body (node indent)
5008 "Print a statement, or a block without braces."
5009 (if (js2-block-node-p node)
5010 (dolist (kid (js2-block-node-kids node))
5011 (js2-print-ast kid indent))
5012 (js2-print-ast node indent)))
5014 (defun js2-print-list (args &optional delimiter)
5015 (cl-loop with len = (length args)
5019 (when arg (js2-print-ast arg 0))
5021 (insert (or delimiter ", ")))))
5023 (defun js2-print-tree (ast)
5024 "Prints an AST to the current buffer.
5025 Makes `js2-ast-parent-nodes' available to the printer functions."
5026 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
5027 (js2-print-ast ast)))
5029 (defun js2-print-ast (node &optional indent)
5030 "Helper function for printing AST nodes.
5031 Requires `js2-ast-parent-nodes' to be non-nil.
5032 You should use `js2-print-tree' instead of this function."
5033 (let ((printer (get (aref node 0) 'js2-printer))
5035 ;; TODO: wedge comments in here somewhere
5037 (funcall printer node i))))
5039 (defconst js2-side-effecting-tokens
5040 (let ((tokens (make-bool-vector js2-num-tokens nil)))
5041 (dolist (tt (list js2-ASSIGN
5111 (if js2-instanceof-has-side-effects
5112 (aset tokens js2-INSTANCEOF t))
5115 (defun js2-node-has-side-effects (node)
5116 "Return t if NODE has side effects."
5117 (when node ; makes it easier to handle malformed expressions
5118 (let ((tt (js2-node-type node)))
5120 ;; This doubtless needs some work, since EXPR_VOID is used
5121 ;; in several ways in Rhino and I may not have caught them all.
5122 ;; I'll wait for people to notice incorrect warnings.
5123 ((and (= tt js2-EXPR_VOID)
5124 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
5125 (let ((expr (js2-expr-stmt-node-expr node)))
5126 (or (js2-node-has-side-effects expr)
5127 (when (js2-string-node-p expr)
5128 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
5130 (js2-node-has-side-effects (js2-infix-node-right node)))
5133 (or (js2-node-has-side-effects (js2-infix-node-right node))
5134 (js2-node-has-side-effects (js2-infix-node-left node))))
5136 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
5137 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
5138 ((js2-paren-node-p node)
5139 (js2-node-has-side-effects (js2-paren-node-expr node)))
5140 ((= tt js2-ERROR) ; avoid cascaded error messages
5143 (aref js2-side-effecting-tokens tt))))))
5145 (defconst js2-stmt-node-types
5149 js2-DEFAULT ; e4x "default xml namespace" statement
5163 "Node types that only appear in statement contexts.
5164 The list does not include nodes that always appear as the child
5165 of another specific statement type, such as switch-cases,
5166 catch and finally blocks, and else-clauses. The list also excludes
5167 nodes like yield, let and var, which may appear in either expression
5168 or statement context, and in the latter context always have a
5169 `js2-expr-stmt-node' parent. Finally, the list does not include
5170 functions or scripts, which are treated separately from statements
5171 by the JavaScript parser and runtime.")
5173 (defun js2-stmt-node-p (node)
5174 "Heuristic for figuring out if NODE is a statement.
5175 Some node types can appear in either an expression context or a
5176 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
5177 For these node types in a statement context, the parent will be a
5178 `js2-expr-stmt-node'.
5179 Functions aren't included in the check."
5180 (memq (js2-node-type node) js2-stmt-node-types))
5182 (defun js2-mode-find-first-stmt (node)
5183 "Search upward starting from NODE looking for a statement.
5184 For purposes of this function, a `js2-function-node' counts."
5185 (while (not (or (js2-stmt-node-p node)
5186 (js2-function-node-p node)))
5187 (setq node (js2-node-parent node)))
5190 (defun js2-node-parent-stmt (node)
5191 "Return the node's first ancestor that is a statement.
5192 Returns nil if NODE is a `js2-ast-root'. Note that any expression
5193 appearing in a statement context will have a parent that is a
5194 `js2-expr-stmt-node' that will be returned by this function."
5195 (let ((parent (js2-node-parent node)))
5196 (if (or (null parent)
5197 (js2-stmt-node-p parent)
5198 (and (js2-function-node-p parent)
5199 (not (eq (js2-function-node-form parent)
5200 'FUNCTION_EXPRESSION))))
5202 (js2-node-parent-stmt parent))))
5204 ;; In the Mozilla Rhino sources, Roshan James writes:
5205 ;; Does consistent-return analysis on the function body when strict mode is
5208 ;; function (x) { return (x+1) }
5212 ;; function (x) { if (x < 0) return (x+1); }
5214 ;; is not because the function can potentially return a value when the
5215 ;; condition is satisfied and if not, the function does not explicitly
5218 ;; This extends to checking mismatches such as "return" and "return <value>"
5219 ;; used in the same function. Warnings are not emitted if inconsistent
5220 ;; returns exist in code that can be statically shown to be unreachable.
5222 ;; function (x) { while (true) { ... if (..) { return value } ... } }
5224 ;; emits no warning. However if the loop had a break statement, then a
5225 ;; warning would be emitted.
5227 ;; The consistency analysis looks at control structures such as loops, ifs,
5228 ;; switch, try-catch-finally blocks, examines the reachable code paths and
5229 ;; warns the user about an inconsistent set of termination possibilities.
5231 ;; These flags enumerate the possible ways a statement/function can
5232 ;; terminate. These flags are used by endCheck() and by the Parser to
5233 ;; detect inconsistent return usage.
5235 ;; END_UNREACHED is reserved for code paths that are assumed to always be
5236 ;; able to execute (example: throw, continue)
5238 ;; END_DROPS_OFF indicates if the statement can transfer control to the
5239 ;; next one. Statement such as return dont. A compound statement may have
5240 ;; some branch that drops off control to the next statement.
5242 ;; END_RETURNS indicates that the statement can return with no value.
5243 ;; END_RETURNS_VALUE indicates that the statement can return a value.
5245 ;; A compound statement such as
5249 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
5251 (defconst js2-END_UNREACHED 0)
5252 (defconst js2-END_DROPS_OFF 1)
5253 (defconst js2-END_RETURNS 2)
5254 (defconst js2-END_RETURNS_VALUE 4)
5255 (defconst js2-END_YIELDS 8)
5257 (defun js2-has-consistent-return-usage (node)
5258 "Check that every return usage in a function body is consistent.
5259 Returns t if the function satisfies strict mode requirement."
5260 (let ((n (js2-end-check node)))
5261 ;; either it doesn't return a value in any branch...
5262 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
5263 ;; or it returns a value (or is unreached) at every branch
5264 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5268 (defun js2-end-check-if (node)
5269 "Ensure that return usage in then/else blocks is consistent.
5270 If there is no else block, then the return statement can fall through.
5271 Returns logical OR of END_* flags"
5272 (let ((th (js2-if-node-then-part node))
5273 (el (js2-if-node-else-part node)))
5276 (logior (js2-end-check th) (if el
5278 js2-END_DROPS_OFF)))))
5280 (defun js2-end-check-switch (node)
5281 "Consistency of return statements is checked between the case statements.
5282 If there is no default, then the switch can fall through. If there is a
5283 default, we check to see if all code paths in the default return or if
5284 there is a code path that can fall through.
5285 Returns logical OR of END_* flags."
5286 (let ((rv js2-END_UNREACHED)
5288 ;; examine the cases
5290 (dolist (c (js2-switch-node-cases node))
5291 (if (js2-case-node-expr c)
5292 (js2-set-flag rv (js2-end-check-block c))
5293 (setq default-case c)
5294 (throw 'break nil))))
5295 ;; we don't care how the cases drop into each other
5296 (js2-clear-flag rv js2-END_DROPS_OFF)
5297 ;; examine the default
5298 (js2-set-flag rv (if default-case
5299 (js2-end-check default-case)
5303 (defun js2-end-check-try (node)
5304 "If the block has a finally, return consistency is checked in the
5305 finally block. If all code paths in the finally return, then the
5306 returns in the try-catch blocks don't matter. If there is a code path
5307 that does not return or if there is no finally block, the returns
5308 of the try and catch blocks are checked for mismatch.
5309 Returns logical OR of END_* flags."
5310 (let ((finally (js2-try-node-finally-block node))
5312 ;; check the finally if it exists
5313 (setq rv (if finally
5314 (js2-end-check (js2-finally-node-body finally))
5316 ;; If the finally block always returns, then none of the returns
5317 ;; in the try or catch blocks matter.
5318 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5319 (js2-clear-flag rv js2-END_DROPS_OFF)
5320 ;; examine the try block
5321 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5322 ;; check each catch block
5323 (dolist (cb (js2-try-node-catch-clauses node))
5324 (js2-set-flag rv (js2-end-check cb))))
5327 (defun js2-end-check-loop (node)
5328 "Return statement in the loop body must be consistent.
5329 The default assumption for any kind of a loop is that it will eventually
5330 terminate. The only exception is a loop with a constant true condition.
5331 Code that follows such a loop is examined only if one can determine
5332 statically that there is a break out of the loop.
5334 for(... ; ... ; ...) {}
5339 Returns logical OR of END_* flags."
5340 (let ((rv (js2-end-check (js2-loop-node-body node)))
5342 ((js2-while-node-p node)
5343 (js2-while-node-condition node))
5344 ((js2-do-node-p node)
5345 (js2-do-node-condition node))
5346 ((js2-for-node-p node)
5347 (js2-for-node-condition node)))))
5349 ;; check to see if the loop condition is always true
5351 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5352 (js2-clear-flag rv js2-END_DROPS_OFF))
5354 ;; look for effect of breaks
5355 (js2-set-flag rv (js2-node-get-prop node
5360 (defun js2-end-check-block (node)
5361 "A general block of code is examined statement by statement.
5362 If any statement (even a compound one) returns in all branches, then
5363 subsequent statements are not examined.
5364 Returns logical OR of END_* flags."
5365 (let* ((rv js2-END_DROPS_OFF)
5366 (kids (js2-block-node-kids node))
5368 ;; Check each statement. If the statement can continue onto the next
5369 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5370 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5371 (js2-clear-flag rv js2-END_DROPS_OFF)
5372 (js2-set-flag rv (js2-end-check n))
5373 (setq kids (cdr kids)
5377 (defun js2-end-check-label (node)
5378 "A labeled statement implies that there may be a break to the label.
5379 The function processes the labeled statement and then checks the
5380 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5382 Returns logical OR of END_* flags."
5383 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5384 (logior rv (js2-node-get-prop node
5386 js2-END_UNREACHED))))
5388 (defun js2-end-check-break (node)
5389 "When a break is encountered annotate the statement being broken
5390 out of by setting its CONTROL_BLOCK_PROP property.
5391 Returns logical OR of END_* flags."
5392 (and (js2-break-node-target node)
5393 (js2-node-set-prop (js2-break-node-target node)
5398 (defun js2-end-check (node)
5399 "Examine the body of a function, doing a basic reachability analysis.
5400 Returns a combination of flags END_* flags that indicate
5401 how the function execution can terminate. These constitute only the
5402 pessimistic set of termination conditions. It is possible that at
5403 runtime certain code paths will never be actually taken. Hence this
5404 analysis will flag errors in cases where there may not be errors.
5405 Returns logical OR of END_* flags"
5408 ((js2-break-node-p node)
5409 (js2-end-check-break node))
5410 ((js2-expr-stmt-node-p node)
5411 (if (setq kid (js2-expr-stmt-node-expr node))
5414 ((or (js2-continue-node-p node)
5415 (js2-throw-node-p node))
5417 ((js2-return-node-p node)
5418 (if (setq kid (js2-return-node-retval node))
5419 js2-END_RETURNS_VALUE
5421 ((js2-loop-node-p node)
5422 (js2-end-check-loop node))
5423 ((js2-switch-node-p node)
5424 (js2-end-check-switch node))
5425 ((js2-labeled-stmt-node-p node)
5426 (js2-end-check-label node))
5427 ((js2-if-node-p node)
5428 (js2-end-check-if node))
5429 ((js2-try-node-p node)
5430 (js2-end-check-try node))
5431 ((js2-block-node-p node)
5432 (if (null (js2-block-node-kids node))
5434 (js2-end-check-block node)))
5435 ((js2-yield-node-p node)
5438 js2-END_DROPS_OFF))))
5440 (defun js2-always-defined-boolean-p (node)
5441 "Check if NODE always evaluates to true or false in boolean context.
5442 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5444 (let ((tt (js2-node-type node))
5447 ((or (= tt js2-FALSE) (= tt js2-NULL))
5452 (setq num (js2-number-node-num-value node))
5453 (if (and (not (eq num 0.0e+NaN))
5460 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5461 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5463 (defvar js2-tokens nil
5464 "List of all defined token names.") ; initialized in `js2-token-names'
5466 (defconst js2-token-names
5467 (let* ((names (make-vector js2-num-tokens -1))
5468 (case-fold-search nil) ; only match js2-UPPER_CASE
5469 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5470 (cl-loop for sym in syms
5473 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5475 (aset names (symbol-value sym) ; code, e.g. 152
5477 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5478 (push sym js2-tokens)))
5480 "Vector mapping int values to token string names, sans `js2-' prefix.")
5482 (defun js2-tt-name (tok)
5483 "Return a string name for TOK, a token symbol or code.
5484 Signals an error if it's not a recognized token."
5487 (setq code (symbol-value tok)))
5490 (if (and (numberp code)
5491 (not (cl-minusp code))
5492 (< code js2-num-tokens))
5493 (aref js2-token-names code)
5494 (error "Invalid token: %s" code)))))
5496 (defsubst js2-tt-sym (tok)
5497 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5498 (intern (js2-tt-name tok)))
5500 (defconst js2-token-codes
5501 (let ((table (make-hash-table :test 'eq :size 256)))
5502 (cl-loop for name across js2-token-names
5503 for sym = (intern (concat "js2-" (upcase name)))
5505 (puthash sym (symbol-value sym) table))
5506 ;; clean up a few that are "wrong" in Rhino's token codes
5507 (puthash 'js2-DELETE js2-DELPROP table)
5509 "Hashtable mapping token type symbols to their bytecodes.")
5511 (defsubst js2-tt-code (sym)
5512 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5513 (or (gethash sym js2-token-codes)
5514 (error "Invalid token symbol: %s " sym))) ; signal code bug
5516 (defun js2-report-scan-error (msg &optional no-throw beg len)
5517 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5518 (js2-report-error msg nil
5519 (or beg (js2-current-token-beg))
5520 (or len (js2-current-token-len)))
5522 (throw 'return js2-ERROR)))
5524 (defun js2-set-string-from-buffer (token)
5525 "Set `string' and `end' slots for TOKEN, return the string."
5526 (setf (js2-token-end token) js2-ts-cursor
5527 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5529 ;; TODO: could potentially avoid a lot of consing by allocating a
5530 ;; char buffer the way Rhino does.
5531 (defsubst js2-add-to-string (c)
5532 (push c js2-ts-string-buffer))
5534 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5535 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5536 ;; any other character: when it's not part of the current token, we
5537 ;; unget it, allowing it to be read again by the following call.
5538 (defsubst js2-unget-char ()
5539 (cl-decf js2-ts-cursor))
5541 ;; Rhino distinguishes \r and \n line endings. We don't need to
5542 ;; because we only scan from Emacs buffers, which always use \n.
5543 (defun js2-get-char ()
5544 "Read and return the next character from the input buffer.
5545 Increments `js2-ts-lineno' if the return value is a newline char.
5546 Updates `js2-ts-cursor' to the point after the returned char.
5547 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5548 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5550 ;; check for end of buffer
5551 (if (>= js2-ts-cursor (point-max))
5552 (setq js2-ts-hit-eof t
5553 js2-ts-cursor (1+ js2-ts-cursor)
5554 c js2-EOF_CHAR) ; return value
5555 ;; otherwise read next char
5556 (setq c (char-before (cl-incf js2-ts-cursor)))
5557 ;; if we read a newline, update counters
5559 (setq js2-ts-line-start js2-ts-cursor
5560 js2-ts-lineno (1+ js2-ts-lineno)))
5561 ;; TODO: skip over format characters
5564 (defun js2-read-unicode-escape ()
5565 "Read a \\uNNNN sequence from the input.
5566 Assumes the ?\ and ?u have already been read.
5567 Returns the unicode character, or nil if it wasn't a valid character.
5568 Doesn't change the values of any scanner variables."
5569 ;; I really wish I knew a better way to do this, but I can't
5570 ;; find the Emacs function that takes a 16-bit int and converts
5571 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5572 ;; Have to first check that it's 4 hex characters or it may stop
5575 (let ((s (buffer-substring-no-properties js2-ts-cursor
5576 (+ 4 js2-ts-cursor))))
5577 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5578 (read (concat "?\\u" s))))))
5580 (defun js2-match-char (test)
5581 "Consume and return next character if it matches TEST, a character.
5582 Returns nil and consumes nothing if TEST is not the next character."
5583 (let ((c (js2-get-char)))
5589 (defun js2-peek-char ()
5594 (defun js2-identifier-start-p (c)
5595 "Is C a valid start to an ES5 Identifier?
5596 See http://es5.github.io/#x7.6"
5599 (memq (get-char-code-property c 'general-category)
5601 '(Lu Ll Lt Lm Lo Nl))))
5603 (defun js2-identifier-part-p (c)
5604 "Is C a valid part of an ES5 Identifier?
5605 See http://es5.github.io/#x7.6"
5607 (memq c '(?$ ?_ ?\u200c ?\u200d))
5608 (memq (get-char-code-property c 'general-category)
5615 ;; Connector Punctuation
5618 (defun js2-alpha-p (c)
5619 (cond ((and (<= ?A c) (<= c ?Z)) t)
5620 ((and (<= ?a c) (<= c ?z)) t)
5623 (defsubst js2-digit-p (c)
5624 (and (<= ?0 c) (<= c ?9)))
5626 (defun js2-js-space-p (c)
5628 (memq c '(#x20 #x9 #xB #xC #xD))
5631 ;; TODO: change this nil to check for Unicode space character
5634 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5636 (defun js2-skip-line ()
5637 "Skip to end of line."
5638 (while (not (memq (js2-get-char) js2-eol-chars)))
5640 (setf (js2-token-end (js2-current-token)) js2-ts-cursor))
5642 (defun js2-init-scanner (&optional buf line)
5643 "Create token stream for BUF starting on LINE.
5644 BUF defaults to `current-buffer' and LINE defaults to 1.
5646 A buffer can only have one scanner active at a time, which yields
5647 dramatically simpler code than using a defstruct. If you need to
5648 have simultaneous scanners in a buffer, copy the regions to scan
5650 (with-current-buffer (or buf (current-buffer))
5651 (setq js2-ts-dirty-line nil
5654 js2-ts-lineno (or line 1)
5655 js2-ts-line-end-char -1
5656 js2-ts-cursor (point-min)
5657 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5658 js2-ti-tokens-cursor 0
5660 js2-ts-is-xml-attribute nil
5661 js2-ts-xml-is-tag-content nil
5662 js2-ts-xml-open-tags-count 0
5663 js2-ts-string-buffer nil)))
5665 ;; This function uses the cached op, string and number fields in
5666 ;; TokenStream; if getToken has been called since the passed token
5667 ;; was scanned, the op or string printed may be incorrect.
5668 (defun js2-token-to-string (token)
5669 ;; Not sure where this function is used in Rhino. Not tested.
5670 (if (not js2-debug-print-trees)
5672 (let ((name (js2-tt-name token)))
5674 ((memq token '(js2-STRING js2-REGEXP js2-NAME
5675 js2-TEMPLATE_HEAD js2-NO_SUBS_TEMPLATE))
5676 (concat name " `" (js2-current-token-string) "'"))
5677 ((eq token js2-NUMBER)
5678 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5682 (defconst js2-keywords
5684 case catch class const continue
5685 debugger default delete do
5687 false finally for function
5688 if in instanceof import
5693 this throw true try typeof
5698 ;; Token names aren't exactly the same as the keywords, unfortunately.
5699 ;; E.g. delete is js2-DELPROP.
5700 (defconst js2-kwd-tokens
5701 (let ((table (make-vector js2-num-tokens nil))
5704 js2-CASE js2-CATCH js2-CLASS js2-CONST js2-CONTINUE
5705 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5707 js2-ELSE js2-EXTENDS js2-EXPORT
5708 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5709 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5713 js2-SUPER js2-SWITCH
5714 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5719 (aset table i 'font-lock-keyword-face))
5720 (aset table js2-STRING 'font-lock-string-face)
5721 (aset table js2-REGEXP 'font-lock-string-face)
5722 (aset table js2-NO_SUBS_TEMPLATE 'font-lock-string-face)
5723 (aset table js2-TEMPLATE_HEAD 'font-lock-string-face)
5724 (aset table js2-COMMENT 'font-lock-comment-face)
5725 (aset table js2-THIS 'font-lock-builtin-face)
5726 (aset table js2-SUPER 'font-lock-builtin-face)
5727 (aset table js2-VOID 'font-lock-constant-face)
5728 (aset table js2-NULL 'font-lock-constant-face)
5729 (aset table js2-TRUE 'font-lock-constant-face)
5730 (aset table js2-FALSE 'font-lock-constant-face)
5731 (aset table js2-NOT 'font-lock-negation-char-face)
5733 "Vector whose values are non-nil for tokens that are keywords.
5734 The values are default faces to use for highlighting the keywords.")
5736 ;; FIXME: Support strict mode-only future reserved words, after we know
5737 ;; which parts scopes are in strict mode, and which are not.
5738 (defconst js2-reserved-words '(class enum export extends import static super)
5739 "Future reserved keywords in ECMAScript 5.1.")
5741 (defconst js2-keyword-names
5742 (let ((table (make-hash-table :test 'equal)))
5743 (cl-loop for k in js2-keywords
5745 (symbol-name k) ; instanceof
5746 (intern (concat "js2-"
5747 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5750 "JavaScript keywords by name, mapped to their symbols.")
5752 (defconst js2-reserved-word-names
5753 (let ((table (make-hash-table :test 'equal)))
5754 (cl-loop for k in js2-reserved-words
5756 (puthash (symbol-name k) 'js2-RESERVED table))
5758 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5760 (defun js2-collect-string (buf)
5761 "Convert BUF, a list of chars, to a string.
5762 Reverses BUF before converting."
5764 (apply #'string (nreverse buf))
5767 (defun js2-string-to-keyword (s)
5768 "Return token for S, a string, if S is a keyword or reserved word.
5769 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5770 (or (gethash s js2-keyword-names)
5771 (gethash s js2-reserved-word-names)))
5773 (defsubst js2-ts-set-char-token-bounds (token)
5774 "Used when next token is one character."
5775 (setf (js2-token-beg token) (1- js2-ts-cursor)
5776 (js2-token-end token) js2-ts-cursor))
5778 (defsubst js2-ts-return (token type)
5779 "Update the `end' and `type' slots of TOKEN,
5780 then throw `return' with value TYPE."
5781 (setf (js2-token-end token) js2-ts-cursor
5782 (js2-token-type token) type)
5783 (throw 'return type))
5785 (defun js2-x-digit-to-int (c accumulator)
5786 "Build up a hex number.
5787 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5788 corresponding number. Otherwise return -1."
5791 ;; Use 0..9 < A..Z < a..z
5796 (throw 'check nil)))
5799 (cl-decf c (- ?A 10))
5800 (throw 'check nil)))
5803 (cl-decf c (- ?a 10))
5804 (throw 'check nil))))
5806 (logior c (lsh accumulator 4))))
5808 (defun js2-get-token (&optional modifier)
5809 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5810 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5813 This function will not return a newline (js2-EOL) - instead, it
5814 gobbles newlines until it finds a non-newline token. Call
5815 `js2-peek-token-or-eol' when you care about newlines.
5817 This function will also not return a js2-COMMENT. Instead, it
5818 records comments found in `js2-scanned-comments'. If the token
5819 returned by this function immediately follows a jsdoc comment,
5820 the token is flagged as such."
5821 (if (zerop js2-ti-lookahead)
5822 (js2-get-token-internal modifier)
5823 (cl-decf js2-ti-lookahead)
5824 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5825 (let ((tt (js2-current-token-type)))
5826 (cl-assert (not (= tt js2-EOL)))
5829 (defun js2-unget-token ()
5830 (cl-assert (< js2-ti-lookahead js2-ti-max-lookahead))
5831 (cl-incf js2-ti-lookahead)
5832 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5834 (defun js2-get-token-internal (modifier)
5835 (let* ((token (js2-get-token-internal-1 modifier)) ; call scanner
5836 (tt (js2-token-type token))
5840 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5844 (when js2-record-comments
5845 (js2-record-comment token)))
5846 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5847 (setq token (js2-get-token-internal-1 modifier) ; call scanner again
5848 tt (js2-token-type token)))
5851 (setf (js2-token-follows-eol-p token) t))
5853 ;; perform lexical fontification as soon as token is scanned
5854 (when js2-parse-ide-mode
5857 (js2-record-face 'js2-error token))
5858 ((setq face (aref js2-kwd-tokens tt))
5859 (js2-record-face face token))
5860 ((and (= tt js2-NAME)
5861 (equal (js2-token-string token) "undefined"))
5862 (js2-record-face 'font-lock-constant-face token))))
5865 (defsubst js2-string-to-number (str base)
5866 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5868 (string-to-number str base)
5869 (overflow-error -1)))
5871 (defun js2-get-token-internal-1 (modifier)
5872 "Return next JavaScript token type, an int such as js2-RETURN.
5873 During operation, creates an instance of `js2-token' struct, sets
5874 its relevant fields and puts it into `js2-ti-tokens'."
5875 (let (identifier-start
5876 is-unicode-escape-start c
5877 contains-escape escape-val str result base
5878 quote-char look-for-slash continue tt
5879 (token (js2-new-token 0)))
5883 (when (eq modifier 'TEMPLATE_TAIL)
5884 (setf (js2-token-beg token) (1- js2-ts-cursor))
5885 (throw 'return (js2-get-string-or-template-token ?` token)))
5887 ;; Eat whitespace, possibly sensitive to newlines.
5890 (setq c (js2-get-char))
5892 ((eq c js2-EOF_CHAR)
5894 (js2-ts-set-char-token-bounds token)
5895 (throw 'return js2-EOF))
5897 (js2-ts-set-char-token-bounds token)
5898 (setq js2-ts-dirty-line nil)
5899 (throw 'return js2-EOL))
5900 ((not (js2-js-space-p c))
5901 (if (/= c ?-) ; in case end of HTML comment
5902 (setq js2-ts-dirty-line t))
5903 (setq continue nil))))
5904 ;; Assume the token will be 1 char - fixed up below.
5905 (js2-ts-set-char-token-bounds token)
5907 (throw 'return js2-XMLATTR))
5908 ;; identifier/keyword/instanceof?
5909 ;; watch out for starting with a <backslash>
5912 (setq c (js2-get-char))
5914 (setq identifier-start t
5915 is-unicode-escape-start t
5916 js2-ts-string-buffer nil)
5917 (setq identifier-start nil)
5921 (when (setq identifier-start (js2-identifier-start-p c))
5922 (setq js2-ts-string-buffer nil)
5923 (js2-add-to-string c))))
5924 (when identifier-start
5925 (setq contains-escape is-unicode-escape-start)
5928 (if is-unicode-escape-start
5929 ;; strictly speaking we should probably push-back
5930 ;; all the bad characters if the <backslash>uXXXX
5931 ;; sequence is malformed. But since there isn't a
5932 ;; correct context(is there?) for a bad Unicode
5933 ;; escape sequence in an identifier, we can report
5938 (setq c (js2-get-char)
5939 escape-val (js2-x-digit-to-int c escape-val))
5940 ;; Next check takes care of c < 0 and bad escape
5941 (if (cl-minusp escape-val)
5942 (throw 'break nil)))
5943 (if (cl-minusp escape-val)
5944 (js2-report-scan-error "msg.invalid.escape" t))
5945 (js2-add-to-string escape-val)
5946 (setq is-unicode-escape-start nil))
5947 (setq c (js2-get-char))
5950 (setq c (js2-get-char))
5952 (setq is-unicode-escape-start t
5954 (js2-report-scan-error "msg.illegal.character" t)))
5956 (if (or (eq c js2-EOF_CHAR)
5957 (not (js2-identifier-part-p c)))
5959 (js2-add-to-string c))))))
5961 (setf str (js2-collect-string js2-ts-string-buffer)
5962 (js2-token-end token) js2-ts-cursor)
5963 ;; FIXME: Invalid in ES5 and ES6, see
5964 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5965 ;; Probably should just drop this conditional.
5966 (unless contains-escape
5967 ;; OPT we shouldn't have to make a string (object!) to
5968 ;; check if it's a keyword.
5969 ;; Return the corresponding token if it's a keyword
5970 (when (and (not (eq modifier 'KEYWORD_IS_NAME))
5971 (setq result (js2-string-to-keyword str)))
5972 (if (and (< js2-language-version 170)
5973 (memq result '(js2-LET js2-YIELD)))
5974 ;; LET and YIELD are tokens only in 1.7 and later
5975 (setq result 'js2-NAME))
5976 (when (eq result 'js2-RESERVED)
5977 (setf (js2-token-string token) str))
5978 (throw 'return (js2-tt-code result))))
5979 ;; If we want to intern these as Rhino does, just use (intern str)
5980 (setf (js2-token-string token) str)
5981 (throw 'return js2-NAME)) ; end identifier/kwd check
5983 (when (or (js2-digit-p c)
5984 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5985 (setq js2-ts-string-buffer nil
5988 (setq c (js2-get-char))
5990 ((or (eq c ?x) (eq c ?X))
5992 (setq c (js2-get-char)))
5993 ((and (or (eq c ?b) (eq c ?B))
5994 (>= js2-language-version 200))
5996 (setq c (js2-get-char)))
5997 ((and (or (eq c ?o) (eq c ?O))
5998 (>= js2-language-version 200))
6000 (setq c (js2-get-char)))
6002 (setq base 'maybe-8))
6004 (js2-add-to-string ?0))))
6007 (if (> 0 (js2-x-digit-to-int c 0))
6008 (js2-report-scan-error "msg.missing.hex.digits")
6009 (while (<= 0 (js2-x-digit-to-int c 0))
6010 (js2-add-to-string c)
6011 (setq c (js2-get-char)))))
6013 (if (not (memq c '(?0 ?1)))
6014 (js2-report-scan-error "msg.missing.binary.digits")
6015 (while (memq c '(?0 ?1))
6016 (js2-add-to-string c)
6017 (setq c (js2-get-char)))))
6019 (if (or (> ?0 c) (< ?7 c))
6020 (js2-report-scan-error "msg.missing.octal.digits")
6021 (while (and (<= ?0 c) (>= ?7 c))
6022 (js2-add-to-string c)
6023 (setq c (js2-get-char)))))
6025 (while (and (<= ?0 c) (<= c ?9))
6026 ;; We permit 08 and 09 as decimal numbers, which
6027 ;; makes our behavior a superset of the ECMA
6028 ;; numeric grammar. We might not always be so
6029 ;; permissive, so we warn about it.
6030 (when (and (eq base 'maybe-8) (>= c ?8))
6031 (js2-report-warning "msg.bad.octal.literal"
6032 (if (eq c ?8) "8" "9"))
6034 (js2-add-to-string c)
6035 (setq c (js2-get-char)))
6036 (when (eq base 'maybe-8)
6038 (when (and (eq base 10) (memq c '(?. ?e ?E)))
6041 (js2-add-to-string c)
6042 (setq c (js2-get-char))
6043 while (js2-digit-p c)))
6044 (when (memq c '(?e ?E))
6045 (js2-add-to-string c)
6046 (setq c (js2-get-char))
6047 (when (memq c '(?+ ?-))
6048 (js2-add-to-string c)
6049 (setq c (js2-get-char)))
6050 (unless (js2-digit-p c)
6051 (js2-report-scan-error "msg.missing.exponent" t))
6053 (js2-add-to-string c)
6054 (setq c (js2-get-char))
6055 while (js2-digit-p c))))
6057 (let ((str (js2-set-string-from-buffer token)))
6058 (setf (js2-token-number token)
6059 (js2-string-to-number str base)))
6060 (throw 'return js2-NUMBER))
6062 (when (or (memq c '(?\" ?\'))
6063 (and (>= js2-language-version 200)
6066 (js2-get-string-or-template-token c token)))
6067 (js2-ts-return token
6070 (throw 'return js2-SEMI))
6072 (throw 'return js2-LB))
6074 (throw 'return js2-RB))
6076 (throw 'return js2-LC))
6078 (throw 'return js2-RC))
6080 (throw 'return js2-LP))
6082 (throw 'return js2-RP))
6084 (throw 'return js2-COMMA))
6086 (throw 'return js2-HOOK))
6088 (if (js2-match-char ?:)
6090 (throw 'return js2-COLON)))
6092 (if (js2-match-char ?.)
6093 (if (js2-match-char ?.)
6094 js2-TRIPLEDOT js2-DOTDOT)
6095 (if (js2-match-char ?\()
6097 (throw 'return js2-DOT))))
6099 (if (js2-match-char ?|)
6100 (throw 'return js2-OR)
6101 (if (js2-match-char ?=)
6103 (throw 'return js2-BITOR))))
6105 (if (js2-match-char ?=)
6107 (throw 'return js2-BITXOR)))
6109 (if (js2-match-char ?&)
6110 (throw 'return js2-AND)
6111 (if (js2-match-char ?=)
6113 (throw 'return js2-BITAND))))
6115 (if (js2-match-char ?=)
6116 (if (js2-match-char ?=)
6118 (throw 'return js2-EQ))
6119 (if (js2-match-char ?>)
6120 (js2-ts-return token js2-ARROW)
6121 (throw 'return js2-ASSIGN))))
6123 (if (js2-match-char ?=)
6124 (if (js2-match-char ?=)
6127 (throw 'return js2-NOT)))
6129 ;; NB:treat HTML begin-comment as comment-till-eol
6130 (when (js2-match-char ?!)
6131 (when (js2-match-char ?-)
6132 (when (js2-match-char ?-)
6134 (setf (js2-token-comment-type (js2-current-token)) 'html)
6135 (throw 'return js2-COMMENT)))
6137 (if (js2-match-char ?<)
6138 (if (js2-match-char ?=)
6141 (if (js2-match-char ?=)
6143 (throw 'return js2-LT))))
6145 (if (js2-match-char ?>)
6146 (if (js2-match-char ?>)
6147 (if (js2-match-char ?=)
6150 (if (js2-match-char ?=)
6153 (if (js2-match-char ?=)
6155 (throw 'return js2-GT))))
6157 (if (js2-match-char ?=)
6159 (throw 'return js2-MUL)))
6161 ;; is it a // comment?
6162 (when (js2-match-char ?/)
6163 (setf (js2-token-beg token) (- js2-ts-cursor 2))
6165 (setf (js2-token-comment-type token) 'line)
6166 ;; include newline so highlighting goes to end of
6167 ;; window, if there actually is a newline; if we
6168 ;; hit eof, then implicitly there isn't
6169 (unless js2-ts-hit-eof
6170 (cl-incf (js2-token-end token)))
6171 (throw 'return js2-COMMENT))
6172 ;; is it a /* comment?
6173 (when (js2-match-char ?*)
6174 (setf look-for-slash nil
6175 (js2-token-beg token) (- js2-ts-cursor 2)
6176 (js2-token-comment-type token)
6177 (if (js2-match-char ?*)
6179 (setq look-for-slash t)
6183 (setq c (js2-get-char))
6185 ((eq c js2-EOF_CHAR)
6186 (setf (js2-token-end token) (1- js2-ts-cursor))
6187 (js2-report-error "msg.unterminated.comment")
6188 (throw 'return js2-COMMENT))
6190 (setq look-for-slash t))
6193 (js2-ts-return token js2-COMMENT)))
6195 (setf look-for-slash nil
6196 (js2-token-end token) js2-ts-cursor)))))
6197 (if (js2-match-char ?=)
6199 (throw 'return js2-DIV)))
6201 (when js2-skip-preprocessor-directives
6203 (setf (js2-token-comment-type token) 'preprocessor
6204 (js2-token-end token) js2-ts-cursor)
6205 (throw 'return js2-COMMENT))
6206 (throw 'return js2-ERROR))
6208 (if (js2-match-char ?=)
6210 (throw 'return js2-MOD)))
6212 (throw 'return js2-BITNOT))
6214 (if (js2-match-char ?=)
6216 (if (js2-match-char ?+)
6218 (throw 'return js2-ADD))))
6221 ((js2-match-char ?=)
6222 (setq c js2-ASSIGN_SUB))
6223 ((js2-match-char ?-)
6224 (unless js2-ts-dirty-line
6225 ;; treat HTML end-comment after possible whitespace
6226 ;; after line start as comment-until-eol
6227 (when (js2-match-char ?>)
6229 (setf (js2-token-comment-type (js2-current-token)) 'html)
6230 (throw 'return js2-COMMENT)))
6234 (setq js2-ts-dirty-line t)
6237 (js2-report-scan-error "msg.illegal.character")))))))
6238 (setf (js2-token-type token) tt)
6241 (defun js2-get-string-or-template-token (quote-char token)
6242 ;; We attempt to accumulate a string the fast way, by
6243 ;; building it directly out of the reader. But if there
6244 ;; are any escaped characters in the string, we revert to
6245 ;; building it out of a string buffer.
6246 (let ((c (js2-get-char))
6247 js2-ts-string-buffer
6248 nc c1 val escape-val)
6250 (while (/= c quote-char)
6252 (when (eq c js2-EOF_CHAR)
6254 (js2-report-error "msg.unterminated.string.lit")
6256 (when (and (eq c ?\n) (not (eq quote-char ?`)))
6258 (js2-report-error "msg.unterminated.string.lit")
6261 ;; We've hit an escaped character
6262 (setq c (js2-get-char))
6271 (setq c1 (js2-read-unicode-escape))
6272 (if js2-parse-ide-mode
6275 ;; just copy the string in IDE-mode
6276 (js2-add-to-string ?\\)
6277 (js2-add-to-string ?u)
6279 (js2-add-to-string (js2-get-char)))
6280 (setq c (js2-get-char))) ; added at end of loop
6281 ;; flag it as an invalid escape
6282 (js2-report-warning "msg.invalid.escape"
6283 nil (- js2-ts-cursor 2) 6))
6284 ;; Get 4 hex digits; if the u escape is not
6285 ;; followed by 4 hex digits, use 'u' + the
6286 ;; literal character sequence that follows.
6287 (js2-add-to-string ?u)
6290 (setq c (js2-get-char)
6291 escape-val (js2-x-digit-to-int c escape-val))
6292 (if (cl-minusp escape-val)
6293 (throw 'continue nil))
6294 (js2-add-to-string c))
6295 ;; prepare for replace of stored 'u' sequence by escape value
6296 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
6299 ;; Get 2 hex digits, defaulting to 'x'+literal
6300 ;; sequence, as above.
6301 (setq c (js2-get-char)
6302 escape-val (js2-x-digit-to-int c 0))
6303 (if (cl-minusp escape-val)
6305 (js2-add-to-string ?x)
6306 (throw 'continue nil))
6309 escape-val (js2-x-digit-to-int c escape-val))
6310 (if (cl-minusp escape-val)
6312 (js2-add-to-string ?x)
6313 (js2-add-to-string c1)
6314 (throw 'continue nil))
6316 (setq c escape-val))))
6318 ;; Remove line terminator after escape to follow
6319 ;; SpiderMonkey and C/C++
6320 (setq c (js2-get-char))
6321 (throw 'continue nil))
6323 (when (and (<= ?0 c) (< c ?8))
6326 (when (and (<= ?0 c) (< c ?8))
6327 (setq val (- (+ (* 8 val) c) ?0)
6329 (when (and (<= ?0 c)
6332 ;; c is 3rd char of octal sequence only
6333 ;; if the resulting val <= 0377
6334 (setq val (- (+ (* 8 val) c) ?0)
6338 (when (and (eq quote-char ?`) (eq c ?$))
6339 (when (eq (setq nc (js2-get-char)) ?\{)
6342 (js2-add-to-string c)
6343 (setq c (js2-get-char)))))
6344 (js2-set-string-from-buffer token)
6345 (if (not (eq quote-char ?`))
6347 (if (and (eq c ?$) (eq nc ?\{))
6349 js2-NO_SUBS_TEMPLATE))))
6351 (defun js2-read-regexp (start-tt)
6352 "Called by parser when it gets / or /= in literal context."
6354 in-class ; inside a '[' .. ']' character-class
6357 (token (js2-new-token 0)))
6358 (setq js2-ts-string-buffer nil)
6359 (if (eq start-tt js2-ASSIGN_DIV)
6361 (js2-add-to-string ?=)
6362 (if (not (eq start-tt js2-DIV))
6363 (error "failed assertion")))
6364 (while (and (not err)
6365 (or (/= (setq c (js2-get-char)) ?/)
6370 (setf (js2-token-end token) (1- js2-ts-cursor)
6372 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
6373 (js2-report-error "msg.unterminated.re.lit"))
6376 (js2-add-to-string c)
6377 (setq c (js2-get-char)))
6381 (setq in-class nil)))
6382 (js2-add-to-string c))))
6386 ((js2-match-char ?g)
6388 ((js2-match-char ?i)
6390 ((js2-match-char ?m)
6392 ((and (js2-match-char ?u)
6393 (>= js2-language-version 200))
6395 ((and (js2-match-char ?y)
6396 (>= js2-language-version 200))
6399 (setq continue nil))))
6400 (if (js2-alpha-p (js2-peek-char))
6401 (js2-report-scan-error "msg.invalid.re.flag" t
6403 (js2-set-string-from-buffer token))
6404 (js2-collect-string flags)))
6406 (defun js2-get-first-xml-token ()
6407 (setq js2-ts-xml-open-tags-count 0
6408 js2-ts-is-xml-attribute nil
6409 js2-ts-xml-is-tag-content nil)
6411 (js2-get-next-xml-token))
6413 (defun js2-xml-discard-string (token)
6414 "Throw away the string in progress and flag an XML parse error."
6415 (setf js2-ts-string-buffer nil
6416 (js2-token-string token) nil)
6417 (js2-report-scan-error "msg.XML.bad.form" t))
6419 (defun js2-get-next-xml-token ()
6420 (setq js2-ts-string-buffer nil) ; for recording the XML
6421 (let ((token (js2-new-token 0))
6426 (setq c (js2-get-char))
6429 (throw 'return js2-ERROR))
6430 (js2-ts-xml-is-tag-content
6433 (js2-add-to-string c)
6434 (setq js2-ts-xml-is-tag-content nil
6435 js2-ts-is-xml-attribute nil))
6437 (js2-add-to-string c)
6438 (when (eq ?> (js2-peek-char))
6439 (setq c (js2-get-char))
6440 (js2-add-to-string c)
6441 (setq js2-ts-xml-is-tag-content nil)
6442 (cl-decf js2-ts-xml-open-tags-count)))
6445 (js2-set-string-from-buffer token)
6446 (throw 'return js2-XML))
6448 (js2-add-to-string c)
6449 (unless (js2-read-quoted-string c token)
6450 (throw 'return js2-ERROR)))
6452 (js2-add-to-string c)
6453 (setq js2-ts-is-xml-attribute t))
6455 (js2-add-to-string c))
6457 (js2-add-to-string c)
6458 (setq js2-ts-is-xml-attribute nil)))
6459 (when (and (not js2-ts-xml-is-tag-content)
6460 (zerop js2-ts-xml-open-tags-count))
6461 (js2-set-string-from-buffer token)
6462 (throw 'return js2-XMLEND)))
6464 ;; else not tag content
6467 (js2-add-to-string c)
6468 (setq c (js2-peek-char))
6471 (setq c (js2-get-char)) ;; skip !
6472 (js2-add-to-string c)
6473 (setq c (js2-peek-char))
6476 (setq c (js2-get-char)) ;; skip -
6477 (js2-add-to-string c)
6480 (js2-add-to-string c)
6481 (unless (js2-read-xml-comment token)
6482 (throw 'return js2-ERROR)))
6483 (js2-xml-discard-string token)
6484 (throw 'return js2-ERROR)))
6486 (setq c (js2-get-char)) ;; skip [
6487 (js2-add-to-string c)
6488 (if (and (= (js2-get-char) ?C)
6489 (= (js2-get-char) ?D)
6490 (= (js2-get-char) ?A)
6491 (= (js2-get-char) ?T)
6492 (= (js2-get-char) ?A)
6493 (= (js2-get-char) ?\[))
6495 (js2-add-to-string ?C)
6496 (js2-add-to-string ?D)
6497 (js2-add-to-string ?A)
6498 (js2-add-to-string ?T)
6499 (js2-add-to-string ?A)
6500 (js2-add-to-string ?\[)
6501 (unless (js2-read-cdata token)
6502 (throw 'return js2-ERROR)))
6503 (js2-xml-discard-string token)
6504 (throw 'return js2-ERROR)))
6506 (unless (js2-read-entity token)
6507 (throw 'return js2-ERROR))))
6508 ;; Allow bare CDATA section, e.g.:
6509 ;; let xml = <![CDATA[ foo bar baz ]]>;
6510 (when (zerop js2-ts-xml-open-tags-count)
6511 (throw 'return js2-XMLEND)))
6513 (setq c (js2-get-char)) ;; skip ?
6514 (js2-add-to-string c)
6515 (unless (js2-read-PI token)
6516 (throw 'return js2-ERROR)))
6519 (setq c (js2-get-char)) ;; skip /
6520 (js2-add-to-string c)
6521 (when (zerop js2-ts-xml-open-tags-count)
6522 (js2-xml-discard-string token)
6523 (throw 'return js2-ERROR))
6524 (setq js2-ts-xml-is-tag-content t)
6525 (cl-decf js2-ts-xml-open-tags-count))
6528 (setq js2-ts-xml-is-tag-content t)
6529 (cl-incf js2-ts-xml-open-tags-count))))
6532 (js2-set-string-from-buffer token)
6533 (throw 'return js2-XML))
6535 (js2-add-to-string c))))))))
6536 (setf (js2-token-end token) js2-ts-cursor)
6537 (setf (js2-token-type token) result)
6540 (defun js2-read-quoted-string (quote token)
6543 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6544 (js2-add-to-string c)
6547 (js2-xml-discard-string token) ;; throw away string in progress
6550 (defun js2-read-xml-comment (token)
6551 (let ((c (js2-get-char)))
6553 (while (/= c js2-EOF_CHAR)
6555 (js2-add-to-string c)
6556 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6557 (setq c (js2-get-char))
6558 (js2-add-to-string c)
6559 (if (eq (js2-peek-char) ?>)
6561 (setq c (js2-get-char)) ;; skip >
6562 (js2-add-to-string c)
6564 (throw 'continue nil)))
6565 (setq c (js2-get-char))))
6566 (js2-xml-discard-string token)
6569 (defun js2-read-cdata (token)
6570 (let ((c (js2-get-char)))
6572 (while (/= c js2-EOF_CHAR)
6574 (js2-add-to-string c)
6575 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6576 (setq c (js2-get-char))
6577 (js2-add-to-string c)
6578 (if (eq (js2-peek-char) ?>)
6580 (setq c (js2-get-char)) ;; Skip >
6581 (js2-add-to-string c)
6583 (throw 'continue nil)))
6584 (setq c (js2-get-char))))
6585 (js2-xml-discard-string token)
6588 (defun js2-read-entity (token)
6592 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6593 (js2-add-to-string c)
6596 (cl-incf decl-tags))
6599 (if (zerop decl-tags)
6600 (throw 'return t)))))
6601 (js2-xml-discard-string token)
6604 (defun js2-read-PI (token)
6605 "Scan an XML processing instruction."
6608 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6609 (js2-add-to-string c)
6610 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6611 (setq c (js2-get-char)) ;; Skip >
6612 (js2-add-to-string c)
6614 (js2-xml-discard-string token)
6619 (defun js2-set-face (beg end face &optional record)
6620 "Fontify a region. If RECORD is non-nil, record for later."
6621 (when (cl-plusp js2-highlight-level)
6622 (setq beg (min (point-max) beg)
6623 beg (max (point-min) beg)
6624 end (min (point-max) end)
6625 end (max (point-min) end))
6627 (push (list beg end face) js2-mode-fontifications)
6628 (put-text-property beg end 'font-lock-face face))))
6630 (defsubst js2-clear-face (beg end)
6631 (remove-text-properties beg end '(font-lock-face nil
6636 (defconst js2-ecma-global-props
6639 '("Infinity" "NaN" "undefined" "arguments") t)
6641 "Value properties of the Ecma-262 Global Object.
6642 Shown at or above `js2-highlight-level' 2.")
6644 ;; might want to add the name "arguments" to this list?
6645 (defconst js2-ecma-object-props
6648 '("prototype" "__proto__" "__parent__") t)
6650 "Value properties of the Ecma-262 Object constructor.
6651 Shown at or above `js2-highlight-level' 2.")
6653 (defconst js2-ecma-global-funcs
6657 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6658 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6660 "Function properties of the Ecma-262 Global object.
6661 Shown at or above `js2-highlight-level' 2.")
6663 (defconst js2-ecma-number-props
6665 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6667 "POSITIVE_INFINITY") t)
6669 "Properties of the Ecma-262 Number constructor.
6670 Shown at or above `js2-highlight-level' 2.")
6672 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6673 "Properties of the Ecma-262 Date constructor.
6674 Shown at or above `js2-highlight-level' 2.")
6676 (defconst js2-ecma-math-props
6679 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6682 "Properties of the Ecma-262 Math object.
6683 Shown at or above `js2-highlight-level' 2.")
6685 (defconst js2-ecma-math-funcs
6688 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6689 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6691 "Function properties of the Ecma-262 Math object.
6692 Shown at or above `js2-highlight-level' 2.")
6694 (defconst js2-ecma-function-props
6698 '(;; properties of the Object prototype object
6699 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6700 "toLocaleString" "toString" "valueOf"
6701 ;; properties of the Function prototype object
6703 ;; properties of the Array prototype object
6704 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6706 ;; properties of the String prototype object
6707 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6708 "localeCompare" "match" "replace" "search" "split" "substring"
6709 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6711 ;; properties of the Number prototype object
6712 "toExponential" "toFixed" "toPrecision"
6713 ;; properties of the Date prototype object
6714 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6715 "getMinutes" "getMonth" "getSeconds" "getTime"
6716 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6717 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6718 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6719 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6720 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6721 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6722 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6723 "toTimeString" "toUTCString"
6724 ;; properties of the RegExp prototype object
6726 ;; properties of the JSON prototype object
6728 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6729 "toSource" "__defineGetter__" "__defineSetter__"
6730 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6731 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6734 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6735 Shown at or above `js2-highlight-level' 3.")
6737 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6738 (let ((target-name (and target
6739 (js2-name-node-p target)
6740 (js2-name-node-name target)))
6741 (prop-name (if prop (js2-name-node-name prop)))
6742 (level2 (>= js2-highlight-level 2))
6743 (level3 (>= js2-highlight-level 3)))
6750 ((and level3 (string-match js2-ecma-function-props prop-name))
6751 'font-lock-builtin-face)
6752 ((and target-name prop)
6754 ((string= target-name "Date")
6755 (if (string-match js2-ecma-date-props prop-name)
6756 'font-lock-builtin-face))
6757 ((string= target-name "Math")
6758 (if (string-match js2-ecma-math-funcs prop-name)
6759 'font-lock-builtin-face))))))
6761 (if (string-match js2-ecma-global-funcs prop-name)
6762 'font-lock-builtin-face)))
6766 ((string= target-name "Number")
6767 (if (string-match js2-ecma-number-props prop-name)
6768 'font-lock-constant-face))
6769 ((string= target-name "Math")
6770 (if (string-match js2-ecma-math-props prop-name)
6771 'font-lock-constant-face))))
6773 (if (string-match js2-ecma-object-props prop-name)
6774 'font-lock-constant-face))))))
6776 (let ((pos (+ (js2-node-pos parent) ; absolute
6777 (js2-node-pos prop)))) ; relative
6779 (+ pos (js2-node-len prop))
6782 (defun js2-parse-highlight-member-expr-node (node)
6783 "Perform syntax highlighting of EcmaScript built-in properties.
6784 The variable `js2-highlight-level' governs this highlighting."
6785 (let (face target prop name pos end parent call-p callee)
6787 ;; case 1: simple name, e.g. foo
6788 ((js2-name-node-p node)
6789 (setq name (js2-name-node-name node))
6790 ;; possible for name to be nil in rare cases - saw it when
6791 ;; running js2-mode on an elisp buffer. Might as well try to
6792 ;; make it so js2-mode never barfs.
6794 (setq face (if (string-match js2-ecma-global-props name)
6795 'font-lock-constant-face))
6797 (setq pos (js2-node-pos node)
6798 end (+ pos (js2-node-len node)))
6799 (js2-set-face pos end face 'record))))
6800 ;; case 2: property access or function call
6801 ((or (js2-prop-get-node-p node)
6802 ;; highlight function call if expr is a prop-get node
6803 ;; or a plain name (i.e. unqualified function call)
6804 (and (setq call-p (js2-call-node-p node))
6805 (setq callee (js2-call-node-target node)) ; separate setq!
6806 (or (js2-prop-get-node-p callee)
6807 (js2-name-node-p callee))))
6809 node (if call-p callee node))
6810 (if (and call-p (js2-name-node-p callee))
6812 (setq target (js2-prop-get-node-left node)
6813 prop (js2-prop-get-node-right node)))
6815 ((js2-name-node-p prop)
6816 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6817 (js2-parse-highlight-prop-get parent target prop call-p))
6818 ((js2-name-node-p target)
6819 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6820 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6822 (defun js2-parse-highlight-member-expr-fn-name (expr)
6823 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6824 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6825 We currently only handle the case where the last component is a prop-get
6826 of a simple name. Called before EXPR has a parent node."
6828 (name (and (js2-prop-get-node-p expr)
6829 (js2-prop-get-node-right expr))))
6830 (when (js2-name-node-p name)
6831 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6832 (js2-node-pos name)))
6833 (+ pos (js2-node-len name))
6834 'font-lock-function-name-face
6837 ;; source: http://jsdoc.sourceforge.net/
6838 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6839 ;; allows type specifications, and needs work before entering the wild.
6841 (defconst js2-jsdoc-param-tag-regexp
6842 (concat "^\\s-*\\*+\\s-*\\(@"
6843 "\\(?:param\\|argument\\)"
6845 "\\s-*\\({[^}]+}\\)?" ; optional type
6846 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6848 "Matches jsdoc tags with optional type and optional param name.")
6850 (defconst js2-jsdoc-typed-tag-regexp
6851 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6865 "\\)\\)\\s-*\\({[^}]+}\\)?")
6866 "Matches jsdoc tags with optional type.")
6868 (defconst js2-jsdoc-arg-tag-regexp
6869 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6892 "\\)\\)\\s-+\\([^ \t]+\\)")
6893 "Matches jsdoc tags with a single argument.")
6895 (defconst js2-jsdoc-empty-tag-regexp
6896 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6936 "Matches empty jsdoc tags.")
6938 (defconst js2-jsdoc-link-tag-regexp
6939 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6940 "Matches a jsdoc link or code tag.")
6942 (defconst js2-jsdoc-see-tag-regexp
6943 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6944 "Matches a jsdoc @see tag.")
6946 (defconst js2-jsdoc-html-tag-regexp
6947 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6948 "Matches a simple (no attributes) html start- or end-tag.")
6950 (defun js2-jsdoc-highlight-helper ()
6951 (js2-set-face (match-beginning 1)
6954 (if (match-beginning 2)
6956 (goto-char (match-beginning 2))
6957 (= (char-after) ?{))
6958 (js2-set-face (1+ (match-beginning 2))
6961 (js2-set-face (match-beginning 2)
6964 (if (match-beginning 3)
6965 (js2-set-face (match-beginning 3)
6969 (defun js2-highlight-jsdoc (ast)
6970 "Highlight doc comment tags."
6971 (let ((comments (js2-ast-root-comments ast))
6974 (dolist (node comments)
6975 (when (eq (js2-comment-node-format node) 'jsdoc)
6976 (setq beg (js2-node-abs-pos node)
6977 end (+ beg (js2-node-len node)))
6979 (narrow-to-region beg end)
6980 (dolist (re (list js2-jsdoc-param-tag-regexp
6981 js2-jsdoc-typed-tag-regexp
6982 js2-jsdoc-arg-tag-regexp
6983 js2-jsdoc-link-tag-regexp
6984 js2-jsdoc-see-tag-regexp
6985 js2-jsdoc-empty-tag-regexp))
6987 (while (re-search-forward re nil t)
6988 (js2-jsdoc-highlight-helper)))
6989 ;; simple highlighting for html tags
6991 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6992 (js2-set-face (match-beginning 1)
6994 'js2-jsdoc-html-tag-delimiter)
6995 (js2-set-face (match-beginning 2)
6997 'js2-jsdoc-html-tag-name)
6998 (js2-set-face (match-beginning 3)
7000 'js2-jsdoc-html-tag-delimiter))))))))
7002 (defun js2-highlight-assign-targets (_node left right)
7003 "Highlight function properties and external variables."
7005 ;; highlight vars and props assigned function values
7006 (when (or (js2-function-node-p right)
7007 (js2-class-node-p right))
7009 ;; var foo = function() {...}
7010 ((js2-name-node-p left)
7012 ;; foo.bar.baz = function() {...}
7013 ((and (js2-prop-get-node-p left)
7014 (js2-name-node-p (js2-prop-get-node-right left)))
7015 (setq name (js2-prop-get-node-right left))))
7017 (js2-set-face (setq leftpos (js2-node-abs-pos name))
7018 (+ leftpos (js2-node-len name))
7019 'font-lock-function-name-face
7022 (defun js2-record-name-node (node)
7023 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
7024 later. NODE must be a name node."
7025 (let ((leftpos (js2-node-abs-pos node)))
7026 (push (list node js2-current-scope
7028 (+ leftpos (js2-node-len node)))
7029 js2-recorded-identifiers)))
7031 (defun js2-highlight-undeclared-vars ()
7032 "After entire parse is finished, look for undeclared variable references.
7033 We have to wait until entire buffer is parsed, since JavaScript permits var
7034 decls to occur after they're used.
7036 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
7037 it is considered declared."
7039 (dolist (entry js2-recorded-identifiers)
7040 (cl-destructuring-bind (name-node scope pos end) entry
7041 (setq name (js2-name-node-name name-node))
7042 (unless (or (member name js2-global-externs)
7043 (member name js2-default-externs)
7044 (member name js2-additional-externs)
7045 (js2-get-defining-scope scope name pos))
7046 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
7047 'js2-external-variable))))
7048 (setq js2-recorded-identifiers nil)))
7050 (defun js2-set-default-externs ()
7051 "Set the value of `js2-default-externs' based on the various
7052 `js2-include-?-externs' variables."
7053 (setq js2-default-externs
7054 (append js2-ecma-262-externs
7055 (if js2-include-browser-externs js2-browser-externs)
7056 (if (and js2-include-browser-externs
7057 (>= js2-language-version 200)) js2-harmony-externs)
7058 (if js2-include-rhino-externs js2-rhino-externs)
7059 (if js2-include-node-externs js2-node-externs)
7060 (if (or js2-include-browser-externs js2-include-node-externs)
7061 js2-typed-array-externs))))
7063 (defun js2-apply-jslint-globals ()
7064 (setq js2-additional-externs
7065 (nconc (js2-get-jslint-globals)
7066 js2-additional-externs)))
7068 (defun js2-get-jslint-globals ()
7069 (cl-loop for node in (js2-ast-root-comments js2-mode-ast)
7070 when (and (eq 'block (js2-comment-node-format node))
7072 (goto-char (js2-node-abs-pos node))
7073 (looking-at "/\\*global ")))
7074 append (js2-get-jslint-globals-in
7076 (js2-node-abs-end node))))
7078 (defun js2-get-jslint-globals-in (beg end)
7082 (while (re-search-forward js2-mode-identifier-re end t)
7083 (let ((match (match-string 0)))
7084 (unless (member match '("true" "false"))
7085 (push match res)))))
7090 ;; We currently only support imenu, but eventually should support speedbar and
7091 ;; possibly other browsing mechanisms.
7093 ;; The basic strategy is to identify function assignment targets of the form
7094 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
7095 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
7096 ;; for imenu after parsing is finished.
7098 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
7099 ;; JavaScript, and the general problem is undecidable. However, several forms
7100 ;; are readily recognizable at parse-time; the forms we attempt to recognize
7103 ;; function foo() -- function declaration
7104 ;; foo = function() -- function expression assigned to variable
7105 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
7106 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
7107 ;; foo = {bar: {baz: function()}} -- inside nested object literal
7108 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
7109 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
7110 ;; foo = {get bar() {...}} -- getter/setter in obj literal
7111 ;; function foo() {function bar() {...}} -- nested function
7112 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
7114 ;; This list boils down to a few forms that can be combined recursively.
7115 ;; Top-level named function declarations include both the left-hand (name)
7116 ;; and the right-hand (function value) expressions needed to produce an imenu
7117 ;; entry. The other "right-hand" forms we need to look for are:
7118 ;; - functions declared as props/getters/setters in object literals
7119 ;; - nested named function declarations
7120 ;; The "left-hand" expressions that functions can be assigned to include:
7121 ;; - local/global variables
7122 ;; - nested property-get expressions like a.b.c.d
7123 ;; - element gets like foo[10] or foo['bar'] where the index
7124 ;; expression can be trivially converted to a property name. They
7125 ;; effectively then become property gets.
7127 ;; All the different definition types are canonicalized into the form
7128 ;; foo.bar.baz = position-of-function-keyword
7130 ;; We need to build a trie-like structure for imenu. As an example,
7131 ;; consider the following JavaScript code:
7133 ;; a = function() {...} // function at position 5
7134 ;; b = function() {...} // function at position 25
7135 ;; foo = function() {...} // function at position 100
7136 ;; foo.bar = function() {...} // function at position 200
7137 ;; foo.bar.baz = function() {...} // function at position 300
7138 ;; foo.bar.zab = function() {...} // function at position 400
7140 ;; During parsing we accumulate an entry for each definition in
7141 ;; the variable `js2-imenu-recorder', like so:
7147 ;; (fn foo bar baz 300)
7148 ;; (fn foo bar zab 400))
7150 ;; Where 'fn' is the respective function node.
7151 ;; After parsing these entries are merged into this alist-trie:
7155 ;; (foo (<definition> . 3)
7156 ;; (bar (<definition> . 6)
7160 ;; Note the wacky need for a <definition> name. The token can be anything
7161 ;; that isn't a valid JavaScript identifier, because you might make foo
7162 ;; a function and then start setting properties on it that are also functions.
7164 (defun js2-prop-node-name (node)
7165 "Return the name of a node that may be a property-get/property-name.
7166 If NODE is not a valid name-node, string-node or integral number-node,
7167 returns nil. Otherwise returns the string name/value of the node."
7169 ((js2-name-node-p node)
7170 (js2-name-node-name node))
7171 ((js2-string-node-p node)
7172 (js2-string-node-value node))
7173 ((and (js2-number-node-p node)
7174 (string-match "^[0-9]+$" (js2-number-node-value node)))
7175 (js2-number-node-value node))
7176 ((eq (js2-node-type node) js2-THIS)
7178 ((eq (js2-node-type node) js2-SUPER)
7181 (defun js2-node-qname-component (node)
7182 "Return the name of this node, if it contributes to a qname.
7183 Returns nil if the node doesn't contribute."
7185 (or (js2-prop-node-name node)
7186 (if (and (js2-function-node-p node)
7187 (js2-function-node-name node))
7188 (js2-name-node-name (js2-function-node-name node))))))
7190 (defun js2-record-imenu-entry (fn-node qname pos)
7191 "Add an entry to `js2-imenu-recorder'.
7192 FN-NODE should be the current item's function node.
7194 Associate FN-NODE with its QNAME for later lookup.
7195 This is used in postprocessing the chain list. For each chain, we find
7196 the parent function, look up its qname, then prepend a copy of it to the chain."
7197 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
7198 (unless js2-imenu-function-map
7199 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
7200 (puthash fn-node qname js2-imenu-function-map))
7202 (defun js2-record-imenu-functions (node &optional var)
7203 "Record function definitions for imenu.
7204 NODE is a function node or an object literal.
7205 VAR, if non-nil, is the expression that NODE is being assigned to.
7206 When passed arguments of wrong type, does nothing."
7207 (when js2-parse-ide-mode
7208 (let ((fun-p (js2-function-node-p node))
7211 ;; non-anonymous function declaration?
7214 (setq fname-node (js2-function-node-name node)))
7215 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
7216 ;; for remaining forms, compute left-side tree branch first
7217 ((and var (setq qname (js2-compute-nested-prop-get var)))
7219 ;; foo.bar.baz = function
7221 (js2-record-imenu-entry node qname (js2-node-pos node)))
7222 ;; foo.bar.baz = object-literal
7223 ;; look for nested functions: {a: {b: function() {...} }}
7224 ((js2-object-node-p node)
7225 ;; Node position here is still absolute, since the parser
7226 ;; passes the assignment target and value expressions
7227 ;; to us before they are added as children of the assignment node.
7228 (js2-record-object-literal node qname (js2-node-pos node)))))))))
7230 (defun js2-compute-nested-prop-get (node)
7231 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
7232 component nodes as a list. Otherwise return nil. Element-gets are treated
7233 as property-gets if the index expression is a string, or a positive integer."
7234 (let (left right head)
7236 ((or (js2-name-node-p node)
7237 (js2-this-or-super-node-p node))
7239 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
7240 ((js2-prop-get-node-p node) ; foo.bar
7241 (setq left (js2-prop-get-node-left node)
7242 right (js2-prop-get-node-right node))
7243 (if (setq head (js2-compute-nested-prop-get left))
7244 (nconc head (list right))))
7245 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
7246 (setq left (js2-elem-get-node-target node)
7247 right (js2-elem-get-node-element node))
7248 (if (or (js2-string-node-p right) ; ['bar']
7249 (and (js2-number-node-p right) ; [10]
7250 (string-match "^[0-9]+$"
7251 (js2-number-node-value right))))
7252 (if (setq head (js2-compute-nested-prop-get left))
7253 (nconc head (list right))))))))
7255 (defun js2-record-object-literal (node qname pos)
7256 "Recursively process an object literal looking for functions.
7257 NODE is an object literal that is the right-hand child of an assignment
7258 expression. QNAME is a list of nodes representing the assignment target,
7259 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
7260 POS is the absolute position of the node.
7261 We do a depth-first traversal of NODE. For any functions we find,
7262 we append the property name to QNAME, then call `js2-record-imenu-entry'."
7264 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
7265 (let ((left (js2-infix-node-left e))
7266 ;; Element positions are relative to the parent position.
7267 (pos (+ pos (js2-node-pos e))))
7269 ;; foo: function() {...}
7270 ((js2-function-node-p (setq right (js2-infix-node-right e)))
7271 (when (js2-prop-node-name left)
7272 ;; As a policy decision, we record the position of the property,
7273 ;; not the position of the `function' keyword, since the property
7274 ;; is effectively the name of the function.
7275 (js2-record-imenu-entry right (append qname (list left)) pos)))
7276 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
7277 ((js2-object-node-p right)
7278 (js2-record-object-literal right
7279 (append qname (list (js2-infix-node-left e)))
7280 (+ pos (js2-node-pos right)))))))))
7282 (defun js2-node-top-level-decl-p (node)
7283 "Return t if NODE's name is defined in the top-level scope.
7284 Also returns t if NODE's name is not defined in any scope, since it implies
7285 that it's an external variable, which must also be in the top-level scope."
7286 (let* ((name (js2-prop-node-name node))
7287 (this-scope (js2-node-get-enclosing-scope node))
7290 ((js2-this-or-super-node-p node)
7294 ((setq defining-scope (js2-get-defining-scope this-scope name))
7295 (js2-ast-root-p defining-scope))
7298 (defun js2-wrapper-function-p (node)
7299 "Return t if NODE is a function expression that's immediately invoked.
7300 NODE must be `js2-function-node'."
7301 (let ((parent (js2-node-parent node)))
7303 ;; function(){...}();
7304 (and (js2-call-node-p parent)
7305 (eq node (js2-call-node-target parent)))
7306 (and (js2-paren-node-p parent)
7307 ;; (function(){...})();
7308 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
7309 ;; (function(){...}).call(this);
7310 (and (js2-prop-get-node-p parent)
7311 (member (js2-name-node-name (js2-prop-get-node-right parent))
7313 (js2-call-node-p (js2-node-parent parent))))))))
7315 (defun js2-browse-postprocess-chains ()
7316 "Modify function-declaration name chains after parsing finishes.
7317 Some of the information is only available after the parse tree is complete.
7318 For instance, processing a nested scope requires a parent function node."
7319 (let (result fn parent-qname p elem)
7320 (dolist (entry js2-imenu-recorder)
7321 ;; function node goes first
7322 (cl-destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
7323 ;; Examine head's defining scope:
7324 ;; Pre-processed chain, or top-level/external, keep as-is.
7325 (if (or (stringp head) (js2-node-top-level-decl-p head))
7327 (when (js2-this-or-super-node-p head)
7328 (setq chain (cdr chain))) ; discard this-node
7329 (when (setq fn (js2-node-parent-script-or-fn current-fn))
7330 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
7331 (when (eq parent-qname 'not-found)
7332 ;; anonymous function expressions are not recorded
7333 ;; during the parse, so we need to handle this case here
7335 (if (js2-wrapper-function-p fn)
7336 (let ((grandparent (js2-node-parent-script-or-fn fn)))
7337 (if (js2-ast-root-p grandparent)
7339 (gethash grandparent js2-imenu-function-map 'skip)))
7341 (puthash fn parent-qname js2-imenu-function-map))
7342 (if (eq parent-qname 'skip)
7343 ;; We don't show it, let's record that fact.
7344 (remhash current-fn js2-imenu-function-map)
7345 ;; Prepend parent fn qname to this chain.
7346 (let ((qname (append parent-qname chain)))
7347 (puthash current-fn (butlast qname) js2-imenu-function-map)
7348 (push qname result)))))))
7349 ;; Collect chains obtained by third-party code.
7350 (let (js2-imenu-recorder)
7351 (run-hooks 'js2-build-imenu-callbacks)
7352 (dolist (entry js2-imenu-recorder)
7353 (push (cdr entry) result)))
7354 ;; Finally replace each node in each chain with its name.
7355 (dolist (chain result)
7358 (if (js2-node-p (setq elem (car p)))
7359 (setcar p (js2-node-qname-component elem)))
7363 ;; Merge name chains into a trie-like tree structure of nested lists.
7364 ;; To simplify construction of the trie, we first build it out using the rule
7365 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
7366 ;; [key, num-or-list]. The second element can be a number; if so, this key
7367 ;; is a leaf-node with only one value. (I.e. there is only one declaration
7368 ;; associated with the key at this level.) Otherwise the second element is
7369 ;; a list of pairs, with the rule applied recursively. This symmetry permits
7370 ;; a simple recursive formulation.
7372 ;; js2-mode is building the data structure for imenu. The imenu documentation
7373 ;; claims that it's the structure above, but in practice it wants the children
7374 ;; at the same list level as the key for that level, which is how I've drawn
7375 ;; the "Expected final result" above. We'll postprocess the trie to remove the
7376 ;; list wrapper around the children at each level.
7378 ;; A completed nested imenu-alist entry looks like this:
7380 ;; ("<definition>" . 7)
7385 ;; In particular, the documentation for `imenu--index-alist' says that
7386 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
7387 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
7389 (defun js2-treeify (lst)
7390 "Convert (a b c d) to (a ((b ((c d)))))."
7391 (if (null (cddr lst)) ; list length <= 2
7393 (list (car lst) (list (js2-treeify (cdr lst))))))
7395 (defun js2-build-alist-trie (chains trie)
7396 "Merge declaration name chains into a trie-like alist structure for imenu.
7397 CHAINS is the qname chain list produced during parsing. TRIE is a
7398 list of elements built up so far."
7399 (let (head tail pos branch kids)
7400 (dolist (chain chains)
7401 (setq head (car chain)
7403 pos (if (numberp (car tail)) (car tail))
7404 branch (js2-find-if (lambda (n)
7405 (string= (car n) head))
7407 kids (cl-second branch))
7409 ;; case 1: this key isn't in the trie yet
7412 (setcdr (last trie) (list (js2-treeify chain)))
7413 (setq trie (list (js2-treeify chain)))))
7414 ;; case 2: key is present with a single number entry: replace w/ list
7415 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7416 ;; ("<definition>" 20)))
7418 (setcar (cdr branch)
7419 (list (list "<definition-1>" kids)
7421 (list "<definition-2>" pos)
7422 (js2-treeify tail)))))
7423 ;; case 3: key is there (with kids), and we're a number entry
7427 (list (format "<definition-%d>"
7428 (1+ (cl-loop for kid in kids
7429 count (eq ?< (aref (car kid) 0)))))
7431 ;; case 4: key is there with kids, need to merge in our chain
7433 (js2-build-alist-trie (list tail) kids))))
7436 (defun js2-flatten-trie (trie)
7437 "Convert TRIE to imenu-format.
7438 Recurses through nodes, and for each one whose second element is a list,
7439 appends the list's flattened elements to the current element. Also
7440 changes the tails into conses. For instance, this pre-flattened trie
7452 Note that the root of the trie has no key, just a list of chains.
7453 This is also true for the value of any key with multiple children,
7454 e.g. key 'c' in the example above."
7457 (mapcar #'js2-flatten-trie trie))
7459 (if (numberp (cl-second trie))
7460 (cons (car trie) (cl-second trie))
7461 ;; else pop list and append its kids
7462 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7464 (defun js2-build-imenu-index ()
7465 "Turn `js2-imenu-recorder' into an imenu data structure."
7466 (when (eq js2-imenu-recorder 'empty)
7467 (setq js2-imenu-recorder nil))
7468 (let* ((chains (js2-browse-postprocess-chains))
7469 (result (js2-build-alist-trie chains nil)))
7470 (js2-flatten-trie result)))
7472 (defun js2-test-print-chains (chains)
7473 "Print a list of qname chains.
7474 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7475 i.e. one or more nodes, and an integer position as the list tail."
7476 (mapconcat (lambda (chain)
7478 (mapconcat (lambda (elem)
7479 (if (js2-node-p elem)
7480 (or (js2-node-qname-component elem)
7482 (number-to-string elem)))
7491 (defconst js2-version "1.8.5"
7492 "Version of JavaScript supported.")
7494 (defun js2-record-face (face &optional token)
7495 "Record a style run of FACE for TOKEN or the current token."
7496 (unless token (setq token (js2-current-token)))
7497 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7499 (defsubst js2-node-end (n)
7500 "Computes the absolute end of node N.
7501 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7502 is only true until the node is added to its parent; i.e., while parsing."
7506 (defun js2-record-comment (token)
7507 "Record a comment in `js2-scanned-comments'."
7508 (let ((ct (js2-token-comment-type token))
7509 (beg (js2-token-beg token))
7510 (end (js2-token-end token)))
7511 (push (make-js2-comment-node :len (- end beg)
7513 js2-scanned-comments)
7514 (when js2-parse-ide-mode
7515 (js2-record-face (if (eq ct 'jsdoc)
7517 'font-lock-comment-face)
7519 (when (memq ct '(html preprocessor))
7520 ;; Tell cc-engine the bounds of the comment.
7521 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7523 (defun js2-peek-token ()
7524 "Return the next token type without consuming it.
7525 If `js2-ti-lookahead' is positive, return the type of next token
7526 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7527 (if (not (zerop js2-ti-lookahead))
7529 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7530 (let ((tt (js2-get-token-internal nil)))
7534 (defalias 'js2-next-token 'js2-get-token)
7536 (defun js2-match-token (match &optional dont-unget)
7537 "Get next token and return t if it matches MATCH, a bytecode.
7538 Returns nil and consumes nothing if MATCH is not the next token."
7539 (if (/= (js2-get-token) match)
7540 (ignore (unless dont-unget (js2-unget-token)))
7543 (defun js2-match-contextual-kwd (name)
7544 "Consume and return t if next token is `js2-NAME', and its
7545 string is NAME. Returns nil and keeps current token otherwise."
7546 (if (or (/= (js2-get-token) js2-NAME)
7547 (not (string= (js2-current-token-string) name)))
7551 (js2-record-face 'font-lock-keyword-face)
7554 (defun js2-get-prop-name-token ()
7555 (js2-get-token (and (>= js2-language-version 170) 'KEYWORD_IS_NAME)))
7557 (defun js2-match-prop-name ()
7558 "Consume token and return t if next token is a valid property name.
7559 If `js2-language-version' is >= 180, a keyword or reserved word
7560 is considered valid name as well."
7561 (if (eq js2-NAME (js2-get-prop-name-token))
7566 (defun js2-must-match-prop-name (msg-id &optional pos len)
7567 (if (js2-match-prop-name)
7569 (js2-report-error msg-id nil pos len)
7572 (defun js2-peek-token-or-eol ()
7573 "Return js2-EOL if the next token immediately follows a newline.
7574 Else returns the next token. Used in situations where we don't
7575 consider certain token types valid if they are preceded by a newline.
7576 One example is the postfix ++ or -- operator, which has to be on the
7577 same line as its operand."
7578 (let ((tt (js2-get-token))
7579 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7585 (defun js2-must-match (token msg-id &optional pos len)
7586 "Match next token to token code TOKEN, or record a syntax error.
7587 MSG-ID is the error message to report if the match fails.
7588 Returns t on match, nil if no match."
7589 (if (js2-match-token token t)
7591 (js2-report-error msg-id nil pos len)
7595 (defun js2-must-match-name (msg-id)
7596 (if (js2-match-token js2-NAME t)
7598 (if (eq (js2-current-token-type) js2-RESERVED)
7599 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7600 (js2-report-error msg-id)
7604 (defsubst js2-inside-function ()
7605 (cl-plusp js2-nesting-of-function))
7607 (defun js2-set-requires-activation ()
7608 (if (js2-function-node-p js2-current-script-or-fn)
7609 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7611 (defun js2-check-activation-name (name _token)
7612 (when (js2-inside-function)
7613 ;; skip language-version 1.2 check from Rhino
7614 (if (or (string= "arguments" name)
7615 (and js2-compiler-activation-names ; only used in codegen
7616 (gethash name js2-compiler-activation-names)))
7617 (js2-set-requires-activation))))
7619 (defun js2-set-is-generator ()
7620 (let ((fn-node js2-current-script-or-fn))
7621 (when (and (js2-function-node-p fn-node)
7622 (not (js2-function-node-generator-type fn-node)))
7623 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7625 (defun js2-must-have-xml ()
7626 (unless js2-compiler-xml-available
7627 (js2-report-error "msg.XML.not.available")))
7629 (defun js2-push-scope (scope)
7630 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7631 (cl-assert (js2-scope-p scope))
7632 (cl-assert (null (js2-scope-parent-scope scope)))
7633 (cl-assert (not (eq js2-current-scope scope)))
7634 (setf (js2-scope-parent-scope scope) js2-current-scope
7635 js2-current-scope scope))
7637 (defsubst js2-pop-scope ()
7638 (setq js2-current-scope
7639 (js2-scope-parent-scope js2-current-scope)))
7641 (defun js2-enter-loop (loop-node)
7642 (push loop-node js2-loop-set)
7643 (push loop-node js2-loop-and-switch-set)
7644 (js2-push-scope loop-node)
7645 ;; Tell the current labeled statement (if any) its statement,
7646 ;; and set the jump target of the first label to the loop.
7647 ;; These are used in `js2-parse-continue' to verify that the
7648 ;; continue target is an actual labeled loop. (And for codegen.)
7649 (when js2-labeled-stmt
7650 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7651 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7652 js2-labeled-stmt))) loop-node)))
7654 (defun js2-exit-loop ()
7656 (pop js2-loop-and-switch-set)
7659 (defsubst js2-enter-switch (switch-node)
7660 (push switch-node js2-loop-and-switch-set))
7662 (defsubst js2-exit-switch ()
7663 (pop js2-loop-and-switch-set))
7665 (defun js2-parse (&optional buf cb)
7666 "Tell the js2 parser to parse a region of JavaScript.
7668 BUF is a buffer or buffer name containing the code to parse.
7669 Call `narrow-to-region' first to parse only part of the buffer.
7671 The returned AST root node is given some additional properties:
7672 `node-count' - total number of nodes in the AST
7673 `buffer' - BUF. The buffer it refers to may change or be killed,
7674 so the value is not necessarily reliable.
7676 An optional callback CB can be specified to report parsing
7677 progress. If `(functionp CB)' returns t, it will be called with
7678 the current line number once before parsing begins, then again
7679 each time the lexer reaches a new line number.
7681 CB can also be a list of the form `(symbol cb ...)' to specify
7682 multiple callbacks with different criteria. Each symbol is a
7683 criterion keyword, and the following element is the callback to
7686 :line - called whenever the line number changes
7687 :token - called for each new token consumed
7689 The list of criteria could be extended to include entering or
7690 leaving a statement, an expression, or a function definition."
7691 (if (and cb (not (functionp cb)))
7692 (error "criteria callbacks not yet implemented"))
7693 (let ((inhibit-point-motion-hooks t)
7694 (js2-compiler-xml-available (>= js2-language-version 160))
7695 ;; This is a recursive-descent parser, so give it a big stack.
7696 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7697 (max-specpdl-size (max max-specpdl-size 3000))
7698 (case-fold-search nil)
7700 (with-current-buffer (or buf (current-buffer))
7701 (setq js2-scanned-comments nil
7702 js2-parsed-errors nil
7703 js2-parsed-warnings nil
7704 js2-imenu-recorder nil
7705 js2-imenu-function-map nil
7708 (setq ast (js2-do-parse))
7709 (unless js2-ts-hit-eof
7710 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7711 (setf (js2-ast-root-errors ast) js2-parsed-errors
7712 (js2-ast-root-warnings ast) js2-parsed-warnings)
7713 ;; if we didn't find any declarations, put a dummy in this list so we
7714 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7715 (unless js2-imenu-recorder
7716 (setq js2-imenu-recorder 'empty))
7717 (run-hooks 'js2-parse-finished-hook)
7720 ;; Corresponds to Rhino's Parser.parse() method.
7721 (defun js2-do-parse ()
7722 "Parse current buffer starting from current point.
7723 Scanner should be initialized."
7724 (let ((pos js2-ts-cursor)
7725 (end js2-ts-cursor) ; in case file is empty
7727 ;; initialize buffer-local parsing vars
7728 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7729 js2-current-script-or-fn root
7730 js2-current-scope root
7731 js2-nesting-of-function 0
7732 js2-labeled-stmt nil
7733 js2-recorded-identifiers nil) ; for js2-highlight
7734 (while (/= (setq tt (js2-get-token)) js2-EOF)
7735 (if (= tt js2-FUNCTION)
7737 (setq n (if js2-called-by-compile-function
7738 (js2-parse-function-expr)
7739 (js2-parse-function-stmt))))
7740 ;; not a function - parse a statement
7742 (setq n (js2-parse-statement)))
7743 ;; add function or statement to script
7744 (setq end (js2-node-end n))
7745 (js2-block-node-push root n))
7746 ;; add comments to root in lexical order
7747 (when js2-scanned-comments
7748 ;; if we find a comment beyond end of normal kids, use its end
7749 (setq end (max end (js2-node-end (cl-first js2-scanned-comments))))
7750 (dolist (comment js2-scanned-comments)
7751 (push comment (js2-ast-root-comments root))
7752 (js2-node-add-children root comment)))
7753 (setf (js2-node-len root) (- end pos))
7754 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7755 ;; Give extensions a chance to muck with things before highlighting starts.
7756 (let ((js2-additional-externs js2-additional-externs))
7758 (run-hooks 'js2-post-parse-callbacks))
7759 (js2-highlight-undeclared-vars))
7762 (defun js2-parse-function-closure-body (fn-node)
7763 "Parse a JavaScript 1.8 function closure body."
7764 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7766 (js2-report-error "msg.no.brace.body" nil
7767 (js2-node-pos fn-node)
7768 (- js2-ts-cursor (js2-node-pos fn-node)))
7769 (js2-node-add-children fn-node
7770 (setf (js2-function-node-body fn-node)
7771 (js2-parse-expr t))))))
7773 (defun js2-parse-function-body (fn-node)
7774 (js2-must-match js2-LC "msg.no.brace.body"
7775 (js2-node-pos fn-node)
7776 (- js2-ts-cursor (js2-node-pos fn-node)))
7777 (let ((pos (js2-current-token-beg)) ; LC position
7778 (pn (make-js2-block-node)) ; starts at LC position
7781 (cl-incf js2-nesting-of-function)
7783 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7786 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7787 (js2-parse-statement)
7789 (js2-parse-function-stmt))))
7790 (cl-decf js2-nesting-of-function))
7791 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7792 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7793 (setq end (js2-current-token-end)))
7794 (setf (js2-node-pos pn) pos
7795 (js2-node-len pn) (- end pos))
7796 (setf (js2-function-node-body fn-node) pn)
7797 (js2-node-add-children fn-node pn)
7800 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7801 "Declare and fontify destructuring parameters inside NODE.
7802 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7804 ((js2-name-node-p node)
7806 (js2-define-symbol decl-type (js2-name-node-name node)
7807 node ignore-not-in-block)
7809 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7810 (+ leftpos (js2-node-len node))
7812 ((js2-object-node-p node)
7813 (dolist (elem (js2-object-node-elems node))
7814 (js2-define-destruct-symbols
7815 ;; In abbreviated destructuring {a, b}, right == left.
7816 (js2-object-prop-node-right elem)
7817 decl-type face ignore-not-in-block)))
7818 ((js2-array-node-p node)
7819 (dolist (elem (js2-array-node-elems node))
7821 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7822 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7823 (js2-node-len node)))))
7825 (defun js2-parse-function-params (function-type fn-node pos)
7826 (if (js2-match-token js2-RP)
7827 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7828 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7829 (eq (js2-current-token-type) js2-NAME)))
7830 params param default-found rest-param-at)
7831 (when paren-free-arrow
7833 (cl-loop for tt = (js2-peek-token)
7836 ;; destructuring param
7837 ((and (not paren-free-arrow)
7838 (or (= tt js2-LB) (= tt js2-LC)))
7841 (js2-report-error "msg.no.default.after.default.param"))
7842 (setq param (js2-parse-destruct-primary-expr))
7843 (js2-define-destruct-symbols param
7845 'js2-function-param)
7846 (push param params))
7849 (when (and (>= js2-language-version 200)
7850 (not paren-free-arrow)
7851 (js2-match-token js2-TRIPLEDOT)
7852 (not rest-param-at))
7853 ;; to report errors if there are more parameters
7854 (setq rest-param-at (length params)))
7855 (js2-must-match-name "msg.no.parm")
7856 (js2-record-face 'js2-function-param)
7857 (setq param (js2-create-name-node))
7858 (js2-define-symbol js2-LP (js2-current-token-string) param)
7859 ;; default parameter value
7860 (when (or (and default-found
7862 (js2-must-match js2-ASSIGN
7863 "msg.no.default.after.default.param"
7864 (js2-node-pos param)
7865 (js2-node-len param)))
7866 (and (>= js2-language-version 200)
7867 (js2-match-token js2-ASSIGN)))
7868 (cl-assert (not paren-free-arrow))
7869 (let* ((pos (js2-node-pos param))
7870 (tt (js2-current-token-type))
7871 (op-pos (- (js2-current-token-beg) pos))
7873 (right (js2-parse-assign-expr))
7874 (len (- (js2-node-end right) pos)))
7875 (setq param (make-js2-assign-node
7876 :type tt :pos pos :len len :op-pos op-pos
7877 :left left :right right)
7879 (js2-node-add-children param left right)))
7880 (push param params)))
7881 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7882 (js2-report-error "msg.param.after.rest" nil
7883 (js2-node-pos param) (js2-node-len param)))
7885 (js2-match-token js2-COMMA))
7886 (when (and (not paren-free-arrow)
7887 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7888 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7890 (setf (js2-function-node-rest-p fn-node) t))
7892 (js2-node-add-children fn-node p)
7893 (push p (js2-function-node-params fn-node))))))
7895 (defun js2-check-inconsistent-return-warning (fn-node name)
7896 "Possibly show inconsistent-return warning.
7897 Last token scanned is the close-curly for the function body."
7898 (when (and js2-mode-show-strict-warnings
7899 js2-strict-inconsistent-return-warning
7900 (not (js2-has-consistent-return-usage
7901 (js2-function-node-body fn-node))))
7902 ;; Have it extend from close-curly to bol or beginning of block.
7903 (let ((pos (save-excursion
7904 (goto-char (js2-current-token-end))
7905 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7907 (end (js2-current-token-end)))
7908 (if (cl-plusp (js2-name-node-length name))
7909 (js2-add-strict-warning "msg.no.return.value"
7910 (js2-name-node-name name) pos end)
7911 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7913 (defun js2-parse-function-stmt ()
7914 (let ((pos (js2-current-token-beg))
7915 (star-p (js2-match-token js2-MUL)))
7916 (js2-must-match-name "msg.unnamed.function.stmt")
7917 (let ((name (js2-create-name-node t))
7920 ((js2-match-token js2-LP)
7921 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7922 (js2-allow-member-expr-as-function-name
7923 (setq member-expr (js2-parse-member-expr-tail nil name))
7924 (js2-parse-highlight-member-expr-fn-name member-expr)
7925 (js2-must-match js2-LP "msg.no.paren.parms")
7926 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7927 (js2-function-node-member-expr pn) member-expr)
7930 (js2-report-error "msg.no.paren.parms")
7931 (make-js2-error-node))))))
7933 (defun js2-parse-function-expr ()
7934 (let ((pos (js2-current-token-beg))
7935 (star-p (js2-match-token js2-MUL))
7937 (when (js2-match-token js2-NAME)
7938 (setq name (js2-create-name-node t)))
7939 (js2-must-match js2-LP "msg.no.paren.parms")
7940 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7942 (defun js2-parse-function (function-type pos star-p &optional name)
7943 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7944 beginning of the first token (function keyword, unless it's an
7945 arrow function), NAME is js2-name-node."
7947 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7948 (setq lp (js2-current-token-beg)))
7949 (setf fn-node (make-js2-function-node :pos pos
7952 :lp (if lp (- lp pos))
7953 :generator-type (and star-p 'STAR)))
7955 (js2-set-face (js2-node-pos name) (js2-node-end name)
7956 'font-lock-function-name-face 'record)
7957 (when (and (eq function-type 'FUNCTION_STATEMENT)
7958 (cl-plusp (js2-name-node-length name)))
7959 ;; Function statements define a symbol in the enclosing scope
7960 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7961 (if (or (js2-inside-function) (cl-plusp js2-nesting-of-with))
7962 ;; 1. Nested functions are not affected by the dynamic scope flag
7963 ;; as dynamic scope is already a parent of their scope.
7964 ;; 2. Functions defined under the with statement also immune to
7965 ;; this setup, in which case dynamic scope is ignored in favor
7966 ;; of the with object.
7967 (setf (js2-function-node-ignore-dynamic fn-node) t))
7968 ;; dynamically bind all the per-function variables
7969 (let ((js2-current-script-or-fn fn-node)
7970 (js2-current-scope fn-node)
7971 (js2-nesting-of-with 0)
7975 js2-loop-and-switch-set)
7976 (js2-parse-function-params function-type fn-node pos)
7977 (when (eq function-type 'FUNCTION_ARROW)
7978 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7979 (if (and (>= js2-language-version 180)
7980 (/= (js2-peek-token) js2-LC))
7981 (js2-parse-function-closure-body fn-node)
7982 (js2-parse-function-body fn-node))
7983 (js2-check-inconsistent-return-warning fn-node name)
7986 (js2-node-add-children fn-node name)
7987 ;; Function expressions define a name only in the body of the
7988 ;; function, and only if not hidden by a parameter name
7989 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7990 (null (js2-scope-get-symbol js2-current-scope
7991 (js2-name-node-name name))))
7992 (js2-define-symbol js2-FUNCTION
7993 (js2-name-node-name name)
7995 (when (eq function-type 'FUNCTION_STATEMENT)
7996 (js2-record-imenu-functions fn-node))))
7998 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7999 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
8000 ;; We wait until after parsing the function to set its parent scope,
8001 ;; since `js2-define-symbol' needs the defining-scope check to stop
8002 ;; at the function boundary when checking for redeclarations.
8003 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
8006 (defun js2-parse-statements (&optional parent)
8007 "Parse a statement list. Last token consumed must be js2-LC.
8009 PARENT can be a `js2-block-node', in which case the statements are
8010 appended to PARENT. Otherwise a new `js2-block-node' is created
8013 This function does not match the closing js2-RC: the caller
8014 matches the RC so it can provide a suitable error message if not
8015 matched. This means it's up to the caller to set the length of
8016 the node to include the closing RC. The node start pos is set to
8017 the absolute buffer start position, and the caller should fix it
8018 up to be relative to the parent node. All children of this block
8019 node are given relative start positions and correct lengths."
8020 (let ((pn (or parent (make-js2-block-node)))
8022 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
8024 (js2-block-node-push pn (js2-parse-statement)))
8027 (defun js2-parse-statement ()
8029 ;; coarse-grained user-interrupt check - needs work
8030 (and js2-parse-interruptable-p
8031 (zerop (% (cl-incf js2-parse-stmt-count)
8032 js2-statements-per-pause))
8034 (throw 'interrupted t))
8035 (setq pn (js2-statement-helper))
8036 ;; no-side-effects warning check
8037 (unless (js2-node-has-side-effects pn)
8038 (setq end (js2-node-end pn))
8041 (setq beg (max (js2-node-pos pn) (point-at-bol))))
8042 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
8045 ;; These correspond to the switch cases in Parser.statementHelper
8046 (defconst js2-parsers
8047 (let ((parsers (make-vector js2-num-tokens
8048 #'js2-parse-expr-stmt)))
8049 (aset parsers js2-BREAK #'js2-parse-break)
8050 (aset parsers js2-CLASS #'js2-parse-class-stmt)
8051 (aset parsers js2-CONST #'js2-parse-const-var)
8052 (aset parsers js2-CONTINUE #'js2-parse-continue)
8053 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
8054 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
8055 (aset parsers js2-DO #'js2-parse-do)
8056 (aset parsers js2-EXPORT #'js2-parse-export)
8057 (aset parsers js2-FOR #'js2-parse-for)
8058 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
8059 (aset parsers js2-IF #'js2-parse-if)
8060 (aset parsers js2-IMPORT #'js2-parse-import)
8061 (aset parsers js2-LC #'js2-parse-block)
8062 (aset parsers js2-LET #'js2-parse-let-stmt)
8063 (aset parsers js2-NAME #'js2-parse-name-or-label)
8064 (aset parsers js2-RETURN #'js2-parse-ret-yield)
8065 (aset parsers js2-SEMI #'js2-parse-semi)
8066 (aset parsers js2-SWITCH #'js2-parse-switch)
8067 (aset parsers js2-THROW #'js2-parse-throw)
8068 (aset parsers js2-TRY #'js2-parse-try)
8069 (aset parsers js2-VAR #'js2-parse-const-var)
8070 (aset parsers js2-WHILE #'js2-parse-while)
8071 (aset parsers js2-WITH #'js2-parse-with)
8072 (aset parsers js2-YIELD #'js2-parse-ret-yield)
8074 "A vector mapping token types to parser functions.")
8076 (defun js2-parse-warn-missing-semi (beg end)
8077 (and js2-mode-show-strict-warnings
8078 js2-strict-missing-semi-warning
8079 (js2-add-strict-warning
8080 "msg.missing.semi" nil
8081 ;; back up to beginning of statement or line
8082 (max beg (save-excursion
8087 (defconst js2-no-semi-insertion
8101 "List of tokens that don't do automatic semicolon insertion.")
8103 (defconst js2-autoinsert-semi-and-warn
8104 (list js2-ERROR js2-EOF js2-RC))
8106 (defun js2-statement-helper ()
8107 (let* ((tt (js2-get-token))
8109 (parser (if (= tt js2-ERROR)
8111 (aref js2-parsers tt)))
8113 ;; If the statement is set, then it's been told its label by now.
8114 (and js2-labeled-stmt
8115 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
8116 (setq js2-labeled-stmt nil))
8117 (setq pn (funcall parser))
8118 ;; Don't do auto semi insertion for certain statement types.
8119 (unless (or (memq first-tt js2-no-semi-insertion)
8120 (js2-labeled-stmt-node-p pn))
8121 (js2-auto-insert-semicolon pn))
8124 (defun js2-auto-insert-semicolon (pn)
8125 (let* ((tt (js2-get-token))
8126 (pos (js2-node-pos pn)))
8129 ;; extend the node bounds to include the semicolon.
8130 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8131 ((memq tt js2-autoinsert-semi-and-warn)
8132 (js2-unget-token) ; Not ';', do not consume.
8134 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8136 (if (not (js2-token-follows-eol-p (js2-current-token)))
8137 ;; Report error if no EOL or autoinsert ';' otherwise
8138 (js2-report-error "msg.no.semi.stmt")
8139 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
8140 (js2-unget-token) ; Not ';', do not consume.
8143 (defun js2-parse-condition ()
8144 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
8145 The parens are discarded and the expression node is returned.
8146 The `pos' field of the return value is set to an absolute position
8147 that must be fixed up by the caller.
8148 Return value is a list (EXPR LP RP), with absolute paren positions."
8150 (if (js2-must-match js2-LP "msg.no.paren.cond")
8151 (setq lp (js2-current-token-beg)))
8152 (setq pn (js2-parse-expr))
8153 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
8154 (setq rp (js2-current-token-beg)))
8155 ;; Report strict warning on code like "if (a = 7) ..."
8156 (if (and js2-strict-cond-assign-warning
8157 (js2-assign-node-p pn))
8158 (js2-add-strict-warning "msg.equal.as.assign" nil
8160 (+ (js2-node-pos pn)
8161 (js2-node-len pn))))
8164 (defun js2-parse-if ()
8165 "Parser for if-statement. Last matched token must be js2-IF."
8166 (let ((pos (js2-current-token-beg))
8167 cond if-true if-false else-pos end pn)
8168 (setq cond (js2-parse-condition)
8169 if-true (js2-parse-statement)
8170 if-false (if (js2-match-token js2-ELSE)
8172 (setq else-pos (- (js2-current-token-beg) pos))
8173 (js2-parse-statement)))
8174 end (js2-node-end (or if-false if-true))
8175 pn (make-js2-if-node :pos pos
8177 :condition (car cond)
8181 :lp (js2-relpos (cl-second cond) pos)
8182 :rp (js2-relpos (cl-third cond) pos)))
8183 (js2-node-add-children pn (car cond) if-true if-false)
8186 (defun js2-parse-import ()
8187 "Parse import statement. The current token must be js2-IMPORT."
8188 (unless (js2-ast-root-p js2-current-scope)
8189 (js2-report-error "msg.mod.import.decl.at.top.level"))
8190 (let ((beg (js2-current-token-beg)))
8191 (cond ((js2-match-token js2-STRING)
8192 (make-js2-import-node
8194 :len (- (js2-current-token-end) beg)
8195 :module-id (js2-current-token-string)))
8197 (let* ((import-clause (js2-parse-import-clause))
8198 (from-clause (and import-clause (js2-parse-from-clause)))
8199 (module-id (when from-clause (js2-from-clause-node-module-id from-clause)))
8200 (node (make-js2-import-node
8202 :len (- (js2-current-token-end) beg)
8203 :import import-clause
8205 :module-id module-id)))
8207 (js2-node-add-children node import-clause))
8209 (js2-node-add-children node from-clause))
8212 (defun js2-parse-import-clause ()
8213 "Parse the bindings in an import statement.
8214 This can take many forms:
8216 ImportedDefaultBinding -> 'foo'
8217 NameSpaceImport -> '* as lib'
8218 NamedImports -> '{foo as bar, bang}'
8219 ImportedDefaultBinding , NameSpaceImport -> 'foo, * as lib'
8220 ImportedDefaultBinding , NamedImports -> 'foo, {bar, baz as bif}'
8222 Try to match namespace imports and named imports first because nothing can
8223 come after them. If it is an imported default binding, then it could have named
8224 imports or a namespace import that follows it.
8226 (let* ((beg (js2-current-token-beg))
8227 (clause (make-js2-import-clause-node
8231 ((js2-match-token js2-MUL)
8232 (let ((ns-import (js2-parse-namespace-import)))
8234 (let ((name-node (js2-namespace-import-node-name ns-import)))
8236 js2-LET (js2-name-node-name name-node) name-node t)))
8237 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8238 (push ns-import children)))
8239 ((js2-match-token js2-LC)
8240 (let ((imports (js2-parse-export-bindings t)))
8241 (setf (js2-import-clause-node-named-imports clause) imports)
8242 (dolist (import imports)
8243 (push import children)
8244 (let ((name-node (js2-export-binding-node-local-name import)))
8247 js2-LET (js2-name-node-name name-node) name-node t))))))
8248 ((= (js2-peek-token) js2-NAME)
8249 (let ((binding (js2-maybe-parse-export-binding)))
8250 (let ((node-name (js2-export-binding-node-local-name binding)))
8251 (js2-define-symbol js2-LET (js2-name-node-name node-name) node-name t))
8252 (setf (js2-import-clause-node-default-binding clause) binding)
8253 (push binding children))
8254 (when (js2-match-token js2-COMMA)
8256 ((js2-match-token js2-MUL)
8257 (let ((ns-import (js2-parse-namespace-import)))
8258 (let ((name-node (js2-namespace-import-node-name ns-import)))
8260 js2-LET (js2-name-node-name name-node) name-node t))
8261 (setf (js2-import-clause-node-namespace-import clause) ns-import)
8262 (push ns-import children)))
8263 ((js2-match-token js2-LC)
8264 (let ((imports (js2-parse-export-bindings t)))
8265 (setf (js2-import-clause-node-named-imports clause) imports)
8266 (dolist (import imports)
8267 (push import children)
8268 (let ((name-node (js2-export-binding-node-local-name import)))
8271 js2-LET (js2-name-node-name name-node) name-node t))))))
8272 (t (js2-report-error "msg.syntax")))))
8273 (t (js2-report-error "msg.mod.declaration.after.import")))
8274 (setf (js2-node-len clause) (- (js2-current-token-end) beg))
8275 (apply #'js2-node-add-children clause children)
8278 (defun js2-parse-namespace-import ()
8279 "Parse a namespace import expression such as '* as bar'.
8280 The current token must be js2-MUL."
8281 (let ((beg (js2-current-token-beg)))
8282 (when (js2-must-match js2-NAME "msg.syntax")
8283 (if (equal "as" (js2-current-token-string))
8284 (when (js2-must-match-prop-name "msg.syntax")
8285 (let ((node (make-js2-namespace-import-node
8287 :len (- (js2-current-token-end) beg)
8288 :name (make-js2-name-node
8289 :pos (js2-current-token-beg)
8290 :len (js2-current-token-end)
8291 :name (js2-current-token-string)))))
8292 (js2-node-add-children node (js2-namespace-import-node-name node))
8295 (js2-report-error "msg.syntax")))))
8298 (defun js2-parse-from-clause ()
8299 "Parse the from clause in an import or export statement. E.g. from 'src/lib'"
8300 (when (js2-must-match-name "msg.mod.from.after.import.spec.set")
8301 (let ((beg (js2-current-token-beg)))
8302 (if (equal "from" (js2-current-token-string))
8304 ((js2-match-token js2-STRING)
8305 (make-js2-from-clause-node
8307 :len (- (js2-current-token-end) beg)
8308 :module-id (js2-current-token-string)
8310 ((js2-match-token js2-THIS)
8311 (when (js2-must-match-name "msg.mod.spec.after.from")
8312 (if (equal "module" (js2-current-token-string))
8313 (make-js2-from-clause-node
8315 :len (- (js2-current-token-end) beg)
8320 (js2-report-error "msg.mod.spec.after.from")
8322 (t (js2-report-error "msg.mod.spec.after.from") nil))
8324 (js2-report-error "msg.mod.from.after.import.spec.set")
8327 (defun js2-parse-export-bindings (&optional import-p)
8328 "Parse a list of export binding expressions such as {}, {foo, bar}, and
8329 {foo as bar, baz as bang}. The current token must be
8330 js2-LC. Return a lisp list of js2-export-binding-node"
8331 (let ((bindings (list)))
8333 (let ((binding (js2-maybe-parse-export-binding)))
8335 (push binding bindings))
8336 (js2-match-token js2-COMMA)))
8337 (when (js2-must-match js2-RC (if import-p
8338 "msg.mod.rc.after.import.spec.list"
8339 "msg.mod.rc.after.export.spec.list"))
8340 (reverse bindings))))
8342 (defun js2-maybe-parse-export-binding ()
8343 "Attempt to parse a binding expression found inside an import/export statement.
8344 This can take the form of either as single js2-NAME token as in 'foo' or as in a
8345 rebinding expression 'bar as foo'. If it matches, it will return an instance of
8346 js2-export-binding-node and consume all the tokens. If it does not match, it
8347 consumes no tokens."
8348 (let ((extern-name (when (js2-match-prop-name) (js2-current-token-string)))
8349 (beg (js2-current-token-beg))
8350 (extern-name-len (js2-current-token-len))
8351 (is-reserved-name (or (= (js2-current-token-type) js2-RESERVED)
8352 (aref js2-kwd-tokens (js2-current-token-type)))))
8354 (let ((as (and (js2-match-token js2-NAME) (js2-current-token-string))))
8355 (if (and as (equal "as" (js2-current-token-string)))
8358 (and (js2-match-token js2-DEFAULT) "default")
8359 (and (js2-match-token js2-NAME) (js2-current-token-string)))))
8361 (let ((node (make-js2-export-binding-node
8363 :len (- (js2-current-token-end) beg)
8364 :local-name (make-js2-name-node
8366 :pos (js2-current-token-beg)
8367 :len (js2-current-token-len))
8368 :extern-name (make-js2-name-node
8371 :len extern-name-len))))
8372 (js2-node-add-children
8374 (js2-export-binding-node-local-name node)
8375 (js2-export-binding-node-extern-name node))
8379 (when as (js2-unget-token))
8380 (let* ((name-node (make-js2-name-node
8381 :name (js2-current-token-string)
8382 :pos (js2-current-token-beg)
8383 :len (js2-current-token-len)))
8384 (node (make-js2-export-binding-node
8385 :pos (js2-current-token-beg)
8386 :len (js2-current-token-len)
8387 :local-name name-node
8388 :extern-name name-node)))
8389 (when is-reserved-name
8390 (js2-report-error "msg.mod.as.after.reserved.word" extern-name))
8391 (js2-node-add-children node name-node)
8395 (defun js2-parse-switch ()
8396 "Parser for switch-statement. Last matched token must be js2-SWITCH."
8397 (let ((pos (js2-current-token-beg))
8398 tt pn discriminant has-default case-expr case-node
8399 case-pos cases stmt lp)
8400 (if (js2-must-match js2-LP "msg.no.paren.switch")
8401 (setq lp (js2-current-token-beg)))
8402 (setq discriminant (js2-parse-expr)
8403 pn (make-js2-switch-node :discriminant discriminant
8405 :lp (js2-relpos lp pos)))
8406 (js2-node-add-children pn discriminant)
8407 (js2-enter-switch pn)
8410 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
8411 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
8412 (js2-must-match js2-LC "msg.no.brace.switch")
8415 (setq tt (js2-next-token)
8416 case-pos (js2-current-token-beg))
8419 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
8420 (throw 'break nil)) ; done
8422 (setq case-expr (js2-parse-expr))
8423 (js2-must-match js2-COLON "msg.no.colon.case"))
8426 (js2-report-error "msg.double.switch.default"))
8429 (js2-must-match js2-COLON "msg.no.colon.case"))
8431 (js2-report-error "msg.bad.switch")
8432 (throw 'break nil)))
8433 (setq case-node (make-js2-case-node :pos case-pos
8434 :len (- (js2-current-token-end) case-pos)
8436 (js2-node-add-children case-node case-expr)
8437 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
8441 (setf stmt (js2-parse-statement)
8442 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
8443 (js2-block-node-push case-node stmt))
8444 (push case-node cases)))
8445 ;; add cases last, as pushing reverses the order to be correct
8447 (js2-node-add-children pn kid)
8448 (push kid (js2-switch-node-cases pn)))
8450 (js2-exit-switch))))
8452 (defun js2-parse-while ()
8453 "Parser for while-statement. Last matched token must be js2-WHILE."
8454 (let ((pos (js2-current-token-beg))
8455 (pn (make-js2-while-node))
8460 (setf cond (js2-parse-condition)
8461 (js2-while-node-condition pn) (car cond)
8462 body (js2-parse-statement)
8463 (js2-while-node-body pn) body
8464 (js2-node-len pn) (- (js2-node-end body) pos)
8465 (js2-while-node-lp pn) (js2-relpos (cl-second cond) pos)
8466 (js2-while-node-rp pn) (js2-relpos (cl-third cond) pos))
8467 (js2-node-add-children pn body (car cond)))
8471 (defun js2-parse-do ()
8472 "Parser for do-statement. Last matched token must be js2-DO."
8473 (let ((pos (js2-current-token-beg))
8474 (pn (make-js2-do-node))
8479 (setq body (js2-parse-statement))
8480 (js2-must-match js2-WHILE "msg.no.while.do")
8481 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
8482 cond (js2-parse-condition)
8483 (js2-do-node-condition pn) (car cond)
8484 (js2-do-node-body pn) body
8486 (js2-do-node-lp pn) (js2-relpos (cl-second cond) pos)
8487 (js2-do-node-rp pn) (js2-relpos (cl-third cond) pos))
8488 (js2-node-add-children pn (car cond) body))
8490 ;; Always auto-insert semicolon to follow SpiderMonkey:
8491 ;; It is required by ECMAScript but is ignored by the rest of
8492 ;; world; see bug 238945
8493 (if (js2-match-token js2-SEMI)
8494 (setq end js2-ts-cursor))
8495 (setf (js2-node-len pn) (- end pos))
8498 (defun js2-parse-export ()
8499 "Parse an export statement.
8500 The Last matched token must be js2-EXPORT. Currently, the 'default' and 'expr'
8501 expressions should only be either hoistable expressions (function or generator)
8502 or assignment expressions, but there is no checking to enforce that and so it
8503 will parse without error a small subset of
8504 invalid export statements."
8505 (unless (js2-ast-root-p js2-current-scope)
8506 (js2-report-error "msg.mod.export.decl.at.top.level"))
8507 (let ((beg (js2-current-token-beg))
8509 exports-list from-clause declaration default)
8511 ((js2-match-token js2-MUL)
8512 (setq from-clause (js2-parse-from-clause))
8514 (push from-clause children)))
8515 ((js2-match-token js2-LC)
8516 (setq exports-list (js2-parse-export-bindings))
8518 (dolist (export exports-list)
8519 (push export children)))
8520 (when (js2-match-token js2-NAME)
8521 (if (equal "from" (js2-current-token-string))
8524 (setq from-clause (js2-parse-from-clause)))
8525 (js2-unget-token))))
8526 ((js2-match-token js2-DEFAULT)
8527 (setq default (js2-parse-expr)))
8528 ((or (js2-match-token js2-VAR) (js2-match-token js2-CONST) (js2-match-token js2-LET))
8529 (setq declaration (js2-parse-variables (js2-current-token-type) (js2-current-token-beg))))
8531 (setq declaration (js2-parse-expr))))
8533 (push from-clause children))
8535 (push declaration children)
8536 (when (not (js2-function-node-p declaration))
8537 (js2-auto-insert-semicolon declaration)))
8539 (push default children)
8540 (when (not (js2-function-node-p default))
8541 (js2-auto-insert-semicolon default)))
8542 (let ((node (make-js2-export-node
8544 :len (- (js2-current-token-end) beg)
8545 :exports-list exports-list
8546 :from-clause from-clause
8547 :declaration declaration
8549 (apply #'js2-node-add-children node children)
8552 (defun js2-parse-for ()
8553 "Parse a for, for-in or for each-in statement.
8554 Last matched token must be js2-FOR."
8555 (let ((for-pos (js2-current-token-beg))
8556 (tmp-scope (make-js2-scope))
8557 pn is-for-each is-for-in-or-of is-for-of
8558 in-pos each-pos tmp-pos
8559 init ; Node init is also foo in 'foo in object'.
8560 cond ; Node cond is also object in 'foo in object'.
8561 incr ; 3rd section of for-loop initializer.
8563 ;; See if this is a for each () instead of just a for ()
8564 (when (js2-match-token js2-NAME)
8565 (if (string= "each" (js2-current-token-string))
8568 each-pos (- (js2-current-token-beg) for-pos)) ; relative
8569 (js2-record-face 'font-lock-keyword-face))
8570 (js2-report-error "msg.no.paren.for")))
8571 (if (js2-must-match js2-LP "msg.no.paren.for")
8572 (setq lp (- (js2-current-token-beg) for-pos)))
8573 (setq tt (js2-get-token))
8574 ;; Capture identifiers inside parens. We can't create the node
8575 ;; (and use it as the current scope) until we know its type.
8576 (js2-push-scope tmp-scope)
8579 ;; parse init clause
8580 (let ((js2-in-for-init t)) ; set as dynamic variable
8584 (setq init (make-js2-empty-expr-node)))
8585 ((or (= tt js2-VAR) (= tt js2-LET))
8586 (setq init (js2-parse-variables tt (js2-current-token-beg))))
8589 (setq init (js2-parse-expr)))))
8590 (if (or (js2-match-token js2-IN)
8591 (and (>= js2-language-version 200)
8592 (js2-match-contextual-kwd "of")
8593 (setq is-for-of t)))
8594 (setq is-for-in-or-of t
8595 in-pos (- (js2-current-token-beg) for-pos)
8596 ;; scope of iteration target object is not the scope we've created above.
8597 ;; stash current scope temporary.
8598 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8599 (js2-parse-expr))) ; object over which we're iterating
8600 ;; else ordinary for loop - parse cond and incr
8601 (js2-must-match js2-SEMI "msg.no.semi.for")
8602 (setq cond (if (= (js2-peek-token) js2-SEMI)
8603 (make-js2-empty-expr-node) ; no loop condition
8605 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8606 (setq tmp-pos (js2-current-token-end)
8607 incr (if (= (js2-peek-token) js2-RP)
8608 (make-js2-empty-expr-node :pos tmp-pos)
8609 (js2-parse-expr)))))
8611 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8612 (setq rp (- (js2-current-token-beg) for-pos)))
8613 (if (not is-for-in-or-of)
8614 (setq pn (make-js2-for-node :init init
8619 ;; cond could be null if 'in obj' got eaten by the init node.
8620 (if (js2-infix-node-p init)
8621 ;; it was (foo in bar) instead of (var foo in bar)
8622 (setq cond (js2-infix-node-right init)
8623 init (js2-infix-node-left init))
8624 (if (and (js2-var-decl-node-p init)
8625 (> (length (js2-var-decl-node-kids init)) 1))
8626 (js2-report-error "msg.mult.index")))
8627 (setq pn (make-js2-for-in-node :iterator init
8630 :foreach-p is-for-each
8635 ;; Transplant the declarations.
8636 (setf (js2-scope-symbol-table pn)
8637 (js2-scope-symbol-table tmp-scope))
8641 ;; We have to parse the body -after- creating the loop node,
8642 ;; so that the loop node appears in the js2-loop-set, allowing
8643 ;; break/continue statements to find the enclosing loop.
8644 (setf body (js2-parse-statement)
8645 (js2-loop-node-body pn) body
8646 (js2-node-pos pn) for-pos
8647 (js2-node-len pn) (- (js2-node-end body) for-pos))
8648 (js2-node-add-children pn init cond incr body))
8653 (defun js2-parse-try ()
8654 "Parse a try statement. Last matched token must be js2-TRY."
8655 (let ((try-pos (js2-current-token-beg))
8662 (if (/= (js2-peek-token) js2-LC)
8663 (js2-report-error "msg.no.brace.try"))
8664 (setq try-block (js2-parse-statement)
8665 try-end (js2-node-end try-block)
8666 peek (js2-peek-token))
8669 (while (js2-match-token js2-CATCH)
8670 (let* ((catch-pos (js2-current-token-beg))
8671 (catch-node (make-js2-catch-node :pos catch-pos))
8676 (if saw-default-catch
8677 (js2-report-error "msg.catch.unreachable"))
8678 (if (js2-must-match js2-LP "msg.no.paren.catch")
8679 (setq lp (- (js2-current-token-beg) catch-pos)))
8680 (js2-push-scope catch-node)
8681 (let ((tt (js2-peek-token)))
8683 ;; Destructuring pattern:
8684 ;; catch ({ message, file }) { ... }
8685 ((or (= tt js2-LB) (= tt js2-LC))
8687 (setq param (js2-parse-destruct-primary-expr))
8688 (js2-define-destruct-symbols param js2-LET nil))
8691 (js2-must-match-name "msg.bad.catchcond")
8692 (setq param (js2-create-name-node))
8693 (js2-define-symbol js2-LET (js2-current-token-string) param))))
8695 (if (js2-match-token js2-IF)
8696 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8697 catch-cond (js2-parse-expr))
8698 (setq saw-default-catch t))
8699 (if (js2-must-match js2-RP "msg.bad.catchcond")
8700 (setq rp (- (js2-current-token-beg) catch-pos)))
8701 (js2-must-match js2-LC "msg.no.brace.catchblock")
8702 (js2-parse-statements catch-node)
8703 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8704 (setq try-end (js2-current-token-end)))
8706 (setf (js2-node-len catch-node) (- try-end catch-pos)
8707 (js2-catch-node-param catch-node) param
8708 (js2-catch-node-guard-expr catch-node) catch-cond
8709 (js2-catch-node-guard-kwd catch-node) guard-kwd
8710 (js2-catch-node-lp catch-node) lp
8711 (js2-catch-node-rp catch-node) rp)
8712 (js2-node-add-children catch-node param catch-cond)
8713 (push catch-node catch-blocks))))
8714 ((/= peek js2-FINALLY)
8715 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8716 (js2-node-pos try-block)
8717 (- (setq try-end (js2-node-end try-block))
8718 (js2-node-pos try-block)))))
8719 (when (js2-match-token js2-FINALLY)
8720 (let ((finally-pos (js2-current-token-beg))
8721 (block (js2-parse-statement)))
8722 (setq try-end (js2-node-end block)
8723 finally-block (make-js2-finally-node :pos finally-pos
8724 :len (- try-end finally-pos)
8726 (js2-node-add-children finally-block block)))
8727 (let ((pn (make-js2-try-node :pos try-pos
8728 :len (- try-end try-pos)
8729 :try-block try-block
8730 :finally-block finally-block)))
8731 (js2-node-add-children pn try-block finally-block)
8732 ;; Push them onto the try-node, which reverses and corrects their order.
8733 (dolist (cb catch-blocks)
8734 (js2-node-add-children pn cb)
8735 (push cb (js2-try-node-catch-clauses pn)))
8738 (defun js2-parse-throw ()
8739 "Parser for throw-statement. Last matched token must be js2-THROW."
8740 (let ((pos (js2-current-token-beg))
8742 (if (= (js2-peek-token-or-eol) js2-EOL)
8743 ;; ECMAScript does not allow new lines before throw expression,
8745 (js2-report-error "msg.bad.throw.eol"))
8746 (setq expr (js2-parse-expr)
8747 pn (make-js2-throw-node :pos pos
8748 :len (- (js2-node-end expr) pos)
8750 (js2-node-add-children pn expr)
8753 (defun js2-match-jump-label-name (label-name)
8754 "If break/continue specified a label, return that label's labeled stmt.
8755 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8756 does not match an existing label, reports an error and returns nil."
8757 (let ((bundle (cdr (assoc label-name js2-label-set))))
8759 (js2-report-error "msg.undef.label"))
8762 (defun js2-parse-break ()
8763 "Parser for break-statement. Last matched token must be js2-BREAK."
8764 (let ((pos (js2-current-token-beg))
8765 (end (js2-current-token-end))
8766 break-target ; statement to break from
8767 break-label ; in "break foo", name-node representing the foo
8768 labels ; matching labeled statement to break to
8770 (when (eq (js2-peek-token-or-eol) js2-NAME)
8772 (setq break-label (js2-create-name-node)
8773 end (js2-node-end break-label)
8774 ;; matchJumpLabelName only matches if there is one
8775 labels (js2-match-jump-label-name (js2-current-token-string))
8776 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8777 (unless (or break-target break-label)
8778 ;; no break target specified - try for innermost enclosing loop/switch
8779 (if (null js2-loop-and-switch-set)
8781 (js2-report-error "msg.bad.break" nil pos (length "break")))
8782 (setq break-target (car js2-loop-and-switch-set))))
8783 (setq pn (make-js2-break-node :pos pos
8786 :target break-target))
8787 (js2-node-add-children pn break-label) ; but not break-target
8790 (defun js2-parse-continue ()
8791 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8792 (let ((pos (js2-current-token-beg))
8793 (end (js2-current-token-end))
8794 label ; optional user-specified label, a `js2-name-node'
8795 labels ; current matching labeled stmt, if any
8796 target ; the `js2-loop-node' target of this continue stmt
8798 (when (= (js2-peek-token-or-eol) js2-NAME)
8800 (setq label (js2-create-name-node)
8801 end (js2-node-end label)
8802 ;; matchJumpLabelName only matches if there is one
8803 labels (js2-match-jump-label-name (js2-current-token-string))))
8805 ((null labels) ; no current label to go to
8806 (if (null js2-loop-set) ; no loop to continue to
8807 (js2-report-error "msg.continue.outside" nil pos
8808 (length "continue"))
8809 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8811 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8812 (setq target (js2-labeled-stmt-node-stmt labels))
8813 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8814 (setq pn (make-js2-continue-node :pos pos
8818 (js2-node-add-children pn label) ; but not target - it's not our child
8821 (defun js2-parse-with ()
8822 "Parser for with-statement. Last matched token must be js2-WITH."
8823 (let ((pos (js2-current-token-beg))
8825 (if (js2-must-match js2-LP "msg.no.paren.with")
8826 (setq lp (js2-current-token-beg)))
8827 (setq obj (js2-parse-expr))
8828 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8829 (setq rp (js2-current-token-beg)))
8830 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8831 (setq body (js2-parse-statement)))
8832 (setq pn (make-js2-with-node :pos pos
8833 :len (- (js2-node-end body) pos)
8836 :lp (js2-relpos lp pos)
8837 :rp (js2-relpos rp pos)))
8838 (js2-node-add-children pn obj body)
8841 (defun js2-parse-const-var ()
8842 "Parser for var- or const-statement.
8843 Last matched token must be js2-CONST or js2-VAR."
8844 (let ((tt (js2-current-token-type))
8845 (pos (js2-current-token-beg))
8847 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8848 pn (make-js2-expr-stmt-node :pos pos
8849 :len (- (js2-node-end expr) pos)
8851 (js2-node-add-children pn expr)
8854 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8855 (let ((pn (make-js2-expr-stmt-node :pos pos
8856 :len (js2-node-len expr)
8857 :type (if (js2-inside-function)
8862 (js2-node-add-children pn expr))
8865 (defun js2-parse-let-stmt ()
8866 "Parser for let-statement. Last matched token must be js2-LET."
8867 (let ((pos (js2-current-token-beg))
8869 (if (= (js2-peek-token) js2-LP)
8870 ;; let expression in statement context
8871 (setq expr (js2-parse-let pos 'statement)
8872 pn (js2-wrap-with-expr-stmt pos expr t))
8873 ;; else we're looking at a statement like let x=6, y=7;
8874 (setf expr (js2-parse-variables js2-LET pos)
8875 pn (js2-wrap-with-expr-stmt pos expr t)
8876 (js2-node-type pn) js2-EXPR_RESULT))
8879 (defun js2-parse-ret-yield ()
8880 (js2-parse-return-or-yield (js2-current-token-type) nil))
8882 (defconst js2-parse-return-stmt-enders
8883 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8885 (defsubst js2-now-all-set (before after mask)
8886 "Return whether or not the bits in the mask have changed to all set.
8887 BEFORE is bits before change, AFTER is bits after change, and MASK is
8888 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8890 (and (/= (logand before mask) mask)
8891 (= (logand after mask) mask)))
8893 (defun js2-parse-return-or-yield (tt expr-context)
8894 (let* ((pos (js2-current-token-beg))
8895 (end (js2-current-token-end))
8896 (before js2-end-flags)
8897 (inside-function (js2-inside-function))
8898 (gen-type (and inside-function (js2-function-node-generator-type
8899 js2-current-script-or-fn)))
8900 e ret name yield-star-p)
8901 (unless inside-function
8902 (js2-report-error (if (eq tt js2-RETURN)
8905 (when (and inside-function
8907 (js2-match-token js2-MUL))
8908 (setq yield-star-p t))
8909 ;; This is ugly, but we don't want to require a semicolon.
8910 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8911 (setq e (js2-parse-expr)
8912 end (js2-node-end e)))
8915 (js2-set-flag js2-end-flags (if (null e)
8917 js2-end-returns-value))
8918 (setq ret (make-js2-return-node :pos pos
8921 (js2-node-add-children ret e)
8922 ;; See if we need a strict mode warning.
8923 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8924 ;; more thorough and accurate than this before/after flag check.
8925 ;; E.g. if there's a finally-block that always returns, we shouldn't
8926 ;; show a warning generated by inconsistent returns in the catch blocks.
8927 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8928 ;; so we know which returns/yields to highlight, and we should get rid of
8929 ;; all the checking in `js2-parse-return-or-yield'.
8930 (if (and js2-strict-inconsistent-return-warning
8931 (js2-now-all-set before js2-end-flags
8932 (logior js2-end-returns js2-end-returns-value)))
8933 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8934 ((eq gen-type 'COMPREHENSION)
8935 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8936 ;; like SpiderMonkey does.
8937 (js2-report-error "msg.syntax" nil pos 5))
8939 (setq ret (make-js2-yield-node :pos pos
8942 :star-p yield-star-p))
8943 (js2-node-add-children ret e)
8944 (unless expr-context
8946 ret (js2-wrap-with-expr-stmt pos e t))
8947 (js2-set-requires-activation)
8948 (js2-set-is-generator))))
8949 ;; see if we are mixing yields and value returns.
8950 (when (and inside-function
8951 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8952 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8954 (setq name (js2-function-name js2-current-script-or-fn))
8955 (if (zerop (length name))
8956 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8957 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8960 (defun js2-parse-debugger ()
8961 (make-js2-keyword-node :type js2-DEBUGGER))
8963 (defun js2-parse-block ()
8964 "Parser for a curly-delimited statement block.
8965 Last token matched must be `js2-LC'."
8966 (let ((pos (js2-current-token-beg))
8967 (pn (make-js2-scope)))
8971 (js2-parse-statements pn)
8972 (js2-must-match js2-RC "msg.no.brace.block")
8973 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8977 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8978 (defun js2-parse-semi ()
8979 "Parse a statement or handle an error.
8980 Current token type is `js2-SEMI' or `js2-ERROR'."
8981 (let ((tt (js2-current-token-type)) pos len)
8982 (if (eq tt js2-SEMI)
8983 (make-js2-empty-expr-node :len 1)
8984 (setq pos (js2-current-token-beg)
8985 len (- (js2-current-token-end) pos))
8986 (js2-report-error "msg.syntax" nil pos len)
8987 (make-js2-error-node :pos pos :len len))))
8989 (defun js2-parse-default-xml-namespace ()
8990 "Parse a `default xml namespace = <expr>' e4x statement."
8991 (let ((pos (js2-current-token-beg))
8994 (js2-set-requires-activation)
8995 (setq len (- js2-ts-cursor pos))
8996 (unless (and (js2-match-token js2-NAME)
8997 (string= (js2-current-token-string) "xml"))
8998 (js2-report-error "msg.bad.namespace" nil pos len))
8999 (unless (and (js2-match-token js2-NAME)
9000 (string= (js2-current-token-string) "namespace"))
9001 (js2-report-error "msg.bad.namespace" nil pos len))
9002 (unless (js2-match-token js2-ASSIGN)
9003 (js2-report-error "msg.bad.namespace" nil pos len))
9004 (setq expr (js2-parse-expr)
9005 end (js2-node-end expr)
9006 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
9010 (js2-node-add-children unary expr)
9011 (make-js2-expr-stmt-node :pos pos
9015 (defun js2-record-label (label bundle)
9016 ;; current token should be colon that `js2-parse-primary-expr' left untouched
9018 (let ((name (js2-label-node-name label))
9021 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
9022 ;; flag both labels if possible when used in editing mode
9023 (if (and js2-parse-ide-mode
9024 (setq dup (js2-get-label-by-name labeled-stmt name)))
9025 (js2-report-error "msg.dup.label" nil
9026 (js2-node-abs-pos dup) (js2-node-len dup)))
9027 (js2-report-error "msg.dup.label" nil
9028 (js2-node-pos label) (js2-node-len label)))
9029 (js2-labeled-stmt-node-add-label bundle label)
9030 (js2-node-add-children bundle label)
9031 ;; Add one reference to the bundle per label in `js2-label-set'
9032 (push (cons name bundle) js2-label-set)))
9034 (defun js2-parse-name-or-label ()
9035 "Parser for identifier or label. Last token matched must be js2-NAME.
9036 Called when we found a name in a statement context. If it's a label, we gather
9037 up any following labels and the next non-label statement into a
9038 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
9039 expression and return it wrapped in a `js2-expr-stmt-node'."
9040 (let ((pos (js2-current-token-beg))
9043 ;; set check for label and call down to `js2-parse-primary-expr'
9044 (setq expr (js2-maybe-parse-label))
9046 ;; Parse the non-label expression and wrap with expression stmt.
9047 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
9048 ;; else parsed a label
9049 (setq bundle (make-js2-labeled-stmt-node :pos pos))
9050 (js2-record-label expr bundle)
9051 ;; look for more labels
9052 (while (and continue (= (js2-get-token) js2-NAME))
9053 (if (setq expr (js2-maybe-parse-label))
9054 (js2-record-label expr bundle)
9055 (setq expr (js2-parse-expr)
9056 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
9058 (js2-auto-insert-semicolon stmt)))
9059 ;; no more labels; now parse the labeled statement
9062 (let ((js2-labeled-stmt bundle)) ; bind dynamically
9064 (setq stmt (js2-statement-helper))))
9065 ;; remove the labels for this statement from the global set
9066 (dolist (label (js2-labeled-stmt-node-labels bundle))
9067 (setq js2-label-set (remove label js2-label-set))))
9068 (setf (js2-labeled-stmt-node-stmt bundle) stmt
9069 (js2-node-len bundle) (- (js2-node-end stmt) pos))
9070 (js2-node-add-children bundle stmt)
9073 (defun js2-maybe-parse-label ()
9074 (cl-assert (= (js2-current-token-type) js2-NAME))
9076 (next-tt (js2-get-token))
9077 (label-end (js2-current-token-end)))
9078 ;; Do not consume colon, it is used as unwind indicator
9079 ;; to return to statementHelper.
9081 (if (= next-tt js2-COLON)
9083 (setq label-pos (js2-current-token-beg))
9084 (make-js2-label-node :pos label-pos
9085 :len (- label-end label-pos)
9086 :name (js2-current-token-string))
9087 (js2-set-face label-pos
9089 'font-lock-variable-name-face 'record))
9090 ;; Backtrack from the name token, too.
9094 (defun js2-parse-expr-stmt ()
9095 "Default parser in statement context, if no recognized statement found."
9096 (js2-wrap-with-expr-stmt (js2-current-token-beg)
9099 (js2-parse-expr)) t))
9101 (defun js2-parse-variables (decl-type pos)
9102 "Parse a comma-separated list of variable declarations.
9103 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
9105 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
9106 For 'var' or 'const', the keyword should be the token last scanned.
9108 POS is the position where the node should start. It's sometimes the
9109 var/const/let keyword, and other times the beginning of the first token
9110 in the first variable declaration.
9112 Returns the parsed `js2-var-decl-node' expression node."
9113 (let* ((result (make-js2-var-decl-node :decl-type decl-type
9115 destructuring kid-pos tt init name end nbeg nend vi
9118 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
9119 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
9120 ;; var {a, b} = baz;
9122 (setq destructuring nil
9125 kid-pos (js2-current-token-beg)
9126 end (js2-current-token-end)
9128 (if (or (= tt js2-LB) (= tt js2-LC))
9129 ;; Destructuring assignment, e.g., var [a, b] = ...
9130 (setq destructuring (js2-parse-destruct-primary-expr)
9131 end (js2-node-end destructuring))
9132 ;; Simple variable name
9134 (when (js2-must-match-name "msg.bad.var")
9135 (setq name (js2-create-name-node)
9136 nbeg (js2-current-token-beg)
9137 nend (js2-current-token-end)
9139 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
9140 (when (js2-match-token js2-ASSIGN)
9141 (setq init (js2-parse-assign-expr)
9142 end (js2-node-end init))
9143 (js2-record-imenu-functions init name))
9145 (js2-set-face nbeg nend (if (js2-function-node-p init)
9146 'font-lock-function-name-face
9147 'font-lock-variable-name-face)
9149 (setq vi (make-js2-var-init-node :pos kid-pos
9150 :len (- end kid-pos)
9154 (if (and (null init) (not js2-in-for-init))
9155 (js2-report-error "msg.destruct.assign.no.init"))
9156 (js2-define-destruct-symbols destructuring
9158 'font-lock-variable-name-face)
9159 (setf (js2-var-init-node-target vi) destructuring))
9160 (setf (js2-var-init-node-target vi) name))
9161 (setf (js2-var-init-node-initializer vi) init)
9162 (js2-node-add-children vi name destructuring init)
9163 (js2-block-node-push result vi)
9164 (unless (js2-match-token js2-COMMA)
9165 (setq continue nil)))
9166 (setf (js2-node-len result) (- end pos))
9169 (defun js2-parse-let (pos &optional stmt-p)
9170 "Parse a let expression or statement.
9171 A let-expression is of the form `let (vars) expr'.
9172 A let-statement is of the form `let (vars) {statements}'.
9173 The third form of let is a variable declaration list, handled
9174 by `js2-parse-variables'."
9175 (let ((pn (make-js2-let-node :pos pos))
9177 (if (js2-must-match js2-LP "msg.no.paren.after.let")
9178 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
9182 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
9183 (if (js2-must-match js2-RP "msg.no.paren.let")
9184 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
9185 (if (and stmt-p (js2-match-token js2-LC))
9188 (setf beg (js2-current-token-beg) ; position stmt at LC
9189 body (js2-parse-statements))
9190 (js2-must-match js2-RC "msg.no.curly.let")
9191 (setf (js2-node-len body) (- (js2-current-token-end) beg)
9192 (js2-node-len pn) (- (js2-current-token-end) pos)
9193 (js2-let-node-body pn) body
9194 (js2-node-type pn) js2-LET))
9196 (setf body (js2-parse-expr)
9197 (js2-node-len pn) (- (js2-node-end body) pos)
9198 (js2-let-node-body pn) body))
9199 (setf (js2-let-node-vars pn) vars)
9200 (js2-node-add-children pn vars body))
9204 (defun js2-define-new-symbol (decl-type name node &optional scope)
9205 (js2-scope-put-symbol (or scope js2-current-scope)
9207 (make-js2-symbol decl-type name node)))
9209 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
9210 "Define a symbol in the current scope.
9211 If NODE is non-nil, it is the AST node associated with the symbol."
9212 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
9213 (symbol (if defining-scope
9214 (js2-scope-get-symbol defining-scope name)))
9215 (sdt (if symbol (js2-symbol-decl-type symbol) -1))
9216 (pos (if node (js2-node-abs-pos node)))
9217 (len (if node (js2-node-len node))))
9219 ((and symbol ; already defined
9220 (or (= sdt js2-CONST) ; old version is const
9221 (= decl-type js2-CONST) ; new version is const
9222 ;; two let-bound vars in this block have same name
9223 (and (= sdt js2-LET)
9224 (eq defining-scope js2-current-scope))))
9227 ((= sdt js2-CONST) "msg.const.redecl")
9228 ((= sdt js2-LET) "msg.let.redecl")
9229 ((= sdt js2-VAR) "msg.var.redecl")
9230 ((= sdt js2-FUNCTION) "msg.function.redecl")
9231 (t "msg.parm.redecl"))
9233 ((= decl-type js2-LET)
9234 (if (and (not ignore-not-in-block)
9235 (or (= (js2-node-type js2-current-scope) js2-IF)
9236 (js2-loop-node-p js2-current-scope)))
9237 (js2-report-error "msg.let.decl.not.in.block")
9238 (js2-define-new-symbol decl-type name node)))
9239 ((or (= decl-type js2-VAR)
9240 (= decl-type js2-CONST)
9241 (= decl-type js2-FUNCTION))
9243 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
9244 (js2-add-strict-warning "msg.var.redecl" name)
9245 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
9246 (js2-add-strict-warning "msg.var.hides.arg" name)))
9247 (js2-define-new-symbol decl-type name node
9248 js2-current-script-or-fn)))
9249 ((= decl-type js2-LP)
9251 ;; must be duplicate parameter. Second parameter hides the
9252 ;; first, so go ahead and add the second pararameter
9253 (js2-report-warning "msg.dup.parms" name))
9254 (js2-define-new-symbol decl-type name node))
9255 (t (js2-code-bug)))))
9257 (defun js2-parse-paren-expr-or-generator-comp ()
9258 (let ((px-pos (js2-current-token-beg)))
9260 ((and (>= js2-language-version 200)
9261 (js2-match-token js2-FOR))
9262 (js2-parse-generator-comp px-pos))
9263 ((and (>= js2-language-version 200)
9264 (js2-match-token js2-RP))
9265 ;; Not valid expression syntax, but this is valid in an arrow
9266 ;; function with no params: () => body.
9267 (if (eq (js2-peek-token) js2-ARROW)
9268 ;; Return whatever, it will hopefully be rewinded and
9269 ;; reparsed when we reach the =>.
9270 (make-js2-keyword-node :type js2-NULL)
9271 (js2-report-error "msg.syntax")
9272 (make-js2-error-node)))
9274 (let* ((js2-in-for-init nil)
9275 (expr (js2-parse-expr))
9276 (pn (make-js2-paren-node :pos px-pos
9278 (js2-node-add-children pn (js2-paren-node-expr pn))
9279 (js2-must-match js2-RP "msg.no.paren")
9280 (setf (js2-node-len pn) (- (js2-current-token-end) px-pos))
9283 (defun js2-parse-expr (&optional oneshot)
9284 (let* ((pn (js2-parse-assign-expr))
9285 (pos (js2-node-pos pn))
9289 (while (and (not oneshot)
9290 (js2-match-token js2-COMMA))
9291 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
9292 (if (= (js2-peek-token) js2-YIELD)
9293 (js2-report-error "msg.yield.parenthesized"))
9294 (setq right (js2-parse-assign-expr)
9296 pn (make-js2-infix-node :type js2-COMMA
9298 :len (- js2-ts-cursor pos)
9302 (js2-node-add-children pn left right))
9305 (defun js2-parse-assign-expr ()
9306 (let ((tt (js2-get-token))
9307 (pos (js2-current-token-beg))
9308 pn left right op-pos
9309 ts-state recorded-identifiers parsed-errors)
9310 (if (= tt js2-YIELD)
9311 (js2-parse-return-or-yield tt t)
9312 ;; Save the tokenizer state in case we find an arrow function
9313 ;; and have to rewind.
9314 (setq ts-state (make-js2-ts-state)
9315 recorded-identifiers js2-recorded-identifiers
9316 parsed-errors js2-parsed-errors)
9317 ;; not yield - parse assignment expression
9318 (setq pn (js2-parse-cond-expr)
9321 ((and (<= js2-first-assign tt)
9322 (<= tt js2-last-assign))
9323 ;; tt express assignment (=, |=, ^=, ..., %=)
9324 (setq op-pos (- (js2-current-token-beg) pos) ; relative
9326 (setq right (js2-parse-assign-expr)
9327 pn (make-js2-assign-node :type tt
9329 :len (- (js2-node-end right) pos)
9333 (when js2-parse-ide-mode
9334 (js2-highlight-assign-targets pn left right)
9335 (js2-record-imenu-functions right left))
9336 ;; do this last so ide checks above can use absolute positions
9337 (js2-node-add-children pn left right))
9338 ((and (= tt js2-ARROW)
9339 (>= js2-language-version 200))
9340 (js2-ts-seek ts-state)
9341 (setq js2-recorded-identifiers recorded-identifiers
9342 js2-parsed-errors parsed-errors)
9343 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
9348 (defun js2-parse-cond-expr ()
9349 (let ((pos (js2-current-token-beg))
9350 (pn (js2-parse-or-expr))
9356 (when (js2-match-token js2-HOOK)
9357 (setq q-pos (- (js2-current-token-beg) pos)
9358 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
9359 (js2-must-match js2-COLON "msg.no.colon.cond")
9360 (setq c-pos (- (js2-current-token-beg) pos)
9361 if-false (js2-parse-assign-expr)
9363 pn (make-js2-cond-node :pos pos
9364 :len (- (js2-node-end if-false) pos)
9365 :test-expr test-expr
9367 :false-expr if-false
9370 (js2-node-add-children pn test-expr if-true if-false))
9373 (defun js2-make-binary (type left parser)
9374 "Helper for constructing a binary-operator AST node.
9375 LEFT is the left-side-expression, already parsed, and the
9376 binary operator should have just been matched.
9377 PARSER is a function to call to parse the right operand,
9378 or a `js2-node' struct if it has already been parsed.
9379 FIXME: The latter option is unused?"
9380 (let* ((pos (js2-node-pos left))
9381 (op-pos (- (js2-current-token-beg) pos))
9382 (right (if (js2-node-p parser)
9386 (pn (make-js2-infix-node :type type
9388 :len (- (js2-node-end right) pos)
9392 (js2-node-add-children pn left right)
9395 (defun js2-parse-or-expr ()
9396 (let ((pn (js2-parse-and-expr)))
9397 (when (js2-match-token js2-OR)
9398 (setq pn (js2-make-binary js2-OR
9400 'js2-parse-or-expr)))
9403 (defun js2-parse-and-expr ()
9404 (let ((pn (js2-parse-bit-or-expr)))
9405 (when (js2-match-token js2-AND)
9406 (setq pn (js2-make-binary js2-AND
9408 'js2-parse-and-expr)))
9411 (defun js2-parse-bit-or-expr ()
9412 (let ((pn (js2-parse-bit-xor-expr)))
9413 (while (js2-match-token js2-BITOR)
9414 (setq pn (js2-make-binary js2-BITOR
9416 'js2-parse-bit-xor-expr)))
9419 (defun js2-parse-bit-xor-expr ()
9420 (let ((pn (js2-parse-bit-and-expr)))
9421 (while (js2-match-token js2-BITXOR)
9422 (setq pn (js2-make-binary js2-BITXOR
9424 'js2-parse-bit-and-expr)))
9427 (defun js2-parse-bit-and-expr ()
9428 (let ((pn (js2-parse-eq-expr)))
9429 (while (js2-match-token js2-BITAND)
9430 (setq pn (js2-make-binary js2-BITAND
9432 'js2-parse-eq-expr)))
9435 (defconst js2-parse-eq-ops
9436 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
9438 (defun js2-parse-eq-expr ()
9439 (let ((pn (js2-parse-rel-expr))
9441 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
9442 (setq pn (js2-make-binary tt
9444 'js2-parse-rel-expr)))
9448 (defconst js2-parse-rel-ops
9449 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
9451 (defun js2-parse-rel-expr ()
9452 (let ((pn (js2-parse-shift-expr))
9456 (setq tt (js2-get-token))
9458 ((and js2-in-for-init (= tt js2-IN))
9460 (setq continue nil))
9461 ((memq tt js2-parse-rel-ops)
9462 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
9465 (setq continue nil))))
9468 (defconst js2-parse-shift-ops
9469 (list js2-LSH js2-URSH js2-RSH))
9471 (defun js2-parse-shift-expr ()
9472 (let ((pn (js2-parse-add-expr))
9476 (setq tt (js2-get-token))
9477 (if (memq tt js2-parse-shift-ops)
9478 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
9480 (setq continue nil)))
9483 (defun js2-parse-add-expr ()
9484 (let ((pn (js2-parse-mul-expr))
9488 (setq tt (js2-get-token))
9489 (if (or (= tt js2-ADD) (= tt js2-SUB))
9490 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
9492 (setq continue nil)))
9495 (defconst js2-parse-mul-ops
9496 (list js2-MUL js2-DIV js2-MOD))
9498 (defun js2-parse-mul-expr ()
9499 (let ((pn (js2-parse-unary-expr))
9503 (setq tt (js2-get-token))
9504 (if (memq tt js2-parse-mul-ops)
9505 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
9507 (setq continue nil)))
9510 (defun js2-make-unary (type parser &rest args)
9511 "Make a unary node of type TYPE.
9512 PARSER is either a node (for postfix operators) or a function to call
9513 to parse the operand (for prefix operators)."
9514 (let* ((pos (js2-current-token-beg))
9515 (postfix (js2-node-p parser))
9518 (apply parser args)))
9521 (if postfix ; e.g. i++
9522 (setq pos (js2-node-pos expr)
9523 end (js2-current-token-end))
9524 (setq end (js2-node-end expr)))
9525 (setq pn (make-js2-unary-node :type type
9529 (js2-node-add-children pn expr)
9532 (defconst js2-incrementable-node-types
9533 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
9534 "Node types that can be the operand of a ++ or -- operator.")
9536 (defun js2-check-bad-inc-dec (tt beg end unary)
9537 (unless (memq (js2-node-type (js2-unary-node-operand unary))
9538 js2-incrementable-node-types)
9539 (js2-report-error (if (= tt js2-INC)
9542 nil beg (- end beg))))
9544 (defun js2-parse-unary-expr ()
9545 (let ((tt (js2-current-token-type))
9548 ((or (= tt js2-VOID)
9553 (js2-make-unary tt 'js2-parse-unary-expr))
9556 ;; Convert to special POS token in decompiler and parse tree
9557 (js2-make-unary js2-POS 'js2-parse-unary-expr))
9560 ;; Convert to special NEG token in decompiler and parse tree
9561 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
9566 (setq beg (js2-current-token-beg)
9567 end (js2-current-token-end)
9568 expr (js2-make-unary tt 'js2-parse-member-expr t))
9569 (js2-check-bad-inc-dec tt beg end expr)))
9572 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
9575 (make-js2-error-node)) ; try to continue
9577 js2-compiler-xml-available)
9578 ;; XML stream encountered in expression.
9579 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
9581 (setq pn (js2-parse-member-expr t)
9582 ;; Don't look across a newline boundary for a postfix incop.
9583 tt (js2-peek-token-or-eol))
9584 (when (or (= tt js2-INC) (= tt js2-DEC))
9587 pn (js2-make-unary tt expr))
9588 (js2-node-set-prop pn 'postfix t)
9589 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
9592 (defun js2-parse-xml-initializer ()
9593 "Parse an E4X XML initializer.
9594 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
9595 Then I'll postprocess the result, depending on whether we're in IDE
9596 mode or codegen mode, and generate the appropriate rewritten AST.
9597 IDE mode uses a rich AST that models the XML structure. Codegen mode
9598 just concatenates everything and makes a new XML or XMLList out of it."
9599 (let ((tt (js2-get-first-xml-token))
9600 pn-xml pn expr kids expr-pos
9603 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
9604 (js2-report-error "msg.syntax"))
9605 (setq pn-xml (make-js2-xml-node))
9608 (setq first-token nil)
9609 (setq tt (js2-get-next-xml-token)))
9611 ;; js2-XML means we found a {expr} in the XML stream.
9612 ;; The token string is the XML up to the left-curly.
9614 (push (make-js2-string-node :pos (js2-current-token-beg)
9615 :len (- js2-ts-cursor (js2-current-token-beg)))
9617 (js2-must-match js2-LC "msg.syntax")
9618 (setq expr-pos js2-ts-cursor
9619 expr (if (eq (js2-peek-token) js2-RC)
9620 (make-js2-empty-expr-node :pos expr-pos)
9622 (js2-must-match js2-RC "msg.syntax")
9623 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9624 :len (js2-node-len expr)
9626 (js2-node-add-children pn expr)
9628 ;; a js2-XMLEND token means we hit the final close-tag.
9630 (push (make-js2-string-node :pos (js2-current-token-beg)
9631 :len (- js2-ts-cursor (js2-current-token-beg)))
9633 (dolist (kid (nreverse kids))
9634 (js2-block-node-push pn-xml kid))
9635 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9636 (js2-node-pos pn-xml))
9639 (js2-report-error "msg.syntax")
9640 (setq continue nil))))
9644 (defun js2-parse-argument-list ()
9645 "Parse an argument list and return it as a Lisp list of nodes.
9646 Returns the list in reverse order. Consumes the right-paren token."
9648 (unless (js2-match-token js2-RP)
9650 (let ((tt (js2-get-token)))
9651 (if (= tt js2-YIELD)
9652 (js2-report-error "msg.yield.parenthesized"))
9653 (if (and (= tt js2-TRIPLEDOT)
9654 (>= js2-language-version 200))
9655 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
9657 (push (js2-parse-assign-expr) result)))
9659 (js2-match-token js2-COMMA))
9660 (js2-must-match js2-RP "msg.no.paren.arg")
9663 (defun js2-parse-member-expr (&optional allow-call-syntax)
9664 (let ((tt (js2-current-token-type))
9665 pn pos target args beg end init)
9667 (setq pn (js2-parse-primary-expr))
9668 ;; parse a 'new' expression
9670 (setq pos (js2-current-token-beg)
9672 target (js2-parse-member-expr)
9673 end (js2-node-end target)
9674 pn (make-js2-new-node :pos pos
9677 (js2-highlight-function-call (js2-current-token))
9678 (js2-node-add-children pn target)
9679 (when (js2-match-token js2-LP)
9680 ;; Add the arguments to pn, if any are supplied.
9681 (setf beg pos ; start of "new" keyword
9682 pos (js2-current-token-beg)
9683 args (nreverse (js2-parse-argument-list))
9684 (js2-new-node-args pn) args
9685 end (js2-current-token-end)
9686 (js2-new-node-lp pn) (- pos beg)
9687 (js2-new-node-rp pn) (- end 1 beg))
9688 (apply #'js2-node-add-children pn args))
9689 (when (and js2-allow-rhino-new-expr-initializer
9690 (js2-match-token js2-LC))
9691 (setf init (js2-parse-object-literal)
9692 end (js2-node-end init)
9693 (js2-new-node-initializer pn) init)
9694 (js2-node-add-children pn init))
9695 (setf (js2-node-len pn) (- end beg))) ; end outer if
9696 (js2-parse-member-expr-tail allow-call-syntax pn)))
9698 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9699 "Parse a chain of property/array accesses or function calls.
9700 Includes parsing for E4X operators like `..' and `.@'.
9701 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9702 Returns an expression tree that includes PN, the parent node."
9706 (setq tt (js2-get-token))
9708 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9709 (setq pn (js2-parse-property-access tt pn)))
9710 ((= tt js2-DOTQUERY)
9711 (setq pn (js2-parse-dot-query pn)))
9713 (setq pn (js2-parse-element-get pn)))
9716 (if allow-call-syntax
9717 (setq pn (js2-parse-function-call pn))
9718 (setq continue nil)))
9719 ((= tt js2-TEMPLATE_HEAD)
9720 (setq pn (js2-parse-tagged-template pn (js2-parse-template-literal))))
9721 ((= tt js2-NO_SUBS_TEMPLATE)
9722 (setq pn (js2-parse-tagged-template pn (make-js2-string-node :type tt))))
9725 (setq continue nil))))
9726 (if (>= js2-highlight-level 2)
9727 (js2-parse-highlight-member-expr-node pn))
9730 (defun js2-parse-tagged-template (tag-node tpl-node)
9731 "Parse tagged template expression."
9732 (let* ((beg (js2-node-pos tag-node))
9733 (pn (make-js2-tagged-template-node :beg beg
9734 :len (- (js2-current-token-end) beg)
9736 :template tpl-node)))
9737 (js2-node-add-children pn tag-node tpl-node)
9740 (defun js2-parse-dot-query (pn)
9741 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9742 Last token parsed must be `js2-DOTQUERY'."
9743 (let ((pos (js2-node-pos pn))
9746 (js2-set-requires-activation)
9747 (setq op-pos (js2-current-token-beg)
9748 expr (js2-parse-expr)
9749 end (js2-node-end expr)
9750 pn (make-js2-xml-dot-query-node :left pn
9754 (js2-node-add-children pn
9755 (js2-xml-dot-query-node-left pn)
9756 (js2-xml-dot-query-node-right pn))
9757 (if (js2-must-match js2-RP "msg.no.paren")
9758 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9759 end (js2-current-token-end)))
9760 (setf (js2-node-len pn) (- end pos))
9763 (defun js2-parse-element-get (pn)
9764 "Parse an element-get expression, e.g. foo[bar].
9765 Last token parsed must be `js2-RB'."
9766 (let ((lb (js2-current-token-beg))
9767 (pos (js2-node-pos pn))
9769 (setq expr (js2-parse-expr))
9770 (if (js2-must-match js2-RB "msg.no.bracket.index")
9771 (setq rb (js2-current-token-beg)))
9772 (setq pn (make-js2-elem-get-node :target pn
9775 :lb (js2-relpos lb pos)
9776 :rb (js2-relpos rb pos)
9777 :len (- (js2-current-token-end) pos)))
9778 (js2-node-add-children pn
9779 (js2-elem-get-node-target pn)
9780 (js2-elem-get-node-element pn))
9783 (defun js2-highlight-function-call (token)
9784 (when (eq (js2-token-type token) js2-NAME)
9785 (js2-record-face 'js2-function-call token)))
9787 (defun js2-parse-function-call (pn)
9788 (js2-highlight-function-call (js2-current-token))
9791 (pos (js2-node-pos pn)))
9792 (setq pn (make-js2-call-node :pos pos
9794 :lp (- (js2-current-token-beg) pos)))
9795 (js2-node-add-children pn (js2-call-node-target pn))
9796 ;; Add the arguments to pn, if any are supplied.
9797 (setf args (nreverse (js2-parse-argument-list))
9798 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9799 (js2-call-node-args pn) args)
9800 (apply #'js2-node-add-children pn args)
9801 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9804 (defun js2-parse-property-access (tt pn)
9805 "Parse a property access, XML descendants access, or XML attr access."
9806 (let ((member-type-flags 0)
9807 (dot-pos (js2-current-token-beg))
9808 (dot-len (if (= tt js2-DOTDOT) 2 1))
9810 ref ; right side of . or .. operator
9812 (when (= tt js2-DOTDOT)
9814 (setq member-type-flags js2-descendants-flag))
9815 (if (not js2-compiler-xml-available)
9817 (js2-must-match-prop-name "msg.no.name.after.dot")
9818 (setq name (js2-create-name-node t js2-GETPROP)
9819 result (make-js2-prop-get-node :left pn
9820 :pos (js2-current-token-beg)
9822 :len (js2-current-token-len)))
9823 (js2-node-add-children result pn name)
9825 ;; otherwise look for XML operators
9826 (setf result (if (= tt js2-DOT)
9827 (make-js2-prop-get-node)
9828 (make-js2-infix-node :type js2-DOTDOT))
9829 (js2-node-pos result) (js2-node-pos pn)
9830 (js2-infix-node-op-pos result) dot-pos
9831 (js2-infix-node-left result) pn ; do this after setting position
9832 tt (js2-get-prop-name-token))
9834 ;; handles: name, ns::name, ns::*, ns::[expr]
9836 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9837 ;; handles: *, *::name, *::*, *::[expr]
9839 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9840 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9842 (setq result (js2-parse-attribute-access)))
9844 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9846 (setf (js2-node-len result) (- (js2-node-end ref)
9847 (js2-node-pos result))
9848 (js2-infix-node-right result) ref))
9849 (if (js2-infix-node-p result)
9850 (js2-node-add-children result
9851 (js2-infix-node-left result)
9852 (js2-infix-node-right result)))
9855 (defun js2-parse-attribute-access ()
9856 "Parse an E4X XML attribute expression.
9857 This includes expressions of the forms:
9859 @attr @ns::attr @ns::*
9861 @[expr] @*::[expr] @ns::[expr]
9863 Called if we peeked an '@' token."
9864 (let ((tt (js2-get-prop-name-token))
9865 (at-pos (js2-current-token-beg)))
9867 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9869 (js2-parse-property-name at-pos nil 0))
9870 ;; handles: @*, @*::name, @*::*, @*::[expr]
9872 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9875 (js2-parse-xml-elem-ref at-pos))
9877 (js2-report-error "msg.no.name.after.xmlAttr")
9878 ;; Avoid cascaded errors that happen if we make an error node here.
9879 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9881 (defun js2-parse-property-name (at-pos s member-type-flags)
9882 "Check if :: follows name in which case it becomes qualified name.
9884 AT-POS is a natural number if we just read an '@' token, else nil.
9885 S is the name or string that was matched: an identifier, 'throw' or '*'.
9886 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9888 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9889 operator, or the name is followed by ::. For a plain name, returns a
9890 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9891 (let ((pos (or at-pos (js2-current-token-beg)))
9893 (name (js2-create-name-node t (js2-current-token-type) s))
9896 (when (js2-match-token js2-COLONCOLON)
9898 colon-pos (js2-current-token-beg)
9899 tt (js2-get-prop-name-token))
9901 ;; handles name::name
9903 (setq name (js2-create-name-node)))
9906 (setq name (js2-create-name-node nil nil "*")))
9907 ;; handles name::[expr]
9909 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9911 (js2-report-error "msg.no.name.after.coloncolon"))))
9912 (if (and (null ns) (zerop member-type-flags))
9916 (make-js2-xml-prop-ref-node :pos pos
9917 :len (- (js2-node-end name) pos)
9919 :colon-pos colon-pos
9921 (js2-node-add-children pn name))))))
9923 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9924 "Parse the [expr] portion of an xml element reference.
9925 For instance, @[expr], @*::[expr], or ns::[expr]."
9926 (let* ((lb (js2-current-token-beg))
9927 (pos (or at-pos lb))
9929 (expr (js2-parse-expr))
9930 (end (js2-node-end expr))
9932 (if (js2-must-match js2-RB "msg.no.bracket.index")
9933 (setq rb (js2-current-token-beg)
9934 end (js2-current-token-end)))
9937 (make-js2-xml-elem-ref-node :pos pos
9939 :namespace namespace
9940 :colon-pos colon-pos
9943 :lb (js2-relpos lb pos)
9944 :rb (js2-relpos rb pos)))
9945 (js2-node-add-children pn namespace expr))))
9947 (defun js2-parse-destruct-primary-expr ()
9948 (let ((js2-is-in-destructuring t))
9949 (js2-parse-primary-expr)))
9951 (defun js2-parse-primary-expr ()
9952 "Parse a literal (leaf) expression of some sort.
9953 Includes complex literals such as functions, object-literals,
9954 array-literals, array comprehensions and regular expressions."
9955 (let (pn ; parent node (usually return value)
9957 (setq tt (js2-current-token-type))
9960 (js2-parse-class-expr))
9961 ((= tt js2-FUNCTION)
9962 (js2-parse-function-expr))
9964 (js2-parse-array-comp-or-literal))
9966 (js2-parse-object-literal))
9968 (js2-parse-let (js2-current-token-beg)))
9970 (js2-parse-paren-expr-or-generator-comp))
9973 (js2-parse-attribute-access))
9975 (js2-parse-name tt))
9977 (make-js2-number-node))
9978 ((or (= tt js2-STRING) (= tt js2-NO_SUBS_TEMPLATE))
9979 (make-js2-string-node :type tt))
9980 ((= tt js2-TEMPLATE_HEAD)
9981 (js2-parse-template-literal))
9982 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9983 ;; Got / or /= which in this context means a regexp literal
9984 (let ((px-pos (js2-current-token-beg))
9985 (flags (js2-read-regexp tt))
9986 (end (js2-current-token-end)))
9988 (make-js2-regexp-node :pos px-pos
9990 :value (js2-current-token-string)
9992 (js2-set-face px-pos end 'font-lock-string-face 'record)
9993 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9994 ((or (= tt js2-NULL)
9999 (make-js2-keyword-node :type tt))
10000 ((= tt js2-TRIPLEDOT)
10001 ;; Likewise, only valid in an arrow function with a rest param.
10002 (if (and (js2-match-token js2-NAME)
10003 (js2-match-token js2-RP)
10004 (eq (js2-peek-token) js2-ARROW))
10006 (js2-unget-token) ; Put back the right paren.
10007 ;; See the previous case.
10008 (make-js2-keyword-node :type js2-NULL))
10009 (js2-report-error "msg.syntax")
10010 (make-js2-error-node)))
10011 ((= tt js2-RESERVED)
10012 (js2-report-error "msg.reserved.id")
10013 (make-js2-name-node))
10015 ;; the scanner or one of its subroutines reported the error.
10016 (make-js2-error-node))
10018 (let* ((px-pos (point-at-bol))
10019 (len (- js2-ts-cursor px-pos)))
10020 (js2-report-error "msg.unexpected.eof" nil px-pos len))
10021 (make-js2-error-node :pos (1- js2-ts-cursor)))
10023 (js2-report-error "msg.syntax")
10024 (make-js2-error-node)))))
10026 (defun js2-parse-template-literal ()
10027 (let ((beg (js2-current-token-beg))
10028 (kids (list (make-js2-string-node :type js2-TEMPLATE_HEAD)))
10029 (tt js2-TEMPLATE_HEAD))
10030 (while (eq tt js2-TEMPLATE_HEAD)
10031 (push (js2-parse-expr) kids)
10032 (js2-must-match js2-RC "msg.syntax")
10033 (setq tt (js2-get-token 'TEMPLATE_TAIL))
10034 (push (make-js2-string-node :type tt) kids))
10035 (setq kids (nreverse kids))
10036 (let ((tpl (make-js2-template-node :beg beg
10037 :len (- (js2-current-token-end) beg)
10039 (apply #'js2-node-add-children tpl kids)
10042 (defun js2-parse-name (_tt)
10043 (let ((name (js2-current-token-string))
10045 (setq node (if js2-compiler-xml-available
10046 (js2-parse-property-name nil name 0)
10047 (js2-create-name-node 'check-activation nil name)))
10048 (if js2-highlight-external-variables
10049 (js2-record-name-node node))
10052 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
10053 (js2-add-strict-warning
10055 ;; back up from comma to beginning of line or array/objlit
10057 (js2-node-pos (car elems))
10060 (goto-char comma-pos)
10061 (back-to-indentation)
10065 (defun js2-parse-array-comp-or-literal ()
10066 (let ((pos (js2-current-token-beg)))
10067 (if (and (>= js2-language-version 200)
10068 (js2-match-token js2-FOR))
10069 (js2-parse-array-comp pos)
10070 (js2-parse-array-literal pos))))
10072 (defun js2-parse-array-literal (pos)
10073 (let ((after-lb-or-comma t)
10074 after-comma tt elems pn
10076 (unless js2-is-in-destructuring
10077 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
10079 (setq tt (js2-get-token))
10083 (setq after-comma (js2-current-token-end))
10084 (if (not after-lb-or-comma)
10085 (setq after-lb-or-comma t)
10089 (= tt js2-EOF)) ; prevent infinite loop
10091 (js2-report-error "msg.no.bracket.arg" nil pos))
10092 (when (and after-comma (< js2-language-version 170))
10093 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
10094 pos (remove nil elems) after-comma))
10096 pn (make-js2-array-node :pos pos
10097 :len (- js2-ts-cursor pos)
10098 :elems (nreverse elems)))
10099 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
10100 ;; destructuring binding
10101 (js2-is-in-destructuring
10102 (push (if (or (= tt js2-LC)
10105 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
10106 (js2-parse-destruct-primary-expr)
10108 (js2-report-error "msg.bad.var")
10109 (make-js2-error-node))
10111 (setq after-lb-or-comma nil
10114 ((and (>= js2-language-version 170)
10115 (= tt js2-FOR) ; check for array comprehension
10116 (not after-lb-or-comma) ; "for" can't follow a comma
10117 elems ; must have at least 1 element
10118 (not (cdr elems))) ; but no 2nd element
10121 pn (js2-parse-legacy-array-comp (car elems) pos)))
10124 (unless after-lb-or-comma
10125 (js2-report-error "msg.no.bracket.arg"))
10126 (if (and (= tt js2-TRIPLEDOT)
10127 (>= js2-language-version 200))
10129 (push (js2-make-unary tt 'js2-parse-assign-expr)
10132 (push (js2-parse-assign-expr) elems))
10133 (setq after-lb-or-comma nil
10134 after-comma nil))))
10135 (unless js2-is-in-destructuring
10139 (defun js2-parse-legacy-array-comp (expr pos)
10140 "Parse a legacy array comprehension (JavaScript 1.7).
10141 EXPR is the first expression after the opening left-bracket.
10142 POS is the beginning of the LB token preceding EXPR.
10143 We should have just parsed the 'for' keyword before calling this function."
10144 (let ((current-scope js2-current-scope)
10145 loops first filter result)
10148 (while (js2-match-token js2-FOR)
10149 (let ((loop (make-js2-comp-loop-node)))
10150 (js2-push-scope loop)
10152 (js2-parse-comp-loop loop)))
10153 ;; First loop takes expr scope's parent.
10154 (setf (js2-scope-parent-scope (setq first (car (last loops))))
10155 (js2-scope-parent-scope current-scope))
10156 ;; Set expr scope's parent to the last loop.
10157 (setf (js2-scope-parent-scope current-scope) (car loops))
10158 (if (/= (js2-get-token) js2-IF)
10160 (setq filter (js2-parse-condition))))
10161 (dotimes (_ (1- (length loops)))
10163 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10164 (setq result (make-js2-comp-node :pos pos
10165 :len (- js2-ts-cursor pos)
10167 :loops (nreverse loops)
10168 :filters (and filter (list (car filter)))
10169 :form 'LEGACY_ARRAY))
10170 ;; Set comp loop's parent to the last loop.
10171 ;; TODO: Get rid of the bogus expr scope.
10172 (setf (js2-scope-parent-scope result) first)
10173 (apply #'js2-node-add-children result expr (car filter)
10174 (js2-comp-node-loops result))
10177 (defun js2-parse-array-comp (pos)
10178 "Parse an ES6 array comprehension.
10179 POS is the beginning of the LB token.
10180 We should have just parsed the 'for' keyword before calling this function."
10181 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
10182 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
10185 (defun js2-parse-generator-comp (pos)
10186 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
10187 (js2-current-script-or-fn
10188 (make-js2-function-node :generator-type 'COMPREHENSION))
10189 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
10190 (js2-must-match js2-RP "msg.no.paren" pos)
10193 (defun js2-parse-comprehension (pos form)
10194 (let (loops filters expr result)
10198 (while (js2-match-token js2-FOR)
10199 (let ((loop (make-js2-comp-loop-node)))
10200 (js2-push-scope loop)
10202 (js2-parse-comp-loop loop)))
10203 (while (js2-match-token js2-IF)
10204 (push (car (js2-parse-condition)) filters))
10205 (setq expr (js2-parse-assign-expr)))
10208 (setq result (make-js2-comp-node :pos pos
10209 :len (- js2-ts-cursor pos)
10211 :loops (nreverse loops)
10212 :filters (nreverse filters)
10214 (apply #'js2-node-add-children result (js2-comp-node-loops result))
10215 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
10218 (defun js2-parse-comp-loop (pn &optional only-of-p)
10219 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
10220 The current token should be the initial FOR.
10221 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
10222 (let ((pos (js2-comp-loop-node-pos pn))
10223 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
10224 (when (and (not only-of-p) (js2-match-token js2-NAME))
10225 (if (string= (js2-current-token-string) "each")
10228 each-pos (- (js2-current-token-beg) pos)) ; relative
10229 (js2-record-face 'font-lock-keyword-face))
10230 (js2-report-error "msg.no.paren.for")))
10231 (if (js2-must-match js2-LP "msg.no.paren.for")
10232 (setq lp (- (js2-current-token-beg) pos)))
10233 (setq tt (js2-peek-token))
10238 (setq iter (js2-parse-destruct-primary-expr))
10239 (js2-define-destruct-symbols iter js2-LET
10240 'font-lock-variable-name-face t))
10241 ((js2-match-token js2-NAME)
10242 (setq iter (js2-create-name-node)))
10244 (js2-report-error "msg.bad.var")))
10245 ;; Define as a let since we want the scope of the variable to
10246 ;; be restricted to the array comprehension
10247 (if (js2-name-node-p iter)
10248 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
10249 (if (or (and (not only-of-p) (js2-match-token js2-IN))
10250 (and (>= js2-language-version 200)
10251 (js2-match-contextual-kwd "of")
10253 (setq in-pos (- (js2-current-token-beg) pos))
10254 (js2-report-error "msg.in.after.for.name"))
10255 (setq obj (js2-parse-expr))
10256 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
10257 (setq rp (- (js2-current-token-beg) pos)))
10258 (setf (js2-node-pos pn) pos
10259 (js2-node-len pn) (- js2-ts-cursor pos)
10260 (js2-comp-loop-node-iterator pn) iter
10261 (js2-comp-loop-node-object pn) obj
10262 (js2-comp-loop-node-in-pos pn) in-pos
10263 (js2-comp-loop-node-each-pos pn) each-pos
10264 (js2-comp-loop-node-foreach-p pn) foreach-p
10265 (js2-comp-loop-node-forof-p pn) forof-p
10266 (js2-comp-loop-node-lp pn) lp
10267 (js2-comp-loop-node-rp pn) rp)
10268 (js2-node-add-children pn iter obj)
10271 (defun js2-parse-class-stmt ()
10272 (let ((pos (js2-current-token-beg))
10273 (_ (js2-must-match-name "msg.unnamed.class.stmt"))
10274 (name (js2-create-name-node t)))
10275 (js2-set-face (js2-node-pos name) (js2-node-end name)
10276 'font-lock-function-name-face 'record)
10277 (let ((node (js2-parse-class pos 'CLASS_STATEMENT name)))
10278 (js2-define-symbol js2-FUNCTION
10279 (js2-name-node-name name)
10283 (defun js2-parse-class-expr ()
10284 (let ((pos (js2-current-token-beg))
10286 (when (js2-match-token js2-NAME)
10287 (setq name (js2-create-name-node t)))
10288 (js2-parse-class pos 'CLASS_EXPRESSION name)))
10290 (defun js2-parse-class (pos form name)
10291 ;; class X [extends ...] {
10292 (let (pn elems extends)
10293 (if (js2-match-token js2-EXTENDS)
10294 (if (= (js2-peek-token) js2-LC)
10295 (js2-report-error "msg.missing.extends")
10296 ;; TODO(sdh): this should be left-hand-side-expr, not assign-expr
10297 (setq extends (js2-parse-assign-expr))
10299 (js2-report-error "msg.bad.extends"))))
10300 (js2-must-match js2-LC "msg.no.brace.class")
10301 (setq elems (js2-parse-object-literal-elems t)
10302 pn (make-js2-class-node :pos pos
10303 :len (- js2-ts-cursor pos)
10308 (apply #'js2-node-add-children pn (js2-class-node-elems pn))
10311 (defun js2-parse-object-literal ()
10312 (let* ((pos (js2-current-token-beg))
10313 (elems (js2-parse-object-literal-elems))
10314 (result (make-js2-object-node :pos pos
10315 :len (- js2-ts-cursor pos)
10317 (apply #'js2-node-add-children result (js2-object-node-elems result))
10320 (defun js2-parse-object-literal-elems (&optional class-p)
10321 (let ((pos (js2-current-token-beg))
10324 tt elems elem after-comma)
10326 (setq tt (js2-get-prop-name-token)
10329 (when (and class-p (= js2-NAME tt)
10330 (string= "static" (js2-current-token-string)))
10331 (js2-record-face 'font-lock-keyword-face)
10333 tt (js2-get-prop-name-token)))
10335 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
10336 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
10337 ;; TODO(sdh): support *foo() {...}
10338 ((or (= js2-NAME tt)
10340 (setq after-comma nil
10341 elem (js2-parse-named-prop tt))
10342 (if (and (null elem)
10343 (not js2-recover-from-parse-errors))
10344 (setq continue nil)))
10345 ;; {[Symbol.iterator]: ...}
10346 ((and (= tt js2-LB)
10347 (>= js2-language-version 200))
10348 (let ((expr (js2-parse-expr)))
10349 (js2-must-match js2-RB "msg.missing.computed.rb")
10350 (setq after-comma nil
10351 elem (js2-parse-plain-property expr))))
10352 ;; {12: x} or {10.7: x}
10354 (setq after-comma nil
10355 elem (js2-parse-plain-property (make-js2-number-node))))
10356 ;; Break out of loop, and handle trailing commas.
10360 (setq continue nil)
10362 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
10363 pos elems after-comma)))
10365 (js2-report-error "msg.bad.prop")
10366 (unless js2-recover-from-parse-errors
10367 (setq continue nil)))) ; end switch
10368 ;; Handle static for classes' codegen.
10370 (if elem (js2-node-set-prop elem 'STATIC t)
10371 (js2-report-error "msg.unexpected.static")))
10372 ;; Handle commas, depending on class-p.
10373 (let ((tok (js2-get-prop-name-token)))
10374 (if (eq tok js2-COMMA)
10376 (js2-report-error "msg.class.unexpected.comma")
10377 (setq after-comma (js2-current-token-end)))
10379 (unless class-p (setq continue nil))))
10380 ;; Append any parsed element.
10381 (if elem (push elem elems))) ; end loop
10382 (js2-must-match js2-RC "msg.no.brace.prop")
10385 (defun js2-parse-named-prop (tt)
10386 "Parse a name, string, or getter/setter object property.
10387 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
10388 (let ((string-prop (and (= tt js2-STRING)
10389 (make-js2-string-node)))
10391 (ppos (js2-current-token-beg))
10392 (pend (js2-current-token-end))
10393 (name (js2-create-name-node))
10394 (prop (js2-current-token-string)))
10396 ;; getter/setter prop
10397 ((and (= tt js2-NAME)
10398 (= (js2-peek-token) js2-NAME)
10399 (or (string= prop "get")
10400 (string= prop "set")))
10402 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
10403 (js2-record-face 'font-lock-function-name-face) ; for peeked name
10404 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
10405 (js2-parse-getter-setter-prop ppos name prop))
10406 ;; method definition: {f() {...}}
10407 ((and (= (js2-peek-token) js2-LP)
10408 (>= js2-language-version 200))
10409 (js2-record-face 'font-lock-function-name-face) ; name
10410 (js2-parse-getter-setter-prop ppos name ""))
10414 (setq expr (js2-parse-plain-property (or string-prop name)))
10415 (when (and (not string-prop)
10416 (not js2-is-in-destructuring)
10417 js2-highlight-external-variables
10418 (js2-node-get-prop expr 'SHORTHAND))
10419 (js2-record-name-node name))
10420 (js2-set-face ppos pend
10421 (if (js2-function-node-p
10422 (js2-object-prop-node-right expr))
10423 'font-lock-function-name-face
10424 'font-lock-variable-name-face)
10427 (defun js2-parse-plain-property (prop)
10428 "Parse a non-getter/setter property in an object literal.
10429 PROP is the node representing the property: a number, name or string."
10430 (let* ((tt (js2-get-token))
10431 (pos (js2-node-pos prop))
10434 ;; Abbreviated property, as in {foo, bar}
10435 ((and (>= js2-language-version 200)
10436 (or (= tt js2-COMMA)
10438 (not (js2-number-node-p prop)))
10440 (setq result (make-js2-object-prop-node
10444 :op-pos (js2-current-token-len)))
10445 (js2-node-add-children result prop)
10446 (js2-node-set-prop result 'SHORTHAND t)
10450 (if (= tt js2-COLON)
10451 (setq colon (- (js2-current-token-beg) pos)
10452 expr (js2-parse-assign-expr))
10453 (js2-report-error "msg.no.colon.prop")
10454 (setq expr (make-js2-error-node)))
10455 (setq result (make-js2-object-prop-node
10457 ;; don't include last consumed token in length
10458 :len (- (+ (js2-node-pos expr)
10459 (js2-node-len expr))
10464 (js2-node-add-children result prop expr)
10467 (defun js2-parse-getter-setter-prop (pos prop type-string)
10468 "Parse getter or setter property in an object literal.
10469 JavaScript syntax is:
10471 { get foo() {...}, set foo(x) {...} }
10473 and expression closure style is also supported
10475 { get foo() x, set foo(x) _x = x }
10477 POS is the start position of the `get' or `set' keyword.
10478 PROP is the `js2-name-node' representing the property name.
10479 GET-P is non-nil if the keyword was `get'."
10481 ((string= "get" type-string) js2-GET)
10482 ((string= "set" type-string) js2-SET)
10485 (fn (js2-parse-function-expr)))
10486 ;; it has to be an anonymous function, as we already parsed the name
10487 (if (/= (js2-node-type fn) js2-FUNCTION)
10488 (js2-report-error "msg.bad.prop")
10489 (if (cl-plusp (length (js2-function-name fn)))
10490 (js2-report-error "msg.bad.prop")))
10491 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
10492 (setq end (js2-node-end fn)
10493 result (make-js2-getter-setter-node :type type
10498 (js2-node-add-children result prop fn)
10501 (defun js2-create-name-node (&optional check-activation-p token string)
10502 "Create a name node using the current token and, optionally, STRING.
10503 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
10504 (let* ((beg (js2-current-token-beg))
10505 (tt (js2-current-token-type))
10507 (if (= js2-NAME tt)
10508 (js2-current-token-string)
10509 (js2-tt-name tt))))
10511 (setq name (make-js2-name-node :pos beg
10514 (if check-activation-p
10515 (js2-check-activation-name s (or token js2-NAME)))
10518 ;;; Indentation support
10520 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
10521 ;; Karl cleverly deduces that the desired indentation level is often a
10522 ;; function of paren/bracket/brace nesting depth, which can be determined
10523 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
10524 ;; then does some equally clever checks to see if we're in the context of a
10525 ;; substatement of a possibly braceless statement keyword such as if, while,
10526 ;; or finally. This approach yields pretty good results.
10528 ;; The indenter is often "wrong", however, and needs to be overridden.
10529 ;; The right long-term solution is probably to emulate (or integrate
10530 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
10531 ;; parse tree from `js2-parse' is present, which is not true at the
10532 ;; moment the user is typing, computing indentation is still thousands
10533 ;; of lines of code to handle every possible syntactic edge case.
10535 ;; In the meantime, the compromise solution is that we offer a "bounce
10536 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
10537 ;; current line indent among various likely guess points. This approach
10538 ;; is far from perfect, but should at least make it slightly easier to
10539 ;; move the line towards its desired indentation when manually
10540 ;; overriding Karl's heuristic nesting guesser.
10542 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
10543 ;; extensions such as `let' and Array comprehensions. Major kudos to
10544 ;; Karl for coming up with the initial approach, which packs a lot of
10545 ;; punch for so little code.
10547 (defconst js2-possibly-braceless-keywords-re
10548 (concat "else[ \t]+if\\|for[ \t]+each\\|"
10549 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
10550 "try" "while" "with" "let")))
10551 "Regular expression matching keywords that are optionally
10552 followed by an opening brace.")
10554 (defconst js2-indent-operator-re
10555 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
10556 (regexp-opt '("in" "instanceof") 'words))
10557 "Regular expression matching operators that affect indentation
10558 of continued expressions.")
10560 (defconst js2-declaration-keyword-re
10561 (regexp-opt '("var" "let" "const") 'words)
10562 "Regular expression matching variable declaration keywords.")
10564 (defun js2-re-search-forward-inner (regexp &optional bound count)
10565 "Auxiliary function for `js2-re-search-forward'."
10566 (let (parse saved-point)
10568 (re-search-forward regexp bound)
10569 (setq parse (if saved-point
10570 (parse-partial-sexp saved-point (point))
10571 (syntax-ppss (point))))
10572 (cond ((nth 3 parse)
10574 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
10575 (save-excursion (end-of-line) (point)) t))
10579 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
10580 (re-search-forward "\\*/"))
10582 (setq count (1- count))))
10583 (setq saved-point (point))))
10586 (defun js2-re-search-forward (regexp &optional bound noerror count)
10587 "Search forward but ignore strings and comments.
10588 Invokes `re-search-forward' but treats the buffer as if strings
10589 and comments have been removed."
10590 (let ((saved-point (point)))
10591 (condition-case err
10592 (cond ((null count)
10593 (js2-re-search-forward-inner regexp bound 1))
10595 (js2-re-search-backward-inner regexp bound (- count)))
10597 (js2-re-search-forward-inner regexp bound count)))
10599 (goto-char saved-point)
10601 (error (error-message-string err)))))))
10603 (defun js2-re-search-backward-inner (regexp &optional bound count)
10604 "Auxiliary function for `js2-re-search-backward'."
10607 (re-search-backward regexp bound)
10608 (setq parse (syntax-ppss (point)))
10609 (cond ((nth 3 parse)
10610 (re-search-backward
10611 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
10612 (line-beginning-position) t))
10614 (goto-char (nth 8 parse)))
10616 (and (eq (char-before) ?/) (eq (char-after) ?*)))
10617 (re-search-backward "/\\*"))
10619 (setq count (1- count))))))
10622 (defun js2-re-search-backward (regexp &optional bound noerror count)
10623 "Search backward but ignore strings and comments.
10624 Invokes `re-search-backward' but treats the buffer as if strings
10625 and comments have been removed."
10626 (let ((saved-point (point)))
10627 (condition-case err
10628 (cond ((null count)
10629 (js2-re-search-backward-inner regexp bound 1))
10631 (js2-re-search-forward-inner regexp bound (- count)))
10633 (js2-re-search-backward-inner regexp bound count)))
10635 (goto-char saved-point)
10637 (error (error-message-string err)))))))
10639 (defun js2-looking-at-operator-p ()
10640 "Return non-nil if text after point is a non-comma operator."
10641 (and (looking-at js2-indent-operator-re)
10642 (or (not (looking-at ":"))
10644 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
10645 (looking-at "?"))))))
10647 (defun js2-continued-expression-p ()
10648 "Return non-nil if the current line continues an expression."
10650 (back-to-indentation)
10651 (or (js2-looking-at-operator-p)
10652 (when (catch 'found
10653 (while (and (re-search-backward "\n" nil t)
10654 (let ((state (syntax-ppss)))
10655 (when (nth 4 state)
10656 (goto-char (nth 8 state))) ;; skip comments
10657 (skip-chars-backward " \t")
10660 (throw 'found t))))))
10662 (when (js2-looking-at-operator-p)
10664 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
10666 (defun js2-end-of-do-while-loop-p ()
10667 "Return non-nil if word after point is `while' of a do-while
10668 statement, else returns nil. A braceless do-while statement
10669 spanning several lines requires that the start of the loop is
10670 indented to the same column as the current line."
10673 (when (looking-at "\\s-*\\<while\\>")
10674 (if (save-excursion
10675 (skip-chars-backward "[ \t\n]*}")
10676 (looking-at "[ \t\n]*}"))
10678 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
10679 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
10680 (or (looking-at "\\<do\\>")
10681 (let ((saved-indent (current-indentation)))
10682 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
10683 (/= (current-indentation) saved-indent)))
10684 (and (looking-at "[ \t]*\\<do\\>")
10685 (not (js2-re-search-forward
10686 "\\<while\\>" (point-at-eol) t))
10687 (= (current-indentation) saved-indent))))))))
10689 (defun js2-multiline-decl-indentation ()
10690 "Return the declaration indentation column if the current line belongs
10691 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
10692 (let (forward-sexp-function ; use Lisp version
10693 at-opening-bracket)
10695 (back-to-indentation)
10696 (when (not (looking-at js2-declaration-keyword-re))
10697 (when (looking-at js2-indent-operator-re)
10698 (goto-char (match-end 0))) ; continued expressions are ok
10699 (while (and (not at-opening-bracket)
10701 (let ((pos (point)))
10704 (or (eq (char-before) ?,)
10705 (and (not (eq (char-before) ?\;))
10706 (prog2 (skip-syntax-backward ".")
10707 (looking-at js2-indent-operator-re)
10708 (js2-backward-sws))
10709 (not (eq (char-before) ?\;)))
10710 (js2-same-line pos)))))
10713 (scan-error (setq at-opening-bracket t))))
10714 (when (looking-at js2-declaration-keyword-re)
10715 (goto-char (match-end 0))
10716 (1+ (current-column)))))))
10718 (defun js2-ctrl-statement-indentation ()
10719 "Return the proper indentation of current line if it is a control statement.
10720 Returns an indentation if this line starts the body of a control
10721 statement without braces, else returns nil."
10722 (let (forward-sexp-function)
10724 (back-to-indentation)
10725 (when (and (not (js2-same-line (point-min)))
10726 (not (looking-at "{"))
10727 (js2-re-search-backward "[[:graph:]]" nil t)
10728 (not (looking-at "[{([]"))
10731 (when (= (char-before) ?\))
10732 ;; scan-sexps sometimes throws an error
10733 (ignore-errors (backward-sexp))
10734 (skip-chars-backward " \t" (point-at-bol)))
10735 (let ((pt (point)))
10736 (back-to-indentation)
10737 (when (looking-at "}[ \t]*")
10738 (goto-char (match-end 0)))
10739 (and (looking-at js2-possibly-braceless-keywords-re)
10740 (= (match-end 0) pt)
10741 (not (js2-end-of-do-while-loop-p))))))
10742 (+ (current-indentation) js2-basic-offset)))))
10744 (defun js2-indent-in-array-comp (parse-status)
10745 "Return non-nil if we think we're in an array comprehension.
10746 In particular, return the buffer position of the first `for' kwd."
10747 (let ((bracket (nth 1 parse-status))
10751 (goto-char bracket)
10752 (when (looking-at "\\[")
10755 (if (looking-at "[[{]")
10756 (let (forward-sexp-function) ; use Lisp version
10757 (forward-sexp) ; skip destructuring form
10759 (if (and (/= (char-after) ?,) ; regular array
10760 (looking-at "for"))
10761 (match-beginning 0)))
10762 ;; to skip arbitrary expressions we need the parser,
10763 ;; so we'll just guess at it.
10764 (if (and (> end (point)) ; not empty literal
10765 (re-search-forward "[^,]]* \\(for\\) " end t)
10766 ;; not inside comment or string literal
10767 (let ((state (parse-partial-sexp bracket (point))))
10768 (not (or (nth 3 state) (nth 4 state)))))
10769 (match-beginning 1))))))))
10771 (defun js2-array-comp-indentation (parse-status for-kwd)
10772 (if (js2-same-line for-kwd)
10773 ;; first continuation line
10775 (goto-char (nth 1 parse-status))
10777 (skip-chars-forward " \t")
10780 (goto-char for-kwd)
10781 (current-column))))
10783 (defun js2-proper-indentation (parse-status)
10784 "Return the proper indentation for the current line."
10786 (back-to-indentation)
10787 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10788 (at-closing-bracket (looking-at "[]})]"))
10789 (same-indent-p (or at-closing-bracket
10790 (looking-at "\\<case\\>[^:]")
10791 (and (looking-at "\\<default:")
10794 (not (memq (char-before) '(?, ?{)))))))
10795 (continued-expr-p (js2-continued-expression-p))
10796 (declaration-indent (and js2-pretty-multiline-declarations
10797 (js2-multiline-decl-indentation)))
10798 (bracket (nth 1 parse-status))
10801 ;; indent array comprehension continuation lines specially
10803 (>= js2-language-version 170)
10804 (not (js2-same-line bracket))
10805 (setq beg (js2-indent-in-array-comp parse-status))
10806 (>= (point) (save-excursion
10808 (point-at-bol)))) ; at or after first loop?
10809 (js2-array-comp-indentation parse-status beg))
10813 ((and declaration-indent continued-expr-p)
10814 (+ declaration-indent js2-basic-offset))
10816 (declaration-indent)
10819 (goto-char bracket)
10821 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10822 (when (save-excursion (skip-chars-backward " \t)")
10825 (back-to-indentation)
10826 (and (eq js2-pretty-multiline-declarations 'all)
10827 (looking-at js2-declaration-keyword-re)
10828 (goto-char (1+ (match-end 0))))
10830 (cond (same-indent-p
10833 (+ (current-column) (* 2 js2-basic-offset)))
10835 (+ (current-column) js2-basic-offset))))
10836 (if (and js2-indent-switch-body
10837 (not at-closing-bracket)
10838 (looking-at "\\_<switch\\_>"))
10839 (+ indent js2-basic-offset)
10842 (unless same-indent-p
10844 (skip-chars-forward " \t"))
10845 (current-column))))
10847 (continued-expr-p js2-basic-offset)
10851 (defun js2-lineup-comment (parse-status)
10852 "Indent a multi-line block comment continuation line."
10853 (let* ((beg (nth 8 parse-status))
10854 (first-line (js2-same-line beg))
10855 (offset (save-excursion
10857 (if (looking-at "/\\*")
10858 (+ 1 (current-column))
10861 (indent-line-to offset))))
10863 (defun js2-backward-sws ()
10864 "Move backward through whitespace and comments."
10866 (while (forward-comment -1)))
10868 (defun js2-forward-sws ()
10869 "Move forward through whitespace and comments."
10871 (while (forward-comment 1)))
10873 (defun js2-current-indent (&optional pos)
10874 "Return column of indentation on current line.
10875 If POS is non-nil, go to that point and return indentation for that line."
10879 (back-to-indentation)
10882 (defun js2-arglist-close ()
10883 "Return non-nil if we're on a line beginning with a close-paren/brace."
10885 (goto-char (point-at-bol))
10887 (looking-at "[])}]")))
10889 (defun js2-indent-looks-like-label-p ()
10890 (goto-char (point-at-bol))
10892 (looking-at (concat js2-mode-identifier-re ":")))
10894 (defun js2-indent-in-objlit-p (parse-status)
10895 "Return non-nil if this looks like an object-literal entry."
10896 (let ((start (nth 1 parse-status)))
10900 (and (zerop (forward-line -1))
10901 (not (< (point) start)) ; crossed a {} boundary
10902 (js2-indent-looks-like-label-p)))
10904 (js2-indent-looks-like-label-p)))))
10906 ;; If prev line looks like foobar({ then we're passing an object
10907 ;; literal to a function call, and people pretty much always want to
10908 ;; de-dent back to the previous line, so move the 'basic-offset'
10909 ;; position to the front.
10910 (defun js2-indent-objlit-arg-p (parse-status)
10912 (back-to-indentation)
10914 (and (eq (1- (point)) (nth 1 parse-status))
10915 (eq (char-before) ?{)
10918 (skip-chars-backward " \t")
10919 (eq (char-before) ?\()))))
10921 (defun js2-indent-case-block-p ()
10923 (back-to-indentation)
10925 (goto-char (point-at-bol))
10926 (skip-chars-forward " \t")
10927 (looking-at "case\\s-.+:")))
10929 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10930 "Cycle among alternate computed indentation positions.
10931 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10932 of the buffer to the current point. NORMAL-COL is the indentation
10933 column computed by the heuristic guesser based on current paren,
10934 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10936 (let ((cur-indent (js2-current-indent))
10937 (old-buffer-undo-list buffer-undo-list)
10938 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10939 (current-line (save-excursion
10940 (forward-line 0) ; move to bol
10941 (1+ (count-lines (point-min) (point)))))
10942 positions pos main-pos anchor arglist-cont same-indent
10943 basic-offset computed-pos)
10944 ;; temporarily don't record undo info, if user requested this
10945 (when js2-mode-indent-inhibit-undo
10946 (setq buffer-undo-list t))
10949 ;; First likely point: indent from beginning of previous code line
10950 (push (setq basic-offset
10952 (back-to-indentation)
10954 (back-to-indentation)
10959 ;; (First + epsilon) likely point: indent 2x from beginning of
10960 ;; previous code line. Google does it this way.
10961 (push (setq basic-offset
10963 (back-to-indentation)
10965 (back-to-indentation)
10967 (* 2 js2-basic-offset)))
10970 ;; Second likely point: indent from assign-expr RHS. This
10971 ;; is just a crude guess based on finding " = " on the previous
10972 ;; line containing actual code.
10973 (setq pos (save-excursion
10975 (goto-char (point-at-bol))
10976 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10978 (goto-char (match-end 1))
10979 (skip-chars-forward " \t\r\n")
10980 (current-column))))
10982 (cl-incf pos js2-basic-offset)
10983 (push pos positions))
10985 ;; Third likely point: same indent as previous line of code.
10986 ;; Make it the first likely point if we're not on an
10987 ;; arglist-close line and previous line ends in a comma, or
10988 ;; both this line and prev line look like object-literal
10990 (setq pos (save-excursion
10991 (goto-char (point-at-bol))
10993 (back-to-indentation)
10996 ;; while we're here, look for trailing comma
10997 (if (save-excursion
10998 (goto-char (point-at-eol))
11000 (eq (char-before) ?,))
11001 (setq arglist-cont (1- (point)))))))
11003 (if (and (or arglist-cont
11004 (js2-indent-in-objlit-p parse-status))
11005 (not (js2-arglist-close)))
11006 (setq same-indent pos))
11007 (push pos positions))
11009 ;; Fourth likely point: first preceding code with less indentation.
11010 ;; than the immediately preceding code line.
11011 (setq pos (save-excursion
11012 (back-to-indentation)
11014 (back-to-indentation)
11015 (setq anchor (current-column))
11016 (while (and (zerop (forward-line -1))
11018 (back-to-indentation)
11021 (setq pos (current-column))))
11022 (push pos positions)
11024 ;; nesting-heuristic position, main by default
11025 (push (setq main-pos normal-col) positions)
11027 ;; delete duplicates and sort positions list
11028 (setq positions (sort (delete-dups positions) '<))
11030 ;; comma-list continuation lines: prev line indent takes precedence
11032 (setq main-pos same-indent))
11034 ;; common special cases where we want to indent in from previous line
11035 (if (or (js2-indent-case-block-p)
11036 (js2-indent-objlit-arg-p parse-status))
11037 (setq main-pos basic-offset))
11039 ;; if bouncing backwards, reverse positions list
11041 (setq positions (reverse positions)))
11043 ;; record whether we're already sitting on one of the alternatives
11044 (setq pos (member cur-indent positions))
11047 ;; case 0: we're one one of the alternatives and this is the
11048 ;; first time they've pressed TAB on this line (best-guess).
11049 ((and js2-mode-indent-ignore-first-tab
11051 ;; first time pressing TAB on this line?
11052 (not (eq js2-mode-last-indented-line current-line)))
11054 (setq computed-pos nil))
11055 ;; case 1: only one computed position => use it
11056 ((null (cdr positions))
11057 (setq computed-pos 0))
11058 ;; case 2: not on any of the computed spots => use main spot
11060 (setq computed-pos (js2-position main-pos positions)))
11061 ;; case 3: on last position: cycle to first position
11063 (setq computed-pos 0))
11064 ;; case 4: on intermediate position: cycle to next position
11066 (setq computed-pos (js2-position (cl-second pos) positions))))
11068 ;; see if any hooks want to indent; otherwise we do it
11069 (cl-loop with result = nil
11070 for hook in js2-indent-hook
11071 while (null result)
11073 (setq result (funcall hook positions computed-pos))
11075 (unless (or result (null computed-pos))
11076 (indent-line-to (nth computed-pos positions)))))
11079 (if js2-mode-indent-inhibit-undo
11080 (setq buffer-undo-list old-buffer-undo-list))
11081 ;; see commentary for `js2-mode-last-indented-line'
11082 (setq js2-mode-last-indented-line current-line))))
11084 (defun js2-indent-bounce-backwards ()
11085 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
11086 cycles between the computed indentation positions in reverse order."
11088 (js2-indent-line t))
11090 (defun js2-1-line-comment-continuation-p ()
11091 "Return t if we're in a 1-line comment continuation.
11092 If so, we don't ever want to use bounce-indent."
11096 (looking-at "\\s-*//"))
11100 (when (looking-at "\\s-*$")
11103 (looking-at "\\s-*//")))))
11105 (defun js2-indent-line (&optional bounce-backwards)
11106 "Indent the current line as JavaScript source text."
11108 (let (parse-status offset indent-col
11109 ;; Don't whine about errors/warnings when we're indenting.
11110 ;; This has to be set before calling parse-partial-sexp below.
11111 (inhibit-point-motion-hooks t))
11112 (setq parse-status (save-excursion
11113 (syntax-ppss (point-at-bol)))
11114 offset (- (point) (save-excursion
11115 (back-to-indentation)
11117 (js2-with-underscore-as-word-syntax
11118 (if (nth 4 parse-status)
11119 (js2-lineup-comment parse-status)
11120 (setq indent-col (js2-proper-indentation parse-status))
11121 ;; See comments below about `js2-mode-last-indented-line'.
11123 ;; bounce-indenting is disabled during electric-key indent.
11124 ;; It doesn't work well on first line of buffer.
11125 ((and js2-bounce-indent-p
11126 (not (js2-same-line (point-min)))
11127 (not (js2-1-line-comment-continuation-p)))
11128 (js2-bounce-indent indent-col parse-status bounce-backwards))
11129 ;; just indent to the guesser's likely spot
11130 (t (indent-line-to indent-col))))
11131 (when (cl-plusp offset)
11132 (forward-char offset)))))
11134 (defun js2-indent-region (start end)
11135 "Indent the region, but don't use bounce indenting."
11136 (let ((js2-bounce-indent-p nil)
11137 (indent-region-function nil)
11138 (after-change-functions (remq 'js2-mode-edit
11139 after-change-functions)))
11140 (indent-region start end nil) ; nil for byte-compiler
11141 (js2-mode-edit start end (- end start))))
11143 (defvar js2-minor-mode-map
11144 (let ((map (make-sparse-keymap)))
11145 (define-key map (kbd "C-c C-`") #'js2-next-error)
11146 (define-key map [mouse-1] #'js2-mode-show-node)
11148 "Keymap used when `js2-minor-mode' is active.")
11151 (define-minor-mode js2-minor-mode
11152 "Minor mode for running js2 as a background linter.
11153 This allows you to use a different major mode for JavaScript editing,
11154 such as `js-mode', while retaining the asynchronous error/warning
11155 highlighting features of `js2-mode'."
11157 :lighter " js-lint"
11159 (js2-minor-mode-enter)
11160 (js2-minor-mode-exit)))
11162 (defun js2-minor-mode-enter ()
11163 "Initialization for `js2-minor-mode'."
11164 (set (make-local-variable 'max-lisp-eval-depth)
11165 (max max-lisp-eval-depth 3000))
11166 (setq next-error-function #'js2-next-error)
11167 (js2-set-default-externs)
11168 ;; Experiment: make reparse-delay longer for longer files.
11169 (if (cl-plusp js2-dynamic-idle-timer-adjust)
11170 (setq js2-idle-timer-delay
11171 (* js2-idle-timer-delay
11172 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11173 (setq js2-mode-buffer-dirty-p t
11174 js2-mode-parsing nil)
11175 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
11176 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
11177 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
11178 (when js2-include-jslint-globals
11179 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11180 (run-hooks 'js2-init-hook)
11183 (defun js2-minor-mode-exit ()
11184 "Turn off `js2-minor-mode'."
11185 (setq next-error-function nil)
11186 (remove-hook 'after-change-functions #'js2-mode-edit t)
11187 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
11188 (when js2-mode-node-overlay
11189 (delete-overlay js2-mode-node-overlay)
11190 (setq js2-mode-node-overlay nil))
11191 (js2-remove-overlays)
11192 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
11193 (setq js2-mode-ast nil))
11195 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
11196 (make-variable-buffer-local 'js2-source-buffer)
11198 (cl-defun js2-display-error-list ()
11199 "Display a navigable buffer listing parse errors/warnings."
11201 (unless (js2-have-errors-p)
11202 (message "No errors")
11203 (cl-return-from js2-display-error-list))
11204 (cl-labels ((annotate-list
11206 "Add diagnostic TYPE and line number to errs list"
11207 (mapcar (lambda (err)
11208 (list err type (line-number-at-pos (nth 1 err))))
11210 (let* ((srcbuf (current-buffer))
11211 (errbuf (get-buffer-create "*js-lint*"))
11212 (errors (annotate-list
11213 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
11214 'js2-error)) ; must be a valid face name
11215 (warnings (annotate-list
11216 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
11217 'js2-warning)) ; must be a valid face name
11218 (all-errs (sort (append errors warnings)
11219 (lambda (e1 e2) (< (cl-cadar e1) (cl-cadar e2))))))
11220 (with-current-buffer errbuf
11221 (let ((inhibit-read-only t))
11223 (dolist (err all-errs)
11224 (cl-destructuring-bind ((msg-key beg _end &rest) type line) err
11225 (insert-text-button
11226 (format "line %d: %s" line (js2-get-msg msg-key))
11228 'follow-link "\C-m"
11229 'action 'js2-error-buffer-jump
11230 'js2-msg (js2-get-msg msg-key)
11233 (js2-error-buffer-mode)
11234 (setq js2-source-buffer srcbuf)
11235 (pop-to-buffer errbuf)
11236 (goto-char (point-min))
11238 (js2-error-buffer-view))))))
11240 (defvar js2-error-buffer-mode-map
11241 (let ((map (make-sparse-keymap)))
11242 (define-key map "n" #'js2-error-buffer-next)
11243 (define-key map "p" #'js2-error-buffer-prev)
11244 (define-key map (kbd "RET") #'js2-error-buffer-jump)
11245 (define-key map "o" #'js2-error-buffer-view)
11246 (define-key map "q" #'js2-error-buffer-quit)
11248 "Keymap used for js2 diagnostics buffers.")
11250 (defun js2-error-buffer-mode ()
11251 "Major mode for js2 diagnostics buffers.
11252 Selecting an error will jump it to the corresponding source-buffer error.
11253 \\{js2-error-buffer-mode-map}"
11255 (setq major-mode 'js2-error-buffer-mode
11256 mode-name "JS Lint Diagnostics")
11257 (use-local-map js2-error-buffer-mode-map)
11258 (setq truncate-lines t)
11259 (set-buffer-modified-p nil)
11260 (setq buffer-read-only t)
11261 (run-hooks 'js2-error-buffer-mode-hook))
11263 (defun js2-error-buffer-next ()
11264 "Move to next error and view it."
11266 (when (zerop (forward-line 1))
11267 (js2-error-buffer-view)))
11269 (defun js2-error-buffer-prev ()
11270 "Move to previous error and view it."
11272 (when (zerop (forward-line -1))
11273 (js2-error-buffer-view)))
11275 (defun js2-error-buffer-quit ()
11276 "Kill the current buffer."
11280 (defun js2-error-buffer-jump (&rest ignored)
11281 "Jump cursor to current error in source buffer."
11283 (when (js2-error-buffer-view)
11284 (pop-to-buffer js2-source-buffer)))
11286 (defun js2-error-buffer-view ()
11287 "Scroll source buffer to show error at current line."
11290 ((not (eq major-mode 'js2-error-buffer-mode))
11291 (message "Not in a js2 errors buffer"))
11292 ((not (buffer-live-p js2-source-buffer))
11293 (message "Source buffer has been killed"))
11294 ((not (wholenump (get-text-property (point) 'js2-pos)))
11295 (message "There does not seem to be an error here"))
11297 (let ((pos (get-text-property (point) 'js2-pos))
11298 (msg (get-text-property (point) 'js2-msg)))
11299 (save-selected-window
11300 (pop-to-buffer js2-source-buffer)
11305 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
11306 ;; FIXME: Should derive from js-mode.
11307 "Major mode for editing JavaScript code."
11308 ;; Used by comment-region; don't change it.
11309 (set (make-local-variable 'comment-start) "//")
11310 (set (make-local-variable 'comment-end) "")
11311 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
11312 (set (make-local-variable 'max-lisp-eval-depth)
11313 (max max-lisp-eval-depth 3000))
11314 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
11315 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
11316 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
11317 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
11318 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
11319 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
11320 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
11321 ;; for characters inside regexp literals.
11322 (set (make-local-variable 'parse-sexp-lookup-properties) t)
11323 ;; this is necessary to make `show-paren-function' work properly
11324 (set (make-local-variable 'parse-sexp-ignore-comments) t)
11325 ;; needed for M-x rgrep, among other things
11326 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
11328 (set (make-local-variable 'electric-indent-chars)
11329 (append "{}()[]:;,*." electric-indent-chars))
11330 (set (make-local-variable 'electric-layout-rules)
11331 '((?\; . after) (?\{ . after) (?\} . before)))
11333 ;; some variables needed by cc-engine for paragraph-fill, etc.
11334 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
11335 c-comment-start-regexp "/[*/]\\|\\s|"
11336 c-line-comment-starter "//"
11337 c-paragraph-start js2-paragraph-start
11338 c-paragraph-separate "$"
11339 c-syntactic-ws-start js2-syntactic-ws-start
11340 c-syntactic-ws-end js2-syntactic-ws-end
11341 c-syntactic-eol js2-syntactic-eol)
11343 (let ((c-buffer-is-cc-mode t))
11344 ;; Copied from `js-mode'. Also see Bug#6071.
11345 (make-local-variable 'paragraph-start)
11346 (make-local-variable 'paragraph-separate)
11347 (make-local-variable 'paragraph-ignore-fill-prefix)
11348 (make-local-variable 'adaptive-fill-mode)
11349 (make-local-variable 'adaptive-fill-regexp)
11350 (c-setup-paragraph-variables))
11352 (setq font-lock-defaults '(nil t))
11354 ;; Experiment: make reparse-delay longer for longer files.
11355 (when (cl-plusp js2-dynamic-idle-timer-adjust)
11356 (setq js2-idle-timer-delay
11357 (* js2-idle-timer-delay
11358 (/ (point-max) js2-dynamic-idle-timer-adjust))))
11360 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
11361 (add-hook 'after-change-functions #'js2-mode-edit nil t)
11362 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
11363 (setq next-error-function #'js2-next-error)
11364 (imenu-add-to-menubar (concat "IM-" mode-name))
11365 (add-to-invisibility-spec '(js2-outline . t))
11366 (set (make-local-variable 'line-move-ignore-invisible) t)
11367 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
11369 (setq js2-mode-functions-hidden nil
11370 js2-mode-comments-hidden nil
11371 js2-mode-buffer-dirty-p t
11372 js2-mode-parsing nil)
11374 (js2-set-default-externs)
11376 (when js2-include-jslint-globals
11377 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
11379 (run-hooks 'js2-init-hook)
11383 (defun js2-mode-exit ()
11384 "Exit `js2-mode' and clean up."
11386 (when js2-mode-node-overlay
11387 (delete-overlay js2-mode-node-overlay)
11388 (setq js2-mode-node-overlay nil))
11389 (js2-remove-overlays)
11390 (setq js2-mode-ast nil)
11391 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
11392 (remove-from-invisibility-spec '(js2-outline . t))
11393 (js2-mode-show-all)
11394 (with-silent-modifications
11395 (js2-clear-face (point-min) (point-max))))
11397 (defun js2-mode-reset-timer ()
11398 "Cancel any existing parse timer and schedule a new one."
11399 (if js2-mode-parse-timer
11400 (cancel-timer js2-mode-parse-timer))
11401 (setq js2-mode-parsing nil)
11402 (let ((timer (timer-create)))
11403 (setq js2-mode-parse-timer timer)
11404 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
11405 (timer-set-idle-time timer js2-idle-timer-delay)
11406 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
11407 (timer-activate-when-idle timer nil)))
11409 (defun js2-mode-idle-reparse (buffer)
11410 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
11411 it to be reparsed when the buffer is selected."
11412 (cond ((eq buffer (current-buffer))
11414 ((buffer-live-p buffer)
11415 ;; reparse when the buffer is selected again
11416 (with-current-buffer buffer
11417 (add-hook 'window-configuration-change-hook
11418 #'js2-mode-idle-reparse-inner
11421 (defun js2-mode-idle-reparse-inner ()
11422 (remove-hook 'window-configuration-change-hook
11423 #'js2-mode-idle-reparse-inner
11427 (defun js2-mode-edit (_beg _end _len)
11428 "Schedule a new parse after buffer is edited.
11429 Buffer edit spans from BEG to END and is of length LEN."
11430 (setq js2-mode-buffer-dirty-p t)
11431 (js2-mode-hide-overlay)
11432 (js2-mode-reset-timer))
11434 (defun js2-minor-mode-edit (_beg _end _len)
11435 "Callback for buffer edits in `js2-mode'.
11436 Schedules a new parse after buffer is edited.
11437 Buffer edit spans from BEG to END and is of length LEN."
11438 (setq js2-mode-buffer-dirty-p t)
11439 (js2-mode-hide-overlay)
11440 (js2-mode-reset-timer))
11442 (defun js2-reparse (&optional force)
11443 "Re-parse current buffer after user finishes some data entry.
11444 If we get any user input while parsing, including cursor motion,
11445 we discard the parse and reschedule it. If FORCE is nil, then the
11446 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
11449 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
11450 (unless js2-mode-parsing
11451 (setq js2-mode-parsing t)
11453 (when (or js2-mode-buffer-dirty-p force)
11454 (js2-remove-overlays)
11455 (setq js2-mode-buffer-dirty-p nil
11456 js2-mode-fontifications nil
11457 js2-mode-deferred-properties nil)
11458 (if js2-mode-verbose-parse-p
11459 (message "parsing..."))
11462 (setq interrupted-p
11463 (catch 'interrupted
11465 (with-silent-modifications
11466 ;; if parsing is interrupted, comments and regex
11467 ;; literals stay ignored by `parse-partial-sexp'
11468 (remove-text-properties (point-min) (point-max)
11470 (js2-mode-apply-deferred-properties)
11471 (js2-mode-remove-suppressed-warnings)
11472 (js2-mode-show-warnings)
11473 (js2-mode-show-errors)
11474 (if (>= js2-highlight-level 1)
11475 (js2-highlight-jsdoc js2-mode-ast)))
11479 ;; unfinished parse => try again
11480 (setq js2-mode-buffer-dirty-p t)
11481 (js2-mode-reset-timer))
11482 (if js2-mode-verbose-parse-p
11483 (message "Parse time: %s" time))))
11484 (setq js2-mode-parsing nil)
11485 (unless interrupted-p
11486 (setq js2-mode-parse-timer nil))))))
11488 (defun js2-mode-show-node (event)
11489 "Debugging aid: highlight selected AST node on mouse click."
11491 (mouse-set-point event)
11492 (setq deactivate-mark t)
11493 (when js2-mode-show-overlay
11494 (let ((node (js2-node-at-point))
11497 (message "No node found at location %s" (point))
11498 (setq beg (js2-node-abs-pos node)
11499 end (+ beg (js2-node-len node)))
11500 (if js2-mode-node-overlay
11501 (move-overlay js2-mode-node-overlay beg end)
11502 (setq js2-mode-node-overlay (make-overlay beg end))
11503 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
11504 (with-silent-modifications
11505 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
11506 (message "%s, parent: %s"
11507 (js2-node-short-name node)
11508 (if (js2-node-parent node)
11509 (js2-node-short-name (js2-node-parent node))
11512 (defun js2-mode-hide-overlay (&optional _p1 p2)
11513 "Remove the debugging overlay when the point moves.
11514 P1 and P2 are the old and new values of point, respectively."
11515 (when js2-mode-node-overlay
11516 (let ((beg (overlay-start js2-mode-node-overlay))
11517 (end (overlay-end js2-mode-node-overlay)))
11518 ;; Sometimes we're called spuriously.
11522 (with-silent-modifications
11523 (remove-text-properties beg end '(point-left nil)))
11524 (delete-overlay js2-mode-node-overlay)
11525 (setq js2-mode-node-overlay nil)))))
11527 (defun js2-mode-reset ()
11528 "Debugging helper: reset everything."
11533 (defun js2-mode-show-warn-or-err (e face)
11534 "Highlight a warning or error E with FACE.
11535 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
11536 The last element is optional. When present, use instead of FACE."
11537 (let* ((key (cl-first e))
11538 (beg (cl-second e))
11539 (end (+ beg (cl-third e)))
11540 ;; Don't inadvertently go out of bounds.
11541 (beg (max (point-min) (min beg (point-max))))
11542 (end (max (point-min) (min end (point-max))))
11543 (ovl (make-overlay beg end)))
11544 (overlay-put ovl 'font-lock-face (or (cl-fourth e) face))
11545 (overlay-put ovl 'js2-error t)
11546 (put-text-property beg end 'help-echo (js2-get-msg key))
11547 (put-text-property beg end 'point-entered #'js2-echo-error)))
11549 (defun js2-remove-overlays ()
11550 "Remove overlays from buffer that have a `js2-error' property."
11551 (let ((beg (point-min))
11554 (dolist (o (overlays-in beg end))
11555 (when (overlay-get o 'js2-error)
11556 (delete-overlay o))))))
11558 (defun js2-error-at-point (&optional pos)
11559 "Return non-nil if there's an error overlay at POS.
11560 Defaults to point."
11561 (cl-loop with pos = (or pos (point))
11562 for o in (overlays-at pos)
11563 thereis (overlay-get o 'js2-error)))
11565 (defun js2-mode-apply-deferred-properties ()
11566 "Apply fontifications and other text properties recorded during parsing."
11567 (when (cl-plusp js2-highlight-level)
11568 ;; We defer clearing faces as long as possible to eliminate flashing.
11569 (js2-clear-face (point-min) (point-max))
11570 ;; Have to reverse the recorded fontifications list so that errors
11571 ;; and warnings overwrite the normal fontifications.
11572 (dolist (f (nreverse js2-mode-fontifications))
11573 (put-text-property (cl-first f) (cl-second f) 'font-lock-face (cl-third f)))
11574 (setq js2-mode-fontifications nil))
11575 (dolist (p js2-mode-deferred-properties)
11576 (apply #'put-text-property p))
11577 (setq js2-mode-deferred-properties nil))
11579 (defun js2-mode-show-errors ()
11580 "Highlight syntax errors."
11581 (when js2-mode-show-parse-errors
11582 (dolist (e (js2-ast-root-errors js2-mode-ast))
11583 (js2-mode-show-warn-or-err e 'js2-error))))
11585 (defun js2-mode-remove-suppressed-warnings ()
11586 "Take suppressed warnings out of the AST warnings list.
11587 This ensures that the counts and `next-error' are correct."
11588 (setf (js2-ast-root-warnings js2-mode-ast)
11591 (let ((key (caar e)))
11593 (and (not js2-strict-trailing-comma-warning)
11594 (string-match "trailing\\.comma" key))
11595 (and (not js2-strict-cond-assign-warning)
11596 (string= key "msg.equal.as.assign"))
11597 (and js2-missing-semi-one-line-override
11598 (string= key "msg.missing.semi")
11599 (let* ((beg (cl-second e))
11600 (node (js2-node-at-point beg))
11601 (fn (js2-mode-find-parent-fn node))
11602 (body (and fn (js2-function-node-body fn)))
11603 (lc (and body (js2-node-abs-pos body)))
11604 (rc (and lc (+ lc (js2-node-len body)))))
11609 (and (js2-same-line lc)
11610 (js2-same-line rc))))))))))
11611 (js2-ast-root-warnings js2-mode-ast))))
11613 (defun js2-mode-show-warnings ()
11614 "Highlight strict-mode warnings."
11615 (when js2-mode-show-strict-warnings
11616 (dolist (e (js2-ast-root-warnings js2-mode-ast))
11617 (js2-mode-show-warn-or-err e 'js2-warning))))
11619 (defun js2-echo-error (_old-point new-point)
11620 "Called by point-motion hooks."
11621 (let ((msg (get-text-property new-point 'help-echo)))
11622 (when (and (stringp msg)
11623 (not (active-minibuffer-window))
11624 (not (current-message)))
11627 (defalias 'js2-echo-help #'js2-echo-error)
11629 (defun js2-line-break (&optional _soft)
11630 "Break line at point and indent, continuing comment if within one.
11631 If inside a string, and `js2-concat-multiline-strings' is not
11632 nil, turn it into concatenation."
11634 (let ((parse-status (syntax-ppss)))
11636 ;; Check if we're inside a string.
11637 ((nth 3 parse-status)
11638 (if js2-concat-multiline-strings
11639 (js2-mode-split-string parse-status)
11641 ;; Check if inside a block comment.
11642 ((nth 4 parse-status)
11643 (js2-mode-extend-comment (nth 8 parse-status)))
11645 (newline-and-indent)))))
11647 (defun js2-mode-split-string (parse-status)
11648 "Turn a newline in mid-string into a string concatenation.
11649 PARSE-STATUS is as documented in `parse-partial-sexp'."
11650 (let* ((quote-char (nth 3 parse-status))
11651 (at-eol (eq js2-concat-multiline-strings 'eol)))
11652 (insert quote-char)
11653 (insert (if at-eol " +\n" "\n"))
11657 (insert quote-char)
11659 (insert quote-char)
11660 (backward-char 1))))
11662 (defun js2-mode-extend-comment (start-pos)
11663 "Indent the line and, when inside a comment block, add comment prefix."
11664 (let (star single col first-line needs-close)
11666 (back-to-indentation)
11667 (when (< (point) start-pos)
11668 (goto-char start-pos))
11670 ((looking-at "\\*[^/]")
11672 col (current-column)))
11673 ((looking-at "/\\*")
11676 col (1+ (current-column))))
11679 col (current-column)))))
11680 ;; Heuristic for whether we need to close the comment:
11681 ;; if we've got a parse error here, assume it's an unterminated
11685 (eq (get-text-property (1- (point)) 'point-entered)
11687 ;; The heuristic above doesn't work well when we're
11688 ;; creating a comment and there's another one downstream,
11689 ;; as our parser thinks this one ends at the end of the
11690 ;; next one. (You can have a /* inside a js block comment.)
11691 ;; So just close it if the next non-ws char isn't a *.
11695 (skip-chars-forward " \t\r\n")
11696 (not (eq (char-after) ?*))))))
11697 (delete-horizontal-space)
11703 (if (and first-line needs-close)
11710 (and (zerop (forward-line 1))
11711 (looking-at "\\s-*//"))))
11714 ;; Don't need to extend the comment after all.
11715 (js2-indent-line)))
11717 (defun js2-beginning-of-line ()
11718 "Toggle point between bol and first non-whitespace char in line.
11719 Also moves past comment delimiters when inside comments."
11724 (back-to-indentation))
11726 (skip-chars-forward "/ \t"))
11727 ((and (eq (char-after) ?*)
11728 (setq node (js2-comment-at-point))
11729 (memq (js2-comment-node-format node) '(jsdoc block))
11731 (skip-chars-backward " \t")
11733 (skip-chars-forward "\* \t"))
11735 (goto-char (point-at-bol))))))
11737 (defun js2-end-of-line ()
11738 "Toggle point between eol and last non-whitespace char in line."
11741 (skip-chars-backward " \t")
11742 (goto-char (point-at-eol))))
11744 (defun js2-mode-wait-for-parse (callback)
11745 "Invoke CALLBACK when parsing is finished.
11746 If parsing is already finished, calls CALLBACK immediately."
11747 (if (not js2-mode-buffer-dirty-p)
11749 (push callback js2-mode-pending-parse-callbacks)
11750 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11752 (defun js2-mode-parse-finished ()
11753 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11754 ;; We can't let errors propagate up, since it prevents the
11755 ;; `js2-parse' method from completing normally and returning
11756 ;; the ast, which makes things mysteriously not work right.
11758 (dolist (cb js2-mode-pending-parse-callbacks)
11759 (condition-case err
11761 (error (message "%s" err))))
11762 (setq js2-mode-pending-parse-callbacks nil)))
11764 (defun js2-mode-flag-region (from to flag)
11765 "Hide or show text from FROM to TO, according to FLAG.
11766 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11767 Returns the created overlay if FLAG is non-nil."
11768 (remove-overlays from to 'invisible 'js2-outline)
11770 (let ((o (make-overlay from to)))
11771 (overlay-put o 'invisible 'js2-outline)
11772 (overlay-put o 'isearch-open-invisible
11773 'js2-isearch-open-invisible)
11776 ;; Function to be set as an outline-isearch-open-invisible' property
11777 ;; to the overlay that makes the outline invisible (see
11778 ;; `js2-mode-flag-region').
11779 (defun js2-isearch-open-invisible (_overlay)
11780 ;; We rely on the fact that isearch places point on the matched text.
11781 (js2-mode-show-element))
11783 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11784 "Return cons cell of bounds of folding overlay at POS.
11785 Returns nil if not found."
11786 (let ((overlays (overlays-at (or pos (point))))
11788 (while (and overlays
11790 (if (overlay-get (car overlays) 'invisible)
11791 (setq o (car overlays))
11792 (setq overlays (cdr overlays))))
11794 (cons (overlay-start o) (overlay-end o)))))
11796 (defun js2-mode-function-at-point (&optional pos)
11797 "Return the innermost function node enclosing current point.
11798 Returns nil if point is not in a function."
11799 (let ((node (js2-node-at-point pos)))
11800 (while (and node (not (js2-function-node-p node)))
11801 (setq node (js2-node-parent node)))
11802 (if (js2-function-node-p node)
11805 (defun js2-mode-toggle-element ()
11806 "Hide or show the foldable element at the point."
11808 (let (comment fn pos)
11811 ;; /* ... */ comment?
11812 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11813 (if (js2-mode-invisible-overlay-bounds
11814 (setq pos (+ 3 (js2-node-abs-pos comment))))
11817 (js2-mode-show-element))
11818 (js2-mode-hide-element)))
11821 (back-to-indentation)
11822 (looking-at js2-mode-//-comment-re))
11823 (js2-mode-toggle-//-comment))
11825 ((setq fn (js2-mode-function-at-point))
11826 (setq pos (and (js2-function-node-body fn)
11827 (js2-node-abs-pos (js2-function-node-body fn))))
11828 (goto-char (1+ pos))
11829 (if (js2-mode-invisible-overlay-bounds)
11830 (js2-mode-show-element)
11831 (js2-mode-hide-element)))
11833 (message "Nothing at point to hide or show"))))))
11835 (defun js2-mode-hide-element ()
11836 "Fold/hide contents of a block, showing ellipses.
11837 Show the hidden text with \\[js2-mode-show-element]."
11839 (if js2-mode-buffer-dirty-p
11840 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11841 (let (node body beg end)
11843 ((js2-mode-invisible-overlay-bounds)
11844 (message "already hidden"))
11846 (setq node (js2-node-at-point))
11848 ((js2-block-comment-p node)
11849 (js2-mode-hide-comment node))
11851 (while (and node (not (js2-function-node-p node)))
11852 (setq node (js2-node-parent node)))
11854 (setq body (js2-function-node-body node)))
11856 (setq beg (js2-node-abs-pos body)
11857 end (+ beg (js2-node-len body)))
11858 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11859 (message "No collapsable element found at point"))))))))
11861 (defun js2-mode-show-element ()
11862 "Show the hidden element at current point."
11864 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11866 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11867 (message "Nothing to un-hide"))))
11869 (defun js2-mode-show-all ()
11870 "Show all of the text in the buffer."
11872 (js2-mode-flag-region (point-min) (point-max) nil))
11874 (defun js2-mode-toggle-hide-functions ()
11876 (if js2-mode-functions-hidden
11877 (js2-mode-show-functions)
11878 (js2-mode-hide-functions)))
11880 (defun js2-mode-hide-functions ()
11881 "Hides all non-nested function bodies in the buffer.
11882 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11883 to open an individual entry."
11885 (if js2-mode-buffer-dirty-p
11886 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11887 (if (null js2-mode-ast)
11888 (message "Oops - parsing failed")
11889 (setq js2-mode-functions-hidden t)
11890 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11892 (defun js2-mode-function-hider (n endp)
11894 (let ((tt (js2-node-type n))
11897 ((and (= tt js2-FUNCTION)
11898 (setq body (js2-function-node-body n)))
11899 (setq beg (js2-node-abs-pos body)
11900 end (+ beg (js2-node-len body)))
11901 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11902 nil) ; don't process children of function
11904 t))))) ; keep processing other AST nodes
11906 (defun js2-mode-show-functions ()
11907 "Un-hide any folded function bodies in the buffer."
11909 (setq js2-mode-functions-hidden nil)
11911 (goto-char (point-min))
11912 (while (/= (goto-char (next-overlay-change (point)))
11914 (dolist (o (overlays-at (point)))
11915 (when (and (overlay-get o 'invisible)
11916 (not (overlay-get o 'comment)))
11917 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11919 (defun js2-mode-hide-comment (n)
11920 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11923 (beg (+ (js2-node-abs-pos n) head))
11924 (end (- (+ beg (js2-node-len n)) head 2))
11925 (o (js2-mode-flag-region beg end 'hide)))
11926 (overlay-put o 'comment t)))
11928 (defun js2-mode-toggle-hide-comments ()
11929 "Folds all block comments in the buffer.
11930 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11931 to open an individual entry."
11933 (if js2-mode-comments-hidden
11934 (js2-mode-show-comments)
11935 (js2-mode-hide-comments)))
11937 (defun js2-mode-hide-comments ()
11939 (if js2-mode-buffer-dirty-p
11940 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11941 (if (null js2-mode-ast)
11942 (message "Oops - parsing failed")
11943 (setq js2-mode-comments-hidden t)
11944 (dolist (n (js2-ast-root-comments js2-mode-ast))
11945 (when (js2-block-comment-p n)
11946 (js2-mode-hide-comment n)))
11947 (js2-mode-hide-//-comments)))
11949 (defun js2-mode-extend-//-comment (direction)
11950 "Find start or end of a block of similar //-comment lines.
11951 DIRECTION is -1 to look back, 1 to look forward.
11952 INDENT is the indentation level to match.
11953 Returns the end-of-line position of the furthest adjacent
11954 //-comment line with the same indentation as the current line.
11955 If there is no such matching line, returns current end of line."
11956 (let ((pos (point-at-eol))
11957 (indent (current-indentation)))
11959 (while (and (zerop (forward-line direction))
11960 (looking-at js2-mode-//-comment-re)
11961 (eq indent (length (match-string 1))))
11962 (setq pos (point-at-eol)))
11965 (defun js2-mode-hide-//-comments ()
11966 "Fold adjacent 1-line comments, showing only snippet of first one."
11969 (goto-char (point-min))
11970 (while (re-search-forward js2-mode-//-comment-re nil t)
11972 end (js2-mode-extend-//-comment 1))
11973 (unless (eq beg end)
11974 (overlay-put (js2-mode-flag-region beg end 'hide)
11977 (forward-char 1)))))
11979 (defun js2-mode-toggle-//-comment ()
11980 "Fold or un-fold any multi-line //-comment at point.
11981 Caller should have determined that this line starts with a //-comment."
11982 (let* ((beg (point-at-eol))
11986 (if (js2-mode-invisible-overlay-bounds)
11987 (js2-mode-show-element)
11988 ;; else hide the comment
11989 (setq beg (js2-mode-extend-//-comment -1)
11990 end (js2-mode-extend-//-comment 1))
11991 (unless (eq beg end)
11992 (overlay-put (js2-mode-flag-region beg end 'hide)
11995 (defun js2-mode-show-comments ()
11996 "Un-hide any hidden comments, leaving other hidden elements alone."
11998 (setq js2-mode-comments-hidden nil)
12000 (goto-char (point-min))
12001 (while (/= (goto-char (next-overlay-change (point)))
12003 (dolist (o (overlays-at (point)))
12004 (when (overlay-get o 'comment)
12005 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
12007 (defun js2-mode-display-warnings-and-errors ()
12008 "Turn on display of warnings and errors."
12010 (setq js2-mode-show-parse-errors t
12011 js2-mode-show-strict-warnings t)
12012 (js2-reparse 'force))
12014 (defun js2-mode-hide-warnings-and-errors ()
12015 "Turn off display of warnings and errors."
12017 (setq js2-mode-show-parse-errors nil
12018 js2-mode-show-strict-warnings nil)
12019 (js2-reparse 'force))
12021 (defun js2-mode-toggle-warnings-and-errors ()
12022 "Toggle the display of warnings and errors.
12023 Some users don't like having warnings/errors reported while they type."
12025 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
12026 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
12027 (if (called-interactively-p 'any)
12028 (message "warnings and errors %s"
12029 (if js2-mode-show-parse-errors
12032 (js2-reparse 'force))
12034 (defun js2-mode-customize ()
12036 (customize-group 'js2-mode))
12038 (defun js2-mode-forward-sexp (&optional arg)
12039 "Move forward across one statement or balanced expression.
12040 With ARG, do it that many times. Negative arg -N means
12041 move backward across N balanced expressions."
12043 (setq arg (or arg 1))
12045 (widen) ;; `blink-matching-open' calls `narrow-to-region'
12047 (let (forward-sexp-function
12048 node (start (point)) pos lp rp child)
12051 ;; could probably make this better for some cases:
12052 ;; - if in statement block (e.g. function body), go to parent
12053 ;; - infix exprs like (foo in bar) - maybe go to beginning
12054 ;; of infix expr if in the right-side expression?
12055 ((and arg (cl-minusp arg))
12056 (dotimes (_ (- arg))
12058 (forward-char -1) ; Enter the node we backed up to.
12059 (when (setq node (js2-node-at-point (point) t))
12060 (setq pos (js2-node-abs-pos node))
12061 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12062 (setq lp (car parens)
12064 (when (and lp (> start lp))
12065 (if (and rp (<= start rp))
12066 ;; Between parens, check if there's a child node we can jump.
12067 (when (setq child (js2-node-closest-child node (point) lp t))
12068 (setq pos (js2-node-abs-pos child)))
12069 ;; Before both parens.
12071 (let ((state (parse-partial-sexp start pos)))
12072 (goto-char (if (not (zerop (car state)))
12073 ;; Stumble at the unbalanced paren if < 0, or
12074 ;; jump a bit further if > 0.
12075 (scan-sexps start -1)
12077 (unless pos (goto-char (point-min)))))
12082 (when (setq node (js2-node-at-point (point) t))
12083 (setq pos (js2-node-abs-pos node))
12084 (let ((parens (js2-mode-forward-sexp-parens node pos)))
12085 (setq lp (car parens)
12088 (when (and rp (<= start rp))
12090 (when (setq child (js2-node-closest-child node (point) rp))
12091 (setq pos (js2-node-abs-end child)))
12092 (setq pos (1+ rp))))
12093 ;; No parens or child nodes, looks for the end of the current node.
12094 (cl-incf pos (js2-node-len
12095 (if (js2-expr-stmt-node-p (js2-node-parent node))
12096 ;; Stop after the semicolon.
12097 (js2-node-parent node)
12099 (let ((state (save-excursion (parse-partial-sexp start pos))))
12100 (goto-char (if (not (zerop (car state)))
12101 (scan-sexps start 1)
12103 (unless pos (goto-char (point-max)))))))))
12105 (defun js2-mode-forward-sexp-parens (node abs-pos)
12106 "Return a cons cell with positions of main parens in NODE."
12108 ((or (js2-array-node-p node)
12109 (js2-object-node-p node)
12110 (js2-comp-node-p node)
12111 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
12112 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
12113 ((js2-paren-expr-node-p node)
12114 (let ((lp (js2-node-lp node))
12115 (rp (js2-node-rp node)))
12116 (cons (when lp (+ abs-pos lp))
12117 (when rp (+ abs-pos rp)))))))
12119 (defun js2-node-closest-child (parent point limit &optional before)
12120 (let* ((parent-pos (js2-node-abs-pos parent))
12121 (rpoint (- point parent-pos))
12122 (rlimit (- limit parent-pos))
12123 (min (min rpoint rlimit))
12124 (max (max rpoint rlimit))
12129 (lambda (node _end-p)
12130 (if (eq node parent)
12132 (let ((pos (js2-node-pos node)) ;; Both relative values.
12133 (end (+ (js2-node-pos node) (js2-node-len node))))
12134 (when (and (>= pos min) (<= end max)
12135 (if before (< pos rpoint) (> end rpoint)))
12137 (when (> end rpoint)
12138 (throw 'done nil)))
12142 (defun js2-errors ()
12143 "Return a list of errors found."
12145 (js2-ast-root-errors js2-mode-ast)))
12147 (defun js2-warnings ()
12148 "Return a list of warnings found."
12150 (js2-ast-root-warnings js2-mode-ast)))
12152 (defun js2-have-errors-p ()
12153 "Return non-nil if any parse errors or warnings were found."
12154 (or (js2-errors) (js2-warnings)))
12156 (defun js2-errors-and-warnings ()
12157 "Return a copy of the concatenated errors and warnings lists.
12158 They are appended: first the errors, then the warnings.
12159 Entries are of the form (MSG BEG END)."
12161 (append (js2-ast-root-errors js2-mode-ast)
12162 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
12164 (defun js2-next-error (&optional arg reset)
12165 "Move to next parse error.
12166 Typically invoked via \\[next-error].
12167 ARG is the number of errors, forward or backward, to move.
12168 RESET means start over from the beginning."
12170 (if (not (or (js2-errors) (js2-warnings)))
12171 (message "No errors")
12173 (goto-char (point-min)))
12174 (let* ((errs (js2-errors-and-warnings))
12178 (backward (cl-minusp count))
12179 (sorter (if backward '> '<))
12180 (stopper (if backward '< '>))
12181 (count (abs count))
12183 ;; Sort by start position.
12184 (setq errs (sort errs (lambda (e1 e2)
12185 (funcall sorter (cl-second e1) (cl-second e2))))
12187 ;; Find nth error with pos > start.
12188 (while (and errs continue)
12189 (when (funcall stopper (cl-cadar errs) start)
12190 (setq err (car errs))
12191 (if (zerop (cl-decf count))
12192 (setq continue nil)))
12193 (setq errs (cdr errs)))
12194 ;; Clear for `js2-echo-error'.
12197 (goto-char (cl-second err))
12198 ;; Wrap around to first error.
12199 (goto-char (cl-second (car all-errs)))
12200 ;; If we were already on it, echo msg again.
12201 (if (= (point) start)
12202 (js2-echo-error (point) (point)))))))
12204 (defun js2-down-mouse-3 ()
12205 "Make right-click move the point to the click location.
12206 This makes right-click context menu operations a bit more intuitive.
12207 The point will not move if the region is active, however, to avoid
12208 destroying the region selection."
12210 (when (and js2-move-point-on-right-click
12212 (let ((e last-input-event))
12214 (goto-char (cl-cadadr e))))))
12216 (defun js2-mode-create-imenu-index ()
12217 "Return an alist for `imenu--index-alist'."
12218 ;; This is built up in `js2-parse-record-imenu' during parsing.
12220 ;; if we have an ast but no recorder, they're requesting a rescan
12221 (unless js2-imenu-recorder
12222 (js2-reparse 'force))
12224 (js2-build-imenu-index)
12225 (setq js2-imenu-recorder nil
12226 js2-imenu-function-map nil))))
12228 (defun js2-mode-find-tag ()
12229 "Replacement for `find-tag-default'.
12230 `find-tag-default' returns a ridiculous answer inside comments."
12232 (js2-with-underscore-as-word-syntax
12234 (if (and (not (looking-at "[[:alnum:]_$]"))
12235 (looking-back "[[:alnum:]_$]"))
12236 (setq beg (progn (forward-word -1) (point))
12237 end (progn (forward-word 1) (point)))
12238 (setq beg (progn (forward-word 1) (point))
12239 end (progn (forward-word -1) (point))))
12240 (replace-regexp-in-string
12242 (buffer-substring-no-properties beg end))))))
12244 (defun js2-mode-forward-sibling ()
12245 "Move to the end of the sibling following point in parent.
12246 Returns non-nil if successful, or nil if there was no following sibling."
12247 (let* ((node (js2-node-at-point))
12248 (parent (js2-mode-find-enclosing-fn node))
12250 (when (setq sib (js2-node-find-child-after (point) parent))
12251 (goto-char (+ (js2-node-abs-pos sib)
12252 (js2-node-len sib))))))
12254 (defun js2-mode-backward-sibling ()
12255 "Move to the beginning of the sibling node preceding point in parent.
12256 Parent is defined as the enclosing script or function."
12257 (let* ((node (js2-node-at-point))
12258 (parent (js2-mode-find-enclosing-fn node))
12260 (when (setq sib (js2-node-find-child-before (point) parent))
12261 (goto-char (js2-node-abs-pos sib)))))
12263 (defun js2-beginning-of-defun (&optional arg)
12264 "Go to line on which current function starts, and return t on success.
12265 If we're not in a function or already at the beginning of one, go
12266 to beginning of previous script-level element.
12267 With ARG N, do that N times. If N is negative, move forward."
12268 (setq arg (or arg 1))
12270 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
12272 ((js2-function-node-p parent)
12273 (goto-char (js2-node-abs-pos parent)))
12275 (js2-mode-backward-sibling)))
12277 (js2-beginning-of-defun (1- arg))
12279 (when (js2-end-of-defun)
12280 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
12282 (defun js2-end-of-defun ()
12283 "Go to the char after the last position of the current function
12284 or script-level element."
12285 (let* ((node (js2-node-at-point))
12286 (parent (or (and (js2-function-node-p node) node)
12287 (js2-node-parent-script-or-fn node)))
12289 (unless (js2-function-node-p parent)
12290 ;; Use current script-level node, or, if none, the next one.
12291 (setq script (or parent node)
12292 parent (js2-node-find-child-before (point) script))
12293 (when (or (null parent)
12294 (>= (point) (+ (js2-node-abs-pos parent)
12295 (js2-node-len parent))))
12296 (setq parent (js2-node-find-child-after (point) script))))
12298 (goto-char (+ (js2-node-abs-pos parent)
12299 (js2-node-len parent))))))
12301 (defun js2-mark-defun (&optional allow-extend)
12302 "Put mark at end of this function, point at beginning.
12303 The function marked is the one that contains point.
12305 Interactively, if this command is repeated,
12306 or (in Transient Mark mode) if the mark is active,
12307 it marks the next defun after the ones already marked."
12310 (when (and allow-extend
12311 (or (and (eq last-command this-command) (mark t))
12312 (and transient-mark-mode mark-active)))
12313 (let ((sib (save-excursion
12315 (if (js2-mode-forward-sibling)
12321 ;; no more siblings - try extending to enclosing node
12322 (goto-char (mark t)))))
12323 (when (not extended)
12324 (let ((node (js2-node-at-point (point) t)) ; skip comments
12325 ast fn stmt parent beg end)
12326 (when (js2-ast-root-p node)
12328 node (or (js2-node-find-child-after (point) node)
12329 (js2-node-find-child-before (point) node))))
12330 ;; only mark whole buffer if we can't find any children
12333 (if (js2-function-node-p node)
12335 (setq fn (js2-mode-find-enclosing-fn node)
12336 stmt (if (or (null fn)
12337 (js2-ast-root-p fn))
12338 (js2-mode-find-first-stmt node))
12339 parent (or stmt fn)))
12340 (setq beg (js2-node-abs-pos parent)
12341 end (+ beg (js2-node-len parent)))
12344 (exchange-point-and-mark)))))
12346 (defun js2-narrow-to-defun ()
12347 "Narrow to the function enclosing point."
12349 (let* ((node (js2-node-at-point (point) t)) ; skip comments
12350 (fn (if (js2-script-node-p node)
12352 (js2-mode-find-enclosing-fn node)))
12353 (beg (js2-node-abs-pos fn)))
12354 (unless (js2-ast-root-p fn)
12355 (narrow-to-region beg (+ beg (js2-node-len fn))))))
12357 (provide 'js2-mode)
12359 ;;; js2-mode.el ends here