Find file
Fetching contributors…
Cannot retrieve contributors at this time
11620 lines (10408 sloc) 435 KB
;;; js2-mode.el --- an improved JavaScript editing mode
;; Copyright (C) 2009 Free Software Foundation, Inc.
;; Author: Steve Yegge <>
;; Contributors: mooz <>
;; Dmitry Gutov <>
;; Version: See `js2-mode-version'
;; Keywords: languages, javascript
;; 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
;; 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 <>.
;;; Commentary:
;; This JavaScript editing mode supports:
;; - strict recognition of the Ecma-262 language standard
;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
;; - 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
;; - typing helpers such as automatic insertion of matching braces/parens
;; - many customization options
;; 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.
;;; Code:
(require 'cl))
(require 'imenu)
(require 'cc-cmds) ; for `c-fill-paragraph'
(require 'cc-mode) ; (only) for `c-populate-syntax-table'
(require 'cc-langs) ; it's here in Emacs 21...
(require 'cc-engine)) ; for `c-paragraph-start' et. al.
;;; 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
Math NaN Number Object RangeError ReferenceError RegExp
String SyntaxError TypeError URIError arguments
decodeURI decodeURIComponent encodeURI
encodeURIComponent escape eval isFinite isNaN
parseFloat parseInt undefined unescape))
"Ecma-262 externs. Included in `js2-externs' by default.")
(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
;; Window
window alert confirm document java navigator prompt screen
self top
;; 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))
"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-gears-externs
(mapcar 'symbol-name
;; TODO(stevey): add these
"Google Gears externs.
Set `js2-include-gears-externs' to t to include them.")
;;; Variables
(defun js2-mark-safe-local (name pred)
"Make the variable NAME buffer-local and mark it as safe file-local
variable with predicate PRED."
(make-variable-buffer-local name)
(put name 'safe-local-variable pred))
(defvar js2-emacs22 (>= emacs-major-version 22))
(defcustom js2-highlight-level 2
"Amount of syntax highlighting to perform.
0 or a negative value means do no highlighting.
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-basic-offset (if (and (boundp 'c-basic-offset)
(numberp c-basic-offset))
"Number of spaces to indent nested statements.
Similar to `c-basic-offset'."
:group 'js2-mode
:type 'integer)
(js2-mark-safe-local 'js2-basic-offset 'integerp)
;; TODO(stevey): move this code into a separate minor mode.
(defcustom js2-mirror-mode nil
"Non-nil to insert closing brackets, parens, etc. automatically."
:group 'js2-mode
:type 'boolean)
(defcustom js2-auto-indent-p nil
"Automatic indentation with punctuation characters.
If non-nil, the current line is indented when certain punctuations
are inserted."
:group 'js2-mode
:type 'boolean)
(defcustom js2-bounce-indent-p nil
"Non-nil to have indent-line function choose among alternatives.
If nil, the indent-line function will indent to a predetermined column
based on heuristic guessing. If non-nil, then if the current line is
already indented to that predetermined column, indenting will choose
another likely column and indent to that spot. Repeated invocation of
the indent-line function will cycle among the computed alternatives.
See the function `js2-bounce-indent' for details. When it is non-nil,
js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
:type 'boolean
:group 'js2-mode)
(defcustom js2-consistent-level-indent-inner-bracket-p t
"Non-nil to make indentation level inner bracket consistent,
regardless of the beginning bracket position."
:group 'js2-mode
:type 'boolean)
(js2-mark-safe-local 'js2-consistent-level-indent-inner-bracket-p 'booleanp)
(defcustom js2-pretty-multiline-decl-indentation-p t
"Non-nil to line up multiline declarations vertically. See the
function `js-multiline-decl-indentation' for details."
:group 'js2-mode
:type 'boolean)
(js2-mark-safe-local 'js2-pretty-multiline-decl-indentation-p 'booleanp)
(defcustom js2-always-indent-assigned-expr-in-decls-p nil
"If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
always additionally indent function expression or array/object literal
assigned in a declaration, even when only one var is declared."
:group 'js2-mode
:type 'boolean)
(js2-mark-safe-local 'js2-always-indent-assigned-expr-in-decls-p 'booleanp)
(defcustom js2-indent-on-enter-key nil
"Non-nil to have Enter/Return key indent the line.
This is unusual for Emacs modes but common in IDEs like Eclipse."
:type 'boolean
:group 'js2-mode)
(defcustom js2-enter-indents-newline nil
"Non-nil to have Enter/Return key indent the newly-inserted line.
This is unusual for Emacs modes but common in IDEs like Eclipse."
:type 'boolean
:group 'js2-mode)
(defcustom js2-rebind-eol-bol-keys t
"Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
If non-nil, bounce between bol/eol and first/last non-whitespace char."
:group 'js2-mode
:type 'boolean)
(defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
"Keys that auto-indent when `js2-auto-indent-p' is non-nil.
Each value in the list is passed to `define-key'."
:type 'list
:group 'js2-mode)
(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-mode-escape-quotes t
"Non-nil to disable automatic quote-escaping inside strings."
:type 'boolean
:group 'js2-mode)
(defcustom js2-mode-squeeze-spaces t
"Non-nil to normalize whitespace when filling in comments.
Multiple runs of spaces are converted to a single space."
:type 'boolean
:group 'js2-mode)
(defcustom js2-mode-show-parse-errors t
"True to highlight parse errors."
: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 forbids them, but many browsers permit them. IE is the
big exception, and can produce bugs if you have trailing commas."
: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-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 180
"Configures what JavaScript language version to recognize.
Currently versions 150, 160, 170 and 180 are supported, corresponding
to JavaScript 1.5, 1.6, 1.7 and 1.8, 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-allow-keywords-as-property-names t
"If non-nil, you can use JavaScript keywords as object property names.
var foo = {int: 5, while: 6, continue: 7};
foo.return = 8;
Ecma-262 forbids this syntax, but many browsers support it."
:type 'boolean
: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-cleanup-whitespace nil
"Non-nil to invoke `delete-trailing-whitespace' before saves."
: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 etc. 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)
(defvar js2-mode-version 20101228
"Release number for `js2-mode'.")
;; scanner variables
(defmacro js2-deflocal (name value &optional comment)
"Define a buffer-local variable NAME with VALUE and COMMENT."
(defvar ,name ,value ,comment)
(make-variable-buffer-local ',name)))
;; We record the start and end position of each token.
(js2-deflocal js2-token-beg 1)
(js2-deflocal js2-token-end -1)
(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)
(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-first-assign js2-ASSIGN)
(defvar js2-last-assign js2-ASSIGN_MOD)
(defvar js2-HOOK 101) ; conditional (?:)
(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-ENUM 161) ; for "enum" reserved word
(defconst js2-num-tokens (1+ js2-ENUM))
(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-regexp-flags nil
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-string ""
"Token stream buffer-local variable.
Last string scanned.")
(js2-deflocal js2-ts-number nil
"Token stream buffer-local variable.
Last literal number scanned.")
(js2-deflocal js2-ts-hit-eof nil
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-line-start 0
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-lineno 1
"Token stream buffer-local variable.")
(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.")
(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.")
(js2-deflocal js2-ts-comment-type nil
"Token stream buffer-local variable.")
;;; 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
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-clear-ti-mask #xFFFF
"Mask to clear token information bits.")
(defconst js2-ti-after-eol (lsh 1 16)
"Flag: first token of the source line.")
(defconst js2-ti-check-label (lsh 1 17)
"Flag: indicates to check for label.")
;; 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 - 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)
(js2-deflocal js2-current-flagged-token js2-EOF)
(js2-deflocal js2-current-token js2-EOF)
;; 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.")
(defmacro js2-in-lhs (body)
`(let ((js2-is-in-lhs t))
(defmacro js2-in-rhs (body)
`(let ((js2-is-in-lhs nil))
(js2-deflocal js2-is-in-lhs nil
"True while parsing lhs statement")
(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'.
There is also a buffer-local variable `js2-default-externs',
which is initialized by default to include the Ecma-262 externs
and the standard browser externs. The three lists are all
checked during highlighting."
:type 'list
:group 'js2-mode)
(js2-deflocal js2-default-externs nil
"Default external declarations.
These are currently only used for highlighting undeclared variables,
which only worries about top-level (unqualified) references.
As js2-mode's processing improves, we will flesh out this list.
The initial value is set to `js2-ecma-262-externs', unless you
have set `js2-include-browser-externs', in which case the browser
externs are also included.
See `js2-additional-externs' for more information.")
(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.
You can always include them on a per-file basis by calling
`js2-add-browser-externs' from a function on `js2-mode-hook'.
See `js2-additional-externs' for more information about externs."
:type 'boolean
:group 'js2-mode)
(defcustom js2-include-rhino-externs t
"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-gears-externs t
"Non-nil to include Google Gears 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.
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-mode-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.
Finally, you can add a function to `js2-post-parse-callbacks',
which is called after parsing completes, and `root' 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
;; Without 2-token lookahead, labels are a problem.
;; These vars store the token info of the last matched name,
;; iff it wasn't the last matched token. Only valid in some contexts.
(defvar js2-prev-name-token-start nil)
(defvar js2-prev-name-token-string nil)
(defsubst js2-save-name-token-data (pos name)
(setq js2-prev-name-token-start pos
js2-prev-name-token-string name))
;; 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)
(defconst js2-end-yields #x8)
;; 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" (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-face
`((((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-face
`((((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-face
'((t :foreground "SlateGray"))
"Face used to highlight @whatever tags in jsdoc comments."
:group 'js2-mode)
(defface js2-jsdoc-type-face
'((t :foreground "SteelBlue"))
"Face used to highlight {FooBar} types in jsdoc comments."
:group 'js2-mode)
(defface js2-jsdoc-value-face
'((t :foreground "PeachPuff3"))
"Face used to highlight tag values in jsdoc comments."
:group 'js2-mode)
(defface js2-function-param-face
'((t :foreground "SeaGreen"))
"Face used to highlight function parameters in javascript."
:group 'js2-mode)
(defface js2-instance-member-face
'((t :foreground "DarkOrchid"))
"Face used to highlight instance variables in javascript.
Not currently used."
:group 'js2-mode)
(defface js2-private-member-face
'((t :foreground "PeachPuff3"))
"Face used to highlight calls to private methods in javascript.
Not currently used."
:group 'js2-mode)
(defface js2-private-function-call-face
'((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-face
(if js2-emacs22
'((((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")))
'((((type tty pc) (class color) (background light))
(:foreground "magenta"))
(((type tty pc) (class color) (background dark))
(:foreground "yellow"))
(t (:foreground "RosyBrown"))))
"Face used to highlight jsdoc html tag names"
:group 'js2-mode)
(defface js2-jsdoc-html-tag-delimiter-face
(if js2-emacs22
'((((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")))
'((((type tty pc) (class color) (background light))
(:foreground "green"))
(((type tty pc) (class color) (background dark))
(:foreground "green"))
(t (:foreground "dark khaki"))))
"Face used to highlight brackets in jsdoc html tags."
:group 'js2-mode)
(defface js2-magic-paren-face
'((t :underline t))
"Face used to color parens that will be auto-overwritten."
:group 'js2-mode)
(defcustom js2-post-parse-callbacks nil
"A 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 'list
:group 'js2-mode)
(defface js2-external-variable-face
'((t :foreground "orange"))
"Face used 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."
:group 'js2-mode)
(defcustom js2-highlight-external-variables t
"Non-nil to highlight undeclared variable identifiers."
:type 'boolean
:group 'js2-mode)
(defcustom js2-auto-insert-catch-block t
"Non-nil to insert matching catch block on open-curly after `try'."
:type 'boolean
:group 'js2-mode)
(defvar js2-mode-map
(let ((map (make-sparse-keymap))
(define-key map [mouse-1] #'js2-mode-show-node)
(define-key map (kbd "C-m") #'js2-enter-key)
(when js2-rebind-eol-bol-keys
(define-key map (kbd "C-a") #'js2-beginning-of-line)
(define-key map (kbd "C-e") #'js2-end-of-line))
(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 (kbd "C-c C-`") #'js2-next-error)
;; also define user's preference for next-error, if available
(if (setq keys (where-is-internal #'next-error))
(define-key map (car keys) #'js2-next-error))
(define-key map (or (car (where-is-internal #'mark-defun))
(kbd "M-C-h"))
(define-key map (or (car (where-is-internal #'narrow-to-defun))
(kbd "C-x nd"))
(define-key map [down-mouse-3] #'js2-down-mouse-3)
(when js2-auto-indent-p
(mapc (lambda (key)
(define-key map key #'js2-insert-and-indent))
(when js2-bounce-indent-p
(define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
(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" js2-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"))
"Keymap used in `js2-mode' buffers.")
(defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
(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-paragraph-start
;; Note that we also set a 'c-in-sws text property in html comments,
;; so that `c-forward-sws' and `c-backward-sws' work properly.
(defvar js2-syntactic-ws-start
"\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
(defvar js2-syntactic-ws-end
"\\s \\|[\n\r/]\\|\\s!")
(defvar js2-syntactic-eol
(concat "\\s *\\(/\\*[^*\n\r]*"
"\\*+/\\s *\\)*"
"Copied from `java-mode'. Needed for some cc-engine functions.")
(defvar js2-comment-prefix-regexp
(defvar js2-comment-start-skip
"\\(//+\\|/\\*+\\)\\s *")
(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)
"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
;; 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 (funcall #'concat ,@strings)
(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 ""
"Method '%s' must be static with the signature "
"(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
"to define a variable arguments function.")
(js2-msg ""
"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 ""
"Method '%s' occurs multiple times in class '%s'.")
(js2-msg "msg.method.not.found"
"Method '%s' not found in '%s'.")
;; IRFactory
(js2-msg ""
"Invalid left-hand side of loop.")
(js2-msg "msg.mult.index"
"Only one variable allowed in loop.")
(js2-msg ""
"Left hand side of 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 decerement operand.")
(js2-msg "msg.bad.incr"
"Invalid increment operand.")
(js2-msg "msg.bad.yield"
"yield must be in a function.")
(js2-msg "msg.yield.parenthesized"
"yield expression must be parenthesized.")
;; NativeGlobal
(js2-msg ""
"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 ""
"'%s' may only be invoked from a `new' expression.")
(js2-msg "msg.deprec.ctor"
"The '%s' constructor is deprecated.")
;; NativeFunction
(js2-msg ""
"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 ""
"Zero quantifier %s")
(js2-msg ""
"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 ""
"unmatched ) in regular expression.")
(js2-msg ""
"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 ""
"Compilation produced %s syntax errors.")
(js2-msg "msg.var.redecl"
"TypeError: 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 ""
"SyntaxError: let declaration not directly within block")
;; 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 ""
"missing ( before function parameters.")
(js2-msg ""
"missing formal parameter")
(js2-msg ""
"missing ) after formal parameters")
(js2-msg ""
"missing '{' before function body")
(js2-msg ""
"missing } after function body")
(js2-msg ""
"missing ( before condition")
(js2-msg ""
"missing ) after condition")
(js2-msg ""
"missing ; before statement")
(js2-msg "msg.missing.semi"
"missing ; after statement")
(js2-msg ""
"missing name after . operator")
(js2-msg ""
"missing name after :: operator")
(js2-msg ""
"missing name after .. operator")
(js2-msg ""
"missing name after .@")
(js2-msg ""
"missing ] in index expression")
(js2-msg ""
"missing ( before switch expression")
(js2-msg ""
"missing ) after switch expression")
(js2-msg ""
"missing '{' before switch body")
(js2-msg "msg.bad.switch"
"invalid switch statement")
(js2-msg ""
"missing : after case expression")
(js2-msg "msg.double.switch.default"
"double default label in the switch statement")
(js2-msg ""
"missing while after do-loop body")
(js2-msg ""
"missing ( after for")
(js2-msg ""
"missing ; after for-loop initializer")
(js2-msg ""
"missing ; after for-loop condition")
(js2-msg ""
"missing in after for")
(js2-msg ""
"missing ) after for-loop control")
(js2-msg ""
"missing ( before with-statement object")
(js2-msg ""
"missing ) after with-statement object")
(js2-msg ""
"missing ( after let")
(js2-msg ""
"missing ) after variable list")
(js2-msg ""
"missing } after let statement")
(js2-msg "msg.bad.return"
"invalid return")
(js2-msg ""
"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 ""
"missing : in conditional expression")
(js2-msg ""
"missing ) after argument list")
(js2-msg ""
"missing ] after element list")
(js2-msg "msg.bad.prop"
"invalid property id")
(js2-msg ""
"missing : after property id")
(js2-msg ""
"missing } after property list")
(js2-msg ""
"missing ) in parenthetical")
(js2-msg ""
"identifier is a reserved word")
(js2-msg ""
"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 ""
"missing '{' before try block")
(js2-msg ""
"missing '{' before catch-block body")
(js2-msg ""
"'try' without 'catch' or 'finally'")
(js2-msg ""
"function %s does not always return a value")
(js2-msg ""
"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: generator function '%s' returns a value")
(js2-msg "msg.anon.generator.returns"
"TypeError: anonymous 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 ""
"Code has no side effects")
(js2-msg "msg.extra.trailing.comma"
"Trailing comma is not legal in an ECMA-262 object initializer")
(js2-msg "msg.array.trailing.comma"
"Trailing comma yields different behavior across browsers")
(js2-msg ""
(concat "Test for equality (==) mistyped as assignment (=)?"
" (parenthesize to suppress warning)"))
(js2-msg "msg.var.hides.arg"
"Variable %s hides argument")
(js2-msg ""
"Missing = in destructuring declaration")
;; ScriptRuntime
(js2-msg ""
"%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.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 ""
"Cannot convert null to an object.")
(js2-msg ""
"Cannot convert undefined to an object.")
(js2-msg "msg.cyclic.value"
"Cyclic %s value not allowed.")
(js2-msg ""
"'%s' is not defined.")
(js2-msg ""
"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 ""
"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 ""
"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 ""
"Cannot find function %s in object %s.")
(js2-msg "msg.isnt.xml.object"
"%s is not an xml object.")
(js2-msg ""
"%s is not a reference to read reference value.")
(js2-msg ""
"%s is not a reference to set reference value to %s.")
(js2-msg ""
"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 ""
"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 ""
"unterminated regular expression literal")
(js2-msg ""
"invalid flag after regular expression")
(js2-msg ""
"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.reserved.keyword"
"illegal usage of future reserved keyword %s; "
"interpreting it as ordinary identifier")
(js2-msg ""
"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")
;;; Utilities
(defun js2-delete-if (predicate list)
"Remove all items satisfying PREDICATE in LIST."
(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)
(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)))
(defmacro js2-time (form)
"Evaluate FORM, discard result, and return elapsed time in sec"
(declare (debug t))
(let ((beg (make-symbol "--js2-time-beg--"))
(delta (make-symbol "--js2-time-end--")))
`(let ((,beg (current-time))
(/ (truncate (* (- (float-time (current-time))
(float-time ,beg))
(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))))
(defsubst js2-same-line-2 (p1 p2)
"Return t if p1 is on the same line as p2."
(goto-char p1)
(js2-same-line p2)))
(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.
(defsubst js2-record-parse-error (msg &optional arg pos len)
(push (list (list msg arg)
(or pos js2-token-beg)
(or len (- js2-token-end js2-token-beg)))
(defsubst 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
(goto-char js2-ts-cursor)
(defsubst js2-report-warning (msg &optional msg-arg pos len)
(if js2-compiler-report-warning-as-error
(js2-report-error msg msg-arg pos len)
(push (list (list msg msg-arg)
(or pos js2-token-beg)
(or len (- js2-token-end js2-token-beg)))
(defsubst 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)))
;; Stolen shamelessly from James Clark's nxml-mode.
(defmacro js2-with-unmodifying-text-property-changes (&rest body)
"Evaluate BODY without any text property changes modifying the buffer.
Any text properties changes happen as usual but the changes are not treated as
modifications to the buffer."
(declare (indent 0) (debug t))
(let ((modified (make-symbol "modified")))
`(let ((,modified (buffer-modified-p))
(inhibit-read-only t)
(inhibit-modification-hooks t)
(buffer-undo-list t)
(deactivate-mark nil)
;; Apparently these avoid file locking problems.
(buffer-file-name nil)
(buffer-file-truename nil))
(progn ,@body)
(unless ,modified
(restore-buffer-modified-p nil))))))
(defmacro js2-with-underscore-as-word-syntax (&rest body)
"Evaluate BODY with the _ character set to be word-syntax."
(declare (indent 0) (debug t))
(let ((old-syntax (make-symbol "old-syntax")))
`(let ((,old-syntax (string (char-syntax ?_))))
(modify-syntax-entry ?_ "w" js2-mode-syntax-table)
(modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
(defsubst js2-char-uppercase-p (c)
"Return t if C is an uppercase character.
Handles unicode and latin chars properly."
(/= c (downcase c)))
(defsubst js2-char-lowercase-p (c)
"Return t if C is an uppercase character.
Handles unicode and latin chars properly."
(/= c (upcase c)))
;;; 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)))
(defsubst js2-make-pad (indent)
(if (zerop indent)
(make-string (* indent js2-basic-offset) ? )))
(defsubst 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."
(if node
(let ((vfunc (get (aref node 0) 'js2-visitor)))
;; visit the node
(when (funcall callback node nil)
;; visit the kids
((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.
(funcall vfunc node callback))
(error "%s does not define a visitor-traversal function"
(aref node 0)))))
;; call the end-visit
(funcall callback node t))))
(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))))
(defsubst 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))))))
(defsubst 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.
(defsubst 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))))
(defsubst js2-node-abs-end (n)
"Return absolute buffer position of end of N."
(+ (js2-node-abs-pos n) (js2-node-len n)))
;; 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.
(defstruct (js2-block-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-block-node (&key (type js2-BLOCK)
(pos js2-token-beg)
"A block of statements."
kids) ; a lisp list of the child statement nodes
(put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
(put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
(defsubst 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 "}")))
(defstruct (js2-scope
(:include js2-block-node)
(:constructor nil)
(:constructor make-js2-scope (&key (type js2-BLOCK)
(pos js2-token-beg)
;; 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)
(put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
(put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
(defun js2-scope-set-parent-scope (scope parent)
(setf (js2-scope-parent-scope scope) parent
(js2-scope-top scope) (if (null parent)
(js2-scope-top parent))))
(defun js2-node-get-enclosing-scope (node)
"Return the innermost `js2-scope' node surrounding NODE.
Returns nil if there is no enclosing scope node."
(let ((parent (js2-node-parent node)))
(while (not (js2-scope-p parent))
(setq parent (js2-node-parent parent)))
(defun js2-get-defining-scope (scope name)
"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."
(let ((sym (if (symbolp name)
(intern name)))
(continue t))
(while (and scope continue)
(if (and (setq table (js2-scope-symbol-table scope))
(assq sym table))
(setq continue nil
result scope)
(setq scope (js2-scope-parent-scope scope))))
(defsubst 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)
(intern name))
(js2-scope-symbol-table scope)))))
(defsubst 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)))))
(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
name ; string
ast-node) ; a `js2-node'
(defstruct (js2-error-node
(:include js2-node)
(:constructor nil) ; silence emacs21 byte-compiler
(:constructor make-js2-error-node (&key (type js2-ERROR)
(pos js2-token-beg)
"AST node representing a parse error.")
(put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
(put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
(defstruct (js2-script-node
(:include js2-scope)
(:constructor nil)
(:constructor make-js2-script-node (&key (type js2-SCRIPT)
(pos js2-token-beg)
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
(put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
(put 'cl-struct-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)))
(defstruct (js2-ast-root
(:include js2-script-node)
(:constructor nil)
(:constructor make-js2-ast-root (&key (type js2-SCRIPT)
(pos js2-token-beg)
"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
(put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
(put 'cl-struct-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)))
(defstruct (js2-comment-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-comment-node (&key (type js2-COMMENT)
(pos js2-token-beg)
(format js2-ts-comment-type))))
format) ; 'line, 'block, 'jsdoc or 'html
(put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
(put 'cl-struct-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)))
(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)
"An expression statement."
(defsubst js2-expr-stmt-node-set-has-result (node)
"Change the node type to `js2-EXPR_RESULT'. Used for code generation."
(setf (js2-node-type node) js2-EXPR_RESULT))
(put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
(put 'cl-struct-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"))
(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
(defstruct (js2-do-node
(:include js2-loop-node)
(:constructor nil)
(:constructor make-js2-do-node (&key (type js2-DO)
(pos js2-token-beg)
"AST node for do-loop."
condition ; while (expression)
while-pos) ; buffer position of 'while' keyword
(put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
(put 'cl-struct-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")))
(defstruct (js2-while-node
(:include js2-loop-node)
(:constructor nil)
(:constructor make-js2-while-node (&key (type js2-WHILE)
(pos js2-token-beg)
"AST node for while-loop."
condition) ; while-condition
(put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
(put 'cl-struct-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")))
(defstruct (js2-for-node
(:include js2-loop-node)
(:constructor nil)
(:constructor make-js2-for-node (&key (type js2-FOR)
(pos js2-ts-cursor)
"AST node for a C-style for-loop."
init ; initialization expression
condition ; loop condition
update) ; update clause
(put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
(put 'cl-struct-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")))
(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)
"AST node for a 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
(put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
(put 'cl-struct-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)))
(insert pad "for ")
(if foreach
(insert "each "))
(insert "(")
(js2-print-ast (js2-for-in-node-iterator n) 0)
(insert " 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")))
(defstruct (js2-return-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-return-node (&key (type js2-RETURN)
(pos js2-ts-cursor)
"AST node for a return statement."
retval) ; expression to return, or 'undefined
(put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
(put 'cl-struct-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"))
(defstruct (js2-if-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-if-node (&key (type js2-IF)
(pos js2-ts-cursor)
"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
(put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
(put 'cl-struct-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 "}")
((not else-part)
(insert "\n"))
((js2-if-node-p else-part)
(insert " else ")
(js2-print-body else-part i))
(insert " else {\n")
(js2-print-body else-part (1+ i))
(insert pad "}\n")))))
(defstruct (js2-try-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-try-node (&key (type js2-TRY)
(pos js2-ts-cursor)
"AST node for a try-statement."
catch-clauses ; a lisp list of `js2-catch-node'
finally-block) ; a `js2-finally-node'
(put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
(put 'cl-struct-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"))))
(defstruct (js2-catch-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-catch-node (&key (type js2-CATCH)
(pos js2-ts-cursor)
"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'
block ; statements, a `js2-block-node'
lp ; buffer position of left-paren, nil if omitted
rp) ; buffer position of right-paren, nil if omitted
(put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
(put 'cl-struct-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-ast (js2-catch-node-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 (js2-catch-node-block n) (1+ i))
(insert pad "}")))
(defstruct (js2-finally-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-finally-node (&key (type js2-FINALLY)
(pos js2-ts-cursor)
"AST node for a finally clause."
body) ; a `js2-node', often but not always a block node
(put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
(put 'cl-struct-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")))
(defstruct (js2-switch-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-switch-node (&key (type js2-SWITCH)
(pos js2-ts-cursor)
"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
(put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
(put 'cl-struct-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")))
(defstruct (js2-case-node
(:include js2-block-node)
(:constructor nil)
(:constructor make-js2-case-node (&key (type js2-CASE)
(pos js2-ts-cursor)
"AST node for a case clause of a switch statement."
expr) ; the case expression (nil for default)
(put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
(put 'cl-struct-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)))))
(defstruct (js2-throw-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-throw-node (&key (type js2-THROW)
(pos js2-ts-cursor)
"AST node for a throw statement."
expr) ; the expression to throw
(put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
(put 'cl-struct-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"))
(defstruct (js2-with-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-with-node (&key (type js2-WITH)
(pos js2-ts-cursor)
"AST node for a with-statement."
lp ; buffer position of left-paren around object, nil if omitted
rp) ; buffer position of right-paren around object, nil if omitted
(put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
(put 'cl-struct-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")))
(defstruct (js2-label-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-label-node (&key (type js2-LABEL)
(pos js2-ts-cursor)
"AST node for a statement label or case label."
name ; a string
loop) ; for validating and code-generating continue-to-label
(put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
(put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
(defun js2-print-label (n i)
(insert (js2-make-pad i)
(js2-label-node-name n)
(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)
"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
(put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
(put 'cl-struct-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))
(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))))
(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) (1+ 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."
(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))))
(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)
(js2-visit-ast (js2-jump-node-label n) v))
(defstruct (js2-break-node
(:include js2-jump-node)
(:constructor nil)
(:constructor make-js2-break-node (&key (type js2-BREAK)
(pos js2-ts-cursor)
"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.")
(put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
(put 'cl-struct-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"))
(defstruct (js2-continue-node
(:include js2-jump-node)
(:constructor nil)
(:constructor make-js2-continue-node (&key (type js2-CONTINUE)
(pos js2-ts-cursor)
"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.")
(put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
(put 'cl-struct-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"))
(defstruct (js2-function-node
(:include js2-script-node)
(:constructor nil)
(:constructor make-js2-function-node (&key (type js2-FUNCTION)
(pos js2-ts-cursor)
(ftype 'FUNCTION)
(name "")
"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'."
name ; function name (a `js2-name-node', or nil if anonymous)
params ; a lisp list of destructuring forms or simple name nodes
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
is-generator ; t if this function contains a yield
member-expr) ; nonstandard Ecma extension from Rhino
(put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
(put 'cl-struct-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))
(getter (js2-node-get-prop n 'GETTER_SETTER))
(name (js2-function-node-name n))
(params (js2-function-node-params n))
(body (js2-function-node-body n))
(expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
(unless getter
(insert pad "function"))
(when name
(insert " ")
(js2-print-ast name 0))
(insert "(")
(loop with len = (length params)
for param in params
for count from 1
(js2-print-ast param 0)
(if (< count len)
(insert ", ")))
(insert ") {")
(unless expr
(insert "\n"))
;; TODO: fix this to be smarter about indenting, etc.
(js2-print-body body (1+ i))
(insert pad "}")
(unless expr
(insert "\n"))))
(defsubst 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.
(defstruct (js2-var-decl-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-var-decl-node (&key (type js2-VAR)
(pos js2-token-beg)
"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
(put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
(put 'cl-struct-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) "") ; handled by parent let-{expr/stmt}
((= tt js2-CONST) "const ")
(error "malformed var-decl node"))))
(loop with kids = (js2-var-decl-node-kids n)
with len = (length kids)
for kid in kids
for count from 1
(js2-print-ast kid 0)
(if (< count len)
(insert ", ")))))
(defstruct (js2-var-init-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-var-init-node (&key (type js2-VAR)
(pos js2-ts-cursor)
"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'
(put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
(put 'cl-struct-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))))
(defstruct (js2-cond-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-cond-node (&key (type js2-HOOK)
(pos js2-ts-cursor)
"AST node for the ternary operator"
q-pos ; buffer position of ?
c-pos) ; buffer position of :
(put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
(put 'cl-struct-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)))
(defstruct (js2-infix-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-infix-node (&key type
(pos js2-ts-cursor)
"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'
(put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
(put 'cl-struct-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))
(list (cons js2-IN "in")
(cons js2-TYPEOF "typeof")
(cons js2-INSTANCEOF "instanceof")
(cons js2-DELPROP "delete")
(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-DIV "/")
(cons js2-MOD "%")
(cons js2-NOT "!")
(cons js2-BITNOT "~")
(cons js2-POS "+") ; unary plus
(cons js2-NEG "-") ; unary minus
(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_DIV "/=")
(cons js2-ASSIGN_MOD "%="))))
(loop for (k . v) in tokens do
(puthash k v 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)))
(defstruct (js2-assign-node
(:include js2-infix-node)
(:constructor nil)
(:constructor make-js2-assign-node (&key type
(pos js2-ts-cursor)
"Represents any assignment.
The type field holds the actual assignment operator.")
(put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
(put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
(defstruct (js2-unary-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-unary-node (&key type ; required
(pos js2-ts-cursor)
"AST node type for unary operator nodes.
The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
property is added if the operator follows the operand."
operand) ; a `js2-node' expression
(put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
(put 'cl-struct-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))
(insert " "))
(js2-print-ast (js2-unary-node-operand n) 0)
(when postfix
(insert op))))
(defstruct (js2-let-node
(:include js2-scope)
(:constructor nil)
(:constructor make-js2-let-node (&key (type js2-LETEXPR)
(pos js2-token-beg)
"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
(put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
(put 'cl-struct-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 (")
(js2-print-ast (js2-let-node-vars n) 0)
(insert ") ")
(js2-print-ast (js2-let-node-body n) i))
(defstruct (js2-keyword-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-keyword-node (&key type
(pos js2-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.")
(put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
(put 'cl-struct-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)))
((= tt js2-THIS) "this")
((= 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-node-p (node)
"Return t if this node is a `js2-literal-node' of type js2-THIS."
(eq (js2-node-type node) js2-THIS))
(defstruct (js2-new-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-new-node (&key (type js2-NEW)
(pos js2-token-beg)
"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'
(put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
(put 'cl-struct-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)
(dolist (arg (js2-new-node-args n))
(js2-visit-ast arg v))
(js2-visit-ast (js2-new-node-initializer n) v))
(defun js2-print-new-node (n i)
(insert (js2-make-pad i) "new ")
(js2-print-ast (js2-new-node-target n))
(insert "(")
(js2-print-list (js2-new-node-args n))
(insert ")")
(when (js2-new-node-initializer n)
(insert " ")
(js2-print-ast (js2-new-node-initializer n))))
(defstruct (js2-name-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-name-node (&key (type js2-NAME)
(pos js2-token-beg)
(len (- js2-ts-cursor
(name js2-ts-string))))
"AST node for a JavaScript identifier"
name ; a string
scope) ; a `js2-scope' (optional, used for codegen)
(put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
(put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
(defun js2-print-name-node (n i)
(insert (js2-make-pad i)
(js2-name-node-name n)))
(defsubst js2-name-node-length (node)
"Return identifier length of NODE, a `js2-name-node'.
Returns 0 if NODE is nil or its identifier field is nil."
(if node
(length (js2-name-node-name node))
(defstruct (js2-number-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-number-node (&key (type js2-NUMBER)
(pos js2-token-beg)
(len (- js2-ts-cursor
(value js2-ts-string)
(num-value js2-ts-number))))
"AST node for a number literal."
value ; the original string, e.g. "6.02e23"
num-value) ; the parsed number value
(put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
(put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
(defun js2-print-number-node (n i)
(insert (js2-make-pad i)
(number-to-string (js2-number-node-num-value n))))
(defstruct (js2-regexp-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-regexp-node (&key (type js2-REGEXP)
(pos js2-token-beg)
(len (- js2-ts-cursor
"AST node for a regular expression literal."
value ; the regexp string, without // delimiters
flags) ; a string of flags, e.g. `mi'.
(put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
(put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
(defun js2-print-regexp (n i)
(insert (js2-make-pad i)
(js2-regexp-node-value n)
(if (js2-regexp-node-flags n)
(insert (js2-regexp-node-flags n))))
(defstruct (js2-string-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-string-node (&key (type js2-STRING)
(pos js2-token-beg)
(len (- js2-ts-cursor
(value js2-ts-string))))
"String literal.
Escape characters are not evaluated; e.g. \n is 2 chars in value field.
You can tell the quote type by looking at the first character."
value) ; the characters of the string, including the quotes
(put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
(put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
(defun js2-print-string-node (n i)
(insert (js2-make-pad i)
(js2-node-string n)))
(defstruct (js2-array-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
(pos js2-ts-cursor)
"AST node for an array literal."
elems) ; list of expressions. [foo,,bar] yields a nil middle element.
(put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
(put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
(defun js2-visit-array-node (n v)
(dolist (e (js2-array-node-elems n))
(js2-visit-ast e v)))
(defun js2-print-array-node (n i)
(insert (js2-make-pad i) "[")
(js2-print-list (js2-array-node-elems n))
(insert "]"))
(defstruct (js2-object-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
(pos js2-ts-cursor)
"AST node for an object literal expression.
`elems' is a list of either `js2-object-prop-node' or `js2-name-node',
the latter represents abbreviation in destructuring expressions."
(put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
(put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
(defun js2-visit-object-node (n v)
(dolist (e (js2-object-node-elems n))
(js2-visit-ast e v)))
(defun js2-print-object-node (n i)
(insert (js2-make-pad i) "{")
(js2-print-list (js2-object-node-elems n))
(insert "}"))
(defstruct (js2-object-prop-node
(:include js2-infix-node)
(:constructor nil)
(:constructor make-js2-object-prop-node (&key (type js2-COLON)
(pos js2-ts-cursor)
"AST node for an object literal prop:value entry.
The `left' field is the property: a name node, string node or number node.
The `right' field is a `js2-node' representing the initializer value.")
(put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
(put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
(defun js2-print-object-prop-node (n i)
(insert (js2-make-pad i))
(js2-print-ast (js2-object-prop-node-left n) 0)
(insert ":")
(js2-print-ast (js2-object-prop-node-right n) 0))
(defstruct (js2-getter-setter-node
(:include js2-infix-node)
(:constructor nil)
(:constructor make-js2-getter-setter-node (&key type ; GET or SET
(pos js2-ts-cursor)
"AST node for a getter/setter property in an object literal.
The `left' field is the `js2-name-node' naming the getter/setter prop.
The `right' field is always an anonymous `js2-function-node' with a node
property `GETTER_SETTER' set to js2-GET or js2-SET. ")
(put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
(put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
(defun js2-print-getter-setter (n i)
(let ((pad (js2-make-pad i))
(left (js2-getter-setter-node-left n))
(right (js2-getter-setter-node-right n)))
(insert pad)
(insert (if (= (js2-node-type n) js2-GET) "get " "set "))
(js2-print-ast left 0)
(js2-print-ast right 0)))
(defstruct (js2-prop-get-node
(:include js2-infix-node)
(:constructor nil)
(:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
(pos js2-ts-cursor)
"AST node for a dotted property reference, e.g. or foo().bar")
(put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
(put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
(defun js2-visit-prop-get-node (n v)
(js2-visit-ast (js2-prop-get-node-left n) v)
(js2-visit-ast (js2-prop-get-node-right n) v))
(defun js2-print-prop-get-node (n i)
(insert (js2-make-pad i))
(js2-print-ast (js2-prop-get-node-left n) 0)
(insert ".")
(js2-print-ast (js2-prop-get-node-right n) 0))
(defstruct (js2-elem-get-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
(pos js2-ts-cursor)
"AST node for an array index expression such as foo[bar]."
target ; a `js2-node' - the expression preceding the "."
element ; a `js2-node' - the expression in brackets
lb ; position of left-bracket, nil if omitted
rb) ; position of right-bracket, nil if omitted
(put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
(put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
(defun js2-visit-elem-get-node (n v)
(js2-visit-ast (js2-elem-get-node-target n) v)
(js2-visit-ast (js2-elem-get-node-element n) v))
(defun js2-print-elem-get-node (n i)
(insert (js2-make-pad i))
(js2-print-ast (js2-elem-get-node-target n) 0)
(insert "[")
(js2-print-ast (js2-elem-get-node-element n) 0)
(insert "]"))
(defstruct (js2-call-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-call-node (&key (type js2-CALL)
(pos js2-ts-cursor)
"AST node for a JavaScript function call."
target ; a `js2-node' evaluating to the function to call
args ; a lisp list of `js2-node' arguments
lp ; position of open-paren, or nil if missing
rp) ; position of close-paren, or nil if missing
(put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
(put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
(defun js2-visit-call-node (n v)
(js2-visit-ast (js2-call-node-target n) v)
(dolist (arg (js2-call-node-args n))
(js2-visit-ast arg v)))
(defun js2-print-call-node (n i)
(insert (js2-make-pad i))
(js2-print-ast (js2-call-node-target n) 0)
(insert "(")
(js2-print-list (js2-call-node-args n))
(insert ")"))
(defstruct (js2-yield-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-yield-node (&key (type js2-YIELD)
(pos js2-ts-cursor)
"AST node for yield statement or expression."
value) ; optional: value to be yielded
(put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
(put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
(defun js2-visit-yield-node (n v)
(js2-visit-ast (js2-yield-node-value n) v))
(defun js2-print-yield-node (n i)
(insert (js2-make-pad i))
(insert "yield")
(when (js2-yield-node-value n)
(insert " ")
(js2-print-ast (js2-yield-node-value n) 0)))
(defstruct (js2-paren-node
(:include js2-node)
(:constructor nil)
(:constructor make-js2-paren-node (&key (type js2-LP)
(pos js2-ts-cursor)
"AST node for a parenthesized expression.
In particular, used when the parens are syntactically optional,
as opposed to required parens such as those enclosing an if-conditional."
expr) ; `js2-node'
(put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
(put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
(defun js2-visit-paren-node (n v)
(js2-visit-ast (js2-paren-node-expr n) v))
(defun js2-print-paren-node (n i)
(insert (js2-make-pad i))
(insert "(")
(js2-print-ast (js2-paren-node-expr n) 0)
(insert ")"))
(defstruct (js2-array-comp-node
(:include js2-scope)
(:constructor nil)
(:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
(pos js2-ts-cursor)
"AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
result ; result expression (just after left-bracket)
loops ; a lisp list of `js2-array-comp-loop-node'
filter ; guard/filter expression
if-pos ; buffer pos of 'if' keyword, if present, else nil
lp ; buffer position of if-guard left-paren, or nil if not present
rp) ; buffer position of if-guard right-paren, or nil if not present
(put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
(put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
(defun js2-visit-array-comp-node (n v)
(js2-visit-ast (js2-array-comp-node-result n) v)
(dolist (l (js2-array-comp-node-loops n))
(js2-visit-ast l v))
(js2-visit-ast (js2-array-comp-node-filter n) v))
(defun js2-print-array-comp-node (n i)
(let ((pad (js2-make-pad i))
(result (js2-array-comp-node-result n))
(loops (js2-array-comp-node-loops n))
(filter (js2-array-comp-node-filter n)))
(insert pad "[")
(js2-print-ast result 0)
(dolist (l loops)
(insert " ")