Permalink
12890 lines (11562 sloc) 499 KB
;;; js2-mode.el --- Improved JavaScript editing mode
;; Copyright (C) 2009, 2011-2017 Free Software Foundation, Inc.
;; Author: Steve Yegge <steve.yegge@gmail.com>
;; mooz <stillpedant@gmail.com>
;; Dmitry Gutov <dgutov@yandex.ru>
;; URL: https://github.com/mooz/js2-mode/
;; http://code.google.com/p/js2-mode/
;; Version: 20170721
;; Keywords: languages, javascript
;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This JavaScript editing mode supports:
;; - strict recognition of the Ecma-262 language standard
;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
;; - accurate syntax highlighting using a recursive-descent parser
;; - on-the-fly reporting of syntax errors and strict-mode warnings
;; - undeclared-variable warnings using a configurable externs framework
;; - "bouncing" line indentation to choose among alternate indentation points
;; - smart line-wrapping within comments and strings
;; - code folding:
;; - show some or all function bodies as {...}
;; - show some or all block comments as /*...*/
;; - context-sensitive menu bar and popup menus
;; - code browsing using the `imenu' package
;; - many customization options
;; Installation:
;;
;; To install it as your major mode for JavaScript editing:
;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
;; Alternatively, to install it as a minor mode just for JavaScript linting,
;; you must add it to the appropriate major-mode hook. Normally this would be:
;; (add-hook 'js-mode-hook 'js2-minor-mode)
;; You may also want to hook it in for shell scripts running via node.js:
;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
;; Support for JSX is available via the derived mode `js2-jsx-mode'. If you
;; also want JSX support, use that mode instead:
;; (add-to-list 'auto-mode-alist '("\\.jsx?\\'" . js2-jsx-mode))
;; (add-to-list 'interpreter-mode-alist '("node" . js2-jsx-mode))
;; To customize how it works:
;; M-x customize-group RET js2-mode RET
;; Notes:
;; This mode includes a port of Mozilla Rhino's scanner, parser and
;; symbol table. Ideally it should stay in sync with Rhino, keeping
;; `js2-mode' current as the EcmaScript language standard evolves.
;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
;; customizable. It is a surprising amount of work to support customizable
;; indentation. The current compromise is that the tab key lets you cycle among
;; various likely indentation points, similar to the behavior of python-mode.
;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
;; and `mumamo', although it could be made to do so with some effort.
;; This means that `js2-mode' is currently only useful for editing JavaScript
;; files, and not for editing JavaScript within <script> tags or templates.
;; The project page on GitHub is used for development and issue tracking.
;; The original homepage at Google Code has outdated information and is mostly
;; unmaintained.
;;; Code:
(require 'cl-lib)
(require 'imenu)
(require 'js)
(require 'etags)
(eval-and-compile
(if (version< emacs-version "25.0")
(require 'js2-old-indent)
(defvaralias 'js2-basic-offset 'js-indent-level nil)
(defalias 'js2-proper-indentation 'js--proper-indentation)
(defalias 'js2-jsx-indent-line 'js-jsx-indent-line)
(defalias 'js2-indent-line 'js-indent-line)
(defalias 'js2-re-search-forward 'js--re-search-forward)))
;;; Externs (variables presumed to be defined by the host system)
(defvar js2-ecma-262-externs
(mapcar 'symbol-name
'(Array Boolean Date Error EvalError Function Infinity JSON
Math NaN Number Object RangeError ReferenceError RegExp
String SyntaxError TypeError URIError
decodeURI decodeURIComponent encodeURI
encodeURIComponent escape eval isFinite isNaN
parseFloat parseInt undefined unescape))
"Ecma-262 externs. Never highlighted as undeclared variables.")
(defvar js2-browser-externs
(mapcar 'symbol-name
'(;; DOM level 1
Attr CDATASection CharacterData Comment DOMException
DOMImplementation Document DocumentFragment
DocumentType Element Entity EntityReference
ExceptionCode NamedNodeMap Node NodeList Notation
ProcessingInstruction Text
;; DOM level 2
HTMLAnchorElement HTMLAppletElement HTMLAreaElement
HTMLBRElement HTMLBaseElement HTMLBaseFontElement
HTMLBodyElement HTMLButtonElement HTMLCollection
HTMLDListElement HTMLDirectoryElement HTMLDivElement
HTMLDocument HTMLElement HTMLFieldSetElement
HTMLFontElement HTMLFormElement HTMLFrameElement
HTMLFrameSetElement HTMLHRElement HTMLHeadElement
HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
HTMLImageElement HTMLInputElement HTMLIsIndexElement
HTMLLIElement HTMLLabelElement HTMLLegendElement
HTMLLinkElement HTMLMapElement HTMLMenuElement
HTMLMetaElement HTMLModElement HTMLOListElement
HTMLObjectElement HTMLOptGroupElement
HTMLOptionElement HTMLOptionsCollection
HTMLParagraphElement HTMLParamElement HTMLPreElement
HTMLQuoteElement HTMLScriptElement HTMLSelectElement
HTMLStyleElement HTMLTableCaptionElement
HTMLTableCellElement HTMLTableColElement
HTMLTableElement HTMLTableRowElement
HTMLTableSectionElement HTMLTextAreaElement
HTMLTitleElement HTMLUListElement
;; DOM level 3
DOMConfiguration DOMError DOMException
DOMImplementationList DOMImplementationSource
DOMLocator DOMStringList NameList TypeInfo
UserDataHandler
;; Window
window alert confirm document java navigator prompt screen
self top requestAnimationFrame cancelAnimationFrame
;; W3C CSS
CSSCharsetRule CSSFontFace CSSFontFaceRule
CSSImportRule CSSMediaRule CSSPageRule
CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
CSSStyleDeclaration CSSStyleRule CSSStyleSheet
CSSValue CSSValueList Counter DOMImplementationCSS
DocumentCSS DocumentStyle ElementCSSInlineStyle
LinkStyle MediaList RGBColor Rect StyleSheet
StyleSheetList ViewCSS
;; W3C Event
EventListener EventTarget Event DocumentEvent UIEvent
MouseEvent MutationEvent KeyboardEvent
;; W3C Range
DocumentRange Range RangeException
;; W3C XML
XPathResult XMLHttpRequest
;; console object. Provided by at least Chrome and Firefox.
console))
"Browser externs.
You can cause these to be included or excluded with the custom
variable `js2-include-browser-externs'.")
(defvar js2-rhino-externs
(mapcar 'symbol-name
'(Packages importClass importPackage com org java
;; Global object (shell) externs.
defineClass deserialize doctest gc help load
loadClass print quit readFile readUrl runCommand seal
serialize spawn sync toint32 version))
"Mozilla Rhino externs.
Set `js2-include-rhino-externs' to t to include them.")
(defvar js2-node-externs
(mapcar 'symbol-name
'(__dirname __filename Buffer clearInterval clearTimeout require
console exports global module process setInterval setTimeout
querystring setImmediate clearImmediate))
"Node.js externs.
Set `js2-include-node-externs' to t to include them.")
(defvar js2-typed-array-externs
(mapcar 'symbol-name
'(ArrayBuffer Uint8ClampedArray DataView
Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
Float32Array Float64Array))
"Khronos typed array externs. Available in most modern browsers and
in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
are enabled, these will also be included.")
(defvar js2-harmony-externs
(mapcar 'symbol-name
'(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
"ES6 externs. If `js2-include-browser-externs' is enabled and
`js2-language-version' is sufficiently high, these will be included.")
;;; Variables
(defcustom js2-ignored-warnings nil
"A list of warning message types that will not be reported.
Possible values are the keys of `js2-message-table'."
:group 'js2-mode
:type '(repeat string))
(defcustom js2-highlight-level 2
"Amount of syntax highlighting to perform.
0 or a negative value means none.
1 adds basic syntax highlighting.
2 adds highlighting of some Ecma built-in properties.
3 adds highlighting of many Ecma built-in functions."
:group 'js2-mode
:type '(choice (const :tag "None" 0)
(const :tag "Basic" 1)
(const :tag "Include Properties" 2)
(const :tag "Include Functions" 3)))
(defvar js2-mode-dev-mode-p nil
"Non-nil if running in development mode. Normally nil.")
(defgroup js2-mode nil
"An improved JavaScript mode."
:group 'languages)
(defcustom js2-idle-timer-delay 0.2
"Delay in secs before re-parsing after user makes changes.
Multiplied by `js2-dynamic-idle-timer-adjust', which see."
:type 'number
:group 'js2-mode)
(make-variable-buffer-local 'js2-idle-timer-delay)
(defcustom js2-dynamic-idle-timer-adjust 0
"Positive to adjust `js2-idle-timer-delay' based on file size.
The idea is that for short files, parsing is faster so we can be
more responsive to user edits without interfering with editing.
The buffer length in characters (typically bytes) is divided by
this value and used to multiply `js2-idle-timer-delay' for the
buffer. For example, a 21k file and 10k adjust yields 21k/10k
== 2, so js2-idle-timer-delay is multiplied by 2.
If `js2-dynamic-idle-timer-adjust' is 0 or negative,
`js2-idle-timer-delay' is not dependent on the file size."
:type 'number
:group 'js2-mode)
(defcustom js2-concat-multiline-strings t
"When non-nil, `js2-line-break' in mid-string will make it a
string concatenation. When `eol', the '+' will be inserted at the
end of the line, otherwise, at the beginning of the next line."
:type '(choice (const t) (const eol) (const nil))
:group 'js2-mode)
(defcustom js2-mode-show-parse-errors t
"True to highlight parse errors."
:type 'boolean
:group 'js2-mode)
(defcustom js2-mode-assume-strict nil
"Non-nil to start files in strict mode automatically."
:type 'boolean
:group 'js2-mode)
(defcustom js2-mode-show-strict-warnings t
"Non-nil to emit Ecma strict-mode warnings.
Some of the warnings can be individually disabled by other flags,
even if this flag is non-nil."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-trailing-comma-warning t
"Non-nil to warn about trailing commas in array literals.
Ecma-262-5.1 allows them, but older versions of IE raise an error."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-missing-semi-warning t
"Non-nil to warn about semicolon auto-insertion after statement.
Technically this is legal per Ecma-262, but some style guides disallow
depending on it."
:type 'boolean
:group 'js2-mode)
(defcustom js2-missing-semi-one-line-override nil
"Non-nil to permit missing semicolons in one-line functions.
In one-liner functions such as `function identity(x) {return x}'
people often omit the semicolon for a cleaner look. If you are
such a person, you can suppress the missing-semicolon warning
by setting this variable to t."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-inconsistent-return-warning t
"Non-nil to warn about mixing returns with value-returns.
It's perfectly legal to have a `return' and a `return foo' in the
same function, but it's often an indicator of a bug, and it also
interferes with type inference (in systems that support it.)"
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-cond-assign-warning t
"Non-nil to warn about expressions like if (a = b).
This often should have been '==' instead of '='. If the warning
is enabled, you can suppress it on a per-expression basis by
parenthesizing the expression, e.g. if ((a = b)) ..."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-var-redeclaration-warning t
"Non-nil to warn about redeclaring variables in a script or function."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-var-hides-function-arg-warning t
"Non-nil to warn about a var decl hiding a function argument."
:type 'boolean
:group 'js2-mode)
(defcustom js2-skip-preprocessor-directives nil
"Non-nil to treat lines beginning with # as comments.
Useful for viewing Mozilla JavaScript source code."
:type 'boolean
:group 'js2-mode)
(defcustom js2-language-version 200
"Configures what JavaScript language version to recognize.
Currently versions 150, 160, 170, 180 and 200 are supported,
corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
yield, and Array comprehensions, and 1.8 adds function closures."
:type 'integer
:group 'js2-mode)
(defcustom js2-instanceof-has-side-effects nil
"If non-nil, treats the instanceof operator as having side effects.
This is useful for xulrunner apps."
:type 'boolean
:group 'js2-mode)
(defcustom js2-getprop-has-side-effects nil
"If non-nil, treats the getprop operator as having side effects.
This is useful for testing libraries with nontrivial getters and for
compilers that use empty getprops to declare interface properties."
:type 'boolean
:group 'js2-mode)
(defcustom js2-move-point-on-right-click t
"Non-nil to move insertion point when you right-click.
This makes right-click context menu behavior a bit more intuitive,
since menu operations generally apply to the point. The exception
is if there is a region selection, in which case the point does -not-
move, so cut/copy/paste can work properly.
Note that IntelliJ moves the point, and Eclipse leaves it alone,
so this behavior is customizable."
:group 'js2-mode
:type 'boolean)
(defcustom js2-allow-rhino-new-expr-initializer t
"Non-nil to support a Rhino's experimental syntactic construct.
Rhino supports the ability to follow a `new' expression with an object
literal, which is used to set additional properties on the new object
after calling its constructor. Syntax:
new <expr> [ ( arglist ) ] [initializer]
Hence, this expression:
new Object {a: 1, b: 2}
results in an Object with properties a=1 and b=2. This syntax is
apparently not configurable in Rhino - it's currently always enabled,
as of Rhino version 1.7R2."
:type 'boolean
:group 'js2-mode)
(defcustom js2-allow-member-expr-as-function-name nil
"Non-nil to support experimental Rhino syntax for function names.
Rhino supports an experimental syntax configured via the Rhino Context
setting `allowMemberExprAsFunctionName'. The experimental syntax is:
function <member-expr> ( [ arg-list ] ) { <body> }
Where member-expr is a non-parenthesized 'member expression', which
is anything at the grammar level of a new-expression or lower, meaning
any expression that does not involve infix or unary operators.
When <member-expr> is not a simple identifier, then it is syntactic
sugar for assigning the anonymous function to the <member-expr>. Hence,
this code:
function a.b().c[2] (x, y) { ... }
is rewritten as:
a.b().c[2] = function(x, y) {...}
which doesn't seem particularly useful, but Rhino permits it."
:type 'boolean
:group 'js2-mode)
;; scanner variables
(defmacro js2-deflocal (name value &optional comment)
"Define a buffer-local variable NAME with VALUE and COMMENT."
(declare (debug defvar) (doc-string 3))
`(progn
(defvar ,name ,value ,comment)
(make-variable-buffer-local ',name)))
(defvar js2-EOF_CHAR -1
"Represents end of stream. Distinct from js2-EOF token type.")
;; I originally used symbols to represent tokens, but Rhino uses
;; ints and then sets various flag bits in them, so ints it is.
;; The upshot is that we need a `js2-' prefix in front of each name.
(defvar js2-ERROR -1)
(defvar js2-EOF 0)
(defvar js2-EOL 1)
(defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
(defvar js2-LEAVEWITH 3)
(defvar js2-RETURN 4)
(defvar js2-GOTO 5)
(defvar js2-IFEQ 6)
(defvar js2-IFNE 7)
(defvar js2-SETNAME 8)
(defvar js2-BITOR 9)
(defvar js2-BITXOR 10)
(defvar js2-BITAND 11)
(defvar js2-EQ 12)
(defvar js2-NE 13)
(defvar js2-LT 14)
(defvar js2-LE 15)
(defvar js2-GT 16)
(defvar js2-GE 17)
(defvar js2-LSH 18)
(defvar js2-RSH 19)
(defvar js2-URSH 20)
(defvar js2-ADD 21) ; infix plus
(defvar js2-SUB 22) ; infix minus
(defvar js2-MUL 23)
(defvar js2-DIV 24)
(defvar js2-MOD 25)
(defvar js2-NOT 26)
(defvar js2-BITNOT 27)
(defvar js2-POS 28) ; unary plus
(defvar js2-NEG 29) ; unary minus
(defvar js2-NEW 30)
(defvar js2-DELPROP 31)
(defvar js2-TYPEOF 32)
(defvar js2-GETPROP 33)
(defvar js2-GETPROPNOWARN 34)
(defvar js2-SETPROP 35)
(defvar js2-GETELEM 36)
(defvar js2-SETELEM 37)
(defvar js2-CALL 38)
(defvar js2-NAME 39) ; an identifier
(defvar js2-NUMBER 40)
(defvar js2-STRING 41)
(defvar js2-NULL 42)
(defvar js2-THIS 43)
(defvar js2-FALSE 44)
(defvar js2-TRUE 45)
(defvar js2-SHEQ 46) ; shallow equality (===)
(defvar js2-SHNE 47) ; shallow inequality (!==)
(defvar js2-REGEXP 48)
(defvar js2-BINDNAME 49)
(defvar js2-THROW 50)
(defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
(defvar js2-IN 52)
(defvar js2-INSTANCEOF 53)
(defvar js2-LOCAL_LOAD 54)
(defvar js2-GETVAR 55)
(defvar js2-SETVAR 56)
(defvar js2-CATCH_SCOPE 57)
(defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
(defvar js2-ENUM_INIT_VALUES 59)
(defvar js2-ENUM_INIT_ARRAY 60)
(defvar js2-ENUM_NEXT 61)
(defvar js2-ENUM_ID 62)
(defvar js2-THISFN 63)
(defvar js2-RETURN_RESULT 64) ; to return previously stored return result
(defvar js2-ARRAYLIT 65) ; array literal
(defvar js2-OBJECTLIT 66) ; object literal
(defvar js2-GET_REF 67) ; *reference
(defvar js2-SET_REF 68) ; *reference = something
(defvar js2-DEL_REF 69) ; delete reference
(defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
(defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
(defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
;; XML support
(defvar js2-DEFAULTNAMESPACE 73)
(defvar js2-ESCXMLATTR 74)
(defvar js2-ESCXMLTEXT 75)
(defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
(defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
(defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
(defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
(defvar js2-first-bytecode js2-ENTERWITH)
(defvar js2-last-bytecode js2-REF_NS_NAME)
(defvar js2-TRY 80)
(defvar js2-SEMI 81) ; semicolon
(defvar js2-LB 82) ; left and right brackets
(defvar js2-RB 83)
(defvar js2-LC 84) ; left and right curly-braces
(defvar js2-RC 85)
(defvar js2-LP 86) ; left and right parens
(defvar js2-RP 87)
(defvar js2-COMMA 88) ; comma operator
(defvar js2-ASSIGN 89) ; simple assignment (=)
(defvar js2-ASSIGN_BITOR 90) ; |=
(defvar js2-ASSIGN_BITXOR 91) ; ^=
(defvar js2-ASSIGN_BITAND 92) ; &=
(defvar js2-ASSIGN_LSH 93) ; <<=
(defvar js2-ASSIGN_RSH 94) ; >>=
(defvar js2-ASSIGN_URSH 95) ; >>>=
(defvar js2-ASSIGN_ADD 96) ; +=
(defvar js2-ASSIGN_SUB 97) ; -=
(defvar js2-ASSIGN_MUL 98) ; *=
(defvar js2-ASSIGN_DIV 99) ; /=
(defvar js2-ASSIGN_MOD 100) ; %=
(defvar js2-ASSIGN_EXPON 101)
(defvar js2-first-assign js2-ASSIGN)
(defvar js2-last-assign js2-ASSIGN_EXPON)
(defvar js2-COLON 102)
(defvar js2-OR 103) ; logical or (||)
(defvar js2-AND 104) ; logical and (&&)
(defvar js2-INC 105) ; increment/decrement (++ --)
(defvar js2-DEC 106)
(defvar js2-DOT 107) ; member operator (.)
(defvar js2-FUNCTION 108) ; function keyword
(defvar js2-EXPORT 109) ; export keyword
(defvar js2-IMPORT 110) ; import keyword
(defvar js2-IF 111) ; if keyword
(defvar js2-ELSE 112) ; else keyword
(defvar js2-SWITCH 113) ; switch keyword
(defvar js2-CASE 114) ; case keyword
(defvar js2-DEFAULT 115) ; default keyword
(defvar js2-WHILE 116) ; while keyword
(defvar js2-DO 117) ; do keyword
(defvar js2-FOR 118) ; for keyword
(defvar js2-BREAK 119) ; break keyword
(defvar js2-CONTINUE 120) ; continue keyword
(defvar js2-VAR 121) ; var keyword
(defvar js2-WITH 122) ; with keyword
(defvar js2-CATCH 123) ; catch keyword
(defvar js2-FINALLY 124) ; finally keyword
(defvar js2-VOID 125) ; void keyword
(defvar js2-RESERVED 126) ; reserved keywords
(defvar js2-EMPTY 127)
;; Types used for the parse tree - never returned by scanner.
(defvar js2-BLOCK 128) ; statement block
(defvar js2-LABEL 129) ; label
(defvar js2-TARGET 130)
(defvar js2-LOOP 131)
(defvar js2-EXPR_VOID 132) ; expression statement in functions
(defvar js2-EXPR_RESULT 133) ; expression statement in scripts
(defvar js2-JSR 134)
(defvar js2-SCRIPT 135) ; top-level node for entire script
(defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
(defvar js2-USE_STACK 137)
(defvar js2-SETPROP_OP 138) ; x.y op= something
(defvar js2-SETELEM_OP 139) ; x[y] op= something
(defvar js2-LOCAL_BLOCK 140)
(defvar js2-SET_REF_OP 141) ; *reference op= something
;; For XML support:
(defvar js2-DOTDOT 142) ; member operator (..)
(defvar js2-COLONCOLON 143) ; namespace::name
(defvar js2-XML 144) ; XML type
(defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
(defvar js2-XMLATTR 146) ; @
(defvar js2-XMLEND 147)
;; Optimizer-only tokens
(defvar js2-TO_OBJECT 148)
(defvar js2-TO_DOUBLE 149)
(defvar js2-GET 150) ; JS 1.5 get pseudo keyword
(defvar js2-SET 151) ; JS 1.5 set pseudo keyword
(defvar js2-LET 152) ; JS 1.7 let pseudo keyword
(defvar js2-CONST 153)
(defvar js2-SETCONST 154)
(defvar js2-SETCONSTVAR 155)
(defvar js2-ARRAYCOMP 156)
(defvar js2-LETEXPR 157)
(defvar js2-WITHEXPR 158)
(defvar js2-DEBUGGER 159)
(defvar js2-COMMENT 160)
(defvar js2-TRIPLEDOT 161) ; for rest parameter
(defvar js2-ARROW 162) ; function arrow (=>)
(defvar js2-CLASS 163)
(defvar js2-EXTENDS 164)
(defvar js2-SUPER 165)
(defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
(defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
(defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
(defvar js2-AWAIT 169) ; await (pseudo keyword)
(defvar js2-HOOK 170) ; conditional (?:)
(defvar js2-EXPON 171)
(defconst js2-num-tokens (1+ js2-EXPON))
(defconst js2-debug-print-trees nil)
;; Rhino accepts any string or stream as input. Emacs character
;; processing works best in buffers, so we'll assume the input is a
;; buffer. JavaScript strings can be copied into temp buffers before
;; scanning them.
;; Buffer-local variables yield much cleaner code than using `defstruct'.
;; They're the Emacs equivalent of instance variables, more or less.
(js2-deflocal js2-ts-dirty-line nil
"Token stream buffer-local variable.
Indicates stuff other than whitespace since start of line.")
(js2-deflocal js2-ts-hit-eof nil
"Token stream buffer-local variable.")
;; FIXME: Unused.
(js2-deflocal js2-ts-line-start 0
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-lineno 1
"Token stream buffer-local variable.")
;; FIXME: Unused.
(js2-deflocal js2-ts-line-end-char -1
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
"Token stream buffer-local variable.
Current scan position.")
;; FIXME: Unused.
(js2-deflocal js2-ts-is-xml-attribute nil
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-xml-is-tag-content nil
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-xml-open-tags-count 0
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-string-buffer nil
"Token stream buffer-local variable.
List of chars built up while scanning various tokens.")
(cl-defstruct (js2-token
(:constructor nil)
(:constructor make-js2-token (beg)))
"Value returned from the token stream."
(type js2-EOF)
(beg 1)
(end -1)
(string "")
number
number-base
number-legacy-octal-p
regexp-flags
comment-type
follows-eol-p)
;; Have to call `js2-init-scanner' to initialize the values.
(js2-deflocal js2-ti-tokens nil)
(js2-deflocal js2-ti-tokens-cursor nil)
(js2-deflocal js2-ti-lookahead nil)
(cl-defstruct (js2-ts-state
(:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
(cursor js2-ts-cursor)
(tokens (copy-sequence js2-ti-tokens))
(tokens-cursor js2-ti-tokens-cursor)
(lookahead js2-ti-lookahead))))
lineno
cursor
tokens
tokens-cursor
lookahead)
;;; Parser variables
(js2-deflocal js2-parsed-errors nil
"List of errors produced during scanning/parsing.")
(js2-deflocal js2-parsed-warnings nil
"List of warnings produced during scanning/parsing.")
(js2-deflocal js2-recover-from-parse-errors t
"Non-nil to continue parsing after a syntax error.
In recovery mode, the AST will be built in full, and any error
nodes will be flagged with appropriate error information. If
this flag is nil, a syntax error will result in an error being
signaled.
The variable is automatically buffer-local, because different
modes that use the parser will need different settings.")
(js2-deflocal js2-parse-hook nil
"List of callbacks for receiving parsing progress.")
(defvar js2-parse-finished-hook nil
"List of callbacks to notify when parsing finishes.
Not called if parsing was interrupted.")
(js2-deflocal js2-is-eval-code nil
"True if we're evaluating code in a string.
If non-nil, the tokenizer will record the token text, and the AST nodes
will record their source text. Off by default for IDE modes, since the
text is available in the buffer.")
(defvar js2-parse-ide-mode t
"Non-nil if the parser is being used for `js2-mode'.
If non-nil, the parser will set text properties for fontification
and the syntax table. The value should be nil when using the
parser as a frontend to an interpreter or byte compiler.")
;;; Parser instance variables (buffer-local vars for js2-parse)
(defconst js2-ti-after-eol (lsh 1 16)
"Flag: first token of the source line.")
;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
(js2-deflocal js2-compiler-generate-debug-info t)
(js2-deflocal js2-compiler-use-dynamic-scope nil)
(js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
(js2-deflocal js2-compiler-xml-available t)
(js2-deflocal js2-compiler-optimization-level 0)
(js2-deflocal js2-compiler-generating-source t)
(js2-deflocal js2-compiler-strict-mode nil)
(js2-deflocal js2-compiler-report-warning-as-error nil)
(js2-deflocal js2-compiler-generate-observer-count nil)
(js2-deflocal js2-compiler-activation-names nil)
;; SKIP: sourceURI
;; There's a compileFunction method in Context.java - may need it.
(js2-deflocal js2-called-by-compile-function nil
"True if `js2-parse' was called by `js2-compile-function'.
Will only be used when we finish implementing the interpreter.")
;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
;; SKIP: node factory - we're going to just call functions directly,
;; and eventually go to a unified AST format.
(js2-deflocal js2-nesting-of-function 0)
(js2-deflocal js2-recorded-identifiers nil
"Tracks identifiers found during parsing.")
(js2-deflocal js2-is-in-destructuring nil
"True while parsing destructuring expression.")
(js2-deflocal js2-in-use-strict-directive nil
"True while inside a script or function under strict mode.")
(defcustom js2-global-externs nil
"A list of any extern names you'd like to consider always declared.
This list is global and is used by all `js2-mode' files.
You can create buffer-local externs list using `js2-additional-externs'."
:type 'list
:group 'js2-mode)
(defcustom js2-include-browser-externs t
"Non-nil to include browser externs in the master externs list.
If you work on JavaScript files that are not intended for browsers,
such as Mozilla Rhino server-side JavaScript, set this to nil.
See `js2-additional-externs' for more information about externs."
:type 'boolean
:group 'js2-mode)
(defcustom js2-include-rhino-externs nil
"Non-nil to include Mozilla Rhino externs in the master externs list.
See `js2-additional-externs' for more information about externs."
:type 'boolean
:group 'js2-mode)
(defcustom js2-include-node-externs nil
"Non-nil to include Node.js externs in the master externs list.
See `js2-additional-externs' for more information about externs."
:type 'boolean
:group 'js2-mode)
(js2-deflocal js2-additional-externs nil
"A buffer-local list of additional external declarations.
It is used to decide whether variables are considered undeclared
for purposes of highlighting. See `js2-highlight-undeclared-vars'.
Each entry is a Lisp string. The string should be the fully qualified
name of an external entity. All externs should be added to this list,
so that as js2-mode's processing improves it can take advantage of them.
You may want to declare your externs in three ways.
First, you can add externs that are valid for all your JavaScript files.
You should probably do this by adding them to `js2-global-externs', which
is a global list used for all js2-mode files.
Next, you can add a function to `js2-init-hook' that adds additional
externs appropriate for the specific file, perhaps based on its path.
These should go in `js2-additional-externs', which is buffer-local.
Third, you can use JSLint's global declaration, as long as
`js2-include-jslint-globals' is non-nil, which see.
Finally, you can add a function to `js2-post-parse-callbacks',
which is called after parsing completes, and `js2-mode-ast' is bound to
the root of the parse tree. At this stage you can set up an AST
node visitor using `js2-visit-ast' and examine the parse tree
for specific import patterns that may imply the existence of
other externs, possibly tied to your build system. These should also
be added to `js2-additional-externs'.
Your post-parse callback may of course also use the simpler and
faster (but perhaps less robust) approach of simply scanning the
buffer text for your imports, using regular expressions.")
;; SKIP: decompiler
;; SKIP: encoded-source
;;; The following variables are per-function and should be saved/restored
;;; during function parsing...
(js2-deflocal js2-current-script-or-fn nil)
(js2-deflocal js2-current-scope nil)
(js2-deflocal js2-nesting-of-with 0)
(js2-deflocal js2-label-set nil
"An alist mapping label names to nodes.")
(js2-deflocal js2-loop-set nil)
(js2-deflocal js2-loop-and-switch-set nil)
(js2-deflocal js2-has-return-value nil)
(js2-deflocal js2-end-flags 0)
;;; ...end of per function variables
;; These flags enumerate the possible ways a statement/function can
;; terminate. These flags are used by endCheck() and by the Parser to
;; detect inconsistent return usage.
;;
;; END_UNREACHED is reserved for code paths that are assumed to always be
;; able to execute (example: throw, continue)
;;
;; END_DROPS_OFF indicates if the statement can transfer control to the
;; next one. Statement such as return dont. A compound statement may have
;; some branch that drops off control to the next statement.
;;
;; END_RETURNS indicates that the statement can return (without arguments)
;; END_RETURNS_VALUE indicates that the statement can return a value.
;;
;; A compound statement such as
;; if (condition) {
;; return value;
;; }
;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
(defconst js2-end-unreached #x0)
(defconst js2-end-drops-off #x1)
(defconst js2-end-returns #x2)
(defconst js2-end-returns-value #x4)
;; Rhino awkwardly passes a statementLabel parameter to the
;; statementHelper() function, the main statement parser, which
;; is then used by quite a few of the sub-parsers. We just make
;; it a buffer-local variable and make sure it's cleaned up properly.
(js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
;; Similarly, Rhino passes an inForInit boolean through about half
;; the expression parsers. We use a dynamically-scoped variable,
;; which makes it easier to funcall the parsers individually without
;; worrying about whether they take the parameter or not.
(js2-deflocal js2-in-for-init nil)
(js2-deflocal js2-temp-name-counter 0)
(js2-deflocal js2-parse-stmt-count 0)
(defsubst js2-get-next-temp-name ()
(format "$%d" (cl-incf js2-temp-name-counter)))
(defvar js2-parse-interruptable-p t
"Set this to nil to force parse to continue until finished.
This will mostly be useful for interpreters.")
(defvar js2-statements-per-pause 50
"Pause after this many statements to check for user input.
If user input is pending, stop the parse and discard the tree.
This makes for a smoother user experience for large files.
You may have to wait a second or two before the highlighting
and error-reporting appear, but you can always type ahead if
you wish. This appears to be more or less how Eclipse, IntelliJ
and other editors work.")
(js2-deflocal js2-record-comments t
"Instructs the scanner to record comments in `js2-scanned-comments'.")
(js2-deflocal js2-scanned-comments nil
"List of all comments from the current parse.")
(defcustom js2-mode-indent-inhibit-undo nil
"Non-nil to disable collection of Undo information when indenting lines.
Some users have requested this behavior. It's nil by default because
other Emacs modes don't work this way."
:type 'boolean
:group 'js2-mode)
(defcustom js2-mode-indent-ignore-first-tab nil
"If non-nil, ignore first TAB keypress if we look indented properly.
It's fairly common for users to navigate to an already-indented line
and press TAB for reassurance that it's been indented. For this class
of users, we want the first TAB press on a line to be ignored if the
line is already indented to one of the precomputed alternatives.
This behavior is only partly implemented. If you TAB-indent a line,
navigate to another line, and then navigate back, it fails to clear
the last-indented variable, so it thinks you've already hit TAB once,
and performs the indent. A full solution would involve getting on the
point-motion hooks for the entire buffer. If we come across another
use cases that requires watching point motion, I'll consider doing it.
If you set this variable to nil, then the TAB key will always change
the indentation of the current line, if more than one alternative
indentation spot exists."
:type 'boolean
:group 'js2-mode)
(defvar js2-indent-hook nil
"A hook for user-defined indentation rules.
Functions on this hook should expect two arguments: (LIST INDEX)
The LIST argument is the list of computed indentation points for
the current line. INDEX is the list index of the indentation point
that `js2-bounce-indent' plans to use. If INDEX is nil, then the
indent function is not going to change the current line indentation.
If a hook function on this list returns a non-nil value, then
`js2-bounce-indent' assumes the hook function has performed its own
indentation, and will do nothing. If all hook functions on the list
return nil, then `js2-bounce-indent' will use its computed indentation
and reindent the line.
When hook functions on this hook list are called, the variable
`js2-mode-ast' may or may not be set, depending on whether the
parse tree is available. If the variable is nil, you can pass a
callback to `js2-mode-wait-for-parse', and your callback will be
called after the new parse tree is built. This can take some time
in large files.")
(defface js2-warning
`((((class color) (background light))
(:underline "orange"))
(((class color) (background dark))
(:underline "orange"))
(t (:underline t)))
"Face for JavaScript warnings."
:group 'js2-mode)
(defface js2-error
`((((class color) (background light))
(:foreground "red"))
(((class color) (background dark))
(:foreground "red"))
(t (:foreground "red")))
"Face for JavaScript errors."
:group 'js2-mode)
(defface js2-jsdoc-tag
'((t :foreground "SlateGray"))
"Face used to highlight @whatever tags in jsdoc comments."
:group 'js2-mode)
(defface js2-jsdoc-type
'((t :foreground "SteelBlue"))
"Face used to highlight {FooBar} types in jsdoc comments."
:group 'js2-mode)
(defface js2-jsdoc-value
'((t :foreground "PeachPuff3"))
"Face used to highlight tag values in jsdoc comments."
:group 'js2-mode)
(defface js2-function-param
'((t :foreground "SeaGreen"))
"Face used to highlight function parameters in javascript."
:group 'js2-mode)
(defface js2-function-call
'((t :inherit default))
"Face used to highlight function name in calls."
:group 'js2-mode)
(defface js2-object-property
'((t :inherit default))
"Face used to highlight named property in object literal."
:group 'js2-mode)
(defface js2-instance-member
'((t :foreground "DarkOrchid"))
"Face used to highlight instance variables in javascript.
Not currently used."
:group 'js2-mode)
(defface js2-private-member
'((t :foreground "PeachPuff3"))
"Face used to highlight calls to private methods in javascript.
Not currently used."
:group 'js2-mode)
(defface js2-private-function-call
'((t :foreground "goldenrod"))
"Face used to highlight calls to private functions in javascript.
Not currently used."
:group 'js2-mode)
(defface js2-jsdoc-html-tag-name
'((((class color) (min-colors 88) (background light))
(:foreground "rosybrown"))
(((class color) (min-colors 8) (background dark))
(:foreground "yellow"))
(((class color) (min-colors 8) (background light))
(:foreground "magenta")))
"Face used to highlight jsdoc html tag names"
:group 'js2-mode)
(defface js2-jsdoc-html-tag-delimiter
'((((class color) (min-colors 88) (background light))
(:foreground "dark khaki"))
(((class color) (min-colors 8) (background dark))
(:foreground "green"))
(((class color) (min-colors 8) (background light))
(:foreground "green")))
"Face used to highlight brackets in jsdoc html tags."
:group 'js2-mode)
(defface js2-external-variable
'((t :foreground "orange"))
"Face used to highlight undeclared variable identifiers.")
(defcustom js2-init-hook nil
;; FIXME: We don't really need this anymore.
"List of functions to be called after `js2-mode' or
`js2-minor-mode' has initialized all variables, before parsing
the buffer for the first time."
:type 'hook
:group 'js2-mode
:version "20130608")
(defcustom js2-post-parse-callbacks nil
"List of callback functions invoked after parsing finishes.
Currently, the main use for this function is to add synthetic
declarations to `js2-recorded-identifiers', which see."
:type 'hook
:group 'js2-mode)
(defcustom js2-build-imenu-callbacks nil
"List of functions called during Imenu index generation.
It's a good place to add additional entries to it, using
`js2-record-imenu-entry'."
:type 'hook
:group 'js2-mode)
(defcustom js2-highlight-external-variables t
"Non-nil to highlight undeclared variable identifiers.
An undeclared variable is any variable not declared with var or let
in the current scope or any lexically enclosing scope. If you use
such a variable, then you are either expecting it to originate from
another file, or you've got a potential bug."
:type 'boolean
:group 'js2-mode)
(defcustom js2-warn-about-unused-function-arguments nil
"Non-nil to treat function arguments like declared-but-unused variables."
:type 'booleanp
:group 'js2-mode)
(defcustom js2-include-jslint-globals t
"Non-nil to include the identifiers from JSLint global
declaration (see http://www.jslint.com/help.html#global) in the
buffer-local externs list. See `js2-additional-externs' for more
information."
:type 'boolean
:group 'js2-mode)
(defcustom js2-include-jslint-declaration-externs t
"Non-nil to include the identifiers JSLint assumes to be there
under certain declarations in the buffer-local externs list. See
`js2-additional-externs' for more information."
:type 'boolean
:group 'js2-mode)
(defvar js2-mode-map
(let ((map (make-sparse-keymap)))
(define-key map [remap indent-new-comment-line] #'js2-line-break)
(define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
(define-key map (kbd "C-c C-s") #'js2-mode-show-element)
(define-key map (kbd "C-c C-a") #'js2-mode-show-all)
(define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
(define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
(define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
(define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
(define-key map [down-mouse-3] #'js2-down-mouse-3)
(define-key map [remap js-find-symbol] #'js2-jump-to-definition)
(define-key map [menu-bar javascript]
(cons "JavaScript" (make-sparse-keymap "JavaScript")))
(define-key map [menu-bar javascript customize-js2-mode]
'(menu-item "Customize js2-mode" js2-mode-customize
:help "Customize the behavior of this mode"))
(define-key map [menu-bar javascript js2-force-refresh]
'(menu-item "Force buffer refresh" js2-mode-reset
:help "Re-parse the buffer from scratch"))
(define-key map [menu-bar javascript separator-2]
'("--"))
(define-key map [menu-bar javascript next-error]
'(menu-item "Next warning or error" next-error
:enabled (and js2-mode-ast
(or (js2-ast-root-errors js2-mode-ast)
(js2-ast-root-warnings js2-mode-ast)))
:help "Move to next warning or error"))
(define-key map [menu-bar javascript display-errors]
'(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
:visible (not js2-mode-show-parse-errors)
:help "Turn on display of warnings and errors"))
(define-key map [menu-bar javascript hide-errors]
'(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
:visible js2-mode-show-parse-errors
:help "Turn off display of warnings and errors"))
(define-key map [menu-bar javascript separator-1]
'("--"))
(define-key map [menu-bar javascript js2-toggle-function]
'(menu-item "Show/collapse element" js2-mode-toggle-element
:help "Hide or show function body or comment"))
(define-key map [menu-bar javascript show-comments]
'(menu-item "Show block comments" js2-mode-toggle-hide-comments
:visible js2-mode-comments-hidden
:help "Expand all hidden block comments"))
(define-key map [menu-bar javascript hide-comments]
'(menu-item "Hide block comments" js2-mode-toggle-hide-comments
:visible (not js2-mode-comments-hidden)
:help "Show block comments as /*...*/"))
(define-key map [menu-bar javascript show-all-functions]
'(menu-item "Show function bodies" js2-mode-toggle-hide-functions
:visible js2-mode-functions-hidden
:help "Expand all hidden function bodies"))
(define-key map [menu-bar javascript hide-all-functions]
'(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
:visible (not js2-mode-functions-hidden)
:help "Show {...} for all top-level function bodies"))
map)
"Keymap used in `js2-mode' buffers.")
(defcustom js2-bounce-indent-p nil
"Non-nil to bind `js2-indent-bounce' and `js2-indent-bounce-backward'.
They will augment the default indent-line behavior with cycling
among several computed alternatives. See the function
`js2-bounce-indent' for details. The above commands will be
bound to TAB and backtab."
:type 'boolean
:group 'js2-mode
:set (lambda (sym value)
(set-default sym value)
(let ((map js2-mode-map))
(if (not value)
(progn
(define-key map "\t" nil)
(define-key map (kbd "<backtab>") nil))
(define-key map "\t" #'js2-indent-bounce)
(define-key map (kbd "<backtab>") #'js2-indent-bounce-backward)))))
(defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
(defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
"Matches a //-comment line. Must be first non-whitespace on line.
First match-group is the leading whitespace.")
(defvar js2-mode-hook nil)
(js2-deflocal js2-mode-ast nil "Private variable.")
(js2-deflocal js2-mode-parse-timer nil "Private variable.")
(js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
(js2-deflocal js2-mode-parsing nil "Private variable.")
(js2-deflocal js2-mode-node-overlay nil)
(defvar js2-mode-show-overlay js2-mode-dev-mode-p
"Debug: Non-nil to highlight AST nodes on mouse-down.")
(js2-deflocal js2-mode-fontifications nil "Private variable")
(js2-deflocal js2-mode-deferred-properties nil "Private variable")
(js2-deflocal js2-imenu-recorder nil "Private variable")
(js2-deflocal js2-imenu-function-map nil "Private variable")
(defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
"Non-nil to emit status messages during parsing.")
(defvar js2-mode-functions-hidden nil "Private variable.")
(defvar js2-mode-comments-hidden nil "Private variable.")
(defvar js2-mode-syntax-table
(let ((table (make-syntax-table)))
(c-populate-syntax-table table)
(modify-syntax-entry ?` "\"" table)
table)
"Syntax table used in `js2-mode' buffers.")
(defvar js2-mode-abbrev-table nil
"Abbrev table in use in `js2-mode' buffers.")
(define-abbrev-table 'js2-mode-abbrev-table ())
(defvar js2-mode-pending-parse-callbacks nil
"List of functions waiting to be notified that parse is finished.")
(defvar js2-mode-last-indented-line -1)
;;; Localizable error and warning messages
;; Messages are copied from Rhino's Messages.properties.
;; Many of the Java-specific messages have been elided.
;; Add any js2-specific ones at the end, so we can keep
;; this file synced with changes to Rhino's.
(defvar js2-message-table
(make-hash-table :test 'equal :size 250)
"Contains localized messages for `js2-mode'.")
;; TODO(stevey): construct this table at compile-time.
(defmacro js2-msg (key &rest strings)
`(puthash ,key (concat ,@strings)
js2-message-table))
(defun js2-get-msg (msg-key)
"Look up a localized message.
MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
the correct number of ARGS must be provided."
(let* ((key (if (listp msg-key) (car msg-key) msg-key))
(args (if (listp msg-key) (cdr msg-key)))
(msg (gethash key js2-message-table)))
(if msg
(apply #'format msg args)
key))) ; default to showing the key
(js2-msg "msg.dup.parms"
"Duplicate parameter name '%s'.")
(js2-msg "msg.too.big.jump"
"Program too complex: jump offset too big.")
(js2-msg "msg.too.big.index"
"Program too complex: internal index exceeds 64K limit.")
(js2-msg "msg.while.compiling.fn"
"Encountered code generation error while compiling function '%s': %s")
(js2-msg "msg.while.compiling.script"
"Encountered code generation error while compiling script: %s")
;; Context
(js2-msg "msg.ctor.not.found"
"Constructor for '%s' not found.")
(js2-msg "msg.not.ctor"
"'%s' is not a constructor.")
;; FunctionObject
(js2-msg "msg.varargs.ctor"
"Method or constructor '%s' must be static "
"with the signature (Context cx, Object[] args, "
"Function ctorObj, boolean inNewExpr) "
"to define a variable arguments constructor.")
(js2-msg "msg.varargs.fun"
"Method '%s' must be static with the signature "
"(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
"to define a variable arguments function.")
(js2-msg "msg.incompat.call"
"Method '%s' called on incompatible object.")
(js2-msg "msg.bad.parms"
"Unsupported parameter type '%s' in method '%s'.")
(js2-msg "msg.bad.method.return"
"Unsupported return type '%s' in method '%s'.")
(js2-msg "msg.bad.ctor.return"
"Construction of objects of type '%s' is not supported.")
(js2-msg "msg.no.overload"
"Method '%s' occurs multiple times in class '%s'.")
(js2-msg "msg.method.not.found"
"Method '%s' not found in '%s'.")
;; IRFactory
(js2-msg "msg.bad.for.in.lhs"
"Invalid left-hand side of for..in loop.")
(js2-msg "msg.mult.index"
"Only one variable allowed in for..in loop.")
(js2-msg "msg.bad.for.in.destruct"
"Left hand side of for..in loop must be an array of "
"length 2 to accept key/value pair.")
(js2-msg "msg.cant.convert"
"Can't convert to type '%s'.")
(js2-msg "msg.bad.assign.left"
"Invalid assignment left-hand side.")
(js2-msg "msg.bad.decr"
"Invalid decrement operand.")
(js2-msg "msg.bad.incr"
"Invalid increment operand.")
(js2-msg "msg.bad.yield"
"yield must be in a function.")
(js2-msg "msg.bad.await"
"await must be in async functions.")
;; NativeGlobal
(js2-msg "msg.cant.call.indirect"
"Function '%s' must be called directly, and not by way of a "
"function of another name.")
(js2-msg "msg.eval.nonstring"
"Calling eval() with anything other than a primitive "
"string value will simply return the value. "
"Is this what you intended?")
(js2-msg "msg.eval.nonstring.strict"
"Calling eval() with anything other than a primitive "
"string value is not allowed in strict mode.")
(js2-msg "msg.bad.destruct.op"
"Invalid destructuring assignment operator")
;; NativeCall
(js2-msg "msg.only.from.new"
"'%s' may only be invoked from a `new' expression.")
(js2-msg "msg.deprec.ctor"
"The '%s' constructor is deprecated.")
;; NativeFunction
(js2-msg "msg.no.function.ref.found"
"no source found to decompile function reference %s")
(js2-msg "msg.arg.isnt.array"
"second argument to Function.prototype.apply must be an array")
;; NativeGlobal
(js2-msg "msg.bad.esc.mask"
"invalid string escape mask")
;; NativeRegExp
(js2-msg "msg.bad.quant"
"Invalid quantifier %s")
(js2-msg "msg.overlarge.backref"
"Overly large back reference %s")
(js2-msg "msg.overlarge.min"
"Overly large minimum %s")
(js2-msg "msg.overlarge.max"
"Overly large maximum %s")
(js2-msg "msg.zero.quant"
"Zero quantifier %s")
(js2-msg "msg.max.lt.min"
"Maximum %s less than minimum")
(js2-msg "msg.unterm.quant"
"Unterminated quantifier %s")
(js2-msg "msg.unterm.paren"
"Unterminated parenthetical %s")
(js2-msg "msg.unterm.class"
"Unterminated character class %s")
(js2-msg "msg.bad.range"
"Invalid range in character class.")
(js2-msg "msg.trail.backslash"
"Trailing \\ in regular expression.")
(js2-msg "msg.re.unmatched.right.paren"
"unmatched ) in regular expression.")
(js2-msg "msg.no.regexp"
"Regular expressions are not available.")
(js2-msg "msg.bad.backref"
"back-reference exceeds number of capturing parentheses.")
(js2-msg "msg.bad.regexp.compile"
"Only one argument may be specified if the first "
"argument to RegExp.prototype.compile is a RegExp object.")
;; Parser
(js2-msg "msg.got.syntax.errors"
"Compilation produced %s syntax errors.")
(js2-msg "msg.var.redecl"
"Redeclaration of var %s.")
(js2-msg "msg.const.redecl"
"TypeError: redeclaration of const %s.")
(js2-msg "msg.let.redecl"
"TypeError: redeclaration of variable %s.")
(js2-msg "msg.parm.redecl"
"TypeError: redeclaration of formal parameter %s.")
(js2-msg "msg.fn.redecl"
"TypeError: redeclaration of function %s.")
(js2-msg "msg.let.decl.not.in.block"
"SyntaxError: let declaration not directly within block")
(js2-msg "msg.mod.import.decl.at.top.level"
"SyntaxError: import declarations may only appear at the top level")
(js2-msg "msg.mod.as.after.reserved.word"
"SyntaxError: missing keyword 'as' after reserved word %s")
(js2-msg "msg.mod.rc.after.import.spec.list"
"SyntaxError: missing '}' after module specifier list")
(js2-msg "msg.mod.from.after.import.spec.set"
"SyntaxError: missing keyword 'from' after import specifier set")
(js2-msg "msg.mod.declaration.after.import"
"SyntaxError: missing declaration after 'import' keyword")
(js2-msg "msg.mod.spec.after.from"
"SyntaxError: missing module specifier after 'from' keyword")
(js2-msg "msg.mod.export.decl.at.top.level"
"SyntaxError: export declarations may only appear at top level")
(js2-msg "msg.mod.rc.after.export.spec.list"
"SyntaxError: missing '}' after export specifier list")
;; NodeTransformer
(js2-msg "msg.dup.label"
"duplicated label")
(js2-msg "msg.undef.label"
"undefined label")
(js2-msg "msg.bad.break"
"unlabelled break must be inside loop or switch")
(js2-msg "msg.continue.outside"
"continue must be inside loop")
(js2-msg "msg.continue.nonloop"
"continue can only use labels of iteration statements")
(js2-msg "msg.bad.throw.eol"
"Line terminator is not allowed between the throw "
"keyword and throw expression.")
(js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
"function statement requires a name")
(js2-msg "msg.no.paren.parms"
"missing ( before function parameters.")
(js2-msg "msg.no.parm"
"missing formal parameter")
(js2-msg "msg.no.paren.after.parms"
"missing ) after formal parameters")
(js2-msg "msg.no.default.after.default.param" ; added by js2-mode
"parameter without default follows parameter with default")
(js2-msg "msg.param.after.rest" ; added by js2-mode
"parameter after rest parameter")
(js2-msg "msg.bad.arrow.args" ; added by js2-mode
"invalid arrow-function arguments (parentheses around the arrow-function may help)")
(js2-msg "msg.no.brace.body"
"missing '{' before function body")
(js2-msg "msg.no.brace.after.body"
"missing } after function body")
(js2-msg "msg.no.paren.cond"
"missing ( before condition")
(js2-msg "msg.no.paren.after.cond"
"missing ) after condition")
(js2-msg "msg.no.semi.stmt"
"missing ; before statement")
(js2-msg "msg.missing.semi"
"missing ; after statement")
(js2-msg "msg.no.name.after.dot"
"missing name after . operator")
(js2-msg "msg.no.name.after.coloncolon"
"missing name after :: operator")
(js2-msg "msg.no.name.after.dotdot"
"missing name after .. operator")
(js2-msg "msg.no.name.after.xmlAttr"
"missing name after .@")
(js2-msg "msg.no.bracket.index"
"missing ] in index expression")
(js2-msg "msg.no.paren.switch"
"missing ( before switch expression")
(js2-msg "msg.no.paren.after.switch"
"missing ) after switch expression")
(js2-msg "msg.no.brace.switch"
"missing '{' before switch body")
(js2-msg "msg.bad.switch"
"invalid switch statement")
(js2-msg "msg.no.colon.case"
"missing : after case expression")
(js2-msg "msg.double.switch.default"
"double default label in the switch statement")
(js2-msg "msg.no.while.do"
"missing while after do-loop body")
(js2-msg "msg.no.paren.for"
"missing ( after for")
(js2-msg "msg.no.semi.for"
"missing ; after for-loop initializer")
(js2-msg "msg.no.semi.for.cond"
"missing ; after for-loop condition")
(js2-msg "msg.in.after.for.name"
"missing in or of after for")
(js2-msg "msg.no.paren.for.ctrl"
"missing ) after for-loop control")
(js2-msg "msg.no.paren.with"
"missing ( before with-statement object")
(js2-msg "msg.no.paren.after.with"
"missing ) after with-statement object")
(js2-msg "msg.no.with.strict"
"with statements not allowed in strict mode")
(js2-msg "msg.no.paren.after.let"
"missing ( after let")
(js2-msg "msg.no.paren.let"
"missing ) after variable list")
(js2-msg "msg.no.curly.let"
"missing } after let statement")
(js2-msg "msg.bad.return"
"invalid return")
(js2-msg "msg.no.brace.block"
"missing } in compound statement")
(js2-msg "msg.bad.label"
"invalid label")
(js2-msg "msg.bad.var"
"missing variable name")
(js2-msg "msg.bad.var.init"
"invalid variable initialization")
(js2-msg "msg.no.colon.cond"
"missing : in conditional expression")
(js2-msg "msg.no.paren.arg"
"missing ) after argument list")
(js2-msg "msg.no.bracket.arg"
"missing ] after element list")
(js2-msg "msg.bad.prop"
"invalid property id")
(js2-msg "msg.no.colon.prop"
"missing : after property id")
(js2-msg "msg.no.brace.prop"
"missing } after property list")
(js2-msg "msg.no.paren"
"missing ) in parenthetical")
(js2-msg "msg.reserved.id"
"'%s' is a reserved identifier")
(js2-msg "msg.no.paren.catch"
"missing ( before catch-block condition")
(js2-msg "msg.bad.catchcond"
"invalid catch block condition")
(js2-msg "msg.catch.unreachable"
"any catch clauses following an unqualified catch are unreachable")
(js2-msg "msg.no.brace.try"
"missing '{' before try block")
(js2-msg "msg.no.brace.catchblock"
"missing '{' before catch-block body")
(js2-msg "msg.try.no.catchfinally"
"'try' without 'catch' or 'finally'")
(js2-msg "msg.no.return.value"
"function %s does not always return a value")
(js2-msg "msg.anon.no.return.value"
"anonymous function does not always return a value")
(js2-msg "msg.return.inconsistent"
"return statement is inconsistent with previous usage")
(js2-msg "msg.generator.returns"
"TypeError: legacy generator function '%s' returns a value")
(js2-msg "msg.anon.generator.returns"
"TypeError: anonymous legacy generator function returns a value")
(js2-msg "msg.syntax"
"syntax error")
(js2-msg "msg.unexpected.eof"
"Unexpected end of file")
(js2-msg "msg.XML.bad.form"
"illegally formed XML syntax")
(js2-msg "msg.XML.not.available"
"XML runtime not available")
(js2-msg "msg.too.deep.parser.recursion"
"Too deep recursion while parsing")
(js2-msg "msg.no.side.effects"
"Code has no side effects")
(js2-msg "msg.extra.trailing.comma"
"Trailing comma is not supported in some browsers")
(js2-msg "msg.array.trailing.comma"
"Trailing comma yields different behavior across browsers")
(js2-msg "msg.equal.as.assign"
(concat "Test for equality (==) mistyped as assignment (=)?"
" (parenthesize to suppress warning)"))
(js2-msg "msg.var.hides.arg"
"Variable %s hides argument")
(js2-msg "msg.destruct.assign.no.init"
"Missing = in destructuring declaration")
(js2-msg "msg.init.no.destruct"
"Binding initializer not in destructuring assignment")
(js2-msg "msg.no.octal.strict"
"Octal numbers prohibited in strict mode.")
(js2-msg "msg.dup.obj.lit.prop.strict"
"Property '%s' already defined in this object literal.")
(js2-msg "msg.dup.param.strict"
"Parameter '%s' already declared in this function.")
(js2-msg "msg.bad.id.strict"
"'%s' is not a valid identifier for this use in strict mode.")
;; ScriptRuntime
(js2-msg "msg.no.properties"
"%s has no properties.")
(js2-msg "msg.invalid.iterator"
"Invalid iterator value")
(js2-msg "msg.iterator.primitive"
"__iterator__ returned a primitive value")
(js2-msg "msg.assn.create.strict"
"Assignment to undeclared variable %s")
(js2-msg "msg.undeclared.variable" ; added by js2-mode
"Undeclared variable or function '%s'")
(js2-msg "msg.unused.variable" ; added by js2-mode
"Unused variable or function '%s'")
(js2-msg "msg.uninitialized.variable" ; added by js2-mode
"Variable '%s' referenced but never initialized")
(js2-msg "msg.ref.undefined.prop"
"Reference to undefined property '%s'")
(js2-msg "msg.prop.not.found"
"Property %s not found.")
(js2-msg "msg.invalid.type"
"Invalid JavaScript value of type %s")
(js2-msg "msg.primitive.expected"
"Primitive type expected (had %s instead)")
(js2-msg "msg.namespace.expected"
"Namespace object expected to left of :: (found %s instead)")
(js2-msg "msg.null.to.object"
"Cannot convert null to an object.")
(js2-msg "msg.undef.to.object"
"Cannot convert undefined to an object.")
(js2-msg "msg.cyclic.value"
"Cyclic %s value not allowed.")
(js2-msg "msg.is.not.defined"
"'%s' is not defined.")
(js2-msg "msg.undef.prop.read"
"Cannot read property '%s' from %s")
(js2-msg "msg.undef.prop.write"
"Cannot set property '%s' of %s to '%s'")
(js2-msg "msg.undef.prop.delete"
"Cannot delete property '%s' of %s")
(js2-msg "msg.undef.method.call"
"Cannot call method '%s' of %s")
(js2-msg "msg.undef.with"
"Cannot apply 'with' to %s")
(js2-msg "msg.isnt.function"
"%s is not a function, it is %s.")
(js2-msg "msg.isnt.function.in"
"Cannot call property %s in object %s. "
"It is not a function, it is '%s'.")
(js2-msg "msg.function.not.found"
"Cannot find function %s.")
(js2-msg "msg.function.not.found.in"
"Cannot find function %s in object %s.")
(js2-msg "msg.isnt.xml.object"
"%s is not an xml object.")
(js2-msg "msg.no.ref.to.get"
"%s is not a reference to read reference value.")
(js2-msg "msg.no.ref.to.set"
"%s is not a reference to set reference value to %s.")
(js2-msg "msg.no.ref.from.function"
"Function %s can not be used as the left-hand "
"side of assignment or as an operand of ++ or -- operator.")
(js2-msg "msg.bad.default.value"
"Object's getDefaultValue() method returned an object.")
(js2-msg "msg.instanceof.not.object"
"Can't use instanceof on a non-object.")
(js2-msg "msg.instanceof.bad.prototype"
"'prototype' property of %s is not an object.")
(js2-msg "msg.bad.radix"
"illegal radix %s.")
;; ScriptableObject
(js2-msg "msg.default.value"
"Cannot find default value for object.")
(js2-msg "msg.zero.arg.ctor"
"Cannot load class '%s' which has no zero-parameter constructor.")
(js2-msg "msg.ctor.multiple.parms"
"Can't define constructor or class %s since more than "
"one constructor has multiple parameters.")
(js2-msg "msg.extend.scriptable"
"%s must extend ScriptableObject in order to define property %s.")
(js2-msg "msg.bad.getter.parms"
"In order to define a property, getter %s must have zero "
"parameters or a single ScriptableObject parameter.")
(js2-msg "msg.obj.getter.parms"
"Expected static or delegated getter %s to take "
"a ScriptableObject parameter.")
(js2-msg "msg.getter.static"
"Getter and setter must both be static or neither be static.")
(js2-msg "msg.setter.return"
"Setter must have void return type: %s")
(js2-msg "msg.setter2.parms"
"Two-parameter setter must take a ScriptableObject as "
"its first parameter.")
(js2-msg "msg.setter1.parms"
"Expected single parameter setter for %s")
(js2-msg "msg.setter2.expected"
"Expected static or delegated setter %s to take two parameters.")
(js2-msg "msg.setter.parms"
"Expected either one or two parameters for setter.")
(js2-msg "msg.setter.bad.type"
"Unsupported parameter type '%s' in setter '%s'.")
(js2-msg "msg.add.sealed"
"Cannot add a property to a sealed object: %s.")
(js2-msg "msg.remove.sealed"
"Cannot remove a property from a sealed object: %s.")
(js2-msg "msg.modify.sealed"
"Cannot modify a property of a sealed object: %s.")
(js2-msg "msg.modify.readonly"
"Cannot modify readonly property: %s.")
;; TokenStream
(js2-msg "msg.missing.exponent"
"missing exponent")
(js2-msg "msg.caught.nfe"
"number format error")
(js2-msg "msg.unterminated.string.lit"
"unterminated string literal")
(js2-msg "msg.unterminated.comment"
"unterminated comment")
(js2-msg "msg.unterminated.re.lit"
"unterminated regular expression literal")
(js2-msg "msg.invalid.re.flag"
"invalid flag after regular expression")
(js2-msg "msg.no.re.input.for"
"no input for %s")
(js2-msg "msg.illegal.character"
"illegal character")
(js2-msg "msg.invalid.escape"
"invalid Unicode escape sequence")
(js2-msg "msg.bad.namespace"
"not a valid default namespace statement. "
"Syntax is: default xml namespace = EXPRESSION;")
;; TokensStream warnings
(js2-msg "msg.bad.octal.literal"
"illegal octal literal digit %s; "
"interpreting it as a decimal digit")
(js2-msg "msg.missing.hex.digits"
"missing hexadecimal digits after '0x'")
(js2-msg "msg.missing.binary.digits"
"missing binary digits after '0b'")
(js2-msg "msg.missing.octal.digits"
"missing octal digits after '0o'")
(js2-msg "msg.script.is.not.constructor"
"Script objects are not constructors.")
;; Arrays
(js2-msg "msg.arraylength.bad"
"Inappropriate array length.")
;; Arrays
(js2-msg "msg.arraylength.too.big"
"Array length %s exceeds supported capacity limit.")
;; URI
(js2-msg "msg.bad.uri"
"Malformed URI sequence.")
;; Number
(js2-msg "msg.bad.precision"
"Precision %s out of range.")
;; NativeGenerator
(js2-msg "msg.send.newborn"
"Attempt to send value to newborn generator")
(js2-msg "msg.already.exec.gen"
"Already executing generator")
(js2-msg "msg.StopIteration.invalid"
"StopIteration may not be changed to an arbitrary object.")
;; Interpreter
(js2-msg "msg.yield.closing"
"Yield from closing generator")
;; Classes
(js2-msg "msg.unnamed.class.stmt" ; added by js2-mode
"class statement requires a name")
(js2-msg "msg.class.unexpected.comma" ; added by js2-mode
"unexpected ',' between class properties")
(js2-msg "msg.unexpected.static" ; added by js2-mode
"unexpected 'static'")
(js2-msg "msg.missing.extends" ; added by js2-mode
"name is required after extends")
(js2-msg "msg.no.brace.class" ; added by js2-mode
"missing '{' before class body")
(js2-msg "msg.missing.computed.rb" ; added by js2-mode
"missing ']' after computed property expression")
;;; Tokens Buffer
(defconst js2-ti-max-lookahead 2)
(defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
(defun js2-new-token (offset)
(let ((token (make-js2-token (+ offset js2-ts-cursor))))
(setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
(aset js2-ti-tokens js2-ti-tokens-cursor token)
token))
(defsubst js2-current-token ()
(aref js2-ti-tokens js2-ti-tokens-cursor))
(defsubst js2-current-token-string ()
(js2-token-string (js2-current-token)))
(defsubst js2-current-token-type ()
(js2-token-type (js2-current-token)))
(defsubst js2-current-token-beg ()
(js2-token-beg (js2-current-token)))
(defsubst js2-current-token-end ()
(js2-token-end (js2-current-token)))
(defun js2-current-token-len ()
(let ((token (js2-current-token)))
(- (js2-token-end token)
(js2-token-beg token))))
(defun js2-ts-seek (state)
(setq js2-ts-lineno (js2-ts-state-lineno state)
js2-ts-cursor (js2-ts-state-cursor state)
js2-ti-tokens (js2-ts-state-tokens state)
js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
js2-ti-lookahead (js2-ts-state-lookahead state)))
;;; Utilities
(defun js2-delete-if (predicate list)
"Remove all items satisfying PREDICATE in LIST."
(cl-loop for item in list
if (not (funcall predicate item))
collect item))
(defun js2-position (element list)
"Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
Returns nil if element is not found in the list."
(let ((count 0)
found)
(while (and list (not found))
(if (eq element (car list))
(setq found t)
(setq count (1+ count)
list (cdr list))))
(if found count)))
(defun js2-find-if (predicate list)
"Find first item satisfying PREDICATE in LIST."
(let (result)
(while (and list (not result))
(if (funcall predicate (car list))
(setq result (car list)))
(setq list (cdr list)))
result))
(defmacro js2-time (form)
"Evaluate FORM, discard result, and return elapsed time in sec."
(declare (debug t))
(let ((beg (make-symbol "--js2-time-beg--")))
`(let ((,beg (current-time)))
,form
(/ (truncate (* (- (float-time (current-time))
(float-time ,beg))
10000))
10000.0))))
(defsubst js2-same-line (pos)
"Return t if POS is on the same line as current point."
(and (>= pos (point-at-bol))
(<= pos (point-at-eol))))
(defun js2-code-bug ()
"Signal an error when we encounter an unexpected code path."
(error "failed assertion"))
(defsubst js2-record-text-property (beg end prop value)
"Record a text property to set when parsing finishes."
(push (list beg end prop value) js2-mode-deferred-properties))
;; I'd like to associate errors with nodes, but for now the
;; easiest thing to do is get the context info from the last token.
(defun js2-record-parse-error (msg &optional arg pos len)
(push (list (list msg arg)
(or pos (js2-current-token-beg))
(or len (js2-current-token-len)))
js2-parsed-errors))
(defun js2-report-error (msg &optional msg-arg pos len)
"Signal a syntax error or record a parse error."
(if js2-recover-from-parse-errors
(js2-record-parse-error msg msg-arg pos len)
(signal 'js2-syntax-error
(list msg
js2-ts-lineno
(save-excursion
(goto-char js2-ts-cursor)
(current-column))
js2-ts-hit-eof))))
(defun js2-report-warning (msg &optional msg-arg pos len face)
(if js2-compiler-report-warning-as-error
(js2-report-error msg msg-arg pos len)
(push (list (list msg msg-arg)
(or pos (js2-current-token-beg))
(or len (js2-current-token-len))
face)
js2-parsed-warnings)))
(defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
(if js2-compiler-strict-mode
(js2-report-warning msg-id msg-arg beg
(and beg end (- end beg)))))
(put 'js2-syntax-error 'error-conditions
'(error syntax-error js2-syntax-error))
(put 'js2-syntax-error 'error-message "Syntax error")
(put 'js2-parse-error 'error-conditions
'(error parse-error js2-parse-error))
(put 'js2-parse-error 'error-message "Parse error")
(defmacro js2-clear-flag (flags flag)
`(setq ,flags (logand ,flags (lognot ,flag))))
(defmacro js2-set-flag (flags flag)
"Logical-or FLAG into FLAGS."
`(setq ,flags (logior ,flags ,flag)))
(defsubst js2-flag-set-p (flags flag)
(/= 0 (logand flags flag)))
(defsubst js2-flag-not-set-p (flags flag)
(zerop (logand flags flag)))
;;; AST struct and function definitions
;; flags for ast node property 'member-type (used for e4x operators)
(defvar js2-property-flag #x1 "Property access: element is valid name.")
(defvar js2-attribute-flag #x2 "x.@y or x..@y.")
(defvar js2-descendants-flag #x4 "x..y or x..@i.")
(defsubst js2-relpos (pos anchor)
"Convert POS to be relative to ANCHOR.
If POS is nil, returns nil."
(and pos (- pos anchor)))
(defun js2-make-pad (indent)
(if (zerop indent)
""
(make-string (* indent js2-basic-offset) ? )))
(defun js2-visit-ast (node callback)
"Visit every node in ast NODE with visitor CALLBACK.
CALLBACK is a function that takes two arguments: (NODE END-P). It is
called twice: once to visit the node, and again after all the node's
children have been processed. The END-P argument is nil on the first
call and non-nil on the second call. The return value of the callback
affects the traversal: if non-nil, the children of NODE are processed.
If the callback returns nil, or if the node has no children, then the
callback is called immediately with a non-nil END-P argument.
The node traversal is approximately lexical-order, although there
are currently no guarantees around this."
(when node
(let ((vfunc (get (aref node 0) 'js2-visitor)))
;; visit the node
(when (funcall callback node nil)
;; visit the kids
(cond
((eq vfunc 'js2-visit-none)
nil) ; don't even bother calling it
;; Each AST node type has to define a `js2-visitor' function
;; that takes a node and a callback, and calls `js2-visit-ast'
;; on each child of the node.
(vfunc
(funcall vfunc node callback))
(t
(error "%s does not define a visitor-traversal function"
(aref node 0)))))
;; call the end-visit
(funcall callback node t))))
(cl-defstruct (js2-node
(:constructor nil)) ; abstract
"Base AST node type."
(type -1) ; token type
(pos -1) ; start position of this AST node in parsed input
(len 1) ; num characters spanned by the node
props ; optional node property list (an alist)
parent) ; link to parent node; null for root
(defsubst js2-node-get-prop (node prop &optional default)
(or (cadr (assoc prop (js2-node-props node))) default))
(defsubst js2-node-set-prop (node prop value)
(setf (js2-node-props node)
(cons (list prop value) (js2-node-props node))))
(defun js2-fixup-starts (n nodes)
"Adjust the start positions of NODES to be relative to N.
Any node in the list may be nil, for convenience."
(dolist (node nodes)
(when node
(setf (js2-node-pos node) (- (js2-node-pos node)
(js2-node-pos n))))))
(defun js2-node-add-children (parent &rest nodes)
"Set parent node of NODES to PARENT, and return PARENT.
Does nothing if we're not recording parent links.
If any given node in NODES is nil, doesn't record that link."
(js2-fixup-starts parent nodes)
(dolist (node nodes)
(and node
(setf (js2-node-parent node) parent))))
;; Non-recursive since it's called a frightening number of times.
(defun js2-node-abs-pos (n)
(let ((pos (js2-node-pos n)))
(while (setq n (js2-node-parent n))
(setq pos (+ pos (js2-node-pos n))))
pos))
(defsubst js2-node-abs-end (n)
"Return absolute buffer position of end of N."
(+ (js2-node-abs-pos n) (js2-node-len n)))
(defun js2--struct-put (name key value)
(put name key value)
(put (intern (format "cl-struct-%s" name)) key value))
;; It's important to make sure block nodes have a Lisp list for the
;; child nodes, to limit printing recursion depth in an AST that
;; otherwise consists of defstruct vectors. Emacs will crash printing
;; a sufficiently large vector tree.
(cl-defstruct (js2-block-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-block-node (&key (type js2-BLOCK)
(pos (js2-current-token-beg))
len
props
kids)))
"A block of statements."
kids) ; a Lisp list of the child statement nodes
(js2--struct-put 'js2-block-node 'js2-visitor 'js2-visit-block)
(js2--struct-put 'js2-block-node 'js2-printer 'js2-print-block)
(defun js2-visit-block (ast callback)
"Visit the `js2-block-node' children of AST."
(dolist (kid (js2-block-node-kids ast))
(js2-visit-ast kid callback)))
(defun js2-print-block (n i)
(let ((pad (js2-make-pad i)))
(insert pad "{\n")
(dolist (kid (js2-block-node-kids n))
(js2-print-ast kid (1+ i)))
(insert pad "}")))
(cl-defstruct (js2-scope
(:include js2-block-node)
(:constructor nil)
(:constructor make-js2-scope (&key (type js2-BLOCK)
(pos (js2-current-token-beg))
len
kids)))
;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
;; I don't have one of those handy, so I'll use an alist for now.
;; It's as fast as an emacs hashtable for up to about 50 elements,
;; and is much lighter-weight to construct (both CPU and mem).
;; The keys are interned strings (symbols) for faster lookup.
;; Should switch to hybrid alist/hashtable eventually.
symbol-table ; an alist of (symbol . js2-symbol)
parent-scope ; a `js2-scope'
top) ; top-level `js2-scope' (script/function)
(js2--struct-put 'js2-scope 'js2-visitor 'js2-visit-block)
(js2--struct-put 'js2-scope 'js2-printer 'js2-print-none)
(defun js2-node-get-enclosing-scope (node)
"Return the innermost `js2-scope' node surrounding NODE.
Returns nil if there is no enclosing scope node."
(while (and (setq node (js2-node-parent node))
(not (js2-scope-p node))))
node)
(defun js2-get-defining-scope (scope name &optional point)
"Search up scope chain from SCOPE looking for NAME, a string or symbol.
Returns `js2-scope' in which NAME is defined, or nil if not found.
If POINT is non-nil, and if the found declaration type is
`js2-LET', also check that the declaration node is before POINT."
(let ((sym (if (symbolp name)
name
(intern name)))
result
(continue t))
(while (and scope continue)
(if (or
(let ((entry (cdr (assq sym (js2-scope-symbol-table scope)))))
(and entry
(or (not point)
(not (eq js2-LET (js2-symbol-decl-type entry)))
(>= point
(js2-node-abs-pos (js2-symbol-ast-node entry))))))
(and (eq sym 'arguments)
(js2-function-node-p scope)))
(setq continue nil
result scope)
(setq scope (js2-scope-parent-scope scope))))
result))
(defun js2-scope-get-symbol (scope name)
"Return symbol table entry for NAME in SCOPE.
NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
(and (js2-scope-symbol-table scope)
(cdr (assq (if (symbolp name)
name
(intern name))
(js2-scope-symbol-table scope)))))
(defun js2-scope-put-symbol (scope name symbol)
"Enter SYMBOL into symbol-table for SCOPE under NAME.
NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
(let* ((table (js2-scope-symbol-table scope))
(sym (if (symbolp name) name (intern name)))
(entry (assq sym table)))
(if entry
(setcdr entry symbol)
(push (cons sym symbol)
(js2-scope-symbol-table scope)))))
(cl-defstruct (js2-symbol
(:constructor nil)
(:constructor make-js2-symbol (decl-type name &optional ast-node)))
"A symbol table entry."
;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
;; js2-LET, or js2-CONST
decl-type
name ; string
ast-node) ; a `js2-node'
(cl-defstruct (js2-error-node
(:include js2-node)
(:constructor nil) ; silence emacs21 byte-compiler
(:constructor make-js2-error-node (&key (type js2-ERROR)
(pos (js2-current-token-beg))
len)))
"AST node representing a parse error.")
(js2--struct-put 'js2-error-node 'js2-visitor 'js2-visit-none)
(js2--struct-put 'js2-error-node 'js2-printer 'js2-print-none)
(cl-defstruct (js2-script-node
(:include js2-scope)
(:constructor nil)
(:constructor make-js2-script-node (&key (type js2-SCRIPT)
(pos (js2-current-token-beg))
len
;; FIXME: What are those?
var-decls
fun-decls)))
functions ; Lisp list of nested functions
regexps ; Lisp list of (string . flags)
symbols ; alist (every symbol gets unique index)
(param-count 0)
var-names ; vector of string names
consts ; bool-vector matching var-decls
(temp-number 0)) ; for generating temp variables
(js2--struct-put 'js2-script-node 'js2-visitor 'js2-visit-block)
(js2--struct-put 'js2-script-node 'js2-printer 'js2-print-script)
(defun js2-print-script (node indent)
(dolist (kid (js2-block-node-kids node))
(js2-print-ast kid indent)))
(cl-defstruct (js2-ast-root
(:include js2-script-node)
(:constructor nil)
(:constructor make-js2-ast-root (&key (type js2-SCRIPT)
(pos (js2-current-token-beg))
len
buffer)))
"The root node of a js2 AST."
buffer ; the source buffer from which the code was parsed
comments ; a Lisp list of comments, ordered by start position
errors ; a Lisp list of errors found during parsing
warnings ; a Lisp list of warnings found during parsing
node-count) ; number of nodes in the tree, including the root
(js2--struct-put 'js2-ast-root 'js2-visitor 'js2-visit-ast-root)
(js2--struct-put 'js2-ast-root 'js2-printer 'js2-print-script)
(defun js2-visit-ast-root (ast callback)
(dolist (kid (js2-ast-root-kids ast))
(js2-visit-ast kid callback))
(dolist (comment (js2-ast-root-comments ast))
(js2-visit-ast comment callback)))
(cl-defstruct (js2-comment-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-comment-node (&key (type js2-COMMENT)
(pos (js2-current-token-beg))
len
format)))
format) ; 'line, 'block, 'jsdoc or 'html
(js2--struct-put 'js2-comment-node 'js2-visitor 'js2-visit-none)
(js2--struct-put 'js2-comment-node 'js2-printer 'js2-print-comment)
(defun js2-print-comment (n i)
;; We really ought to link end-of-line comments to their nodes.
;; Or maybe we could add a new comment type, 'endline.
(insert (js2-make-pad i)
(js2-node-string n)))
(cl-defstruct (js2-expr-stmt-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
(pos js2-ts-cursor)
len
expr)))
"An expression statement."
expr)
(defsubst js2-expr-stmt-node-set-has-result (node)
"Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
(setf (js2-node-type node) js2-EXPR_RESULT))
(js2--struct-put 'js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
(js2--struct-put 'js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
(defun js2-visit-expr-stmt-node (n v)
(js2-visit-ast (js2-expr-stmt-node-expr n) v))
(defun js2-print-expr-stmt-node (n indent)
(js2-print-ast (js2-expr-stmt-node-expr n) indent)
(insert ";\n"))
(cl-defstruct (js2-loop-node
(:include js2-scope)
(:constructor nil))
"Abstract supertype of loop nodes."
body ; a `js2-block-node'
lp ; position of left-paren, nil if omitted
rp) ; position of right-paren, nil if omitted
(cl-defstruct (js2-do-node
(:include js2-loop-node)
(:constructor nil)
(:constructor make-js2-do-node (&key (type js2-DO)
(pos (js2-current-token-beg))
len
body
condition
while-pos
lp
rp)))
"AST node for do-loop."
condition ; while (expression)
while-pos) ; buffer position of 'while' keyword
(js2--struct-put 'js2-do-node 'js2-visitor 'js2-visit-do-node)
(js2--struct-put 'js2-do-node 'js2-printer 'js2-print-do-node)
(defun js2-visit-do-node (n v)
(js2-visit-ast (js2-do-node-body n) v)
(js2-visit-ast (js2-do-node-condition n) v))
(defun js2-print-do-node (n i)
(let ((pad (js2-make-pad i)))
(insert pad "do {\n")
(dolist (kid (js2-block-node-kids (js2-do-node-body n)))
(js2-print-ast kid (1+ i)))
(insert pad "} while (")
(js2-print-ast (js2-do-node-condition n) 0)
(insert ");\n")))
(cl-defstruct (js2-export-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-export-node (&key (type js2-EXPORT)
(pos (js2-current-token-beg))
len
exports-list
from-clause
declaration
default)))
"AST node for an export statement. There are many things that can be exported,
so many of its properties will be nil.
"
exports-list ; lisp list of js2-export-binding-node to export
from-clause ; js2-from-clause-node for re-exporting symbols from another module
declaration ; js2-var-decl-node (var, let, const) or js2-class-node
default) ; js2-function-node or js2-assign-node
(js2--struct-put 'js2-export-node 'js2-visitor 'js2-visit-export-node)
(js2--struct-put 'js2-export-node 'js2-printer 'js2-print-export-node)
(defun js2-visit-export-node (n v)
(let ((exports-list (js2-export-node-exports-list n))
(from (js2-export-node-from-clause n))
(declaration (js2-export-node-declaration n))
(default (js2-export-node-default n)))
(when exports-list
(dolist (export exports-list)
(js2-visit-ast export v)))
(when from
(js2-visit-ast from v))
(when declaration
(js2-visit-ast declaration v))
(when default
(js2-visit-ast default v))))
(defun js2-print-export-node (n i)
(let ((pad (js2-make-pad i))
(exports-list (js2-export-node-exports-list n))
(from (js2-export-node-from-clause n))
(declaration (js2-export-node-declaration n))
(default (js2-export-node-default n)))
(insert pad "export ")
(cond
(default
(insert "default ")
(js2-print-ast default i))
(declaration
(js2-print-ast declaration i))
((and exports-list from)
(js2-print-named-imports exports-list)
(insert " ")
(js2-print-from-clause from))
(from
(insert "* ")
(js2-print-from-clause from))
(exports-list
(js2-print-named-imports exports-list)))
(unless (or (and default (not (js2-assign-node-p default)))
(and declaration (or (js2-function-node-p declaration)
(js2-class-node-p declaration))))
(insert ";\n"))))
(cl-defstruct (js2-while-node
(:include js2-loop-node)
(:constructor nil)
(:constructor make-js2-while-node (&key (type js2-WHILE)
(pos (js2-current-token-beg))
len body
condition lp
rp)))
"AST node for while-loop."
condition) ; while-condition
(js2--struct-put 'js2-while-node 'js2-visitor 'js2-visit-while-node)
(js2--struct-put 'js2-while-node 'js2-printer 'js2-print-while-node)
(defun js2-visit-while-node (n v)
(js2-visit-ast (js2-while-node-condition n) v)
(js2-visit-ast (js2-while-node-body n) v))
(defun js2-print-while-node (n i)
(let ((pad (js2-make-pad i)))
(insert pad "while (")
(js2-print-ast (js2-while-node-condition n) 0)
(insert ") {\n")
(js2-print-body (js2-while-node-body n) (1+ i))
(insert pad "}\n")))
(cl-defstruct (js2-for-node
(:include js2-loop-node)
(:constructor nil)
(:constructor make-js2-for-node (&key (type js2-FOR)
(pos js2-ts-cursor)
len body init
condition
update lp rp)))
"AST node for a C-style for-loop."
init ; initialization expression
condition ; loop condition
update) ; update clause
(js2--struct-put 'js2-for-node 'js2-visitor 'js2-visit-for-node)
(js2--struct-put 'js2-for-node 'js2-printer 'js2-print-for-node)
(defun js2-visit-for-node (n v)
(js2-visit-ast (js2-for-node-init n) v)
(js2-visit-ast (js2-for-node-condition n) v)
(js2-visit-ast (js2-for-node-update n) v)
(js2-visit-ast (js2-for-node-body n) v))
(defun js2-print-for-node (n i)
(let ((pad (js2-make-pad i)))
(insert pad "for (")
(js2-print-ast (js2-for-node-init n) 0)
(insert "; ")
(js2-print-ast (js2-for-node-condition n) 0)
(insert "; ")
(js2-print-ast (js2-for-node-update n) 0)
(insert ") {\n")
(js2-print-body (js2-for-node-body n) (1+ i))
(insert pad "}\n")))
(cl-defstruct (js2-for-in-node
(:include js2-loop-node)
(:constructor nil)
(:constructor make-js2-for-in-node (&key (type js2-FOR)
(pos js2-ts-cursor)
len body
iterator
object
in-pos
each-pos
foreach-p forof-p
lp rp)))
"AST node for a for..in loop."
iterator ; [var] foo in ...
object ; object over which we're iterating
in-pos ; buffer position of 'in' keyword
each-pos ; buffer position of 'each' keyword, if foreach-p
foreach-p ; t if it's a for-each loop
forof-p) ; t if it's a for-of loop
(js2--struct-put 'js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
(js2--struct-put 'js2-for-in-node 'js2-printer 'js2-print-for-in-node)
(defun js2-visit-for-in-node (n v)
(js2-visit-ast (js2-for-in-node-iterator n) v)
(js2-visit-ast (js2-for-in-node-object n) v)
(js2-visit-ast (js2-for-in-node-body n) v))
(defun js2-print-for-in-node (n i)
(let ((pad (js2-make-pad i))
(foreach (js2-for-in-node-foreach-p n))
(forof (js2-for-in-node-forof-p n)))
(insert pad "for ")
(if foreach
(insert "each "))
(insert "(")
(js2-print-ast (js2-for-in-node-iterator n) 0)
(insert (if forof " of " " in "))
(js2-print-ast (js2-for-in-node-object n) 0)
(insert ") {\n")
(js2-print-body (js2-for-in-node-body n) (1+ i))
(insert pad "}\n")))
(cl-defstruct (js2-return-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-return-node (&key (type js2-RETURN)
(pos js2-ts-cursor)
len
retval)))
"AST node for a return statement."
retval) ; expression to return, or 'undefined
(js2--struct-put 'js2-return-node 'js2-visitor 'js2-visit-return-node)
(js2--struct-put 'js2-return-node 'js2-printer 'js2-print-return-node)
(defun js2-visit-return-node (n v)
(js2-visit-ast (js2-return-node-retval n) v))
(defun js2-print-return-node (n i)
(insert (js2-make-pad i) "return")
(when (js2-return-node-retval n)
(insert " ")
(js2-print-ast (js2-return-node-retval n) 0))
(insert ";\n"))
(cl-defstruct (js2-if-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-if-node (&key (type js2-IF)
(pos js2-ts-cursor)
len condition
then-part
else-pos
else-part lp
rp)))
"AST node for an if-statement."
condition ; expression
then-part ; statement or block
else-pos ; optional buffer position of 'else' keyword
else-part ; optional statement or block
lp ; position of left-paren, nil if omitted
rp) ; position of right-paren, nil if omitted
(js2--struct-put 'js2-if-node 'js2-visitor 'js2-visit-if-node)
(js2--struct-put 'js2-if-node 'js2-printer 'js2-print-if-node)
(defun js2-visit-if-node (n v)
(js2-visit-ast (js2-if-node-condition n) v)
(js2-visit-ast (js2-if-node-then-part n) v)
(js2-visit-ast (js2-if-node-else-part n) v))
(defun js2-print-if-node (n i)
(let ((pad (js2-make-pad i))
(then-part (js2-if-node-then-part n))
(else-part (js2-if-node-else-part n)))
(insert pad "if (")
(js2-print-ast (js2-if-node-condition n) 0)
(insert ") {\n")
(js2-print-body then-part (1+ i))
(insert pad "}")
(cond
((not else-part)
(insert "\n"))
((js2-if-node-p else-part)
(insert " else ")
(js2-print-body else-part i))
(t
(insert " else {\n")
(js2-print-body else-part (1+ i))
(insert pad "}\n")))))
(cl-defstruct (js2-export-binding-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-export-binding-node (&key (type -1)
pos
len
local-name
extern-name)))
"AST node for an external symbol binding.
It contains a local-name node which is the name of the value in the
current scope, and extern-name which is the name of the value in the
imported or exported scope. By default these are the same, but if the
name is aliased as in {foo as bar}, it would have an extern-name node
containing 'foo' and a local-name node containing 'bar'."
local-name ; js2-name-node with the variable name in this scope
extern-name) ; js2-name-node with the value name in the exporting module
(js2--struct-put 'js2-export-binding-node 'js2-printer 'js2-print-extern-binding)
(js2--struct-put 'js2-export-binding-node 'js2-visitor 'js2-visit-extern-binding)
(defun js2-visit-extern-binding (n v)
"Visit an extern binding node. First visit the local-name, and, if
different, visit the extern-name."
(let ((local-name (js2-export-binding-node-local-name n))
(extern-name (js2-export-binding-node-extern-name n)))
(when local-name
(js2-visit-ast local-name v))
(when (not (equal local-name extern-name))
(js2-visit-ast extern-name v))))
(defun js2-print-extern-binding (n _i)
"Print a representation of a single extern binding. E.g. 'foo' or
'foo as bar'."
(let ((local-name (js2-export-binding-node-local-name n))
(extern-name (js2-export-binding-node-extern-name n)))
(insert (js2-name-node-name extern-name))
(when (not (equal local-name extern-name))
(insert " as ")
(insert (js2-name-node-name local-name)))))
(cl-defstruct (js2-import-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-import-node (&key (type js2-IMPORT)
(pos (js2-current-token-beg))
len
import
from
module-id)))
"AST node for an import statement. It follows the form
import ModuleSpecifier;
import ImportClause FromClause;"
import ; js2-import-clause-node specifying which names are to imported.
from ; js2-from-clause-node indicating the module from which to import.
module-id) ; module-id of the import. E.g. 'src/mylib'.
(js2--struct-put 'js2-import-node 'js2-printer 'js2-print-import)
(js2--struct-put 'js2-import-node 'js2-visitor 'js2-visit-import)
(defun js2-visit-import (n v)
(let ((import-clause (js2-import-node-import n))
(from-clause (js2-import-node-from n)))
(when import-clause
(js2-visit-ast import-clause v))
(when from-clause
(js2-visit-ast from-clause v))))
(defun js2-print-import (n i)
"Prints a representation of the import node"
(let ((pad (js2-make-pad i))
(import-clause (js2-import-node-import n))
(from-clause (js2-import-node-from n))
(module-id (js2-import-node-module-id n)))
(insert pad "import ")
(if import-clause
(progn
(js2-print-import-clause import-clause)
(insert " ")
(js2-print-from-clause from-clause))
(insert "'")
(insert module-id)
(insert "'"))
(insert ";\n")))
(cl-defstruct (js2-import-clause-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-import-clause-node (&key (type -1)
pos
len
namespace-import
named-imports
default-binding)))
"AST node corresponding to the import clause of an import statement. This is
the portion of the import that bindings names from the external context to the
local context."
namespace-import ; js2-namespace-import-node. E.g. '* as lib'
named-imports ; lisp list of js2-export-binding-node for all named imports.
default-binding) ; js2-export-binding-node for the default import binding
(js2--struct-put 'js2-import-clause-node 'js2-visitor 'js2-visit-import-clause)
(js2--struct-put 'js2-import-clause-node 'js2-printer 'js2-print-import-clause)
(defun js2-visit-import-clause (n v)
(let ((ns-import (js2-import-clause-node-namespace-import n))
(named-imports (js2-import-clause-node-named-imports n))
(default (js2-import-clause-node-default-binding n)))
(when default
(js2-visit-ast default v))
(when ns-import
(js2-visit-ast ns-import v))
(when named-imports
(dolist (import named-imports)
(js2-visit-ast import v)))))
(defun js2-print-import-clause (n)
(let ((ns-import (js2-import-clause-node-namespace-import n))
(named-imports (js2-import-clause-node-named-imports n))
(default (js2-import-clause-node-default-binding n)))
(cond
((and default ns-import)
(js2-print-ast default)
(insert ", ")
(js2-print-namespace-import ns-import))
((and default named-imports)
(js2-print-ast default)
(insert ", ")
(js2-print-named-imports named-imports))
(default
(js2-print-ast default))
(ns-import
(js2-print-namespace-import ns-import))
(named-imports
(js2-print-named-imports named-imports)))))
(defun js2-print-namespace-import (node)
(insert "* as ")
(insert (js2-name-node-name (js2-namespace-import-node-name node))))
(defun js2-print-named-imports (imports)
(insert "{")
(let ((len (length imports))
(n 0))
(while (< n len)
(js2-print-extern-binding (nth n imports) 0)
(unless (= n (- len 1))
(insert ", "))
(setq n (+ n 1))))
(insert "}"))
(cl-defstruct (js2-namespace-import-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-namespace-import-node (&key (type -1)
pos
len
name)))
"AST node for a complete namespace import.
E.g. the '* as lib' expression in:
import * as lib from 'src/lib'
It contains a single name node referring to the bound name."
name) ; js2-name-node of the bound name.
(defun js2-visit-namespace-import (n v)
(js2-visit-ast (js2-namespace-import-node-name n) v))
(js2--struct-put 'js2-namespace-import-node 'js2-visitor 'js2-visit-namespace-import)
(js2--struct-put 'js2-namespace-import-node 'js2-printer 'js2-print-namespace-import)
(cl-defstruct (js2-from-clause-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-from-clause-node (&key (type js2-NAME)
pos
len
module-id
metadata-p)))
"AST node for the from clause in an import or export statement.
E.g. from 'my/module'. It can refere to either an external module, or to the
modules metadata itself."
module-id ; string containing the module specifier.
metadata-p) ; true if this clause refers to the module's metadata
(js2--struct-put 'js2-from-clause-node 'js2-visitor 'js2-visit-none)
(js2--struct-put 'js2-from-clause-node 'js2-printer 'js2-print-from-clause)
(defun js2-print-from-clause (n)
(insert "from ")
(if (js2-from-clause-node-metadata-p n)
(insert "this module")
(insert "'")
(insert (js2-from-clause-node-module-id n))
(insert "'")))
(cl-defstruct (js2-try-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-try-node (&key (type js2-TRY)
(pos js2-ts-cursor)
len
try-block
catch-clauses
finally-block)))
"AST node for a try-statement."
try-block
catch-clauses ; a Lisp list of `js2-catch-node'
finally-block) ; a `js2-finally-node'
(js2--struct-put 'js2-try-node 'js2-visitor 'js2-visit-try-node)
(js2--struct-put 'js2-try-node 'js2-printer 'js2-print-try-node)
(defun js2-visit-try-node (n v)
(js2-visit-ast (js2-try-node-try-block n) v)
(dolist (clause (js2-try-node-catch-clauses n))
(js2-visit-ast clause v))
(js2-visit-ast (js2-try-node-finally-block n) v))
(defun js2-print-try-node (n i)
(let ((pad (js2-make-pad i))
(catches (js2-try-node-catch-clauses n))
(finally (js2-try-node-finally-block n)))
(insert pad "try {\n")
(js2-print-body (js2-try-node-try-block n) (1+ i))
(insert pad "}")
(when catches
(dolist (catch catches)
(js2-print-ast catch i)))
(if finally
(js2-print-ast finally i)
(insert "\n"))))
(cl-defstruct (js2-catch-node
(:include js2-scope)
(:constructor nil)
(:constructor make-js2-catch-node (&key (type js2-CATCH)
(pos js2-ts-cursor)
len
param
guard-kwd
guard-expr
lp rp)))
"AST node for a catch clause."
param ; destructuring form or simple name node
guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
guard-expr ; catch condition, a `js2-node'
lp ; buffer position of left-paren, nil if omitted
rp) ; buffer position of right-paren, nil if omitted
(js2--struct-put 'js2-catch-node 'js2-visitor 'js2-visit-catch-node)
(js2--struct-put 'js2-catch-node 'js2-printer 'js2-print-catch-node)
(defun js2-visit-catch-node (n v)
(js2-visit-ast (js2-catch-node-param n) v)
(when (js2-catch-node-guard-kwd n)
(js2-visit-ast (js2-catch-node-guard-expr n) v))
(js2-visit-block n v))
(defun js2-print-catch-node (n i)
(let ((pad (js2-make-pad i))
(guard-kwd (js2-catch-node-guard-kwd n))
(guard-expr (js2-catch-node-guard-expr n)))
(insert " catch (")
(js2-print-ast (js2-catch-node-param n) 0)
(when guard-kwd
(insert " if ")
(js2-print-ast guard-expr 0))
(insert ") {\n")
(js2-print-body n (1+ i))
(insert pad "}")))
(cl-defstruct (js2-finally-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-finally-node (&key (type js2-FINALLY)
(pos js2-ts-cursor)
len body)))
"AST node for a finally clause."
body) ; a `js2-node', often but not always a block node
(js2--struct-put 'js2-finally-node 'js2-visitor 'js2-visit-finally-node)
(js2--struct-put 'js2-finally-node 'js2-printer 'js2-print-finally-node)
(defun js2-visit-finally-node (n v)
(js2-visit-ast (js2-finally-node-body n) v))
(defun js2-print-finally-node (n i)
(let ((pad (js2-make-pad i)))
(insert " finally {\n")
(js2-print-body (js2-finally-node-body n) (1+ i))
(insert pad "}\n")))
(cl-defstruct (js2-switch-node
(:include js2-scope)
(:constructor nil)
(:constructor make-js2-switch-node (&key (type js2-SWITCH)
(pos js2-ts-cursor)
len
discriminant
cases lp
rp)))
"AST node for a switch statement."
discriminant ; a `js2-node' (switch expression)
cases ; a Lisp list of `js2-case-node'
lp ; position of open-paren for discriminant, nil if omitted
rp) ; position of close-paren for discriminant, nil if omitted
(js2--struct-put 'js2-switch-node 'js2-visitor 'js2-visit-switch-node)
(js2--struct-put 'js2-switch-node 'js2-printer 'js2-print-switch-node)
(defun js2-visit-switch-node (n v)
(js2-visit-ast (js2-switch-node-discriminant n) v)
(dolist (c (js2-switch-node-cases n))
(js2-visit-ast c v)))
(defun js2-print-switch-node (n i)
(let ((pad (js2-make-pad i))
(cases (js2-switch-node-cases n)))
(insert pad "switch (")
(js2-print-ast (js2-switch-node-discriminant n) 0)
(insert ") {\n")
(dolist (case cases)
(js2-print-ast case i))
(insert pad "}\n")))
(cl-defstruct (js2-case-node
(:include js2-block-node)
(:constructor nil)
(:constructor make-js2-case-node (&key (type js2-CASE)
(pos js2-ts-cursor)
len kids expr)))
"AST node for a case clause of a switch statement."
expr) ; the case expression (nil for default)
(js2--struct-put 'js2-case-node 'js2-visitor 'js2-visit-case-node)
(js2--struct-put 'js2-case-node 'js2-printer 'js2-print-case-node)
(defun js2-visit-case-node (n v)
(js2-visit-ast (js2-case-node-expr n) v)
(js2-visit-block n v))
(defun js2-print-case-node (n i)
(let ((pad (js2-make-pad i))
(expr (js2-case-node-expr n)))
(insert pad)
(if (null expr)
(insert "default:\n")
(insert "case ")
(js2-print-ast expr 0)
(insert ":\n"))
(dolist (kid (js2-case-node-kids n))
(js2-print-ast kid (1+ i)))))
(cl-defstruct (js2-throw-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-throw-node (&key (type js2-THROW)
(pos js2-ts-cursor)
len expr)))
"AST node for a throw statement."
expr) ; the expression to throw
(js2--struct-put 'js2-throw-node 'js2-visitor 'js2-visit-throw-node)
(js2--struct-put 'js2-throw-node 'js2-printer 'js2-print-throw-node)
(defun js2-visit-throw-node (n v)
(js2-visit-ast (js2-throw-node-expr n) v))
(defun js2-print-throw-node (n i)
(insert (js2-make-pad i) "throw ")
(js2-print-ast (js2-throw-node-expr n) 0)
(insert ";\n"))
(cl-defstruct (js2-with-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-with-node (&key (type js2-WITH)
(pos js2-ts-cursor)
len object
body lp rp)))
"AST node for a with-statement."
object
body
lp ; buffer position of left-paren around object, nil if omitted
rp) ; buffer position of right-paren around object, nil if omitted
(js2--struct-put 'js2-with-node 'js2-visitor 'js2-visit-with-node)
(js2--struct-put 'js2-with-node 'js2-printer 'js2-print-with-node)
(defun js2-visit-with-node (n v)
(js2-visit-ast (js2-with-node-object n) v)
(js2-visit-ast (js2-with-node-body n) v))
(defun js2-print-with-node (n i)
(let ((pad (js2-make-pad i)))
(insert pad "with (")
(js2-print-ast (js2-with-node-object n) 0)
(insert ") {\n")
(js2-print-body (js2-with-node-body n) (1+ i))
(insert pad "}\n")))
(cl-defstruct (js2-label-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-label-node (&key (type js2-LABEL)
(pos js2-ts-cursor)
len name)))
"AST node for a statement label or case label."
name ; a string
loop) ; for validating and code-generating continue-to-label
(js2--struct-put 'js2-label-node 'js2-visitor 'js2-visit-none)
(js2--struct-put 'js2-label-node 'js2-printer 'js2-print-label)
(defun js2-print-label (n i)
(insert (js2-make-pad i)
(js2-label-node-name n)
":\n"))
(cl-defstruct (js2-labeled-stmt-node
(:include js2-node)
(:constructor nil)
;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
;; no-side-effects warnings, hence js2-EXPR_RESULT.
(:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
(pos js2-ts-cursor)
len labels stmt)))
"AST node for a statement with one or more labels.
Multiple labels for a statement are collapsed into the labels field."
labels ; Lisp list of `js2-label-node'
stmt) ; the statement these labels are for
(js2--struct-put 'js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
(js2--struct-put 'js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
(defun js2-get-label-by-name (lbl-stmt name)
"Return a `js2-label-node' by NAME from LBL-STMT's labels list.
Returns nil if no such label is in the list."
(let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
result)
(while (and label-list (not result))
(if (string= (js2-label-node-name (car label-list)) name)
(setq result (car label-list))
(setq label-list (cdr label-list))))
result))
(defun js2-visit-labeled-stmt (n v)
(dolist (label (js2-labeled-stmt-node-labels n))
(js2-visit-ast label v))
(js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
(defun js2-print-labeled-stmt (n i)
(dolist (label (js2-labeled-stmt-node-labels n))
(js2-print-ast label i))
(js2-print-ast (js2-labeled-stmt-node-stmt n) i))
(defun js2-labeled-stmt-node-contains (node label)
"Return t if NODE contains LABEL in its label set.
NODE is a `js2-labels-node'. LABEL is an identifier."
(cl-loop for nl in (js2-labeled-stmt-node-labels node)
if (string= label (js2-label-node-name nl))
return t
finally return nil))
(defsubst js2-labeled-stmt-node-add-label (node label)
"Add a `js2-label-node' to the label set for this statement."
(setf (js2-labeled-stmt-node-labels node)
(nconc (js2-labeled-stmt-node-labels node) (list label))))
(cl-defstruct (js2-jump-node
(:include js2-node)
(:constructor nil))
"Abstract supertype of break and continue nodes."
label ; `js2-name-node' for location of label identifier, if present
target) ; target js2-labels-node or loop/switch statement
(defun js2-visit-jump-node (n v)
;; We don't visit the target, since it's a back-link.
(js2-visit-ast (js2-jump-node-label n) v))
(cl-defstruct (js2-break-node
(:include js2-jump-node)
(:constructor nil)
(:constructor make-js2-break-node (&key (type js2-BREAK)
(pos js2-ts-cursor)
len label target)))
"AST node for a break statement.
The label field is a `js2-name-node', possibly nil, for the named label
if provided. E.g. in 'break foo', it represents 'foo'. The target field
is the target of the break - a label node or enclosing loop/switch statement.")
(js2--struct-put 'js2-break-node 'js2-visitor 'js2-visit-jump-node)
(js2--struct-put 'js2-break-node 'js2-printer 'js2-print-break-node)
(defun js2-print-break-node (n i)
(insert (js2-make-pad i) "break")
(when (js2-break-node-label n)
(insert " ")
(js2-print-ast (js2-break-node-label n) 0))
(insert ";\n"))
(cl-defstruct (js2-continue-node
(:include js2-jump-node)
(:constructor nil)
(:constructor make-js2-continue-node (&key (type js2-CONTINUE)
(pos js2-ts-cursor)
len label target)))
"AST node for a continue statement.
The label field is the user-supplied enclosing label name, a `js2-name-node'.
It is nil if continue specifies no label. The target field is the jump target:
a `js2-label-node' or the innermost enclosing loop.")
(js2--struct-put 'js2-continue-node 'js2-visitor 'js2-visit-jump-node)
(js2--struct-put 'js2-continue-node 'js2-printer 'js2-print-continue-node)
(defun js2-print-continue-node (n i)
(insert (js2-make-pad i) "continue")
(when (js2-continue-node-label n)
(insert " ")
(js2-print-ast (js2-continue-node-label n) 0))
(insert ";\n"))
(cl-defstruct (js2-function-node
(:include js2-script-node)
(:constructor nil)
(:constructor make-js2-function-node (&key (type js2-FUNCTION)
(pos js2-ts-cursor)
len
(ftype 'FUNCTION)
(form 'FUNCTION_STATEMENT)
(name "")
params rest-p
body
generator-type
async
lp rp)))
"AST node for a function declaration.
The `params' field is a Lisp list of nodes. Each node is either a simple
`js2-name-node', or if it's a destructuring-assignment parameter, a
`js2-array-node' or `js2-object-node'."
ftype ; FUNCTION, GETTER or SETTER
form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
name ; function name (a `js2-name-node', or nil if anonymous)
params ; a Lisp list of destructuring forms or simple name nodes
rest-p ; if t, the last parameter is rest parameter
body ; a `js2-block-node' or expression node (1.8 only)
lp ; position of arg-list open-paren, or nil if omitted
rp ; position of arg-list close-paren, or nil if omitted
ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
needs-activation ; t if we need an activation object for this frame
generator-type ; STAR, LEGACY, COMPREHENSION or nil
async ; t if the function is defined as `async function`
member-expr) ; nonstandard Ecma extension from Rhino
(js2--struct-put 'js2-function-node 'js2-visitor 'js2-visit-function-node)
(js2--struct-put 'js2-function-node 'js2-printer 'js2-print-function-node)
(defun js2-visit-function-node (n v)
(js2-visit-ast (js2-function-node-name n) v)
(dolist (p (js2-function-node-params n))
(js2-visit-ast p v))
(js2-visit-ast (js2-function-node-body n) v))
(defun js2-print-function-node (n i)
(let* ((pad (js2-make-pad i))
(method (js2-node-get-prop n 'METHOD_TYPE))
(name (or (js2-function-node-name n)
(js2-function-node-member-expr n)))
(params (js2-function-node-params n))
(arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
(rest-p (js2-function-node-rest-p n))
(body (js2-function-node-body n))
(expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
(unless method
(insert pad)
(when (js2-function-node-async n) (insert "async "))
(unless arrow (insert "function"))
(when (eq (js2-function-node-generator-type n) 'STAR)
(insert "*")))
(when name
(insert " ")
(js2-print-ast name 0))
(insert "(")
(cl-loop with len = (length params)
for param in params
for count from 1
do
(when (and rest-p (= count len))
(insert "..."))
(js2-print-ast param 0)
(when (< count len)
(insert ", ")))
(insert ") ")
(when arrow
(insert "=> "))
(insert "{")
;; TODO: fix this to be smarter about indenting, etc.
(unless expr
(insert "\n"))
(if (js2-block-node-p body)
(js2-print-body body (1+ i))
(js2-print-ast body 0))
(insert pad "}")
(unless expr
(insert "\n"))))
(defun js2-function-name (node)
"Return function name for NODE, a `js2-function-node', or nil if anonymous."
(and (js2-function-node-name node)
(js2-name-node-name (js2-function-node-name node))))
;; Having this be an expression node makes it more flexible.
;; There are IDE contexts, such as indentation in a for-loop initializer,
;; that work better if you assume it's an expression. Whenever we have
;; a standalone var/const declaration, we just wrap with an expr stmt.
;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
(cl-defstruct (js2-var-decl-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-var-decl-node (&key (type js2-VAR)
(pos (js2-current-token-beg))
len kids
decl-type)))
"AST node for a variable declaration list (VAR, CONST or LET).
The node bounds differ depending on the declaration type. For VAR or
CONST declarations, the bounds include the var/const keyword. For LET
declarations, the node begins at the position of the first child."
kids ; a Lisp list of `js2-var-init-node' structs.
decl-type) ; js2-VAR, js2-CONST or js2-LET
(js2--struct-put 'js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
(js2--struct-put 'js2-var-decl-node 'js2-printer 'js2-print-var-decl)
(defun js2-visit-var-decl (n v)
(dolist (kid (js2-var-decl-node-kids n))
(js2-visit-ast kid v)))
(defun js2-print-var-decl (n i)
(let ((pad (js2-make-pad i))
(tt (js2-var-decl-node-decl-type n)))
(insert pad)
(insert (cond
((= tt js2-VAR) "var ")
((= tt js2-LET) "let ")
((= tt js2-CONST) "const ")
(t
(error "malformed var-decl node"))))
(cl-loop with kids = (js2-var-decl-node-kids n)
with len = (length kids)
for kid in kids
for count from 1
do
(js2-print-ast kid 0)
(if (< count len)
(insert ", ")))))
(cl-defstruct (js2-var-init-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-var-init-node (&key (type js2-VAR)
(pos js2-ts-cursor)
len target
initializer)))
"AST node for a variable declaration.
The type field will be js2-CONST for a const decl."
target ; `js2-name-node', `js2-object-node', or `js2-array-node'
initializer) ; initializer expression, a `js2-node'
(js2--struct-put 'js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
(js2--struct-put 'js2-var-init-node 'js2-printer 'js2-print-var-init-node)
(defun js2-visit-var-init-node (n v)
(js2-visit-ast (js2-var-init-node-target n) v)
(js2-visit-ast (js2-var-init-node-initializer n) v))
(defun js2-print-var-init-node (n i)
(let ((pad (js2-make-pad i))
(name (js2-var-init-node-target n))
(init (js2-var-init-node-initializer n)))
(insert pad)
(js2-print-ast name 0)
(when init
(insert " = ")
(js2-print-ast init 0))))
(cl-defstruct (js2-cond-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-cond-node (&key (type js2-HOOK)
(pos js2-ts-cursor)
len
test-expr
true-expr
false-expr
q-pos c-pos)))
"AST node for the ternary operator"
test-expr
true-expr
false-expr
q-pos ; buffer position of ?
c-pos) ; buffer position of :
(js2--struct-put 'js2-cond-node 'js2-visitor 'js2-visit-cond-node)
(js2--struct-put 'js2-cond-node 'js2-printer 'js2-print-cond-node)
(defun js2-visit-cond-node (n v)
(js2-visit-ast (js2-cond-node-test-expr n) v)
(js2-visit-ast (js2-cond-node-true-expr n) v)
(js2-visit-ast (js2-cond-node-false-expr n) v))
(defun js2-print-cond-node (n i)
(let ((pad (js2-make-pad i)))
(insert pad)
(js2-print-ast (js2-cond-node-test-expr n) 0)
(insert " ? ")
(js2-print-ast (js2-cond-node-true-expr n) 0)
(insert " : ")
(js2-print-ast (js2-cond-node-false-expr n) 0)))
(cl-defstruct (js2-infix-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-infix-node (&key type
(pos js2-ts-cursor)
len op-pos
left right)))
"Represents infix expressions.
Includes assignment ops like `|=', and the comma operator.
The type field inherited from `js2-node' holds the operator."
op-pos ; buffer position where operator begins
left ; any `js2-node'
right) ; any `js2-node'
(js2--struct-put 'js2-infix-node 'js2-visitor 'js2-visit-infix-node)
(js2--struct-put 'js2-infix-node 'js2-printer 'js2-print-infix-node)
(defun js2-visit-infix-node (n v)
(js2-visit-ast (js2-infix-node-left n) v)
(js2-visit-ast (js2-infix-node-right n) v))
(defconst js2-operator-tokens
(let ((table (make-hash-table :test 'eq))
(tokens
(list (cons js2-IN "in")
(cons js2-TYPEOF "typeof")
(cons js2-INSTANCEOF "instanceof")
(cons js2-DELPROP "delete")
(cons js2-AWAIT "await")
(cons js2-VOID "void")
(cons js2-COMMA ",")
(cons js2-COLON ":")
(cons js2-OR "||")
(cons js2-AND "&&")
(cons js2-INC "++")
(cons js2-DEC "--")
(cons js2-BITOR "|")
(cons js2-BITXOR "^")
(cons js2-BITAND "&")
(cons js2-EQ "==")
(cons js2-NE "!=")
(cons js2-LT "<")
(cons js2-LE "<=")
(cons js2-GT ">")
(cons js2-GE ">=")
(cons js2-LSH "<<")
(cons js2-RSH ">>")
(cons js2-URSH ">>>")
(cons js2-ADD "+") ; infix plus
(cons js2-SUB "-") ; infix minus
(cons js2-MUL "*")
(cons js2-EXPON "**")
(cons js2-DIV "/")
(cons js2-MOD "%")
(cons js2-NOT "!")
(cons js2-BITNOT "~")
(cons js2-POS "+") ; unary plus
(cons js2-NEG "-") ; unary minus
(cons js2-TRIPLEDOT "...")
(cons js2-SHEQ "===") ; shallow equality
(cons js2-SHNE "!==") ; shallow inequality
(cons js2-ASSIGN "=")
(cons js2-ASSIGN_BITOR "|=")
(cons js2-ASSIGN_BITXOR "^=")
(cons js2-ASSIGN_BITAND "&=")
(cons js2-ASSIGN_LSH "<<=")
(cons js2-ASSIGN_RSH ">>=")
(cons js2-ASSIGN_URSH ">>>=")
(cons js2-ASSIGN_ADD "+=")
(cons js2-ASSIGN_SUB "-=")
(cons js2-ASSIGN_MUL "*=")
(cons js2-ASSIGN_EXPON "**=")
(cons js2-ASSIGN_DIV "/=")
(cons js2-ASSIGN_MOD "%="))))
(cl-loop for (k . v) in tokens do
(puthash k v table))
table))
(defun js2-print-infix-node (n i)
(let* ((tt (js2-node-type n))
(op (gethash tt js2-operator-tokens)))
(unless op
(error "unrecognized infix operator %s" (js2-node-type n)))
(insert (js2-make-pad i))
(js2-print-ast (js2-infix-node-left n) 0)
(unless (= tt js2-COMMA)
(insert " "))
(insert op)
(insert " ")
(js2-print-ast (js2-infix-node-right n) 0)))
(cl-defstruct (js2-assign-node
(:include js2-infix-node)
(:constructor nil)
(:constructor make-js2-assign-node (&key type
(pos js2-ts-cursor)
len op-pos
left right)))
"Represents any assignment.
The type field holds the actual assignment operator.")
(js2--struct-put 'js2-assign-node 'js2-visitor 'js2-visit-infix-node)
(js2--struct-put 'js2-assign-node 'js2-printer 'js2-print-infix-node)
(cl-defstruct (js2-unary-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-unary-node (&key type ; required
(pos js2-ts-cursor)
len operand)))
"AST node type for unary operator nodes.
The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
TYPEOF, DELPROP, TRIPLEDOT or AWAIT. For INC or DEC, a 'postfix node
property is added if the operator follows the operand."
operand) ; a `js2-node' expression
(js2--struct-put 'js2-unary-node 'js2-visitor 'js2-visit-unary-node)
(js2--struct-put 'js2-unary-node 'js2-printer 'js2-print-unary-node)
(defun js2-visit-unary-node (n v)
(js2-visit-ast (js2-unary-node-operand n) v))
(defun js2-print-unary-node (n i)
(let* ((tt (js2-node-type n))
(op (gethash tt js2-operator-tokens))
(postfix (js2-node-get-prop n 'postfix)))
(unless op
(error "unrecognized unary operator %s" tt))
(insert (js2-make-pad i))
(unless postfix
(insert op))
(if (or (= tt js2-TYPEOF)
(= tt js2-DELPROP)
(= tt js2-AWAIT)
(= tt js2-VOID))
(insert " "))
(js2-print-ast (js2-unary-node-operand n) 0)
(when postfix
(insert op))))
(cl-defstruct (js2-let-node
(:include js2-scope)
(:constructor nil)
(:constructor make-js2-let-node (&key (type js2-LETEXPR)
(pos (js2-current-token-beg))
len vars body
lp rp)))
"AST node for a let expression or a let statement.
Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
vars ; a `js2-var-decl-node'
body ; a `js2-node' representing the expression or body block
lp
rp)
(js2--struct-put 'js2-let-node 'js2-visitor 'js2-visit-let-node)
(js2--struct-put 'js2-let-node 'js2-printer 'js2-print-let-node)
(defun js2-visit-let-node (n v)
(js2-visit-ast (js2-let-node-vars n) v)
(js2-visit-ast (js2-let-node-body n) v))
(defun js2-print-let-node (n i)
(insert (js2-make-pad i) "let (")
(let ((p (point)))
(js2-print-ast (js2-let-node-vars n) 0)
(delete-region p (+ p 4)))
(insert ") ")
(js2-print-ast (js2-let-node-body n) i))
(cl-defstruct (js2-keyword-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-keyword-node (&key type
(pos (js2-current-token-beg))
(len (- js2-ts-cursor pos)))))
"AST node representing a literal keyword such as `null'.
Used for `null', `this', `true', `false' and `debugger'.
The node type is set to js2-NULL, js2-THIS, etc.")
(js2--struct-put 'js2-keyword-node 'js2-visitor 'js2-visit-none)
(js2--struct-put 'js2-keyword-node 'js2-printer 'js2-print-keyword-node)
(defun js2-print-keyword-node (n i)
(insert (js2-make-pad i)
(let ((tt (js2-node-type n)))
(cond
((= tt js2-THIS) "this")
((= tt js2-SUPER) "super")
((= tt js2-NULL) "null")
((= tt js2-TRUE) "true")
((= tt js2-FALSE) "false")
((= tt js2-DEBUGGER) "debugger")
(t (error "Invalid keyword literal type: %d" tt))))))
(defsubst js2-this-or-super-node-p (node)
"Return t if NODE is a `js2-literal-node' of type js2-THIS or js2-SUPER."
(let ((type (js2-node-type node)))
(or (eq type js2-THIS) (eq type js2-SUPER))))
(cl-defstruct (js2-new-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-new-node (&key (type js2-NEW)
(pos (js2-current-token-beg))
len target
args initializer
lp rp)))
"AST node for new-expression such as new Foo()."
target ; an identifier or reference
args ; a Lisp list of argument nodes
lp ; position of left-paren, nil if omitted
rp ; position of right-paren, nil if omitted
initializer) ; experimental Rhino syntax: optional `js2-object-node'
(js2--struct-put 'js2-new-node 'js2-visitor 'js2-visit-new-node)
(js2--struct-put 'js2-new-node 'js2-printer 'js2-print-new-node)
(defun js2-visit-new-node (n v)
(js2-visit-ast (js2-new-node-target n) v)