1 ;;; js2-mode.el --- Improved JavaScript editing mode
3 ;; Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
14 ;; This file is part of GNU Emacs.
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31 ;; This JavaScript editing mode supports:
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
50 ;; To install it as your major mode for JavaScript editing:
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
54 ;; Alternatively, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
59 ;; You may also want to hook it in for shell scripts running via node.js:
61 ;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
63 ;; To customize how it works:
64 ;; M-x customize-group RET js2-mode RET
68 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
69 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
70 ;; `js2-mode' current as the EcmaScript language standard evolves.
72 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
73 ;; customizable. It is a surprising amount of work to support customizable
74 ;; indentation. The current compromise is that the tab key lets you cycle among
75 ;; various likely indentation points, similar to the behavior of python-mode.
77 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
78 ;; and `mumamo', although it could be made to do so with some effort.
79 ;; This means that `js2-mode' is currently only useful for editing JavaScript
80 ;; files, and not for editing JavaScript within <script> tags or templates.
82 ;; The project page on GitHub is used for development and issue tracking.
83 ;; The original homepage at Google Code has outdated information and is mostly
92 (require 'cc-cmds) ; for `c-fill-paragraph'
95 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
96 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
98 (defvar electric-layout-rules)
100 ;;; Externs (variables presumed to be defined by the host system)
102 (defvar js2-ecma-262-externs
104 '(Array Boolean Date Error EvalError Function Infinity JSON
105 Math NaN Number Object RangeError ReferenceError RegExp
106 String SyntaxError TypeError URIError arguments
107 decodeURI decodeURIComponent encodeURI
108 encodeURIComponent escape eval isFinite isNaN
109 parseFloat parseInt undefined unescape))
110 "Ecma-262 externs. Included in `js2-externs' by default.")
112 (defvar js2-browser-externs
115 Attr CDATASection CharacterData Comment DOMException
116 DOMImplementation Document DocumentFragment
117 DocumentType Element Entity EntityReference
118 ExceptionCode NamedNodeMap Node NodeList Notation
119 ProcessingInstruction Text
122 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
123 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
124 HTMLBodyElement HTMLButtonElement HTMLCollection
125 HTMLDListElement HTMLDirectoryElement HTMLDivElement
126 HTMLDocument HTMLElement HTMLFieldSetElement
127 HTMLFontElement HTMLFormElement HTMLFrameElement
128 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
129 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
130 HTMLImageElement HTMLInputElement HTMLIsIndexElement
131 HTMLLIElement HTMLLabelElement HTMLLegendElement
132 HTMLLinkElement HTMLMapElement HTMLMenuElement
133 HTMLMetaElement HTMLModElement HTMLOListElement
134 HTMLObjectElement HTMLOptGroupElement
135 HTMLOptionElement HTMLOptionsCollection
136 HTMLParagraphElement HTMLParamElement HTMLPreElement
137 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
138 HTMLStyleElement HTMLTableCaptionElement
139 HTMLTableCellElement HTMLTableColElement
140 HTMLTableElement HTMLTableRowElement
141 HTMLTableSectionElement HTMLTextAreaElement
142 HTMLTitleElement HTMLUListElement
145 DOMConfiguration DOMError DOMException
146 DOMImplementationList DOMImplementationSource
147 DOMLocator DOMStringList NameList TypeInfo
151 window alert confirm document java navigator prompt screen
155 CSSCharsetRule CSSFontFace CSSFontFaceRule
156 CSSImportRule CSSMediaRule CSSPageRule
157 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
158 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
159 CSSValue CSSValueList Counter DOMImplementationCSS
160 DocumentCSS DocumentStyle ElementCSSInlineStyle
161 LinkStyle MediaList RGBColor Rect StyleSheet
162 StyleSheetList ViewCSS
165 EventListener EventTarget Event DocumentEvent UIEvent
166 MouseEvent MutationEvent KeyboardEvent
169 DocumentRange Range RangeException
172 XPathResult XMLHttpRequest
174 ;; console object. Provided by at least Chrome and Firefox.
177 You can cause these to be included or excluded with the custom
178 variable `js2-include-browser-externs'.")
180 (defvar js2-rhino-externs
182 '(Packages importClass importPackage com org java
183 ;; Global object (shell) externs.
184 defineClass deserialize doctest gc help load
185 loadClass print quit readFile readUrl runCommand seal
186 serialize spawn sync toint32 version))
187 "Mozilla Rhino externs.
188 Set `js2-include-rhino-externs' to t to include them.")
190 (defvar js2-node-externs
192 '(__dirname __filename Buffer clearInterval clearTimeout require
193 console exports global module process setInterval setTimeout))
195 Set `js2-include-node-externs' to t to include them.")
197 (defvar js2-typed-array-externs
199 '(ArrayBuffer Uint8ClampedArray DataView
200 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
201 Float32Array Float64Array))
202 "Khronos typed array externs. Available in most modern browsers and
203 in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
204 are enabled, these will also be included.")
206 (defvar js2-harmony-externs
208 '(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
209 "ES6 externs. If `js2-include-browser-externs' is enabled and
210 `js2-language-version' is sufficiently high, these will be included.")
214 (defun js2-mark-safe-local (name pred)
215 "Make the variable NAME buffer-local and mark it as safe file-local
216 variable with predicate PRED."
217 (make-variable-buffer-local name)
218 (put name 'safe-local-variable pred))
220 (defcustom js2-highlight-level 2
221 "Amount of syntax highlighting to perform.
222 0 or a negative value means none.
223 1 adds basic syntax highlighting.
224 2 adds highlighting of some Ecma built-in properties.
225 3 adds highlighting of many Ecma built-in functions."
227 :type '(choice (const :tag "None" 0)
228 (const :tag "Basic" 1)
229 (const :tag "Include Properties" 2)
230 (const :tag "Include Functions" 3)))
232 (defvar js2-mode-dev-mode-p nil
233 "Non-nil if running in development mode. Normally nil.")
235 (defgroup js2-mode nil
236 "An improved JavaScript mode."
239 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
240 (numberp c-basic-offset))
243 "Number of spaces to indent nested statements.
244 Similar to `c-basic-offset'."
247 (js2-mark-safe-local 'js2-basic-offset 'integerp)
249 (defcustom js2-bounce-indent-p nil
250 "Non-nil to have indent-line function choose among alternatives.
251 If nil, the indent-line function will indent to a predetermined column
252 based on heuristic guessing. If non-nil, then if the current line is
253 already indented to that predetermined column, indenting will choose
254 another likely column and indent to that spot. Repeated invocation of
255 the indent-line function will cycle among the computed alternatives.
256 See the function `js2-bounce-indent' for details. When it is non-nil,
257 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
261 (defcustom js2-pretty-multiline-declarations t
262 "Non-nil to line up multiline declarations vertically:
268 If the value is not `all', and the first assigned value in
269 declaration is a function/array/object literal spanning several
270 lines, it won't be indented additionally:
272 var o = { var bar = 2,
278 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
280 (defcustom js2-indent-switch-body nil
281 "When nil, case labels are indented on the same level as the
282 containing switch statement. Otherwise, all lines inside
283 switch statement body are indented one additional level."
286 (js2-mark-safe-local 'js2-indent-case-same-as-switch 'booleanp)
288 (defcustom js2-idle-timer-delay 0.2
289 "Delay in secs before re-parsing after user makes changes.
290 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
293 (make-variable-buffer-local 'js2-idle-timer-delay)
295 (defcustom js2-dynamic-idle-timer-adjust 0
296 "Positive to adjust `js2-idle-timer-delay' based on file size.
297 The idea is that for short files, parsing is faster so we can be
298 more responsive to user edits without interfering with editing.
299 The buffer length in characters (typically bytes) is divided by
300 this value and used to multiply `js2-idle-timer-delay' for the
301 buffer. For example, a 21k file and 10k adjust yields 21k/10k
302 == 2, so js2-idle-timer-delay is multiplied by 2.
303 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
304 `js2-idle-timer-delay' is not dependent on the file size."
308 (defcustom js2-concat-multiline-strings t
309 "When non-nil, `js2-line-break' in mid-string will make it a
310 string concatenation. When `eol', the '+' will be inserted at the
311 end of the line, otherwise, at the beginning of the next line."
312 :type '(choice (const t) (const eol) (const nil))
315 (defcustom js2-mode-show-parse-errors t
316 "True to highlight parse errors."
320 (defcustom js2-mode-show-strict-warnings t
321 "Non-nil to emit Ecma strict-mode warnings.
322 Some of the warnings can be individually disabled by other flags,
323 even if this flag is non-nil."
327 (defcustom js2-strict-trailing-comma-warning t
328 "Non-nil to warn about trailing commas in array literals.
329 Ecma-262-5.1 allows them, but older versions of IE raise an error."
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
365 (defcustom js2-strict-var-redeclaration-warning t
366 "Non-nil to warn about redeclaring variables in a script or function."
370 (defcustom js2-strict-var-hides-function-arg-warning t
371 "Non-nil to warn about a var decl hiding a function argument."
375 (defcustom js2-skip-preprocessor-directives nil
376 "Non-nil to treat lines beginning with # as comments.
377 Useful for viewing Mozilla JavaScript source code."
381 (defcustom js2-language-version 200
382 "Configures what JavaScript language version to recognize.
383 Currently versions 150, 160, 170, 180 and 200 are supported,
384 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
385 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
386 yield, and Array comprehensions, and 1.8 adds function closures."
390 (defcustom js2-allow-keywords-as-property-names t
391 "If non-nil, you can use JavaScript keywords as object property names.
394 var foo = {int: 5, while: 6, continue: 7};
397 Ecma-262 5.1 allows this syntax, but some engines still don't."
401 (defcustom js2-instanceof-has-side-effects nil
402 "If non-nil, treats the instanceof operator as having side effects.
403 This is useful for xulrunner apps."
407 (defcustom js2-move-point-on-right-click t
408 "Non-nil to move insertion point when you right-click.
409 This makes right-click context menu behavior a bit more intuitive,
410 since menu operations generally apply to the point. The exception
411 is if there is a region selection, in which case the point does -not-
412 move, so cut/copy/paste can work properly.
414 Note that IntelliJ moves the point, and Eclipse leaves it alone,
415 so this behavior is customizable."
419 (defcustom js2-allow-rhino-new-expr-initializer t
420 "Non-nil to support a Rhino's experimental syntactic construct.
422 Rhino supports the ability to follow a `new' expression with an object
423 literal, which is used to set additional properties on the new object
424 after calling its constructor. Syntax:
426 new <expr> [ ( arglist ) ] [initializer]
428 Hence, this expression:
430 new Object {a: 1, b: 2}
432 results in an Object with properties a=1 and b=2. This syntax is
433 apparently not configurable in Rhino - it's currently always enabled,
434 as of Rhino version 1.7R2."
438 (defcustom js2-allow-member-expr-as-function-name nil
439 "Non-nil to support experimental Rhino syntax for function names.
441 Rhino supports an experimental syntax configured via the Rhino Context
442 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
444 function <member-expr> ( [ arg-list ] ) { <body> }
446 Where member-expr is a non-parenthesized 'member expression', which
447 is anything at the grammar level of a new-expression or lower, meaning
448 any expression that does not involve infix or unary operators.
450 When <member-expr> is not a simple identifier, then it is syntactic
451 sugar for assigning the anonymous function to the <member-expr>. Hence,
454 function a.b().c[2] (x, y) { ... }
458 a.b().c[2] = function(x, y) {...}
460 which doesn't seem particularly useful, but Rhino permits it."
466 (defmacro js2-deflocal (name value &optional comment)
467 "Define a buffer-local variable NAME with VALUE and COMMENT."
469 (defvar ,name ,value ,comment)
470 (make-variable-buffer-local ',name)))
472 (defvar js2-EOF_CHAR -1
473 "Represents end of stream. Distinct from js2-EOF token type.")
475 ;; I originally used symbols to represent tokens, but Rhino uses
476 ;; ints and then sets various flag bits in them, so ints it is.
477 ;; The upshot is that we need a `js2-' prefix in front of each name.
478 (defvar js2-ERROR -1)
481 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
482 (defvar js2-LEAVEWITH 3)
483 (defvar js2-RETURN 4)
487 (defvar js2-SETNAME 8)
489 (defvar js2-BITXOR 10)
490 (defvar js2-BITAND 11)
500 (defvar js2-ADD 21) ; infix plus
501 (defvar js2-SUB 22) ; infix minus
506 (defvar js2-BITNOT 27)
507 (defvar js2-POS 28) ; unary plus
508 (defvar js2-NEG 29) ; unary minus
510 (defvar js2-DELPROP 31)
511 (defvar js2-TYPEOF 32)
512 (defvar js2-GETPROP 33)
513 (defvar js2-GETPROPNOWARN 34)
514 (defvar js2-SETPROP 35)
515 (defvar js2-GETELEM 36)
516 (defvar js2-SETELEM 37)
518 (defvar js2-NAME 39) ; an identifier
519 (defvar js2-NUMBER 40)
520 (defvar js2-STRING 41)
523 (defvar js2-FALSE 44)
525 (defvar js2-SHEQ 46) ; shallow equality (===)
526 (defvar js2-SHNE 47) ; shallow inequality (!==)
527 (defvar js2-REGEXP 48)
528 (defvar js2-BINDNAME 49)
529 (defvar js2-THROW 50)
530 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
532 (defvar js2-INSTANCEOF 53)
533 (defvar js2-LOCAL_LOAD 54)
534 (defvar js2-GETVAR 55)
535 (defvar js2-SETVAR 56)
536 (defvar js2-CATCH_SCOPE 57)
537 (defvar js2-ENUM_INIT_KEYS 58)
538 (defvar js2-ENUM_INIT_VALUES 59)
539 (defvar js2-ENUM_INIT_ARRAY 60)
540 (defvar js2-ENUM_NEXT 61)
541 (defvar js2-ENUM_ID 62)
542 (defvar js2-THISFN 63)
543 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
544 (defvar js2-ARRAYLIT 65) ; array literal
545 (defvar js2-OBJECTLIT 66) ; object literal
546 (defvar js2-GET_REF 67) ; *reference
547 (defvar js2-SET_REF 68) ; *reference = something
548 (defvar js2-DEL_REF 69) ; delete reference
549 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
550 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
551 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
554 (defvar js2-DEFAULTNAMESPACE 73)
555 (defvar js2-ESCXMLATTR 74)
556 (defvar js2-ESCXMLTEXT 75)
557 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
558 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
559 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
560 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
562 (defvar js2-first-bytecode js2-ENTERWITH)
563 (defvar js2-last-bytecode js2-REF_NS_NAME)
566 (defvar js2-SEMI 81) ; semicolon
567 (defvar js2-LB 82) ; left and right brackets
569 (defvar js2-LC 84) ; left and right curly-braces
571 (defvar js2-LP 86) ; left and right parens
573 (defvar js2-COMMA 88) ; comma operator
575 (defvar js2-ASSIGN 89) ; simple assignment (=)
576 (defvar js2-ASSIGN_BITOR 90) ; |=
577 (defvar js2-ASSIGN_BITXOR 91) ; ^=
578 (defvar js2-ASSIGN_BITAND 92) ; &=
579 (defvar js2-ASSIGN_LSH 93) ; <<=
580 (defvar js2-ASSIGN_RSH 94) ; >>=
581 (defvar js2-ASSIGN_URSH 95) ; >>>=
582 (defvar js2-ASSIGN_ADD 96) ; +=
583 (defvar js2-ASSIGN_SUB 97) ; -=
584 (defvar js2-ASSIGN_MUL 98) ; *=
585 (defvar js2-ASSIGN_DIV 99) ; /=
586 (defvar js2-ASSIGN_MOD 100) ; %=
588 (defvar js2-first-assign js2-ASSIGN)
589 (defvar js2-last-assign js2-ASSIGN_MOD)
591 (defvar js2-HOOK 101) ; conditional (?:)
592 (defvar js2-COLON 102)
593 (defvar js2-OR 103) ; logical or (||)
594 (defvar js2-AND 104) ; logical and (&&)
595 (defvar js2-INC 105) ; increment/decrement (++ --)
597 (defvar js2-DOT 107) ; member operator (.)
598 (defvar js2-FUNCTION 108) ; function keyword
599 (defvar js2-EXPORT 109) ; export keyword
600 (defvar js2-IMPORT 110) ; import keyword
601 (defvar js2-IF 111) ; if keyword
602 (defvar js2-ELSE 112) ; else keyword
603 (defvar js2-SWITCH 113) ; switch keyword
604 (defvar js2-CASE 114) ; case keyword
605 (defvar js2-DEFAULT 115) ; default keyword
606 (defvar js2-WHILE 116) ; while keyword
607 (defvar js2-DO 117) ; do keyword
608 (defvar js2-FOR 118) ; for keyword
609 (defvar js2-BREAK 119) ; break keyword
610 (defvar js2-CONTINUE 120) ; continue keyword
611 (defvar js2-VAR 121) ; var keyword
612 (defvar js2-WITH 122) ; with keyword
613 (defvar js2-CATCH 123) ; catch keyword
614 (defvar js2-FINALLY 124) ; finally keyword
615 (defvar js2-VOID 125) ; void keyword
616 (defvar js2-RESERVED 126) ; reserved keywords
618 (defvar js2-EMPTY 127)
620 ;; Types used for the parse tree - never returned by scanner.
622 (defvar js2-BLOCK 128) ; statement block
623 (defvar js2-LABEL 129) ; label
624 (defvar js2-TARGET 130)
625 (defvar js2-LOOP 131)
626 (defvar js2-EXPR_VOID 132) ; expression statement in functions
627 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
629 (defvar js2-SCRIPT 135) ; top-level node for entire script
630 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
631 (defvar js2-USE_STACK 137)
632 (defvar js2-SETPROP_OP 138) ; x.y op= something
633 (defvar js2-SETELEM_OP 139) ; x[y] op= something
634 (defvar js2-LOCAL_BLOCK 140)
635 (defvar js2-SET_REF_OP 141) ; *reference op= something
638 (defvar js2-DOTDOT 142) ; member operator (..)
639 (defvar js2-COLONCOLON 143) ; namespace::name
640 (defvar js2-XML 144) ; XML type
641 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
642 (defvar js2-XMLATTR 146) ; @
643 (defvar js2-XMLEND 147)
645 ;; Optimizer-only tokens
646 (defvar js2-TO_OBJECT 148)
647 (defvar js2-TO_DOUBLE 149)
649 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
650 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
651 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
652 (defvar js2-CONST 153)
653 (defvar js2-SETCONST 154)
654 (defvar js2-SETCONSTVAR 155)
655 (defvar js2-ARRAYCOMP 156)
656 (defvar js2-LETEXPR 157)
657 (defvar js2-WITHEXPR 158)
658 (defvar js2-DEBUGGER 159)
660 (defvar js2-COMMENT 160)
661 (defvar js2-ENUM 161) ; for "enum" reserved word
662 (defvar js2-TRIPLEDOT 162) ; for rest parameter
663 (defvar js2-ARROW 163) ; function arrow (=>)
665 (defconst js2-num-tokens (1+ js2-ARROW))
667 (defconst js2-debug-print-trees nil)
669 ;; Rhino accepts any string or stream as input. Emacs character
670 ;; processing works best in buffers, so we'll assume the input is a
671 ;; buffer. JavaScript strings can be copied into temp buffers before
674 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
675 ;; They're the Emacs equivalent of instance variables, more or less.
677 (js2-deflocal js2-ts-dirty-line nil
678 "Token stream buffer-local variable.
679 Indicates stuff other than whitespace since start of line.")
681 (js2-deflocal js2-ts-hit-eof nil
682 "Token stream buffer-local variable.")
685 (js2-deflocal js2-ts-line-start 0
686 "Token stream buffer-local variable.")
688 (js2-deflocal js2-ts-lineno 1
689 "Token stream buffer-local variable.")
692 (js2-deflocal js2-ts-line-end-char -1
693 "Token stream buffer-local variable.")
695 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
696 "Token stream buffer-local variable.
697 Current scan position.")
700 (js2-deflocal js2-ts-is-xml-attribute nil
701 "Token stream buffer-local variable.")
703 (js2-deflocal js2-ts-xml-is-tag-content nil
704 "Token stream buffer-local variable.")
706 (js2-deflocal js2-ts-xml-open-tags-count 0
707 "Token stream buffer-local variable.")
709 (js2-deflocal js2-ts-string-buffer nil
710 "Token stream buffer-local variable.
711 List of chars built up while scanning various tokens.")
713 (defstruct (js2-token
715 (:constructor make-js2-token (beg)))
716 "Value returned from the token stream."
726 (defstruct (js2-ts-state
727 (:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
728 (cursor js2-ts-cursor)
729 (tokens (copy-sequence js2-ti-tokens))
730 (tokens-cursor js2-ti-tokens-cursor)
731 (lookahead js2-ti-lookahead))))
740 (js2-deflocal js2-parsed-errors nil
741 "List of errors produced during scanning/parsing.")
743 (js2-deflocal js2-parsed-warnings nil
744 "List of warnings produced during scanning/parsing.")
746 (js2-deflocal js2-recover-from-parse-errors t
747 "Non-nil to continue parsing after a syntax error.
749 In recovery mode, the AST will be built in full, and any error
750 nodes will be flagged with appropriate error information. If
751 this flag is nil, a syntax error will result in an error being
754 The variable is automatically buffer-local, because different
755 modes that use the parser will need different settings.")
757 (js2-deflocal js2-parse-hook nil
758 "List of callbacks for receiving parsing progress.")
760 (defvar js2-parse-finished-hook nil
761 "List of callbacks to notify when parsing finishes.
762 Not called if parsing was interrupted.")
764 (js2-deflocal js2-is-eval-code nil
765 "True if we're evaluating code in a string.
766 If non-nil, the tokenizer will record the token text, and the AST nodes
767 will record their source text. Off by default for IDE modes, since the
768 text is available in the buffer.")
770 (defvar js2-parse-ide-mode t
771 "Non-nil if the parser is being used for `js2-mode'.
772 If non-nil, the parser will set text properties for fontification
773 and the syntax table. The value should be nil when using the
774 parser as a frontend to an interpreter or byte compiler.")
776 ;;; Parser instance variables (buffer-local vars for js2-parse)
778 (defconst js2-ti-after-eol (lsh 1 16)
779 "Flag: first token of the source line.")
781 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
783 (js2-deflocal js2-compiler-generate-debug-info t)
784 (js2-deflocal js2-compiler-use-dynamic-scope nil)
785 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
786 (js2-deflocal js2-compiler-xml-available t)
787 (js2-deflocal js2-compiler-optimization-level 0)
788 (js2-deflocal js2-compiler-generating-source t)
789 (js2-deflocal js2-compiler-strict-mode nil)
790 (js2-deflocal js2-compiler-report-warning-as-error nil)
791 (js2-deflocal js2-compiler-generate-observer-count nil)
792 (js2-deflocal js2-compiler-activation-names nil)
796 ;; There's a compileFunction method in Context.java - may need it.
797 (js2-deflocal js2-called-by-compile-function nil
798 "True if `js2-parse' was called by `js2-compile-function'.
799 Will only be used when we finish implementing the interpreter.")
801 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
803 ;; SKIP: node factory - we're going to just call functions directly,
804 ;; and eventually go to a unified AST format.
806 (js2-deflocal js2-nesting-of-function 0)
808 (js2-deflocal js2-recorded-identifiers nil
809 "Tracks identifiers found during parsing.")
811 (js2-deflocal js2-is-in-destructuring nil
812 "True while parsing destructuring expression.")
814 (defcustom js2-global-externs nil
815 "A list of any extern names you'd like to consider always declared.
816 This list is global and is used by all `js2-mode' files.
817 You can create buffer-local externs list using `js2-additional-externs'.
819 There is also a buffer-local variable `js2-default-externs',
820 which is initialized by default to include the Ecma-262 externs
821 and the standard browser externs. The three lists are all
822 checked during highlighting."
826 (js2-deflocal js2-default-externs nil
827 "Default external declarations.
829 These are currently only used for highlighting undeclared variables,
830 which only worries about top-level (unqualified) references.
831 As js2-mode's processing improves, we will flesh out this list.
833 The initial value is set to `js2-ecma-262-externs', unless some
834 of the `js2-include-?-externs' variables are set to t, in which
835 case the browser, Rhino and/or Node.js externs are also included.
837 See `js2-additional-externs' for more information.")
839 (defcustom js2-include-browser-externs t
840 "Non-nil to include browser externs in the master externs list.
841 If you work on JavaScript files that are not intended for browsers,
842 such as Mozilla Rhino server-side JavaScript, set this to nil.
843 See `js2-additional-externs' for more information about externs."
847 (defcustom js2-include-rhino-externs nil
848 "Non-nil to include Mozilla Rhino externs in the master externs list.
849 See `js2-additional-externs' for more information about externs."
853 (defcustom js2-include-node-externs nil
854 "Non-nil to include Node.js externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
859 (js2-deflocal js2-additional-externs nil
860 "A buffer-local list of additional external declarations.
861 It is used to decide whether variables are considered undeclared
862 for purposes of highlighting.
864 Each entry is a Lisp string. The string should be the fully qualified
865 name of an external entity. All externs should be added to this list,
866 so that as js2-mode's processing improves it can take advantage of them.
868 You may want to declare your externs in three ways.
869 First, you can add externs that are valid for all your JavaScript files.
870 You should probably do this by adding them to `js2-global-externs', which
871 is a global list used for all js2-mode files.
873 Next, you can add a function to `js2-init-hook' that adds additional
874 externs appropriate for the specific file, perhaps based on its path.
875 These should go in `js2-additional-externs', which is buffer-local.
877 Third, you can use JSLint's global declaration, as long as
878 `js2-include-jslint-globals' is non-nil, which see.
880 Finally, you can add a function to `js2-post-parse-callbacks',
881 which is called after parsing completes, and `js2-mode-ast' is bound to
882 the root of the parse tree. At this stage you can set up an AST
883 node visitor using `js2-visit-ast' and examine the parse tree
884 for specific import patterns that may imply the existence of
885 other externs, possibly tied to your build system. These should also
886 be added to `js2-additional-externs'.
888 Your post-parse callback may of course also use the simpler and
889 faster (but perhaps less robust) approach of simply scanning the
890 buffer text for your imports, using regular expressions.")
893 ;; SKIP: encoded-source
895 ;;; The following variables are per-function and should be saved/restored
896 ;;; during function parsing...
898 (js2-deflocal js2-current-script-or-fn nil)
899 (js2-deflocal js2-current-scope nil)
900 (js2-deflocal js2-nesting-of-with 0)
901 (js2-deflocal js2-label-set nil
902 "An alist mapping label names to nodes.")
904 (js2-deflocal js2-loop-set nil)
905 (js2-deflocal js2-loop-and-switch-set nil)
906 (js2-deflocal js2-has-return-value nil)
907 (js2-deflocal js2-end-flags 0)
909 ;;; ...end of per function variables
911 ;; These flags enumerate the possible ways a statement/function can
912 ;; terminate. These flags are used by endCheck() and by the Parser to
913 ;; detect inconsistent return usage.
915 ;; END_UNREACHED is reserved for code paths that are assumed to always be
916 ;; able to execute (example: throw, continue)
918 ;; END_DROPS_OFF indicates if the statement can transfer control to the
919 ;; next one. Statement such as return dont. A compound statement may have
920 ;; some branch that drops off control to the next statement.
922 ;; END_RETURNS indicates that the statement can return (without arguments)
923 ;; END_RETURNS_VALUE indicates that the statement can return a value.
925 ;; A compound statement such as
929 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
931 (defconst js2-end-unreached #x0)
932 (defconst js2-end-drops-off #x1)
933 (defconst js2-end-returns #x2)
934 (defconst js2-end-returns-value #x4)
936 ;; Rhino awkwardly passes a statementLabel parameter to the
937 ;; statementHelper() function, the main statement parser, which
938 ;; is then used by quite a few of the sub-parsers. We just make
939 ;; it a buffer-local variable and make sure it's cleaned up properly.
940 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
942 ;; Similarly, Rhino passes an inForInit boolean through about half
943 ;; the expression parsers. We use a dynamically-scoped variable,
944 ;; which makes it easier to funcall the parsers individually without
945 ;; worrying about whether they take the parameter or not.
946 (js2-deflocal js2-in-for-init nil)
947 (js2-deflocal js2-temp-name-counter 0)
948 (js2-deflocal js2-parse-stmt-count 0)
950 (defsubst js2-get-next-temp-name ()
951 (format "$%d" (incf js2-temp-name-counter)))
953 (defvar js2-parse-interruptable-p t
954 "Set this to nil to force parse to continue until finished.
955 This will mostly be useful for interpreters.")
957 (defvar js2-statements-per-pause 50
958 "Pause after this many statements to check for user input.
959 If user input is pending, stop the parse and discard the tree.
960 This makes for a smoother user experience for large files.
961 You may have to wait a second or two before the highlighting
962 and error-reporting appear, but you can always type ahead if
963 you wish. This appears to be more or less how Eclipse, IntelliJ
964 and other editors work.")
966 (js2-deflocal js2-record-comments t
967 "Instructs the scanner to record comments in `js2-scanned-comments'.")
969 (js2-deflocal js2-scanned-comments nil
970 "List of all comments from the current parse.")
972 (defcustom js2-mode-indent-inhibit-undo nil
973 "Non-nil to disable collection of Undo information when indenting lines.
974 Some users have requested this behavior. It's nil by default because
975 other Emacs modes don't work this way."
979 (defcustom js2-mode-indent-ignore-first-tab nil
980 "If non-nil, ignore first TAB keypress if we look indented properly.
981 It's fairly common for users to navigate to an already-indented line
982 and press TAB for reassurance that it's been indented. For this class
983 of users, we want the first TAB press on a line to be ignored if the
984 line is already indented to one of the precomputed alternatives.
986 This behavior is only partly implemented. If you TAB-indent a line,
987 navigate to another line, and then navigate back, it fails to clear
988 the last-indented variable, so it thinks you've already hit TAB once,
989 and performs the indent. A full solution would involve getting on the
990 point-motion hooks for the entire buffer. If we come across another
991 use cases that requires watching point motion, I'll consider doing it.
993 If you set this variable to nil, then the TAB key will always change
994 the indentation of the current line, if more than one alternative
995 indentation spot exists."
999 (defvar js2-indent-hook nil
1000 "A hook for user-defined indentation rules.
1002 Functions on this hook should expect two arguments: (LIST INDEX)
1003 The LIST argument is the list of computed indentation points for
1004 the current line. INDEX is the list index of the indentation point
1005 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1006 indent function is not going to change the current line indentation.
1008 If a hook function on this list returns a non-nil value, then
1009 `js2-bounce-indent' assumes the hook function has performed its own
1010 indentation, and will do nothing. If all hook functions on the list
1011 return nil, then `js2-bounce-indent' will use its computed indentation
1012 and reindent the line.
1014 When hook functions on this hook list are called, the variable
1015 `js2-mode-ast' may or may not be set, depending on whether the
1016 parse tree is available. If the variable is nil, you can pass a
1017 callback to `js2-mode-wait-for-parse', and your callback will be
1018 called after the new parse tree is built. This can take some time
1021 (defface js2-warning
1022 `((((class color) (background light))
1023 (:underline "orange"))
1024 (((class color) (background dark))
1025 (:underline "orange"))
1027 "Face for JavaScript warnings."
1031 `((((class color) (background light))
1032 (:foreground "red"))
1033 (((class color) (background dark))
1034 (:foreground "red"))
1035 (t (:foreground "red")))
1036 "Face for JavaScript errors."
1039 (defface js2-jsdoc-tag
1040 '((t :foreground "SlateGray"))
1041 "Face used to highlight @whatever tags in jsdoc comments."
1044 (defface js2-jsdoc-type
1045 '((t :foreground "SteelBlue"))
1046 "Face used to highlight {FooBar} types in jsdoc comments."
1049 (defface js2-jsdoc-value
1050 '((t :foreground "PeachPuff3"))
1051 "Face used to highlight tag values in jsdoc comments."
1054 (defface js2-function-param
1055 '((t :foreground "SeaGreen"))
1056 "Face used to highlight function parameters in javascript."
1059 (defface js2-function-call
1060 '((t :inherit default))
1061 "Face used to highlight function name in calls."
1064 (defface js2-instance-member
1065 '((t :foreground "DarkOrchid"))
1066 "Face used to highlight instance variables in javascript.
1067 Not currently used."
1070 (defface js2-private-member
1071 '((t :foreground "PeachPuff3"))
1072 "Face used to highlight calls to private methods in javascript.
1073 Not currently used."
1076 (defface js2-private-function-call
1077 '((t :foreground "goldenrod"))
1078 "Face used to highlight calls to private functions in javascript.
1079 Not currently used."
1082 (defface js2-jsdoc-html-tag-name
1083 '((((class color) (min-colors 88) (background light))
1084 (:foreground "rosybrown"))
1085 (((class color) (min-colors 8) (background dark))
1086 (:foreground "yellow"))
1087 (((class color) (min-colors 8) (background light))
1088 (:foreground "magenta")))
1089 "Face used to highlight jsdoc html tag names"
1092 (defface js2-jsdoc-html-tag-delimiter
1093 '((((class color) (min-colors 88) (background light))
1094 (:foreground "dark khaki"))
1095 (((class color) (min-colors 8) (background dark))
1096 (:foreground "green"))
1097 (((class color) (min-colors 8) (background light))
1098 (:foreground "green")))
1099 "Face used to highlight brackets in jsdoc html tags."
1102 (defface js2-external-variable
1103 '((t :foreground "orange"))
1104 "Face used to highlight undeclared variable identifiers.")
1106 (defcustom js2-init-hook nil
1107 "List of functions to be called after `js2-mode' or
1108 `js2-minor-mode' has initialized all variables, before parsing
1109 the buffer for the first time."
1112 :version "20130608")
1114 (defcustom js2-post-parse-callbacks nil
1115 "List of callback functions invoked after parsing finishes.
1116 Currently, the main use for this function is to add synthetic
1117 declarations to `js2-recorded-identifiers', which see."
1121 (defcustom js2-highlight-external-variables t
1122 "Non-nil to highlight undeclared variable identifiers.
1123 An undeclared variable is any variable not declared with var or let
1124 in the current scope or any lexically enclosing scope. If you use
1125 such a variable, then you are either expecting it to originate from
1126 another file, or you've got a potential bug."
1130 (defcustom js2-include-jslint-globals t
1131 "Non-nil to include the identifiers from JSLint global
1132 declaration (see http://www.jslint.com/lint.html#global) in the
1133 buffer-local externs list. See `js2-additional-externs' for more
1138 (defvar js2-mode-map
1139 (let ((map (make-sparse-keymap)))
1140 (define-key map [mouse-1] #'js2-mode-show-node)
1141 (define-key map (kbd "M-j") #'js2-line-break)
1142 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1143 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1144 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1145 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1146 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1147 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1148 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1149 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1150 (when js2-bounce-indent-p
1151 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1153 (define-key map [menu-bar javascript]
1154 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1156 (define-key map [menu-bar javascript customize-js2-mode]
1157 '(menu-item "Customize js2-mode" js2-mode-customize
1158 :help "Customize the behavior of this mode"))
1160 (define-key map [menu-bar javascript js2-force-refresh]
1161 '(menu-item "Force buffer refresh" js2-mode-reset
1162 :help "Re-parse the buffer from scratch"))
1164 (define-key map [menu-bar javascript separator-2]
1167 (define-key map [menu-bar javascript next-error]
1168 '(menu-item "Next warning or error" next-error
1169 :enabled (and js2-mode-ast
1170 (or (js2-ast-root-errors js2-mode-ast)
1171 (js2-ast-root-warnings js2-mode-ast)))
1172 :help "Move to next warning or error"))
1174 (define-key map [menu-bar javascript display-errors]
1175 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1176 :visible (not js2-mode-show-parse-errors)
1177 :help "Turn on display of warnings and errors"))
1179 (define-key map [menu-bar javascript hide-errors]
1180 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1181 :visible js2-mode-show-parse-errors
1182 :help "Turn off display of warnings and errors"))
1184 (define-key map [menu-bar javascript separator-1]
1187 (define-key map [menu-bar javascript js2-toggle-function]
1188 '(menu-item "Show/collapse element" js2-mode-toggle-element
1189 :help "Hide or show function body or comment"))
1191 (define-key map [menu-bar javascript show-comments]
1192 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1193 :visible js2-mode-comments-hidden
1194 :help "Expand all hidden block comments"))
1196 (define-key map [menu-bar javascript hide-comments]
1197 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1198 :visible (not js2-mode-comments-hidden)
1199 :help "Show block comments as /*...*/"))
1201 (define-key map [menu-bar javascript show-all-functions]
1202 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1203 :visible js2-mode-functions-hidden
1204 :help "Expand all hidden function bodies"))
1206 (define-key map [menu-bar javascript hide-all-functions]
1207 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1208 :visible (not js2-mode-functions-hidden)
1209 :help "Show {...} for all top-level function bodies"))
1212 "Keymap used in `js2-mode' buffers.")
1214 (defconst js2-mode-identifier-re "[[:alpha:]_$][[:alnum:]_$]*")
1216 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1217 "Matches a //-comment line. Must be first non-whitespace on line.
1218 First match-group is the leading whitespace.")
1220 (defvar js2-mode-hook nil)
1222 (js2-deflocal js2-mode-ast nil "Private variable.")
1223 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1224 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1225 (js2-deflocal js2-mode-parsing nil "Private variable.")
1226 (js2-deflocal js2-mode-node-overlay nil)
1228 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1229 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1231 (js2-deflocal js2-mode-fontifications nil "Private variable")
1232 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1233 (js2-deflocal js2-imenu-recorder nil "Private variable")
1234 (js2-deflocal js2-imenu-function-map nil "Private variable")
1236 (defvar js2-paragraph-start
1237 "\\(@[[:alpha:]]+\\>\\|$\\)")
1239 ;; Note that we also set a 'c-in-sws text property in html comments,
1240 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1241 (defvar js2-syntactic-ws-start
1242 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1244 (defvar js2-syntactic-ws-end
1245 "\\s \\|[\n\r/]\\|\\s!")
1247 (defvar js2-syntactic-eol
1248 (concat "\\s *\\(/\\*[^*\n\r]*"
1249 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1251 "\\(//\\|/\\*[^*\n\r]*"
1252 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1254 "Copied from `java-mode'. Needed for some cc-engine functions.")
1256 (defvar js2-comment-prefix-regexp
1259 (defvar js2-comment-start-skip
1260 "\\(//+\\|/\\*+\\)\\s *")
1262 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1263 "Non-nil to emit status messages during parsing.")
1265 (defvar js2-mode-functions-hidden nil "Private variable.")
1266 (defvar js2-mode-comments-hidden nil "Private variable.")
1268 (defvar js2-mode-syntax-table
1269 (let ((table (make-syntax-table)))
1270 (c-populate-syntax-table table)
1272 "Syntax table used in `js2-mode' buffers.")
1274 (defvar js2-mode-abbrev-table nil
1275 "Abbrev table in use in `js2-mode' buffers.")
1276 (define-abbrev-table 'js2-mode-abbrev-table ())
1278 (defvar js2-mode-pending-parse-callbacks nil
1279 "List of functions waiting to be notified that parse is finished.")
1281 (defvar js2-mode-last-indented-line -1)
1283 ;;; Localizable error and warning messages
1285 ;; Messages are copied from Rhino's Messages.properties.
1286 ;; Many of the Java-specific messages have been elided.
1287 ;; Add any js2-specific ones at the end, so we can keep
1288 ;; this file synced with changes to Rhino's.
1290 (defvar js2-message-table
1291 (make-hash-table :test 'equal :size 250)
1292 "Contains localized messages for `js2-mode'.")
1294 ;; TODO(stevey): construct this table at compile-time.
1295 (defmacro js2-msg (key &rest strings)
1296 `(puthash ,key (concat ,@strings)
1299 (defun js2-get-msg (msg-key)
1300 "Look up a localized message.
1301 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1302 the correct number of ARGS must be provided."
1303 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1304 (args (if (listp msg-key) (cdr msg-key)))
1305 (msg (gethash key js2-message-table)))
1307 (apply #'format msg args)
1308 key))) ; default to showing the key
1310 (js2-msg "msg.dup.parms"
1311 "Duplicate parameter name '%s'.")
1313 (js2-msg "msg.too.big.jump"
1314 "Program too complex: jump offset too big.")
1316 (js2-msg "msg.too.big.index"
1317 "Program too complex: internal index exceeds 64K limit.")
1319 (js2-msg "msg.while.compiling.fn"
1320 "Encountered code generation error while compiling function '%s': %s")
1322 (js2-msg "msg.while.compiling.script"
1323 "Encountered code generation error while compiling script: %s")
1326 (js2-msg "msg.ctor.not.found"
1327 "Constructor for '%s' not found.")
1329 (js2-msg "msg.not.ctor"
1330 "'%s' is not a constructor.")
1333 (js2-msg "msg.varargs.ctor"
1334 "Method or constructor '%s' must be static "
1335 "with the signature (Context cx, Object[] args, "
1336 "Function ctorObj, boolean inNewExpr) "
1337 "to define a variable arguments constructor.")
1339 (js2-msg "msg.varargs.fun"
1340 "Method '%s' must be static with the signature "
1341 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1342 "to define a variable arguments function.")
1344 (js2-msg "msg.incompat.call"
1345 "Method '%s' called on incompatible object.")
1347 (js2-msg "msg.bad.parms"
1348 "Unsupported parameter type '%s' in method '%s'.")
1350 (js2-msg "msg.bad.method.return"
1351 "Unsupported return type '%s' in method '%s'.")
1353 (js2-msg "msg.bad.ctor.return"
1354 "Construction of objects of type '%s' is not supported.")
1356 (js2-msg "msg.no.overload"
1357 "Method '%s' occurs multiple times in class '%s'.")
1359 (js2-msg "msg.method.not.found"
1360 "Method '%s' not found in '%s'.")
1364 (js2-msg "msg.bad.for.in.lhs"
1365 "Invalid left-hand side of for..in loop.")
1367 (js2-msg "msg.mult.index"
1368 "Only one variable allowed in for..in loop.")
1370 (js2-msg "msg.bad.for.in.destruct"
1371 "Left hand side of for..in loop must be an array of "
1372 "length 2 to accept key/value pair.")
1374 (js2-msg "msg.cant.convert"
1375 "Can't convert to type '%s'.")
1377 (js2-msg "msg.bad.assign.left"
1378 "Invalid assignment left-hand side.")
1380 (js2-msg "msg.bad.decr"
1381 "Invalid decerement operand.")
1383 (js2-msg "msg.bad.incr"
1384 "Invalid increment operand.")
1386 (js2-msg "msg.bad.yield"
1387 "yield must be in a function.")
1389 (js2-msg "msg.yield.parenthesized"
1390 "yield expression must be parenthesized.")
1393 (js2-msg "msg.cant.call.indirect"
1394 "Function '%s' must be called directly, and not by way of a "
1395 "function of another name.")
1397 (js2-msg "msg.eval.nonstring"
1398 "Calling eval() with anything other than a primitive "
1399 "string value will simply return the value. "
1400 "Is this what you intended?")
1402 (js2-msg "msg.eval.nonstring.strict"
1403 "Calling eval() with anything other than a primitive "
1404 "string value is not allowed in strict mode.")
1406 (js2-msg "msg.bad.destruct.op"
1407 "Invalid destructuring assignment operator")
1410 (js2-msg "msg.only.from.new"
1411 "'%s' may only be invoked from a `new' expression.")
1413 (js2-msg "msg.deprec.ctor"
1414 "The '%s' constructor is deprecated.")
1417 (js2-msg "msg.no.function.ref.found"
1418 "no source found to decompile function reference %s")
1420 (js2-msg "msg.arg.isnt.array"
1421 "second argument to Function.prototype.apply must be an array")
1424 (js2-msg "msg.bad.esc.mask"
1425 "invalid string escape mask")
1428 (js2-msg "msg.bad.quant"
1429 "Invalid quantifier %s")
1431 (js2-msg "msg.overlarge.backref"
1432 "Overly large back reference %s")
1434 (js2-msg "msg.overlarge.min"
1435 "Overly large minimum %s")
1437 (js2-msg "msg.overlarge.max"
1438 "Overly large maximum %s")
1440 (js2-msg "msg.zero.quant"
1441 "Zero quantifier %s")
1443 (js2-msg "msg.max.lt.min"
1444 "Maximum %s less than minimum")
1446 (js2-msg "msg.unterm.quant"
1447 "Unterminated quantifier %s")
1449 (js2-msg "msg.unterm.paren"
1450 "Unterminated parenthetical %s")
1452 (js2-msg "msg.unterm.class"
1453 "Unterminated character class %s")
1455 (js2-msg "msg.bad.range"
1456 "Invalid range in character class.")
1458 (js2-msg "msg.trail.backslash"
1459 "Trailing \\ in regular expression.")
1461 (js2-msg "msg.re.unmatched.right.paren"
1462 "unmatched ) in regular expression.")
1464 (js2-msg "msg.no.regexp"
1465 "Regular expressions are not available.")
1467 (js2-msg "msg.bad.backref"
1468 "back-reference exceeds number of capturing parentheses.")
1470 (js2-msg "msg.bad.regexp.compile"
1471 "Only one argument may be specified if the first "
1472 "argument to RegExp.prototype.compile is a RegExp object.")
1475 (js2-msg "msg.got.syntax.errors"
1476 "Compilation produced %s syntax errors.")
1478 (js2-msg "msg.var.redecl"
1479 "TypeError: redeclaration of var %s.")
1481 (js2-msg "msg.const.redecl"
1482 "TypeError: redeclaration of const %s.")
1484 (js2-msg "msg.let.redecl"
1485 "TypeError: redeclaration of variable %s.")
1487 (js2-msg "msg.parm.redecl"
1488 "TypeError: redeclaration of formal parameter %s.")
1490 (js2-msg "msg.fn.redecl"
1491 "TypeError: redeclaration of function %s.")
1493 (js2-msg "msg.let.decl.not.in.block"
1494 "SyntaxError: let declaration not directly within block")
1497 (js2-msg "msg.dup.label"
1500 (js2-msg "msg.undef.label"
1503 (js2-msg "msg.bad.break"
1504 "unlabelled break must be inside loop or switch")
1506 (js2-msg "msg.continue.outside"
1507 "continue must be inside loop")
1509 (js2-msg "msg.continue.nonloop"
1510 "continue can only use labels of iteration statements")
1512 (js2-msg "msg.bad.throw.eol"
1513 "Line terminator is not allowed between the throw "
1514 "keyword and throw expression.")
1516 (js2-msg "msg.unnamed.function.stmt" ; added by js2-mode
1517 "function statement requires a name")
1519 (js2-msg "msg.no.paren.parms"
1520 "missing ( before function parameters.")
1522 (js2-msg "msg.no.parm"
1523 "missing formal parameter")
1525 (js2-msg "msg.no.paren.after.parms"
1526 "missing ) after formal parameters")
1528 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1529 "parameter without default follows parameter with default")
1531 (js2-msg "msg.param.after.rest" ; added by js2-mode
1532 "parameter after rest parameter")
1534 (js2-msg "msg.bad.arrow.args" ; added by js2-mode
1535 "invalid arrow-function arguments (parentheses around the arrow-function may help)")
1537 (js2-msg "msg.no.brace.body"
1538 "missing '{' before function body")
1540 (js2-msg "msg.no.brace.after.body"
1541 "missing } after function body")
1543 (js2-msg "msg.no.paren.cond"
1544 "missing ( before condition")
1546 (js2-msg "msg.no.paren.after.cond"
1547 "missing ) after condition")
1549 (js2-msg "msg.no.semi.stmt"
1550 "missing ; before statement")
1552 (js2-msg "msg.missing.semi"
1553 "missing ; after statement")
1555 (js2-msg "msg.no.name.after.dot"
1556 "missing name after . operator")
1558 (js2-msg "msg.no.name.after.coloncolon"
1559 "missing name after :: operator")
1561 (js2-msg "msg.no.name.after.dotdot"
1562 "missing name after .. operator")
1564 (js2-msg "msg.no.name.after.xmlAttr"
1565 "missing name after .@")
1567 (js2-msg "msg.no.bracket.index"
1568 "missing ] in index expression")
1570 (js2-msg "msg.no.paren.switch"
1571 "missing ( before switch expression")
1573 (js2-msg "msg.no.paren.after.switch"
1574 "missing ) after switch expression")
1576 (js2-msg "msg.no.brace.switch"
1577 "missing '{' before switch body")
1579 (js2-msg "msg.bad.switch"
1580 "invalid switch statement")
1582 (js2-msg "msg.no.colon.case"
1583 "missing : after case expression")
1585 (js2-msg "msg.double.switch.default"
1586 "double default label in the switch statement")
1588 (js2-msg "msg.no.while.do"
1589 "missing while after do-loop body")
1591 (js2-msg "msg.no.paren.for"
1592 "missing ( after for")
1594 (js2-msg "msg.no.semi.for"
1595 "missing ; after for-loop initializer")
1597 (js2-msg "msg.no.semi.for.cond"
1598 "missing ; after for-loop condition")
1600 (js2-msg "msg.in.after.for.name"
1601 "missing in or of after for")
1603 (js2-msg "msg.no.paren.for.ctrl"
1604 "missing ) after for-loop control")
1606 (js2-msg "msg.no.paren.with"
1607 "missing ( before with-statement object")
1609 (js2-msg "msg.no.paren.after.with"
1610 "missing ) after with-statement object")
1612 (js2-msg "msg.no.paren.after.let"
1613 "missing ( after let")
1615 (js2-msg "msg.no.paren.let"
1616 "missing ) after variable list")
1618 (js2-msg "msg.no.curly.let"
1619 "missing } after let statement")
1621 (js2-msg "msg.bad.return"
1624 (js2-msg "msg.no.brace.block"
1625 "missing } in compound statement")
1627 (js2-msg "msg.bad.label"
1630 (js2-msg "msg.bad.var"
1631 "missing variable name")
1633 (js2-msg "msg.bad.var.init"
1634 "invalid variable initialization")
1636 (js2-msg "msg.no.colon.cond"
1637 "missing : in conditional expression")
1639 (js2-msg "msg.no.paren.arg"
1640 "missing ) after argument list")
1642 (js2-msg "msg.no.bracket.arg"
1643 "missing ] after element list")
1645 (js2-msg "msg.bad.prop"
1646 "invalid property id")
1648 (js2-msg "msg.no.colon.prop"
1649 "missing : after property id")
1651 (js2-msg "msg.no.brace.prop"
1652 "missing } after property list")
1654 (js2-msg "msg.no.paren"
1655 "missing ) in parenthetical")
1657 (js2-msg "msg.reserved.id"
1658 "'%s' is a reserved identifier")
1660 (js2-msg "msg.no.paren.catch"
1661 "missing ( before catch-block condition")
1663 (js2-msg "msg.bad.catchcond"
1664 "invalid catch block condition")
1666 (js2-msg "msg.catch.unreachable"
1667 "any catch clauses following an unqualified catch are unreachable")
1669 (js2-msg "msg.no.brace.try"
1670 "missing '{' before try block")
1672 (js2-msg "msg.no.brace.catchblock"
1673 "missing '{' before catch-block body")
1675 (js2-msg "msg.try.no.catchfinally"
1676 "'try' without 'catch' or 'finally'")
1678 (js2-msg "msg.no.return.value"
1679 "function %s does not always return a value")
1681 (js2-msg "msg.anon.no.return.value"
1682 "anonymous function does not always return a value")
1684 (js2-msg "msg.return.inconsistent"
1685 "return statement is inconsistent with previous usage")
1687 (js2-msg "msg.generator.returns"
1688 "TypeError: legacy generator function '%s' returns a value")
1690 (js2-msg "msg.anon.generator.returns"
1691 "TypeError: anonymous legacy generator function returns a value")
1693 (js2-msg "msg.syntax"
1696 (js2-msg "msg.unexpected.eof"
1697 "Unexpected end of file")
1699 (js2-msg "msg.XML.bad.form"
1700 "illegally formed XML syntax")
1702 (js2-msg "msg.XML.not.available"
1703 "XML runtime not available")
1705 (js2-msg "msg.too.deep.parser.recursion"
1706 "Too deep recursion while parsing")
1708 (js2-msg "msg.no.side.effects"
1709 "Code has no side effects")
1711 (js2-msg "msg.extra.trailing.comma"
1712 "Trailing comma is not supported in some browsers")
1714 (js2-msg "msg.array.trailing.comma"
1715 "Trailing comma yields different behavior across browsers")
1717 (js2-msg "msg.equal.as.assign"
1718 (concat "Test for equality (==) mistyped as assignment (=)?"
1719 " (parenthesize to suppress warning)"))
1721 (js2-msg "msg.var.hides.arg"
1722 "Variable %s hides argument")
1724 (js2-msg "msg.destruct.assign.no.init"
1725 "Missing = in destructuring declaration")
1728 (js2-msg "msg.no.properties"
1729 "%s has no properties.")
1731 (js2-msg "msg.invalid.iterator"
1732 "Invalid iterator value")
1734 (js2-msg "msg.iterator.primitive"
1735 "__iterator__ returned a primitive value")
1737 (js2-msg "msg.assn.create.strict"
1738 "Assignment to undeclared variable %s")
1740 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1741 "Undeclared variable or function '%s'")
1743 (js2-msg "msg.ref.undefined.prop"
1744 "Reference to undefined property '%s'")
1746 (js2-msg "msg.prop.not.found"
1747 "Property %s not found.")
1749 (js2-msg "msg.invalid.type"
1750 "Invalid JavaScript value of type %s")
1752 (js2-msg "msg.primitive.expected"
1753 "Primitive type expected (had %s instead)")
1755 (js2-msg "msg.namespace.expected"
1756 "Namespace object expected to left of :: (found %s instead)")
1758 (js2-msg "msg.null.to.object"
1759 "Cannot convert null to an object.")
1761 (js2-msg "msg.undef.to.object"
1762 "Cannot convert undefined to an object.")
1764 (js2-msg "msg.cyclic.value"
1765 "Cyclic %s value not allowed.")
1767 (js2-msg "msg.is.not.defined"
1768 "'%s' is not defined.")
1770 (js2-msg "msg.undef.prop.read"
1771 "Cannot read property '%s' from %s")
1773 (js2-msg "msg.undef.prop.write"
1774 "Cannot set property '%s' of %s to '%s'")
1776 (js2-msg "msg.undef.prop.delete"
1777 "Cannot delete property '%s' of %s")
1779 (js2-msg "msg.undef.method.call"
1780 "Cannot call method '%s' of %s")
1782 (js2-msg "msg.undef.with"
1783 "Cannot apply 'with' to %s")
1785 (js2-msg "msg.isnt.function"
1786 "%s is not a function, it is %s.")
1788 (js2-msg "msg.isnt.function.in"
1789 "Cannot call property %s in object %s. "
1790 "It is not a function, it is '%s'.")
1792 (js2-msg "msg.function.not.found"
1793 "Cannot find function %s.")
1795 (js2-msg "msg.function.not.found.in"
1796 "Cannot find function %s in object %s.")
1798 (js2-msg "msg.isnt.xml.object"
1799 "%s is not an xml object.")
1801 (js2-msg "msg.no.ref.to.get"
1802 "%s is not a reference to read reference value.")
1804 (js2-msg "msg.no.ref.to.set"
1805 "%s is not a reference to set reference value to %s.")
1807 (js2-msg "msg.no.ref.from.function"
1808 "Function %s can not be used as the left-hand "
1809 "side of assignment or as an operand of ++ or -- operator.")
1811 (js2-msg "msg.bad.default.value"
1812 "Object's getDefaultValue() method returned an object.")
1814 (js2-msg "msg.instanceof.not.object"
1815 "Can't use instanceof on a non-object.")
1817 (js2-msg "msg.instanceof.bad.prototype"
1818 "'prototype' property of %s is not an object.")
1820 (js2-msg "msg.bad.radix"
1821 "illegal radix %s.")
1824 (js2-msg "msg.default.value"
1825 "Cannot find default value for object.")
1827 (js2-msg "msg.zero.arg.ctor"
1828 "Cannot load class '%s' which has no zero-parameter constructor.")
1830 (js2-msg "msg.ctor.multiple.parms"
1831 "Can't define constructor or class %s since more than "
1832 "one constructor has multiple parameters.")
1834 (js2-msg "msg.extend.scriptable"
1835 "%s must extend ScriptableObject in order to define property %s.")
1837 (js2-msg "msg.bad.getter.parms"
1838 "In order to define a property, getter %s must have zero "
1839 "parameters or a single ScriptableObject parameter.")
1841 (js2-msg "msg.obj.getter.parms"
1842 "Expected static or delegated getter %s to take "
1843 "a ScriptableObject parameter.")
1845 (js2-msg "msg.getter.static"
1846 "Getter and setter must both be static or neither be static.")
1848 (js2-msg "msg.setter.return"
1849 "Setter must have void return type: %s")
1851 (js2-msg "msg.setter2.parms"
1852 "Two-parameter setter must take a ScriptableObject as "
1853 "its first parameter.")
1855 (js2-msg "msg.setter1.parms"
1856 "Expected single parameter setter for %s")
1858 (js2-msg "msg.setter2.expected"
1859 "Expected static or delegated setter %s to take two parameters.")
1861 (js2-msg "msg.setter.parms"
1862 "Expected either one or two parameters for setter.")
1864 (js2-msg "msg.setter.bad.type"
1865 "Unsupported parameter type '%s' in setter '%s'.")
1867 (js2-msg "msg.add.sealed"
1868 "Cannot add a property to a sealed object: %s.")
1870 (js2-msg "msg.remove.sealed"
1871 "Cannot remove a property from a sealed object: %s.")
1873 (js2-msg "msg.modify.sealed"
1874 "Cannot modify a property of a sealed object: %s.")
1876 (js2-msg "msg.modify.readonly"
1877 "Cannot modify readonly property: %s.")
1880 (js2-msg "msg.missing.exponent"
1883 (js2-msg "msg.caught.nfe"
1884 "number format error")
1886 (js2-msg "msg.unterminated.string.lit"
1887 "unterminated string literal")
1889 (js2-msg "msg.unterminated.comment"
1890 "unterminated comment")
1892 (js2-msg "msg.unterminated.re.lit"
1893 "unterminated regular expression literal")
1895 (js2-msg "msg.invalid.re.flag"
1896 "invalid flag after regular expression")
1898 (js2-msg "msg.no.re.input.for"
1901 (js2-msg "msg.illegal.character"
1902 "illegal character")
1904 (js2-msg "msg.invalid.escape"
1905 "invalid Unicode escape sequence")
1907 (js2-msg "msg.bad.namespace"
1908 "not a valid default namespace statement. "
1909 "Syntax is: default xml namespace = EXPRESSION;")
1911 ;; TokensStream warnings
1912 (js2-msg "msg.bad.octal.literal"
1913 "illegal octal literal digit %s; "
1914 "interpreting it as a decimal digit")
1916 (js2-msg "msg.missing.hex.digits"
1917 "missing hexadecimal digits after '0x'")
1919 (js2-msg "msg.missing.binary.digits"
1920 "missing binary digits after '0b'")
1922 (js2-msg "msg.missing.octal.digits"
1923 "missing octal digits after '0o'")
1925 (js2-msg "msg.script.is.not.constructor"
1926 "Script objects are not constructors.")
1929 (js2-msg "msg.arraylength.bad"
1930 "Inappropriate array length.")
1933 (js2-msg "msg.arraylength.too.big"
1934 "Array length %s exceeds supported capacity limit.")
1937 (js2-msg "msg.bad.uri"
1938 "Malformed URI sequence.")
1941 (js2-msg "msg.bad.precision"
1942 "Precision %s out of range.")
1945 (js2-msg "msg.send.newborn"
1946 "Attempt to send value to newborn generator")
1948 (js2-msg "msg.already.exec.gen"
1949 "Already executing generator")
1951 (js2-msg "msg.StopIteration.invalid"
1952 "StopIteration may not be changed to an arbitrary object.")
1955 (js2-msg "msg.yield.closing"
1956 "Yield from closing generator")
1959 (js2-msg "msg.missing.computed.rb" ; added by js2-mode
1960 "missing ']' after computed property expression")
1964 (defconst js2-ti-max-lookahead 2)
1965 (defconst js2-ti-ntokens (1+ js2-ti-max-lookahead))
1967 ;; Have to call `js2-init-scanner' to initialize the values.
1968 (js2-deflocal js2-ti-tokens nil)
1969 (js2-deflocal js2-ti-tokens-cursor nil)
1970 (js2-deflocal js2-ti-lookahead nil)
1972 (defun js2-new-token (offset)
1973 (let ((token (make-js2-token (+ offset js2-ts-cursor))))
1974 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
1975 (aset js2-ti-tokens js2-ti-tokens-cursor token)
1978 (defsubst js2-current-token ()
1979 (aref js2-ti-tokens js2-ti-tokens-cursor))
1981 (defsubst js2-current-token-string ()
1982 (js2-token-string (js2-current-token)))
1984 (defsubst js2-current-token-type ()
1985 (js2-token-type (js2-current-token)))
1987 (defsubst js2-current-token-beg ()
1988 (js2-token-beg (js2-current-token)))
1990 (defsubst js2-current-token-end ()
1991 (js2-token-end (js2-current-token)))
1993 (defun js2-current-token-len ()
1994 (let ((token (js2-current-token)))
1995 (- (js2-token-end token)
1996 (js2-token-beg token))))
1998 (defun js2-ts-seek (state)
1999 (setq js2-ts-lineno (js2-ts-state-lineno state)
2000 js2-ts-cursor (js2-ts-state-cursor state)
2001 js2-ti-tokens (js2-ts-state-tokens state)
2002 js2-ti-tokens-cursor (js2-ts-state-tokens-cursor state)
2003 js2-ti-lookahead (js2-ts-state-lookahead state)))
2007 (defun js2-delete-if (predicate list)
2008 "Remove all items satisfying PREDICATE in LIST."
2009 (loop for item in list
2010 if (not (funcall predicate item))
2013 (defun js2-position (element list)
2014 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2015 Returns nil if element is not found in the list."
2018 (while (and list (not found))
2019 (if (eq element (car list))
2021 (setq count (1+ count)
2025 (defun js2-find-if (predicate list)
2026 "Find first item satisfying PREDICATE in LIST."
2028 (while (and list (not result))
2029 (if (funcall predicate (car list))
2030 (setq result (car list)))
2031 (setq list (cdr list)))
2034 (defmacro js2-time (form)
2035 "Evaluate FORM, discard result, and return elapsed time in sec."
2037 (let ((beg (make-symbol "--js2-time-beg--"))
2038 (delta (make-symbol "--js2-time-end--")))
2039 `(let ((,beg (current-time))
2042 (/ (truncate (* (- (float-time (current-time))
2047 (defsubst js2-same-line (pos)
2048 "Return t if POS is on the same line as current point."
2049 (and (>= pos (point-at-bol))
2050 (<= pos (point-at-eol))))
2052 (defun js2-code-bug ()
2053 "Signal an error when we encounter an unexpected code path."
2054 (error "failed assertion"))
2056 (defsubst js2-record-text-property (beg end prop value)
2057 "Record a text property to set when parsing finishes."
2058 (push (list beg end prop value) js2-mode-deferred-properties))
2060 ;; I'd like to associate errors with nodes, but for now the
2061 ;; easiest thing to do is get the context info from the last token.
2062 (defun js2-record-parse-error (msg &optional arg pos len)
2063 (push (list (list msg arg)
2064 (or pos (js2-current-token-beg))
2065 (or len (js2-current-token-len)))
2068 (defun js2-report-error (msg &optional msg-arg pos len)
2069 "Signal a syntax error or record a parse error."
2070 (if js2-recover-from-parse-errors
2071 (js2-record-parse-error msg msg-arg pos len)
2072 (signal 'js2-syntax-error
2076 (goto-char js2-ts-cursor)
2080 (defun js2-report-warning (msg &optional msg-arg pos len face)
2081 (if js2-compiler-report-warning-as-error
2082 (js2-report-error msg msg-arg pos len)
2083 (push (list (list msg msg-arg)
2084 (or pos (js2-current-token-beg))
2085 (or len (js2-current-token-len))
2087 js2-parsed-warnings)))
2089 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2090 (if js2-compiler-strict-mode
2091 (js2-report-warning msg-id msg-arg beg
2092 (and beg end (- end beg)))))
2094 (put 'js2-syntax-error 'error-conditions
2095 '(error syntax-error js2-syntax-error))
2096 (put 'js2-syntax-error 'error-message "Syntax error")
2098 (put 'js2-parse-error 'error-conditions
2099 '(error parse-error js2-parse-error))
2100 (put 'js2-parse-error 'error-message "Parse error")
2102 (defmacro js2-clear-flag (flags flag)
2103 `(setq ,flags (logand ,flags (lognot ,flag))))
2105 (defmacro js2-set-flag (flags flag)
2106 "Logical-or FLAG into FLAGS."
2107 `(setq ,flags (logior ,flags ,flag)))
2109 (defsubst js2-flag-set-p (flags flag)
2110 (/= 0 (logand flags flag)))
2112 (defsubst js2-flag-not-set-p (flags flag)
2113 (zerop (logand flags flag)))
2115 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2116 "Evaluate BODY with the _ character set to be word-syntax."
2117 (declare (indent 0) (debug t))
2118 (let ((old-syntax (make-symbol "old-syntax")))
2119 `(let ((,old-syntax (string (char-syntax ?_))))
2122 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2124 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2126 ;;; AST struct and function definitions
2128 ;; flags for ast node property 'member-type (used for e4x operators)
2129 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2130 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2131 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2133 (defsubst js2-relpos (pos anchor)
2134 "Convert POS to be relative to ANCHOR.
2135 If POS is nil, returns nil."
2136 (and pos (- pos anchor)))
2138 (defun js2-make-pad (indent)
2141 (make-string (* indent js2-basic-offset) ? )))
2143 (defun js2-visit-ast (node callback)
2144 "Visit every node in ast NODE with visitor CALLBACK.
2146 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2147 called twice: once to visit the node, and again after all the node's
2148 children have been processed. The END-P argument is nil on the first
2149 call and non-nil on the second call. The return value of the callback
2150 affects the traversal: if non-nil, the children of NODE are processed.
2151 If the callback returns nil, or if the node has no children, then the
2152 callback is called immediately with a non-nil END-P argument.
2154 The node traversal is approximately lexical-order, although there
2155 are currently no guarantees around this."
2157 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2159 (when (funcall callback node nil)
2162 ((eq vfunc 'js2-visit-none)
2163 nil) ; don't even bother calling it
2164 ;; Each AST node type has to define a `js2-visitor' function
2165 ;; that takes a node and a callback, and calls `js2-visit-ast'
2166 ;; on each child of the node.
2168 (funcall vfunc node callback))
2170 (error "%s does not define a visitor-traversal function"
2172 ;; call the end-visit
2173 (funcall callback node t))))
2175 (defstruct (js2-node
2176 (:constructor nil)) ; abstract
2177 "Base AST node type."
2178 (type -1) ; token type
2179 (pos -1) ; start position of this AST node in parsed input
2180 (len 1) ; num characters spanned by the node
2181 props ; optional node property list (an alist)
2182 parent) ; link to parent node; null for root
2184 (defsubst js2-node-get-prop (node prop &optional default)
2185 (or (cadr (assoc prop (js2-node-props node))) default))
2187 (defsubst js2-node-set-prop (node prop value)
2188 (setf (js2-node-props node)
2189 (cons (list prop value) (js2-node-props node))))
2191 (defun js2-fixup-starts (n nodes)
2192 "Adjust the start positions of NODES to be relative to N.
2193 Any node in the list may be nil, for convenience."
2194 (dolist (node nodes)
2196 (setf (js2-node-pos node) (- (js2-node-pos node)
2197 (js2-node-pos n))))))
2199 (defun js2-node-add-children (parent &rest nodes)
2200 "Set parent node of NODES to PARENT, and return PARENT.
2201 Does nothing if we're not recording parent links.
2202 If any given node in NODES is nil, doesn't record that link."
2203 (js2-fixup-starts parent nodes)
2204 (dolist (node nodes)
2206 (setf (js2-node-parent node) parent))))
2208 ;; Non-recursive since it's called a frightening number of times.
2209 (defun js2-node-abs-pos (n)
2210 (let ((pos (js2-node-pos n)))
2211 (while (setq n (js2-node-parent n))
2212 (setq pos (+ pos (js2-node-pos n))))
2215 (defsubst js2-node-abs-end (n)
2216 "Return absolute buffer position of end of N."
2217 (+ (js2-node-abs-pos n) (js2-node-len n)))
2219 ;; It's important to make sure block nodes have a Lisp list for the
2220 ;; child nodes, to limit printing recursion depth in an AST that
2221 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2222 ;; a sufficiently large vector tree.
2224 (defstruct (js2-block-node
2227 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2228 (pos (js2-current-token-beg))
2232 "A block of statements."
2233 kids) ; a Lisp list of the child statement nodes
2235 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2236 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2238 (defun js2-visit-block (ast callback)
2239 "Visit the `js2-block-node' children of AST."
2240 (dolist (kid (js2-block-node-kids ast))
2241 (js2-visit-ast kid callback)))
2243 (defun js2-print-block (n i)
2244 (let ((pad (js2-make-pad i)))
2246 (dolist (kid (js2-block-node-kids n))
2247 (js2-print-ast kid (1+ i)))
2250 (defstruct (js2-scope
2251 (:include js2-block-node)
2253 (:constructor make-js2-scope (&key (type js2-BLOCK)
2254 (pos (js2-current-token-beg))
2257 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2258 ;; I don't have one of those handy, so I'll use an alist for now.
2259 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2260 ;; and is much lighter-weight to construct (both CPU and mem).
2261 ;; The keys are interned strings (symbols) for faster lookup.
2262 ;; Should switch to hybrid alist/hashtable eventually.
2263 symbol-table ; an alist of (symbol . js2-symbol)
2264 parent-scope ; a `js2-scope'
2265 top) ; top-level `js2-scope' (script/function)
2267 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2268 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2270 (defun js2-node-get-enclosing-scope (node)
2271 "Return the innermost `js2-scope' node surrounding NODE.
2272 Returns nil if there is no enclosing scope node."
2273 (let ((parent (js2-node-parent node)))
2274 (while (not (js2-scope-p parent))
2275 (setq parent (js2-node-parent parent)))
2278 (defun js2-get-defining-scope (scope name)
2279 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2280 Returns `js2-scope' in which NAME is defined, or nil if not found."
2281 (let ((sym (if (symbolp name)
2287 (while (and scope continue)
2288 (if (and (setq table (js2-scope-symbol-table scope))
2292 (setq scope (js2-scope-parent-scope scope))))
2295 (defun js2-scope-get-symbol (scope name)
2296 "Return symbol table entry for NAME in SCOPE.
2297 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2298 (and (js2-scope-symbol-table scope)
2299 (cdr (assq (if (symbolp name)
2302 (js2-scope-symbol-table scope)))))
2304 (defun js2-scope-put-symbol (scope name symbol)
2305 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2306 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2307 (let* ((table (js2-scope-symbol-table scope))
2308 (sym (if (symbolp name) name (intern name)))
2309 (entry (assq sym table)))
2311 (setcdr entry symbol)
2312 (push (cons sym symbol)
2313 (js2-scope-symbol-table scope)))))
2315 (defstruct (js2-symbol
2317 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2318 "A symbol table entry."
2319 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2320 ;; js2-LET, or js2-CONST
2323 ast-node) ; a `js2-node'
2325 (defstruct (js2-error-node
2327 (:constructor nil) ; silence emacs21 byte-compiler
2328 (:constructor make-js2-error-node (&key (type js2-ERROR)
2329 (pos (js2-current-token-beg))
2331 "AST node representing a parse error.")
2333 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2334 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2336 (defstruct (js2-script-node
2337 (:include js2-scope)
2339 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2340 (pos (js2-current-token-beg))
2342 ;; FIXME: What are those?
2345 functions ; Lisp list of nested functions
2346 regexps ; Lisp list of (string . flags)
2347 symbols ; alist (every symbol gets unique index)
2349 var-names ; vector of string names
2350 consts ; bool-vector matching var-decls
2351 (temp-number 0)) ; for generating temp variables
2353 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2354 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2356 (defun js2-print-script (node indent)
2357 (dolist (kid (js2-block-node-kids node))
2358 (js2-print-ast kid indent)))
2360 (defstruct (js2-ast-root
2361 (:include js2-script-node)
2363 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2364 (pos (js2-current-token-beg))
2367 "The root node of a js2 AST."
2368 buffer ; the source buffer from which the code was parsed
2369 comments ; a Lisp list of comments, ordered by start position
2370 errors ; a Lisp list of errors found during parsing
2371 warnings ; a Lisp list of warnings found during parsing
2372 node-count) ; number of nodes in the tree, including the root
2374 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2375 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2377 (defun js2-visit-ast-root (ast callback)
2378 (dolist (kid (js2-ast-root-kids ast))
2379 (js2-visit-ast kid callback))
2380 (dolist (comment (js2-ast-root-comments ast))
2381 (js2-visit-ast comment callback)))
2383 (defstruct (js2-comment-node
2386 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2387 (pos (js2-current-token-beg))
2390 format) ; 'line, 'block, 'jsdoc or 'html
2392 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2393 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2395 (defun js2-print-comment (n i)
2396 ;; We really ought to link end-of-line comments to their nodes.
2397 ;; Or maybe we could add a new comment type, 'endline.
2398 (insert (js2-make-pad i)
2399 (js2-node-string n)))
2401 (defstruct (js2-expr-stmt-node
2404 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2408 "An expression statement."
2411 (defsubst js2-expr-stmt-node-set-has-result (node)
2412 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2413 (setf (js2-node-type node) js2-EXPR_RESULT))
2415 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2416 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2418 (defun js2-visit-expr-stmt-node (n v)
2419 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2421 (defun js2-print-expr-stmt-node (n indent)
2422 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2425 (defstruct (js2-loop-node
2426 (:include js2-scope)
2428 "Abstract supertype of loop nodes."
2429 body ; a `js2-block-node'
2430 lp ; position of left-paren, nil if omitted
2431 rp) ; position of right-paren, nil if omitted
2433 (defstruct (js2-do-node
2434 (:include js2-loop-node)
2436 (:constructor make-js2-do-node (&key (type js2-DO)
2437 (pos (js2-current-token-beg))
2444 "AST node for do-loop."
2445 condition ; while (expression)
2446 while-pos) ; buffer position of 'while' keyword
2448 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2449 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2451 (defun js2-visit-do-node (n v)
2452 (js2-visit-ast (js2-do-node-body n) v)
2453 (js2-visit-ast (js2-do-node-condition n) v))
2455 (defun js2-print-do-node (n i)
2456 (let ((pad (js2-make-pad i)))
2457 (insert pad "do {\n")
2458 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2459 (js2-print-ast kid (1+ i)))
2460 (insert pad "} while (")
2461 (js2-print-ast (js2-do-node-condition n) 0)
2464 (defstruct (js2-while-node
2465 (:include js2-loop-node)
2467 (:constructor make-js2-while-node (&key (type js2-WHILE)
2468 (pos (js2-current-token-beg))
2472 "AST node for while-loop."
2473 condition) ; while-condition
2475 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2476 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2478 (defun js2-visit-while-node (n v)
2479 (js2-visit-ast (js2-while-node-condition n) v)
2480 (js2-visit-ast (js2-while-node-body n) v))
2482 (defun js2-print-while-node (n i)
2483 (let ((pad (js2-make-pad i)))
2484 (insert pad "while (")
2485 (js2-print-ast (js2-while-node-condition n) 0)
2487 (js2-print-body (js2-while-node-body n) (1+ i))
2488 (insert pad "}\n")))
2490 (defstruct (js2-for-node
2491 (:include js2-loop-node)
2493 (:constructor make-js2-for-node (&key (type js2-FOR)
2498 "AST node for a C-style for-loop."
2499 init ; initialization expression
2500 condition ; loop condition
2501 update) ; update clause
2503 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2504 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2506 (defun js2-visit-for-node (n v)
2507 (js2-visit-ast (js2-for-node-init n) v)
2508 (js2-visit-ast (js2-for-node-condition n) v)
2509 (js2-visit-ast (js2-for-node-update n) v)
2510 (js2-visit-ast (js2-for-node-body n) v))
2512 (defun js2-print-for-node (n i)
2513 (let ((pad (js2-make-pad i)))
2514 (insert pad "for (")
2515 (js2-print-ast (js2-for-node-init n) 0)
2517 (js2-print-ast (js2-for-node-condition n) 0)
2519 (js2-print-ast (js2-for-node-update n) 0)
2521 (js2-print-body (js2-for-node-body n) (1+ i))
2522 (insert pad "}\n")))
2524 (defstruct (js2-for-in-node
2525 (:include js2-loop-node)
2527 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2536 "AST node for a for..in loop."
2537 iterator ; [var] foo in ...
2538 object ; object over which we're iterating
2539 in-pos ; buffer position of 'in' keyword
2540 each-pos ; buffer position of 'each' keyword, if foreach-p
2541 foreach-p ; t if it's a for-each loop
2542 forof-p) ; t if it's a for-of loop
2544 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2545 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2547 (defun js2-visit-for-in-node (n v)
2548 (js2-visit-ast (js2-for-in-node-iterator n) v)
2549 (js2-visit-ast (js2-for-in-node-object n) v)
2550 (js2-visit-ast (js2-for-in-node-body n) v))
2552 (defun js2-print-for-in-node (n i)
2553 (let ((pad (js2-make-pad i))
2554 (foreach (js2-for-in-node-foreach-p n))
2555 (forof (js2-for-in-node-forof-p n)))
2560 (js2-print-ast (js2-for-in-node-iterator n) 0)
2561 (insert (if forof " of " " in "))
2562 (js2-print-ast (js2-for-in-node-object n) 0)
2564 (js2-print-body (js2-for-in-node-body n) (1+ i))
2565 (insert pad "}\n")))
2567 (defstruct (js2-return-node
2570 (:constructor make-js2-return-node (&key (type js2-RETURN)
2574 "AST node for a return statement."
2575 retval) ; expression to return, or 'undefined
2577 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2578 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2580 (defun js2-visit-return-node (n v)
2581 (js2-visit-ast (js2-return-node-retval n) v))
2583 (defun js2-print-return-node (n i)
2584 (insert (js2-make-pad i) "return")
2585 (when (js2-return-node-retval n)
2587 (js2-print-ast (js2-return-node-retval n) 0))
2590 (defstruct (js2-if-node
2593 (:constructor make-js2-if-node (&key (type js2-IF)
2600 "AST node for an if-statement."
2601 condition ; expression
2602 then-part ; statement or block
2603 else-pos ; optional buffer position of 'else' keyword
2604 else-part ; optional statement or block
2605 lp ; position of left-paren, nil if omitted
2606 rp) ; position of right-paren, nil if omitted
2608 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2609 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2611 (defun js2-visit-if-node (n v)
2612 (js2-visit-ast (js2-if-node-condition n) v)
2613 (js2-visit-ast (js2-if-node-then-part n) v)
2614 (js2-visit-ast (js2-if-node-else-part n) v))
2616 (defun js2-print-if-node (n i)
2617 (let ((pad (js2-make-pad i))
2618 (then-part (js2-if-node-then-part n))
2619 (else-part (js2-if-node-else-part n)))
2621 (js2-print-ast (js2-if-node-condition n) 0)
2623 (js2-print-body then-part (1+ i))
2628 ((js2-if-node-p else-part)
2630 (js2-print-body else-part i))
2632 (insert " else {\n")
2633 (js2-print-body else-part (1+ i))
2634 (insert pad "}\n")))))
2636 (defstruct (js2-try-node
2639 (:constructor make-js2-try-node (&key (type js2-TRY)
2645 "AST node for a try-statement."
2647 catch-clauses ; a Lisp list of `js2-catch-node'
2648 finally-block) ; a `js2-finally-node'
2650 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2651 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2653 (defun js2-visit-try-node (n v)
2654 (js2-visit-ast (js2-try-node-try-block n) v)
2655 (dolist (clause (js2-try-node-catch-clauses n))
2656 (js2-visit-ast clause v))
2657 (js2-visit-ast (js2-try-node-finally-block n) v))
2659 (defun js2-print-try-node (n i)
2660 (let ((pad (js2-make-pad i))
2661 (catches (js2-try-node-catch-clauses n))
2662 (finally (js2-try-node-finally-block n)))
2663 (insert pad "try {\n")
2664 (js2-print-body (js2-try-node-try-block n) (1+ i))
2667 (dolist (catch catches)
2668 (js2-print-ast catch i)))
2670 (js2-print-ast finally i)
2673 (defstruct (js2-catch-node
2676 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2684 "AST node for a catch clause."
2685 param ; destructuring form or simple name node
2686 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2687 guard-expr ; catch condition, a `js2-node'
2688 block ; statements, a `js2-block-node'
2689 lp ; buffer position of left-paren, nil if omitted
2690 rp) ; buffer position of right-paren, nil if omitted
2692 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2693 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2695 (defun js2-visit-catch-node (n v)
2696 (js2-visit-ast (js2-catch-node-param n) v)
2697 (when (js2-catch-node-guard-kwd n)
2698 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2699 (js2-visit-ast (js2-catch-node-block n) v))
2701 (defun js2-print-catch-node (n i)
2702 (let ((pad (js2-make-pad i))
2703 (guard-kwd (js2-catch-node-guard-kwd n))
2704 (guard-expr (js2-catch-node-guard-expr n)))
2706 (js2-print-ast (js2-catch-node-param n) 0)
2709 (js2-print-ast guard-expr 0))
2711 (js2-print-body (js2-catch-node-block n) (1+ i))
2714 (defstruct (js2-finally-node
2717 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2720 "AST node for a finally clause."
2721 body) ; a `js2-node', often but not always a block node
2723 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2724 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2726 (defun js2-visit-finally-node (n v)
2727 (js2-visit-ast (js2-finally-node-body n) v))
2729 (defun js2-print-finally-node (n i)
2730 (let ((pad (js2-make-pad i)))
2731 (insert " finally {\n")
2732 (js2-print-body (js2-finally-node-body n) (1+ i))
2733 (insert pad "}\n")))
2735 (defstruct (js2-switch-node
2738 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2744 "AST node for a switch statement."
2745 discriminant ; a `js2-node' (switch expression)
2746 cases ; a Lisp list of `js2-case-node'
2747 lp ; position of open-paren for discriminant, nil if omitted
2748 rp) ; position of close-paren for discriminant, nil if omitted
2750 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2751 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2753 (defun js2-visit-switch-node (n v)
2754 (js2-visit-ast (js2-switch-node-discriminant n) v)
2755 (dolist (c (js2-switch-node-cases n))
2756 (js2-visit-ast c v)))
2758 (defun js2-print-switch-node (n i)
2759 (let ((pad (js2-make-pad i))
2760 (cases (js2-switch-node-cases n)))
2761 (insert pad "switch (")
2762 (js2-print-ast (js2-switch-node-discriminant n) 0)
2764 (dolist (case cases)
2765 (js2-print-ast case i))
2766 (insert pad "}\n")))
2768 (defstruct (js2-case-node
2769 (:include js2-block-node)
2771 (:constructor make-js2-case-node (&key (type js2-CASE)
2774 "AST node for a case clause of a switch statement."
2775 expr) ; the case expression (nil for default)
2777 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2778 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2780 (defun js2-visit-case-node (n v)
2781 (js2-visit-ast (js2-case-node-expr n) v)
2782 (js2-visit-block n v))
2784 (defun js2-print-case-node (n i)
2785 (let ((pad (js2-make-pad i))
2786 (expr (js2-case-node-expr n)))
2789 (insert "default:\n")
2791 (js2-print-ast expr 0)
2793 (dolist (kid (js2-case-node-kids n))
2794 (js2-print-ast kid (1+ i)))))
2796 (defstruct (js2-throw-node
2799 (:constructor make-js2-throw-node (&key (type js2-THROW)
2802 "AST node for a throw statement."
2803 expr) ; the expression to throw
2805 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2806 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2808 (defun js2-visit-throw-node (n v)
2809 (js2-visit-ast (js2-throw-node-expr n) v))
2811 (defun js2-print-throw-node (n i)
2812 (insert (js2-make-pad i) "throw ")
2813 (js2-print-ast (js2-throw-node-expr n) 0)
2816 (defstruct (js2-with-node
2819 (:constructor make-js2-with-node (&key (type js2-WITH)
2823 "AST node for a with-statement."
2826 lp ; buffer position of left-paren around object, nil if omitted
2827 rp) ; buffer position of right-paren around object, nil if omitted
2829 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2830 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2832 (defun js2-visit-with-node (n v)
2833 (js2-visit-ast (js2-with-node-object n) v)
2834 (js2-visit-ast (js2-with-node-body n) v))
2836 (defun js2-print-with-node (n i)
2837 (let ((pad (js2-make-pad i)))
2838 (insert pad "with (")
2839 (js2-print-ast (js2-with-node-object n) 0)
2841 (js2-print-body (js2-with-node-body n) (1+ i))
2842 (insert pad "}\n")))
2844 (defstruct (js2-label-node
2847 (:constructor make-js2-label-node (&key (type js2-LABEL)
2850 "AST node for a statement label or case label."
2852 loop) ; for validating and code-generating continue-to-label
2854 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2855 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2857 (defun js2-print-label (n i)
2858 (insert (js2-make-pad i)
2859 (js2-label-node-name n)
2862 (defstruct (js2-labeled-stmt-node
2865 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2866 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2867 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2870 "AST node for a statement with one or more labels.
2871 Multiple labels for a statement are collapsed into the labels field."
2872 labels ; Lisp list of `js2-label-node'
2873 stmt) ; the statement these labels are for
2875 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2876 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2878 (defun js2-get-label-by-name (lbl-stmt name)
2879 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2880 Returns nil if no such label is in the list."
2881 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2883 (while (and label-list (not result))
2884 (if (string= (js2-label-node-name (car label-list)) name)
2885 (setq result (car label-list))
2886 (setq label-list (cdr label-list))))
2889 (defun js2-visit-labeled-stmt (n v)
2890 (dolist (label (js2-labeled-stmt-node-labels n))
2891 (js2-visit-ast label v))
2892 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2894 (defun js2-print-labeled-stmt (n i)
2895 (dolist (label (js2-labeled-stmt-node-labels n))
2896 (js2-print-ast label i))
2897 (js2-print-ast (js2-labeled-stmt-node-stmt n) i))
2899 (defun js2-labeled-stmt-node-contains (node label)
2900 "Return t if NODE contains LABEL in its label set.
2901 NODE is a `js2-labels-node'. LABEL is an identifier."
2902 (loop for nl in (js2-labeled-stmt-node-labels node)
2903 if (string= label (js2-label-node-name nl))
2905 finally return nil))
2907 (defsubst js2-labeled-stmt-node-add-label (node label)
2908 "Add a `js2-label-node' to the label set for this statement."
2909 (setf (js2-labeled-stmt-node-labels node)
2910 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2912 (defstruct (js2-jump-node
2915 "Abstract supertype of break and continue nodes."
2916 label ; `js2-name-node' for location of label identifier, if present
2917 target) ; target js2-labels-node or loop/switch statement
2919 (defun js2-visit-jump-node (n v)
2920 ;; We don't visit the target, since it's a back-link.
2921 (js2-visit-ast (js2-jump-node-label n) v))
2923 (defstruct (js2-break-node
2924 (:include js2-jump-node)
2926 (:constructor make-js2-break-node (&key (type js2-BREAK)
2929 "AST node for a break statement.
2930 The label field is a `js2-name-node', possibly nil, for the named label
2931 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2932 is the target of the break - a label node or enclosing loop/switch statement.")
2934 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2935 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2937 (defun js2-print-break-node (n i)
2938 (insert (js2-make-pad i) "break")
2939 (when (js2-break-node-label n)
2941 (js2-print-ast (js2-break-node-label n) 0))
2944 (defstruct (js2-continue-node
2945 (:include js2-jump-node)
2947 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2950 "AST node for a continue statement.
2951 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2952 It is nil if continue specifies no label. The target field is the jump target:
2953 a `js2-label-node' or the innermost enclosing loop.")
2955 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2956 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2958 (defun js2-print-continue-node (n i)
2959 (insert (js2-make-pad i) "continue")
2960 (when (js2-continue-node-label n)
2962 (js2-print-ast (js2-continue-node-label n) 0))
2965 (defstruct (js2-function-node
2966 (:include js2-script-node)
2968 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2972 (form 'FUNCTION_STATEMENT)
2978 "AST node for a function declaration.
2979 The `params' field is a Lisp list of nodes. Each node is either a simple
2980 `js2-name-node', or if it's a destructuring-assignment parameter, a
2981 `js2-array-node' or `js2-object-node'."
2982 ftype ; FUNCTION, GETTER or SETTER
2983 form ; FUNCTION_{STATEMENT|EXPRESSION|ARROW}
2984 name ; function name (a `js2-name-node', or nil if anonymous)
2985 params ; a Lisp list of destructuring forms or simple name nodes
2986 rest-p ; if t, the last parameter is rest parameter
2987 body ; a `js2-block-node' or expression node (1.8 only)
2988 lp ; position of arg-list open-paren, or nil if omitted
2989 rp ; position of arg-list close-paren, or nil if omitted
2990 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2991 needs-activation ; t if we need an activation object for this frame
2992 generator-type ; STAR, LEGACY, COMPREHENSION or nil
2993 member-expr) ; nonstandard Ecma extension from Rhino
2995 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2996 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2998 (defun js2-visit-function-node (n v)
2999 (js2-visit-ast (js2-function-node-name n) v)
3000 (dolist (p (js2-function-node-params n))
3001 (js2-visit-ast p v))
3002 (js2-visit-ast (js2-function-node-body n) v))
3004 (defun js2-print-function-node (n i)
3005 (let* ((pad (js2-make-pad i))
3006 (getter (js2-node-get-prop n 'GETTER_SETTER))
3007 (name (or (js2-function-node-name n)
3008 (js2-function-node-member-expr n)))
3009 (params (js2-function-node-params n))
3010 (arrow (eq (js2-function-node-form n) 'FUNCTION_ARROW))
3011 (rest-p (js2-function-node-rest-p n))
3012 (body (js2-function-node-body n))
3013 (expr (not (eq (js2-function-node-form n) 'FUNCTION_STATEMENT))))
3014 (unless (or getter arrow)
3015 (insert pad "function")
3016 (when (eq (js2-function-node-generator-type n) 'STAR)
3020 (js2-print-ast name 0))
3022 (loop with len = (length params)
3026 (when (and rest-p (= count len))
3028 (js2-print-ast param 0)
3035 ;; TODO: fix this to be smarter about indenting, etc.
3038 (if (js2-block-node-p body)
3039 (js2-print-body body (1+ i))
3040 (js2-print-ast body 0))
3045 (defun js2-function-name (node)
3046 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3047 (and (js2-function-node-name node)
3048 (js2-name-node-name (js2-function-node-name node))))
3050 ;; Having this be an expression node makes it more flexible.
3051 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3052 ;; that work better if you assume it's an expression. Whenever we have
3053 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3054 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3055 (defstruct (js2-var-decl-node
3058 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3059 (pos (js2-current-token-beg))
3062 "AST node for a variable declaration list (VAR, CONST or LET).
3063 The node bounds differ depending on the declaration type. For VAR or
3064 CONST declarations, the bounds include the var/const keyword. For LET
3065 declarations, the node begins at the position of the first child."
3066 kids ; a Lisp list of `js2-var-init-node' structs.
3067 decl-type) ; js2-VAR, js2-CONST or js2-LET
3069 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3070 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3072 (defun js2-visit-var-decl (n v)
3073 (dolist (kid (js2-var-decl-node-kids n))
3074 (js2-visit-ast kid v)))
3076 (defun js2-print-var-decl (n i)
3077 (let ((pad (js2-make-pad i))
3078 (tt (js2-var-decl-node-decl-type n)))
3081 ((= tt js2-VAR) "var ")
3082 ((= tt js2-LET) "let ")
3083 ((= tt js2-CONST) "const ")
3085 (error "malformed var-decl node"))))
3086 (loop with kids = (js2-var-decl-node-kids n)
3087 with len = (length kids)
3091 (js2-print-ast kid 0)
3095 (defstruct (js2-var-init-node
3098 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3102 "AST node for a variable declaration.
3103 The type field will be js2-CONST for a const decl."
3104 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3105 initializer) ; initializer expression, a `js2-node'
3107 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3108 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3110 (defun js2-visit-var-init-node (n v)
3111 (js2-visit-ast (js2-var-init-node-target n) v)
3112 (js2-visit-ast (js2-var-init-node-initializer n) v))
3114 (defun js2-print-var-init-node (n i)
3115 (let ((pad (js2-make-pad i))
3116 (name (js2-var-init-node-target n))
3117 (init (js2-var-init-node-initializer n)))
3119 (js2-print-ast name 0)
3122 (js2-print-ast init 0))))
3124 (defstruct (js2-cond-node
3127 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3134 "AST node for the ternary operator"
3138 q-pos ; buffer position of ?
3139 c-pos) ; buffer position of :
3141 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3142 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3144 (defun js2-visit-cond-node (n v)
3145 (js2-visit-ast (js2-cond-node-test-expr n) v)
3146 (js2-visit-ast (js2-cond-node-true-expr n) v)
3147 (js2-visit-ast (js2-cond-node-false-expr n) v))
3149 (defun js2-print-cond-node (n i)
3150 (let ((pad (js2-make-pad i)))
3152 (js2-print-ast (js2-cond-node-test-expr n) 0)
3154 (js2-print-ast (js2-cond-node-true-expr n) 0)
3156 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3158 (defstruct (js2-infix-node
3161 (:constructor make-js2-infix-node (&key type
3165 "Represents infix expressions.
3166 Includes assignment ops like `|=', and the comma operator.
3167 The type field inherited from `js2-node' holds the operator."
3168 op-pos ; buffer position where operator begins
3169 left ; any `js2-node'
3170 right) ; any `js2-node'
3172 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3173 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3175 (defun js2-visit-infix-node (n v)
3176 (js2-visit-ast (js2-infix-node-left n) v)
3177 (js2-visit-ast (js2-infix-node-right n) v))
3179 (defconst js2-operator-tokens
3180 (let ((table (make-hash-table :test 'eq))
3182 (list (cons js2-IN "in")
3183 (cons js2-TYPEOF "typeof")
3184 (cons js2-INSTANCEOF "instanceof")
3185 (cons js2-DELPROP "delete")
3186 (cons js2-COMMA ",")
3187 (cons js2-COLON ":")
3192 (cons js2-BITOR "|")
3193 (cons js2-BITXOR "^")
3194 (cons js2-BITAND "&")
3203 (cons js2-URSH ">>>")
3204 (cons js2-ADD "+") ; infix plus
3205 (cons js2-SUB "-") ; infix minus
3210 (cons js2-BITNOT "~")
3211 (cons js2-POS "+") ; unary plus
3212 (cons js2-NEG "-") ; unary minus
3213 (cons js2-TRIPLEDOT "...")
3214 (cons js2-SHEQ "===") ; shallow equality
3215 (cons js2-SHNE "!==") ; shallow inequality
3216 (cons js2-ASSIGN "=")
3217 (cons js2-ASSIGN_BITOR "|=")
3218 (cons js2-ASSIGN_BITXOR "^=")
3219 (cons js2-ASSIGN_BITAND "&=")
3220 (cons js2-ASSIGN_LSH "<<=")
3221 (cons js2-ASSIGN_RSH ">>=")
3222 (cons js2-ASSIGN_URSH ">>>=")
3223 (cons js2-ASSIGN_ADD "+=")
3224 (cons js2-ASSIGN_SUB "-=")
3225 (cons js2-ASSIGN_MUL "*=")
3226 (cons js2-ASSIGN_DIV "/=")
3227 (cons js2-ASSIGN_MOD "%="))))
3228 (loop for (k . v) in tokens do
3229 (puthash k v table))
3232 (defun js2-print-infix-node (n i)
3233 (let* ((tt (js2-node-type n))
3234 (op (gethash tt js2-operator-tokens)))
3236 (error "unrecognized infix operator %s" (js2-node-type n)))
3237 (insert (js2-make-pad i))
3238 (js2-print-ast (js2-infix-node-left n) 0)
3239 (unless (= tt js2-COMMA)
3243 (js2-print-ast (js2-infix-node-right n) 0)))
3245 (defstruct (js2-assign-node
3246 (:include js2-infix-node)
3248 (:constructor make-js2-assign-node (&key type
3252 "Represents any assignment.
3253 The type field holds the actual assignment operator.")
3255 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3256 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3258 (defstruct (js2-unary-node
3261 (:constructor make-js2-unary-node (&key type ; required
3264 "AST node type for unary operator nodes.
3265 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3266 TYPEOF, DELPROP or TRIPLEDOT. For INC or DEC, a 'postfix node
3267 property is added if the operator follows the operand."
3268 operand) ; a `js2-node' expression
3270 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3271 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3273 (defun js2-visit-unary-node (n v)
3274 (js2-visit-ast (js2-unary-node-operand n) v))
3276 (defun js2-print-unary-node (n i)
3277 (let* ((tt (js2-node-type n))
3278 (op (gethash tt js2-operator-tokens))
3279 (postfix (js2-node-get-prop n 'postfix)))
3281 (error "unrecognized unary operator %s" tt))
3282 (insert (js2-make-pad i))
3285 (if (or (= tt js2-TYPEOF)
3288 (js2-print-ast (js2-unary-node-operand n) 0)
3292 (defstruct (js2-let-node
3293 (:include js2-scope)
3295 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3296 (pos (js2-current-token-beg))
3299 "AST node for a let expression or a let statement.
3300 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3301 vars ; a `js2-var-decl-node'
3302 body ; a `js2-node' representing the expression or body block
3306 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3307 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3309 (defun js2-visit-let-node (n v)
3310 (js2-visit-ast (js2-let-node-vars n) v)
3311 (js2-visit-ast (js2-let-node-body n) v))
3313 (defun js2-print-let-node (n i)
3314 (insert (js2-make-pad i) "let (")
3316 (js2-print-ast (js2-let-node-vars n) 0)
3317 (delete-region p (+ p 4)))
3319 (js2-print-ast (js2-let-node-body n) i))
3321 (defstruct (js2-keyword-node
3324 (:constructor make-js2-keyword-node (&key type
3325 (pos (js2-current-token-beg))
3326 (len (- js2-ts-cursor pos)))))
3327 "AST node representing a literal keyword such as `null'.
3328 Used for `null', `this', `true', `false' and `debugger'.
3329 The node type is set to js2-NULL, js2-THIS, etc.")
3331 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3332 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3334 (defun js2-print-keyword-node (n i)
3335 (insert (js2-make-pad i)
3336 (let ((tt (js2-node-type n)))
3338 ((= tt js2-THIS) "this")
3339 ((= tt js2-NULL) "null")
3340 ((= tt js2-TRUE) "true")
3341 ((= tt js2-FALSE) "false")
3342 ((= tt js2-DEBUGGER) "debugger")
3343 (t (error "Invalid keyword literal type: %d" tt))))))
3345 (defsubst js2-this-node-p (node)
3346 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3347 (eq (js2-node-type node) js2-THIS))
3349 (defstruct (js2-new-node
3352 (:constructor make-js2-new-node (&key (type js2-NEW)
3353 (pos (js2-current-token-beg))
3357 "AST node for new-expression such as new Foo()."
3358 target ; an identifier or reference
3359 args ; a Lisp list of argument nodes
3360 lp ; position of left-paren, nil if omitted
3361 rp ; position of right-paren, nil if omitted
3362 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3364 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3365 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3367 (defun js2-visit-new-node (n v)
3368 (js2-visit-ast (js2-new-node-target n) v)
3369 (dolist (arg (js2-new-node-args n))
3370 (js2-visit-ast arg v))
3371 (js2-visit-ast (js2-new-node-initializer n) v))
3373 (defun js2-print-new-node (n i)
3374 (insert (js2-make-pad i) "new ")
3375 (js2-print-ast (js2-new-node-target n))
3377 (js2-print-list (js2-new-node-args n))
3379 (when (js2-new-node-initializer n)
3381 (js2-print-ast (js2-new-node-initializer n))))
3383 (defstruct (js2-name-node
3386 (:constructor make-js2-name-node (&key (type js2-NAME)
3387 (pos (js2-current-token-beg))
3388 (len (- js2-ts-cursor
3389 (js2-current-token-beg)))
3390 (name (js2-current-token-string)))))
3391 "AST node for a JavaScript identifier"
3393 scope) ; a `js2-scope' (optional, used for codegen)
3395 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3396 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3398 (defun js2-print-name-node (n i)
3399 (insert (js2-make-pad i)
3400 (js2-name-node-name n)))
3402 (defsubst js2-name-node-length (node)
3403 "Return identifier length of NODE, a `js2-name-node'.
3404 Returns 0 if NODE is nil or its identifier field is nil."
3406 (length (js2-name-node-name node))
3409 (defstruct (js2-number-node
3412 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3413 (pos (js2-current-token-beg))
3414 (len (- js2-ts-cursor
3415 (js2-current-token-beg)))
3416 (value (js2-current-token-string))
3417 (num-value (js2-token-number
3418 (js2-current-token))))))
3419 "AST node for a number literal."
3420 value ; the original string, e.g. "6.02e23"
3421 num-value) ; the parsed number value
3423 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3424 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3426 (defun js2-print-number-node (n i)
3427 (insert (js2-make-pad i)
3428 (number-to-string (js2-number-node-num-value n))))
3430 (defstruct (js2-regexp-node
3433 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3434 (pos (js2-current-token-beg))
3435 (len (- js2-ts-cursor
3436 (js2-current-token-beg)))
3438 "AST node for a regular expression literal."
3439 value ; the regexp string, without // delimiters
3440 flags) ; a string of flags, e.g. `mi'.
3442 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3443 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3445 (defun js2-print-regexp (n i)
3446 (insert (js2-make-pad i)
3448 (js2-regexp-node-value n)
3450 (if (js2-regexp-node-flags n)
3451 (insert (js2-regexp-node-flags n))))
3453 (defstruct (js2-string-node
3456 (:constructor make-js2-string-node (&key (type js2-STRING)
3457 (pos (js2-current-token-beg))
3458 (len (- js2-ts-cursor
3459 (js2-current-token-beg)))
3460 (value (js2-current-token-string)))))
3462 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3463 You can tell the quote type by looking at the first character."
3464 value) ; the characters of the string, including the quotes
3466 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3467 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3469 (defun js2-print-string-node (n i)
3470 (insert (js2-make-pad i)
3471 (js2-node-string n)))
3473 (defstruct (js2-array-node
3476 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3479 "AST node for an array literal."
3480 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3482 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3483 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3485 (defun js2-visit-array-node (n v)
3486 (dolist (e (js2-array-node-elems n))
3487 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3489 (defun js2-print-array-node (n i)
3490 (insert (js2-make-pad i) "[")
3491 (let ((elems (js2-array-node-elems n)))
3492 (js2-print-list elems)
3493 (when (and elems (null (car (last elems))))
3497 (defstruct (js2-object-node
3500 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3504 "AST node for an object literal expression.
3505 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3506 The latter represents abbreviation in destructuring expressions."
3509 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3510 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3512 (defun js2-visit-object-node (n v)
3513 (dolist (e (js2-object-node-elems n))
3514 (js2-visit-ast e v)))
3516 (defun js2-print-object-node (n i)
3517 (insert (js2-make-pad i) "{")
3518 (js2-print-list (js2-object-node-elems n))
3521 (defstruct (js2-object-prop-node
3522 (:include js2-infix-node)
3524 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3528 "AST node for an object literal prop:value entry.
3529 The `left' field is the property: a name node, string node or number node.
3530 The `right' field is a `js2-node' representing the initializer value.")
3532 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3533 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3535 (defun js2-print-object-prop-node (n i)
3536 (let* ((left (js2-object-prop-node-left n))
3537 (computed (not (or (js2-string-node-p left)
3538 (js2-number-node-p left)
3539 (js2-name-node-p left)))))
3540 (insert (js2-make-pad i))
3543 (js2-print-ast left 0)
3546 (if (not (js2-node-get-prop n 'SHORTHAND))
3549 (js2-print-ast (js2-object-prop-node-right n) 0)))))
3551 (defstruct (js2-getter-setter-node
3552 (:include js2-infix-node)
3554 (:constructor make-js2-getter-setter-node (&key type ; GET, SET, or FUNCTION
3557 "AST node for a getter/setter property in an object literal.
3558 The `left' field is the `js2-name-node' naming the getter/setter prop.
3559 The `right' field is always an anonymous `js2-function-node' with a node
3560 property `GETTER_SETTER' set to js2-GET, js2-SET, or js2-FUNCTION. ")
3562 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3563 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3565 (defun js2-print-getter-setter (n i)
3566 (let ((pad (js2-make-pad i))
3567 (left (js2-getter-setter-node-left n))
3568 (right (js2-getter-setter-node-right n)))
3570 (if (/= (js2-node-type n) js2-FUNCTION)
3571 (insert (if (= (js2-node-type n) js2-GET) "get " "set ")))
3572 (js2-print-ast left 0)
3573 (js2-print-ast right 0)))
3575 (defstruct (js2-prop-get-node
3576 (:include js2-infix-node)
3578 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3581 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3583 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3584 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3586 (defun js2-visit-prop-get-node (n v)
3587 (js2-visit-ast (js2-prop-get-node-left n) v)
3588 (js2-visit-ast (js2-prop-get-node-right n) v))
3590 (defun js2-print-prop-get-node (n i)
3591 (insert (js2-make-pad i))
3592 (js2-print-ast (js2-prop-get-node-left n) 0)
3594 (js2-print-ast (js2-prop-get-node-right n) 0))
3596 (defstruct (js2-elem-get-node
3599 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3603 "AST node for an array index expression such as foo[bar]."
3604 target ; a `js2-node' - the expression preceding the "."
3605 element ; a `js2-node' - the expression in brackets
3606 lb ; position of left-bracket, nil if omitted
3607 rb) ; position of right-bracket, nil if omitted
3609 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3610 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3612 (defun js2-visit-elem-get-node (n v)
3613 (js2-visit-ast (js2-elem-get-node-target n) v)
3614 (js2-visit-ast (js2-elem-get-node-element n) v))
3616 (defun js2-print-elem-get-node (n i)
3617 (insert (js2-make-pad i))
3618 (js2-print-ast (js2-elem-get-node-target n) 0)
3620 (js2-print-ast (js2-elem-get-node-element n) 0)
3623 (defstruct (js2-call-node
3626 (:constructor make-js2-call-node (&key (type js2-CALL)
3630 "AST node for a JavaScript function call."
3631 target ; a `js2-node' evaluating to the function to call
3632 args ; a Lisp list of `js2-node' arguments
3633 lp ; position of open-paren, or nil if missing
3634 rp) ; position of close-paren, or nil if missing
3636 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3637 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3639 (defun js2-visit-call-node (n v)
3640 (js2-visit-ast (js2-call-node-target n) v)
3641 (dolist (arg (js2-call-node-args n))
3642 (js2-visit-ast arg v)))
3644 (defun js2-print-call-node (n i)
3645 (insert (js2-make-pad i))
3646 (js2-print-ast (js2-call-node-target n) 0)
3648 (js2-print-list (js2-call-node-args n))
3651 (defstruct (js2-yield-node
3654 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3657 "AST node for yield statement or expression."
3658 star-p ; whether it's yield*
3659 value) ; optional: value to be yielded
3661 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3662 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3664 (defun js2-visit-yield-node (n v)
3665 (js2-visit-ast (js2-yield-node-value n) v))
3667 (defun js2-print-yield-node (n i)
3668 (insert (js2-make-pad i))
3670 (when (js2-yield-node-star-p n)
3672 (when (js2-yield-node-value n)
3674 (js2-print-ast (js2-yield-node-value n) 0)))
3676 (defstruct (js2-paren-node
3679 (:constructor make-js2-paren-node (&key (type js2-LP)
3682 "AST node for a parenthesized expression.
3683 In particular, used when the parens are syntactically optional,
3684 as opposed to required parens such as those enclosing an if-conditional."
3687 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3688 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3690 (defun js2-visit-paren-node (n v)
3691 (js2-visit-ast (js2-paren-node-expr n) v))
3693 (defun js2-print-paren-node (n i)
3694 (insert (js2-make-pad i))
3696 (js2-print-ast (js2-paren-node-expr n) 0)
3699 (defstruct (js2-comp-node
3700 (:include js2-scope)
3702 (:constructor make-js2-comp-node (&key (type js2-ARRAYCOMP)
3707 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3708 result ; result expression (just after left-bracket)
3709 loops ; a Lisp list of `js2-comp-loop-node'
3710 filters ; a Lisp list of guard/filter expressions
3711 form ; ARRAY, LEGACY_ARRAY or STAR_GENERATOR
3712 ; SpiderMonkey also supports "legacy generator expressions", but we dont.
3715 (put 'cl-struct-js2-comp-node 'js2-visitor 'js2-visit-comp-node)
3716 (put 'cl-struct-js2-comp-node 'js2-printer 'js2-print-comp-node)
3718 (defun js2-visit-comp-node (n v)
3719 (js2-visit-ast (js2-comp-node-result n) v)
3720 (dolist (l (js2-comp-node-loops n))
3721 (js2-visit-ast l v))
3722 (dolist (f (js2-comp-node-filters n))
3723 (js2-visit-ast f v)))
3725 (defun js2-print-comp-node (n i)
3726 (let ((pad (js2-make-pad i))
3727 (result (js2-comp-node-result n))
3728 (loops (js2-comp-node-loops n))
3729 (filters (js2-comp-node-filters n))
3730 (legacy-p (eq (js2-comp-node-form n) 'LEGACY_ARRAY))
3731 (gen-p (eq (js2-comp-node-form n) 'STAR_GENERATOR)))
3732 (insert pad (if gen-p "(" "["))
3734 (js2-print-ast result 0))
3750 (js2-print-ast result 0))
3751 (insert (if gen-p ")" "]"))))
3753 (defstruct (js2-comp-loop-node
3754 (:include js2-for-in-node)
3756 (:constructor make-js2-comp-loop-node (&key (type js2-FOR)
3764 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3766 (put 'cl-struct-js2-comp-loop-node 'js2-visitor 'js2-visit-comp-loop)
3767 (put 'cl-struct-js2-comp-loop-node 'js2-printer 'js2-print-comp-loop)
3769 (defun js2-visit-comp-loop (n v)
3770 (js2-visit-ast (js2-comp-loop-node-iterator n) v)
3771 (js2-visit-ast (js2-comp-loop-node-object n) v))
3773 (defun js2-print-comp-loop (n _i)
3775 (when (js2-comp-loop-node-foreach-p n) (insert "each "))
3777 (js2-print-ast (js2-comp-loop-node-iterator n) 0)
3778 (insert (if (js2-comp-loop-node-forof-p n)
3780 (js2-print-ast (js2-comp-loop-node-object n) 0)
3783 (defstruct (js2-empty-expr-node
3786 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3787 (pos (js2-current-token-beg))
3789 "AST node for an empty expression.")
3791 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3792 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3794 (defstruct (js2-xml-node
3795 (:include js2-block-node)
3797 (:constructor make-js2-xml-node (&key (type js2-XML)
3798 (pos (js2-current-token-beg))
3800 "AST node for initial parse of E4X literals.
3801 The kids field is a list of XML fragments, each a `js2-string-node' or
3802 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3804 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3805 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3807 (defun js2-print-xml-node (n i)
3808 (dolist (kid (js2-xml-node-kids n))
3809 (js2-print-ast kid i)))
3811 (defstruct (js2-xml-js-expr-node
3812 (:include js2-xml-node)
3814 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3817 "AST node for an embedded JavaScript {expression} in an E4X literal.
3818 The start and end fields correspond to the curly-braces."
3819 expr) ; a `js2-expr-node' of some sort
3821 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3822 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3824 (defun js2-visit-xml-js-expr (n v)
3825 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3827 (defun js2-print-xml-js-expr (n i)
3828 (insert (js2-make-pad i))
3830 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3833 (defstruct (js2-xml-dot-query-node
3834 (:include js2-infix-node)
3836 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3840 "AST node for an E4X foo.(bar) filter expression.
3841 Note that the left-paren is automatically the character immediately
3842 following the dot (.) in the operator. No whitespace is permitted
3843 between the dot and the lp by the scanner."
3846 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3847 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3849 (defun js2-print-xml-dot-query (n i)
3850 (insert (js2-make-pad i))
3851 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3853 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3856 (defstruct (js2-xml-ref-node
3858 (:constructor nil)) ; abstract
3859 "Base type for E4X XML attribute-access or property-get expressions.
3860 Such expressions can take a variety of forms. The general syntax has
3863 - (optional) an @ (specifying an attribute access)
3864 - (optional) a namespace (a `js2-name-node') and double-colon
3865 - (required) either a `js2-name-node' or a bracketed [expression]
3867 The property-name expressions (examples: ns::name, @name) are
3868 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3869 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3871 This node type (or more specifically, its subclasses) will sometimes
3872 be the right-hand child of a `js2-prop-get-node' or a
3873 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3874 The `js2-xml-ref-node' may also be a standalone primary expression with
3875 no explicit target, which is valid in certain expression contexts such as
3877 company..employee.(@id < 100)
3879 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3880 expression whose parent is a `js2-xml-dot-query-node'."
3885 (defsubst js2-xml-ref-node-attr-access-p (node)
3886 "Return non-nil if this expression began with an @-token."
3887 (and (numberp (js2-xml-ref-node-at-pos node))
3888 (plusp (js2-xml-ref-node-at-pos node))))
3890 (defstruct (js2-xml-prop-ref-node
3891 (:include js2-xml-ref-node)
3893 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3894 (pos (js2-current-token-beg))
3898 "AST node for an E4X XML [expr] property-ref expression.
3899 The JavaScript syntax is an optional @, an optional ns::, and a name.
3901 [ '@' ] [ name '::' ] name
3903 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3904 @ns::*, @*::attr, @*::*, and @*.
3906 The node starts at the @ token, if present. Otherwise it starts at the
3907 namespace name. The node bounds extend through the closing right-bracket,
3908 or if it is missing due to a syntax error, through the end of the index
3912 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3913 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3915 (defun js2-visit-xml-prop-ref-node (n v)
3916 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3917 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3919 (defun js2-print-xml-prop-ref-node (n i)
3920 (insert (js2-make-pad i))
3921 (if (js2-xml-ref-node-attr-access-p n)
3923 (when (js2-xml-prop-ref-node-namespace n)
3924 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3926 (if (js2-xml-prop-ref-node-propname n)
3927 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3929 (defstruct (js2-xml-elem-ref-node
3930 (:include js2-xml-ref-node)
3932 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3933 (pos (js2-current-token-beg))
3937 "AST node for an E4X XML [expr] member-ref expression.
3940 [ '@' ] [ name '::' ] '[' expr ']'
3942 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3944 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3945 is not a legal E4X XML element-ref expression, since it's already used
3946 for standard JavaScript element-get array indexing. Hence, a
3947 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3948 non-nil namespace node, or both.
3950 The node starts at the @ token, if present. Otherwise it starts
3951 at the namespace name. The node bounds extend through the closing
3952 right-bracket, or if it is missing due to a syntax error, through the
3953 end of the index expression."
3954 expr ; the bracketed index expression
3958 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3959 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3961 (defun js2-visit-xml-elem-ref-node (n v)
3962 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3963 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3965 (defun js2-print-xml-elem-ref-node (n i)
3966 (insert (js2-make-pad i))
3967 (if (js2-xml-ref-node-attr-access-p n)
3969 (when (js2-xml-elem-ref-node-namespace n)
3970 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3973 (if (js2-xml-elem-ref-node-expr n)
3974 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3977 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3979 (defstruct (js2-xml-start-tag-node
3980 (:include js2-xml-node)
3982 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3986 "AST node for an XML start-tag. Not currently used.
3987 The `kids' field is a Lisp list of child content nodes."
3988 name ; a `js2-xml-name-node'
3989 attrs ; a Lisp list of `js2-xml-attr-node'
3990 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3992 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3993 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3995 (defun js2-visit-xml-start-tag (n v)
3996 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3997 (dolist (attr (js2-xml-start-tag-node-attrs n))
3998 (js2-visit-ast attr v))
3999 (js2-visit-block n v))
4001 (defun js2-print-xml-start-tag (n i)
4002 (insert (js2-make-pad i) "<")
4003 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4004 (when (js2-xml-start-tag-node-attrs n)
4006 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4009 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4010 ;; and add the end-tag to the kids list of the parent as well.
4011 (defstruct (js2-xml-end-tag-node
4012 (:include js2-xml-node)
4014 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4017 "AST node for an XML end-tag. Not currently used."
4018 name) ; a `js2-xml-name-node'
4020 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4021 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4023 (defun js2-visit-xml-end-tag (n v)
4024 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4026 (defun js2-print-xml-end-tag (n i)
4027 (insert (js2-make-pad i))
4029 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4032 (defstruct (js2-xml-name-node
4033 (:include js2-xml-node)
4035 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4037 len namespace kids)))
4038 "AST node for an E4X XML name. Not currently used.
4039 Any XML name can be qualified with a namespace, hence the namespace field.
4040 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4041 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4042 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4043 namespace) ; a `js2-string-node'
4045 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4046 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4048 (defun js2-visit-xml-name-node (n v)
4049 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4051 (defun js2-print-xml-name-node (n i)
4052 (insert (js2-make-pad i))
4053 (when (js2-xml-name-node-namespace n)
4054 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4056 (dolist (kid (js2-xml-name-node-kids n))
4057 (js2-print-ast kid 0)))
4059 (defstruct (js2-xml-pi-node
4060 (:include js2-xml-node)
4062 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4065 "AST node for an E4X XML processing instruction. Not currently used."
4066 name ; a `js2-xml-name-node'
4067 attrs) ; a list of `js2-xml-attr-node'
4069 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4070 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4072 (defun js2-visit-xml-pi-node (n v)
4073 (js2-visit-ast (js2-xml-pi-node-name n) v)
4074 (dolist (attr (js2-xml-pi-node-attrs n))
4075 (js2-visit-ast attr v)))
4077 (defun js2-print-xml-pi-node (n i)
4078 (insert (js2-make-pad i) "<?")
4079 (js2-print-ast (js2-xml-pi-node-name n))
4080 (when (js2-xml-pi-node-attrs n)
4082 (js2-print-list (js2-xml-pi-node-attrs n)))
4085 (defstruct (js2-xml-cdata-node
4086 (:include js2-xml-node)
4088 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4091 "AST node for a CDATA escape section. Not currently used."
4092 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4094 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4095 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4097 (defun js2-visit-xml-cdata-node (n v)
4098 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4100 (defun js2-print-xml-cdata-node (n i)
4101 (insert (js2-make-pad i))
4102 (js2-print-ast (js2-xml-cdata-node-content n)))
4104 (defstruct (js2-xml-attr-node
4105 (:include js2-xml-node)
4107 (:constructor make-js2-attr-node (&key (type js2-XML)
4110 eq-pos quote-type)))
4111 "AST node representing a foo='bar' XML attribute value. Not yet used."
4112 name ; a `js2-xml-name-node'
4113 value ; a `js2-xml-name-node'
4114 eq-pos ; buffer position of "=" sign
4115 quote-type) ; 'single or 'double
4117 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4118 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4120 (defun js2-visit-xml-attr-node (n v)
4121 (js2-visit-ast (js2-xml-attr-node-name n) v)
4122 (js2-visit-ast (js2-xml-attr-node-value n) v))
4124 (defun js2-print-xml-attr-node (n i)
4125 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4128 (insert (js2-make-pad i))
4129 (js2-print-ast (js2-xml-attr-node-name n) 0)
4131 (js2-print-ast (js2-xml-attr-node-value n) 0)
4134 (defstruct (js2-xml-text-node
4135 (:include js2-xml-node)
4137 (:constructor make-js2-text-node (&key (type js2-XML)
4140 "AST node for an E4X XML text node. Not currently used."
4141 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4143 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4144 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4146 (defun js2-visit-xml-text-node (n v)
4147 (js2-visit-ast (js2-xml-text-node-content n) v))
4149 (defun js2-print-xml-text-node (n i)
4150 (insert (js2-make-pad i))
4151 (dolist (kid (js2-xml-text-node-content n))
4152 (js2-print-ast kid)))
4154 (defstruct (js2-xml-comment-node
4155 (:include js2-xml-node)
4157 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4160 "AST node for E4X XML comment. Not currently used.")
4162 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4163 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4165 (defun js2-print-xml-comment (n i)
4166 (insert (js2-make-pad i)
4167 (js2-node-string n)))
4171 (defsubst js2-node-line (n)
4172 "Fetch the source line number at the start of node N.
4173 This is O(n) in the length of the source buffer; use prudently."
4174 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4176 (defsubst js2-block-node-kid (n i)
4177 "Return child I of node N, or nil if there aren't that many."
4178 (nth i (js2-block-node-kids n)))
4180 (defsubst js2-block-node-first (n)
4181 "Return first child of block node N, or nil if there is none."
4182 (first (js2-block-node-kids n)))
4184 (defun js2-node-root (n)
4185 "Return the root of the AST containing N.
4186 If N has no parent pointer, returns N."
4187 (let ((parent (js2-node-parent n)))
4189 (js2-node-root parent)
4192 (defsubst js2-node-short-name (n)
4193 "Return the short name of node N as a string, e.g. `js2-if-node'."
4194 (substring (symbol-name (aref n 0))
4195 (length "cl-struct-")))
4197 (defun js2-node-child-list (node)
4198 "Return the child list for NODE, a Lisp list of nodes.
4199 Works for block nodes, array nodes, obj literals, funarg lists,
4200 var decls and try nodes (for catch clauses). Note that you should call
4201 `js2-block-node-kids' on the function body for the body statements.
4202 Returns nil for zero-length child lists or unsupported nodes."
4204 ((js2-function-node-p node)
4205 (js2-function-node-params node))
4206 ((js2-block-node-p node)
4207 (js2-block-node-kids node))
4208 ((js2-try-node-p node)
4209 (js2-try-node-catch-clauses node))
4210 ((js2-array-node-p node)
4211 (js2-array-node-elems node))
4212 ((js2-object-node-p node)
4213 (js2-object-node-elems node))
4214 ((js2-call-node-p node)
4215 (js2-call-node-args node))
4216 ((js2-new-node-p node)
4217 (js2-new-node-args node))
4218 ((js2-var-decl-node-p node)
4219 (js2-var-decl-node-kids node))
4223 (defun js2-node-set-child-list (node kids)
4224 "Set the child list for NODE to KIDS."
4226 ((js2-function-node-p node)
4227 (setf (js2-function-node-params node) kids))
4228 ((js2-block-node-p node)
4229 (setf (js2-block-node-kids node) kids))
4230 ((js2-try-node-p node)
4231 (setf (js2-try-node-catch-clauses node) kids))
4232 ((js2-array-node-p node)
4233 (setf (js2-array-node-elems node) kids))
4234 ((js2-object-node-p node)
4235 (setf (js2-object-node-elems node) kids))
4236 ((js2-call-node-p node)
4237 (setf (js2-call-node-args node) kids))
4238 ((js2-new-node-p node)
4239 (setf (js2-new-node-args node) kids))
4240 ((js2-var-decl-node-p node)
4241 (setf (js2-var-decl-node-kids node) kids))
4243 (error "Unsupported node type: %s" (js2-node-short-name node))))
4246 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4247 (defconst js2-paren-expr-nodes
4248 '(cl-struct-js2-comp-loop-node
4249 cl-struct-js2-comp-node
4250 cl-struct-js2-call-node
4251 cl-struct-js2-catch-node
4252 cl-struct-js2-do-node
4253 cl-struct-js2-elem-get-node
4254 cl-struct-js2-for-in-node
4255 cl-struct-js2-for-node
4256 cl-struct-js2-function-node
4257 cl-struct-js2-if-node
4258 cl-struct-js2-let-node
4259 cl-struct-js2-new-node
4260 cl-struct-js2-paren-node
4261 cl-struct-js2-switch-node
4262 cl-struct-js2-while-node
4263 cl-struct-js2-with-node
4264 cl-struct-js2-xml-dot-query-node)
4265 "Node types that can have a parenthesized child expression.
4266 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4268 (defsubst js2-paren-expr-node-p (node)
4269 "Return t for nodes that typically have a parenthesized child expression.
4270 Useful for computing the indentation anchors for arg-lists and conditions.
4271 Note that it may return a false positive, for instance when NODE is
4272 a `js2-new-node' and there are no arguments or parentheses."
4273 (memq (aref node 0) js2-paren-expr-nodes))
4275 ;; Fake polymorphism... yech.
4276 (defun js2-node-lp (node)
4277 "Return relative left-paren position for NODE, if applicable.
4278 For `js2-elem-get-node' structs, returns left-bracket position.
4279 Note that the position may be nil in the case of a parse error."
4281 ((js2-elem-get-node-p node)
4282 (js2-elem-get-node-lb node))
4283 ((js2-loop-node-p node)
4284 (js2-loop-node-lp node))
4285 ((js2-function-node-p node)
4286 (js2-function-node-lp node))
4287 ((js2-if-node-p node)
4288 (js2-if-node-lp node))
4289 ((js2-new-node-p node)
4290 (js2-new-node-lp node))
4291 ((js2-call-node-p node)
4292 (js2-call-node-lp node))
4293 ((js2-paren-node-p node)
4295 ((js2-switch-node-p node)
4296 (js2-switch-node-lp node))
4297 ((js2-catch-node-p node)
4298 (js2-catch-node-lp node))
4299 ((js2-let-node-p node)
4300 (js2-let-node-lp node))
4301 ((js2-comp-node-p node)
4303 ((js2-with-node-p node)
4304 (js2-with-node-lp node))
4305 ((js2-xml-dot-query-node-p node)
4306 (1+ (js2-infix-node-op-pos node)))
4308 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4310 ;; Fake polymorphism... blech.
4311 (defun js2-node-rp (node)
4312 "Return relative right-paren position for NODE, if applicable.
4313 For `js2-elem-get-node' structs, returns right-bracket position.
4314 Note that the position may be nil in the case of a parse error."
4316 ((js2-elem-get-node-p node)
4317 (js2-elem-get-node-rb node))
4318 ((js2-loop-node-p node)
4319 (js2-loop-node-rp node))
4320 ((js2-function-node-p node)
4321 (js2-function-node-rp node))
4322 ((js2-if-node-p node)
4323 (js2-if-node-rp node))
4324 ((js2-new-node-p node)
4325 (js2-new-node-rp node))
4326 ((js2-call-node-p node)
4327 (js2-call-node-rp node))
4328 ((js2-paren-node-p node)
4329 (1- (js2-node-len node)))
4330 ((js2-switch-node-p node)
4331 (js2-switch-node-rp node))
4332 ((js2-catch-node-p node)
4333 (js2-catch-node-rp node))
4334 ((js2-let-node-p node)
4335 (js2-let-node-rp node))
4336 ((js2-comp-node-p node)
4337 (1- (js2-node-len node)))
4338 ((js2-with-node-p node)
4339 (js2-with-node-rp node))
4340 ((js2-xml-dot-query-node-p node)
4341 (1+ (js2-xml-dot-query-node-rp node)))
4343 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4345 (defsubst js2-node-first-child (node)
4346 "Return the first element of `js2-node-child-list' for NODE."
4347 (car (js2-node-child-list node)))
4349 (defsubst js2-node-last-child (node)
4350 "Return the last element of `js2-node-last-child' for NODE."
4351 (car (last (js2-node-child-list node))))
4353 (defun js2-node-prev-sibling (node)
4354 "Return the previous statement in parent.
4355 Works for parents supported by `js2-node-child-list'.
4356 Returns nil if NODE is not in the parent, or PARENT is
4357 not a supported node, or if NODE is the first child."
4358 (let* ((p (js2-node-parent node))
4359 (kids (js2-node-child-list p))
4362 (not (eq node (cadr kids))))
4363 (setq kids (cdr kids)
4367 (defun js2-node-next-sibling (node)
4368 "Return the next statement in parent block.
4369 Returns nil if NODE is not in the block, or PARENT is not
4370 a block node, or if NODE is the last statement."
4371 (let* ((p (js2-node-parent node))
4372 (kids (js2-node-child-list p)))
4374 (not (eq node (car kids))))
4375 (setq kids (cdr kids)))
4378 (defun js2-node-find-child-before (pos parent &optional after)
4379 "Find the last child that starts before POS in parent.
4380 If AFTER is non-nil, returns first child starting after POS.
4381 POS is an absolute buffer position. PARENT is any node
4382 supported by `js2-node-child-list'.
4383 Returns nil if no applicable child is found."
4384 (let ((kids (if (js2-function-node-p parent)
4385 (js2-block-node-kids (js2-function-node-body parent))
4386 (js2-node-child-list parent)))
4387 (beg (js2-node-abs-pos (if (js2-function-node-p parent)
4388 (js2-function-node-body parent)
4392 (setq fn (if after '>= '<))
4393 (while (and kids continue)
4394 (setq kid (car kids))
4395 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4397 continue (not after))
4398 (setq continue after))
4399 (setq kids (cdr kids)))
4402 (defun js2-node-find-child-after (pos parent)
4403 "Find first child that starts after POS in parent.
4404 POS is an absolute buffer position. PARENT is any node
4405 supported by `js2-node-child-list'.
4406 Returns nil if no applicable child is found."
4407 (js2-node-find-child-before pos parent 'after))
4409 (defun js2-node-replace-child (pos parent new-node)
4410 "Replace node at index POS in PARENT with NEW-NODE.
4411 Only works for parents supported by `js2-node-child-list'."
4412 (let ((kids (js2-node-child-list parent))
4415 (setq kids (cdr kids)
4417 (setcar kids new-node)
4418 (js2-node-add-children parent new-node)))
4420 (defun js2-node-buffer (n)
4421 "Return the buffer associated with AST N.
4422 Returns nil if the buffer is not set as a property on the root
4423 node, or if parent links were not recorded during parsing."
4424 (let ((root (js2-node-root n)))
4426 (js2-ast-root-p root)
4427 (js2-ast-root-buffer root))))
4429 (defun js2-block-node-push (n kid)
4430 "Push js2-node KID onto the end of js2-block-node N's child list.
4431 KID is always added to the -end- of the kids list.
4432 Function also calls `js2-node-add-children' to add the parent link."
4433 (let ((kids (js2-node-child-list n)))
4435 (setcdr kids (nconc (cdr kids) (list kid)))
4436 (js2-node-set-child-list n (list kid)))
4437 (js2-node-add-children n kid)))
4439 (defun js2-node-string (node)
4440 (with-current-buffer (or (js2-node-buffer node)
4441 (error "No buffer available for node %s" node))
4442 (let ((pos (js2-node-abs-pos node)))
4443 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4445 ;; Container for storing the node we're looking for in a traversal.
4446 (js2-deflocal js2-discovered-node nil)
4448 ;; Keep track of absolute node position during traversals.
4449 (js2-deflocal js2-visitor-offset nil)
4451 (js2-deflocal js2-node-search-point nil)
4453 (when js2-mode-dev-mode-p
4454 (defun js2-find-node-at-point ()
4456 (let ((node (js2-node-at-point)))
4457 (message "%s" (or node "No node found at point"))))
4458 (defun js2-node-name-at-point ()
4460 (let ((node (js2-node-at-point)))
4461 (message "%s" (if node
4462 (js2-node-short-name node)
4463 "No node found at point.")))))
4465 (defun js2-node-at-point (&optional pos skip-comments)
4466 "Return AST node at POS, a buffer position, defaulting to current point.
4467 The `js2-mode-ast' variable must be set to the current parse tree.
4468 Signals an error if the AST (`js2-mode-ast') is nil.
4469 Always returns a node - if it can't find one, it returns the root.
4470 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4471 (let ((ast js2-mode-ast)
4474 (error "No JavaScript AST available"))
4475 ;; Look through comments first, since they may be inside nodes that
4476 ;; would otherwise report a match.
4477 (setq pos (or pos (point))
4478 result (if (> pos (js2-node-abs-end ast))
4480 (if (not skip-comments)
4481 (js2-comment-at-point pos))))
4483 (setq js2-discovered-node nil
4484 js2-visitor-offset 0
4485 js2-node-search-point pos)
4487 (catch 'js2-visit-done
4488 (js2-visit-ast ast #'js2-node-at-point-visitor))
4489 (setq js2-visitor-offset nil
4490 js2-node-search-point nil))
4491 (setq result js2-discovered-node))
4492 ;; may have found a comment beyond end of last child node,
4493 ;; since visiting the ast-root looks at the comment-list last.
4494 (if (and skip-comments
4495 (js2-comment-node-p result))
4497 (or result js2-mode-ast)))
4499 (defun js2-node-at-point-visitor (node end-p)
4500 (let ((rel-pos (js2-node-pos node))
4503 (point js2-node-search-point))
4506 ;; this evaluates to a non-nil return value, even if it's zero
4507 (decf js2-visitor-offset rel-pos))
4508 ;; we already looked for comments before visiting, and don't want them now
4509 ((js2-comment-node-p node)
4512 (setq abs-pos (incf js2-visitor-offset rel-pos)
4513 ;; we only want to use the node if the point is before
4514 ;; the last character position in the node, so we decrement
4515 ;; the absolute end by 1.
4516 abs-end (+ abs-pos (js2-node-len node) -1))
4518 ;; If this node starts after search-point, stop the search.
4520 (throw 'js2-visit-done nil))
4521 ;; If this node ends before the search-point, don't check kids.
4525 ;; Otherwise point is within this node, possibly in a child.
4526 (setq js2-discovered-node node)
4527 t)))))) ; keep processing kids to look for more specific match
4529 (defsubst js2-block-comment-p (node)
4530 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4531 (and (js2-comment-node-p node)
4532 (memq (js2-comment-node-format node) '(jsdoc block))))
4534 ;; TODO: put the comments in a vector and binary-search them instead
4535 (defun js2-comment-at-point (&optional pos)
4536 "Look through scanned comment nodes for one containing POS.
4537 POS is a buffer position that defaults to current point.
4538 Function returns nil if POS was not in any comment node."
4539 (let ((ast js2-mode-ast)
4540 (x (or pos (point)))
4543 (error "No JavaScript AST available"))
4545 ;; Comments are stored in lexical order.
4546 (dolist (comment (js2-ast-root-comments ast) nil)
4547 (setq beg (js2-node-abs-pos comment)
4548 end (+ beg (js2-node-len comment)))
4551 (throw 'done comment))))))
4553 (defun js2-mode-find-parent-fn (node)
4554 "Find function enclosing NODE.
4555 Returns nil if NODE is not inside a function."
4556 (setq node (js2-node-parent node))
4557 (while (and node (not (js2-function-node-p node)))
4558 (setq node (js2-node-parent node)))
4559 (and (js2-function-node-p node) node))
4561 (defun js2-mode-find-enclosing-fn (node)
4562 "Find function or root enclosing NODE."
4563 (if (js2-ast-root-p node)
4565 (setq node (js2-node-parent node))
4566 (while (not (or (js2-ast-root-p node)
4567 (js2-function-node-p node)))
4568 (setq node (js2-node-parent node)))
4571 (defun js2-mode-find-enclosing-node (beg end)
4572 "Find node fully enclosing BEG and END."
4573 (let ((node (js2-node-at-point beg))
4577 (if (or (js2-ast-root-p node)
4579 (<= (setq pos (js2-node-abs-pos node)) beg)
4580 (>= (+ pos (js2-node-len node)) end)))
4582 (setq node (js2-node-parent node))))
4585 (defun js2-node-parent-script-or-fn (node)
4586 "Find script or function immediately enclosing NODE.
4587 If NODE is the ast-root, returns nil."
4588 (if (js2-ast-root-p node)
4590 (setq node (js2-node-parent node))
4591 (while (and node (not (or (js2-function-node-p node)
4592 (js2-script-node-p node))))
4593 (setq node (js2-node-parent node)))
4596 (defun js2-node-is-descendant (node ancestor)
4597 "Return t if NODE is a descendant of ANCESTOR."
4599 (not (eq node ancestor)))
4600 (setq node (js2-node-parent node)))
4603 ;;; visitor infrastructure
4605 (defun js2-visit-none (_node _callback)
4606 "Visitor for AST node that have no node children."
4609 (defun js2-print-none (_node _indent)
4610 "Visitor for AST node with no printed representation.")
4612 (defun js2-print-body (node indent)
4613 "Print a statement, or a block without braces."
4614 (if (js2-block-node-p node)
4615 (dolist (kid (js2-block-node-kids node))
4616 (js2-print-ast kid indent))
4617 (js2-print-ast node indent)))
4619 (defun js2-print-list (args &optional delimiter)
4620 (loop with len = (length args)
4624 (when arg (js2-print-ast arg 0))
4626 (insert (or delimiter ", ")))))
4628 (defun js2-print-tree (ast)
4629 "Prints an AST to the current buffer.
4630 Makes `js2-ast-parent-nodes' available to the printer functions."
4631 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4632 (js2-print-ast ast)))
4634 (defun js2-print-ast (node &optional indent)
4635 "Helper function for printing AST nodes.
4636 Requires `js2-ast-parent-nodes' to be non-nil.
4637 You should use `js2-print-tree' instead of this function."
4638 (let ((printer (get (aref node 0) 'js2-printer))
4640 ;; TODO: wedge comments in here somewhere
4642 (funcall printer node i))))
4644 (defconst js2-side-effecting-tokens
4645 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4646 (dolist (tt (list js2-ASSIGN
4715 (if js2-instanceof-has-side-effects
4716 (aset tokens js2-INSTANCEOF t))
4719 (defun js2-node-has-side-effects (node)
4720 "Return t if NODE has side effects."
4721 (when node ; makes it easier to handle malformed expressions
4722 (let ((tt (js2-node-type node)))
4724 ;; This doubtless needs some work, since EXPR_VOID is used
4725 ;; in several ways in Rhino and I may not have caught them all.
4726 ;; I'll wait for people to notice incorrect warnings.
4727 ((and (= tt js2-EXPR_VOID)
4728 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4729 (let ((expr (js2-expr-stmt-node-expr node)))
4730 (or (js2-node-has-side-effects expr)
4731 (when (js2-string-node-p expr)
4732 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4734 (js2-node-has-side-effects (js2-infix-node-right node)))
4737 (or (js2-node-has-side-effects (js2-infix-node-right node))
4738 (js2-node-has-side-effects (js2-infix-node-left node))))
4740 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4741 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4742 ((js2-paren-node-p node)
4743 (js2-node-has-side-effects (js2-paren-node-expr node)))
4744 ((= tt js2-ERROR) ; avoid cascaded error messages
4747 (aref js2-side-effecting-tokens tt))))))
4749 (defconst js2-stmt-node-types
4753 js2-DEFAULT ; e4x "default xml namespace" statement
4765 "Node types that only appear in statement contexts.
4766 The list does not include nodes that always appear as the child
4767 of another specific statement type, such as switch-cases,
4768 catch and finally blocks, and else-clauses. The list also excludes
4769 nodes like yield, let and var, which may appear in either expression
4770 or statement context, and in the latter context always have a
4771 `js2-expr-stmt-node' parent. Finally, the list does not include
4772 functions or scripts, which are treated separately from statements
4773 by the JavaScript parser and runtime.")
4775 (defun js2-stmt-node-p (node)
4776 "Heuristic for figuring out if NODE is a statement.
4777 Some node types can appear in either an expression context or a
4778 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4779 For these node types in a statement context, the parent will be a
4780 `js2-expr-stmt-node'.
4781 Functions aren't included in the check."
4782 (memq (js2-node-type node) js2-stmt-node-types))
4784 (defun js2-mode-find-first-stmt (node)
4785 "Search upward starting from NODE looking for a statement.
4786 For purposes of this function, a `js2-function-node' counts."
4787 (while (not (or (js2-stmt-node-p node)
4788 (js2-function-node-p node)))
4789 (setq node (js2-node-parent node)))
4792 (defun js2-node-parent-stmt (node)
4793 "Return the node's first ancestor that is a statement.
4794 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4795 appearing in a statement context will have a parent that is a
4796 `js2-expr-stmt-node' that will be returned by this function."
4797 (let ((parent (js2-node-parent node)))
4798 (if (or (null parent)
4799 (js2-stmt-node-p parent)
4800 (and (js2-function-node-p parent)
4801 (not (eq (js2-function-node-form parent)
4802 'FUNCTION_EXPRESSION))))
4804 (js2-node-parent-stmt parent))))
4806 ;; In the Mozilla Rhino sources, Roshan James writes:
4807 ;; Does consistent-return analysis on the function body when strict mode is
4810 ;; function (x) { return (x+1) }
4814 ;; function (x) { if (x < 0) return (x+1); }
4816 ;; is not because the function can potentially return a value when the
4817 ;; condition is satisfied and if not, the function does not explicitly
4820 ;; This extends to checking mismatches such as "return" and "return <value>"
4821 ;; used in the same function. Warnings are not emitted if inconsistent
4822 ;; returns exist in code that can be statically shown to be unreachable.
4824 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4826 ;; emits no warning. However if the loop had a break statement, then a
4827 ;; warning would be emitted.
4829 ;; The consistency analysis looks at control structures such as loops, ifs,
4830 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4831 ;; warns the user about an inconsistent set of termination possibilities.
4833 ;; These flags enumerate the possible ways a statement/function can
4834 ;; terminate. These flags are used by endCheck() and by the Parser to
4835 ;; detect inconsistent return usage.
4837 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4838 ;; able to execute (example: throw, continue)
4840 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4841 ;; next one. Statement such as return dont. A compound statement may have
4842 ;; some branch that drops off control to the next statement.
4844 ;; END_RETURNS indicates that the statement can return with no value.
4845 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4847 ;; A compound statement such as
4851 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4853 (defconst js2-END_UNREACHED 0)
4854 (defconst js2-END_DROPS_OFF 1)
4855 (defconst js2-END_RETURNS 2)
4856 (defconst js2-END_RETURNS_VALUE 4)
4857 (defconst js2-END_YIELDS 8)
4859 (defun js2-has-consistent-return-usage (node)
4860 "Check that every return usage in a function body is consistent.
4861 Returns t if the function satisfies strict mode requirement."
4862 (let ((n (js2-end-check node)))
4863 ;; either it doesn't return a value in any branch...
4864 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4865 ;; or it returns a value (or is unreached) at every branch
4866 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4870 (defun js2-end-check-if (node)
4871 "Ensure that return usage in then/else blocks is consistent.
4872 If there is no else block, then the return statement can fall through.
4873 Returns logical OR of END_* flags"
4874 (let ((th (js2-if-node-then-part node))
4875 (el (js2-if-node-else-part node)))
4878 (logior (js2-end-check th) (if el
4880 js2-END_DROPS_OFF)))))
4882 (defun js2-end-check-switch (node)
4883 "Consistency of return statements is checked between the case statements.
4884 If there is no default, then the switch can fall through. If there is a
4885 default, we check to see if all code paths in the default return or if
4886 there is a code path that can fall through.
4887 Returns logical OR of END_* flags."
4888 (let ((rv js2-END_UNREACHED)
4890 ;; examine the cases
4892 (dolist (c (js2-switch-node-cases node))
4893 (if (js2-case-node-expr c)
4894 (js2-set-flag rv (js2-end-check-block c))
4895 (setq default-case c)
4896 (throw 'break nil))))
4897 ;; we don't care how the cases drop into each other
4898 (js2-clear-flag rv js2-END_DROPS_OFF)
4899 ;; examine the default
4900 (js2-set-flag rv (if default-case
4901 (js2-end-check default-case)
4905 (defun js2-end-check-try (node)
4906 "If the block has a finally, return consistency is checked in the
4907 finally block. If all code paths in the finally return, then the
4908 returns in the try-catch blocks don't matter. If there is a code path
4909 that does not return or if there is no finally block, the returns
4910 of the try and catch blocks are checked for mismatch.
4911 Returns logical OR of END_* flags."
4912 (let ((finally (js2-try-node-finally-block node))
4914 ;; check the finally if it exists
4915 (setq rv (if finally
4916 (js2-end-check (js2-finally-node-body finally))
4918 ;; If the finally block always returns, then none of the returns
4919 ;; in the try or catch blocks matter.
4920 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4921 (js2-clear-flag rv js2-END_DROPS_OFF)
4922 ;; examine the try block
4923 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4924 ;; check each catch block
4925 (dolist (cb (js2-try-node-catch-clauses node))
4926 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4929 (defun js2-end-check-loop (node)
4930 "Return statement in the loop body must be consistent.
4931 The default assumption for any kind of a loop is that it will eventually
4932 terminate. The only exception is a loop with a constant true condition.
4933 Code that follows such a loop is examined only if one can determine
4934 statically that there is a break out of the loop.
4936 for(... ; ... ; ...) {}
4941 Returns logical OR of END_* flags."
4942 (let ((rv (js2-end-check (js2-loop-node-body node)))
4944 ((js2-while-node-p node)
4945 (js2-while-node-condition node))
4946 ((js2-do-node-p node)
4947 (js2-do-node-condition node))
4948 ((js2-for-node-p node)
4949 (js2-for-node-condition node)))))
4951 ;; check to see if the loop condition is always true
4953 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4954 (js2-clear-flag rv js2-END_DROPS_OFF))
4956 ;; look for effect of breaks
4957 (js2-set-flag rv (js2-node-get-prop node
4962 (defun js2-end-check-block (node)
4963 "A general block of code is examined statement by statement.
4964 If any statement (even a compound one) returns in all branches, then
4965 subsequent statements are not examined.
4966 Returns logical OR of END_* flags."
4967 (let* ((rv js2-END_DROPS_OFF)
4968 (kids (js2-block-node-kids node))
4970 ;; Check each statment. If the statement can continue onto the next
4971 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4972 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4973 (js2-clear-flag rv js2-END_DROPS_OFF)
4974 (js2-set-flag rv (js2-end-check n))
4975 (setq kids (cdr kids)
4979 (defun js2-end-check-label (node)
4980 "A labeled statement implies that there may be a break to the label.
4981 The function processes the labeled statement and then checks the
4982 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4984 Returns logical OR of END_* flags."
4985 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4986 (logior rv (js2-node-get-prop node
4988 js2-END_UNREACHED))))
4990 (defun js2-end-check-break (node)
4991 "When a break is encountered annotate the statement being broken
4992 out of by setting its CONTROL_BLOCK_PROP property.
4993 Returns logical OR of END_* flags."
4994 (and (js2-break-node-target node)
4995 (js2-node-set-prop (js2-break-node-target node)
5000 (defun js2-end-check (node)
5001 "Examine the body of a function, doing a basic reachability analysis.
5002 Returns a combination of flags END_* flags that indicate
5003 how the function execution can terminate. These constitute only the
5004 pessimistic set of termination conditions. It is possible that at
5005 runtime certain code paths will never be actually taken. Hence this
5006 analysis will flag errors in cases where there may not be errors.
5007 Returns logical OR of END_* flags"
5010 ((js2-break-node-p node)
5011 (js2-end-check-break node))
5012 ((js2-expr-stmt-node-p node)
5013 (if (setq kid (js2-expr-stmt-node-expr node))
5016 ((or (js2-continue-node-p node)
5017 (js2-throw-node-p node))
5019 ((js2-return-node-p node)
5020 (if (setq kid (js2-return-node-retval node))
5021 js2-END_RETURNS_VALUE
5023 ((js2-loop-node-p node)
5024 (js2-end-check-loop node))
5025 ((js2-switch-node-p node)
5026 (js2-end-check-switch node))
5027 ((js2-labeled-stmt-node-p node)
5028 (js2-end-check-label node))
5029 ((js2-if-node-p node)
5030 (js2-end-check-if node))
5031 ((js2-try-node-p node)
5032 (js2-end-check-try node))
5033 ((js2-block-node-p node)
5034 (if (null (js2-block-node-kids node))
5036 (js2-end-check-block node)))
5037 ((js2-yield-node-p node)
5040 js2-END_DROPS_OFF))))
5042 (defun js2-always-defined-boolean-p (node)
5043 "Check if NODE always evaluates to true or false in boolean context.
5044 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5046 (let ((tt (js2-node-type node))
5049 ((or (= tt js2-FALSE) (= tt js2-NULL))
5054 (setq num (js2-number-node-num-value node))
5055 (if (and (not (eq num 0.0e+NaN))
5062 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5063 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5065 (defvar js2-tokens nil
5066 "List of all defined token names.") ; initialized in `js2-token-names'
5068 (defconst js2-token-names
5069 (let* ((names (make-vector js2-num-tokens -1))
5070 (case-fold-search nil) ; only match js2-UPPER_CASE
5071 (syms (apropos-internal "^js2-\\(?:[[:upper:]_]+\\)")))
5072 (loop for sym in syms
5075 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5077 (aset names (symbol-value sym) ; code, e.g. 152
5079 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5080 (push sym js2-tokens)))
5082 "Vector mapping int values to token string names, sans `js2-' prefix.")
5084 (defun js2-tt-name (tok)
5085 "Return a string name for TOK, a token symbol or code.
5086 Signals an error if it's not a recognized token."
5089 (setq code (symbol-value tok)))
5092 (if (and (numberp code)
5094 (< code js2-num-tokens))
5095 (aref js2-token-names code)
5096 (error "Invalid token: %s" code)))))
5098 (defsubst js2-tt-sym (tok)
5099 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5100 (intern (js2-tt-name tok)))
5102 (defconst js2-token-codes
5103 (let ((table (make-hash-table :test 'eq :size 256)))
5104 (loop for name across js2-token-names
5105 for sym = (intern (concat "js2-" (upcase name)))
5107 (puthash sym (symbol-value sym) table))
5108 ;; clean up a few that are "wrong" in Rhino's token codes
5109 (puthash 'js2-DELETE js2-DELPROP table)
5111 "Hashtable mapping token type symbols to their bytecodes.")
5113 (defsubst js2-tt-code (sym)
5114 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5115 (or (gethash sym js2-token-codes)
5116 (error "Invalid token symbol: %s " sym))) ; signal code bug
5118 (defun js2-report-scan-error (msg &optional no-throw beg len)
5119 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5120 (js2-report-error msg nil
5121 (or beg (js2-current-token-beg))
5122 (or len (js2-current-token-len)))
5124 (throw 'return js2-ERROR)))
5126 (defun js2-set-string-from-buffer (token)
5127 "Set `string' and `end' slots for TOKEN, return the string."
5128 (setf (js2-token-end token) js2-ts-cursor
5129 (js2-token-string token) (js2-collect-string js2-ts-string-buffer)))
5131 ;; TODO: could potentially avoid a lot of consing by allocating a
5132 ;; char buffer the way Rhino does.
5133 (defsubst js2-add-to-string (c)
5134 (push c js2-ts-string-buffer))
5136 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5137 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5138 ;; any other character: when it's not part of the current token, we
5139 ;; unget it, allowing it to be read again by the following call.
5140 (defsubst js2-unget-char ()
5141 (decf js2-ts-cursor))
5143 ;; Rhino distinguishes \r and \n line endings. We don't need to
5144 ;; because we only scan from Emacs buffers, which always use \n.
5145 (defun js2-get-char ()
5146 "Read and return the next character from the input buffer.
5147 Increments `js2-ts-lineno' if the return value is a newline char.
5148 Updates `js2-ts-cursor' to the point after the returned char.
5149 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5150 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5152 ;; check for end of buffer
5153 (if (>= js2-ts-cursor (point-max))
5154 (setq js2-ts-hit-eof t
5155 js2-ts-cursor (1+ js2-ts-cursor)
5156 c js2-EOF_CHAR) ; return value
5157 ;; otherwise read next char
5158 (setq c (char-before (incf js2-ts-cursor)))
5159 ;; if we read a newline, update counters
5161 (setq js2-ts-line-start js2-ts-cursor
5162 js2-ts-lineno (1+ js2-ts-lineno)))
5163 ;; TODO: skip over format characters
5166 (defun js2-read-unicode-escape ()
5167 "Read a \\uNNNN sequence from the input.
5168 Assumes the ?\ and ?u have already been read.
5169 Returns the unicode character, or nil if it wasn't a valid character.
5170 Doesn't change the values of any scanner variables."
5171 ;; I really wish I knew a better way to do this, but I can't
5172 ;; find the Emacs function that takes a 16-bit int and converts
5173 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5174 ;; Have to first check that it's 4 hex characters or it may stop
5177 (let ((s (buffer-substring-no-properties js2-ts-cursor
5178 (+ 4 js2-ts-cursor))))
5179 (if (string-match "[0-9a-fA-F]\\{4\\}" s)
5180 (read (concat "?\\u" s))))))
5182 (defun js2-match-char (test)
5183 "Consume and return next character if it matches TEST, a character.
5184 Returns nil and consumes nothing if TEST is not the next character."
5185 (let ((c (js2-get-char)))
5191 (defun js2-peek-char ()
5196 (defun js2-identifier-start-p (c)
5197 "Is C a valid start to an ES5 Identifier?
5198 See http://es5.github.io/#x7.6"
5201 (memq (get-char-code-property c 'general-category)
5203 '(Lu Ll Lt Lm Lo Nl))))
5205 (defun js2-identifier-part-p (c)
5206 "Is C a valid part of an ES5 Identifier?
5207 See http://es5.github.io/#x7.6"
5209 (memq c '(?$ ?_ ?\u200c ?\u200d))
5210 (memq (get-char-code-property c 'general-category)
5217 ;; Connector Punctuation
5220 (defun js2-alpha-p (c)
5221 (cond ((and (<= ?A c) (<= c ?Z)) t)
5222 ((and (<= ?a c) (<= c ?z)) t)
5225 (defsubst js2-digit-p (c)
5226 (and (<= ?0 c) (<= c ?9)))
5228 (defun js2-js-space-p (c)
5230 (memq c '(#x20 #x9 #xB #xC #xD))
5233 ;; TODO: change this nil to check for Unicode space character
5236 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5238 (defun js2-skip-line ()
5239 "Skip to end of line."
5240 (while (not (memq (js2-get-char) js2-eol-chars)))
5242 (setf (js2-token-end (js2-current-token)) js2-ts-cursor)
5243 (setq js2-token-end js2-ts-cursor))
5245 (defun js2-init-scanner (&optional buf line)
5246 "Create token stream for BUF starting on LINE.
5247 BUF defaults to `current-buffer' and LINE defaults to 1.
5249 A buffer can only have one scanner active at a time, which yields
5250 dramatically simpler code than using a defstruct. If you need to
5251 have simultaneous scanners in a buffer, copy the regions to scan
5253 (with-current-buffer (or buf (current-buffer))
5254 (setq js2-ts-dirty-line nil
5257 js2-ts-lineno (or line 1)
5258 js2-ts-line-end-char -1
5259 js2-ts-cursor (point-min)
5260 js2-ti-tokens (make-vector js2-ti-ntokens nil)
5261 js2-ti-tokens-cursor 0
5263 js2-ts-is-xml-attribute nil
5264 js2-ts-xml-is-tag-content nil
5265 js2-ts-xml-open-tags-count 0
5266 js2-ts-string-buffer nil)))
5268 ;; This function uses the cached op, string and number fields in
5269 ;; TokenStream; if getToken has been called since the passed token
5270 ;; was scanned, the op or string printed may be incorrect.
5271 (defun js2-token-to-string (token)
5272 ;; Not sure where this function is used in Rhino. Not tested.
5273 (if (not js2-debug-print-trees)
5275 (let ((name (js2-tt-name token)))
5277 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5278 (concat name " `" (js2-current-token-string) "'"))
5279 ((eq token js2-NUMBER)
5280 (format "NUMBER %g" (js2-token-number (js2-current-token))))
5284 (defconst js2-keywords
5286 case catch const continue
5287 debugger default delete do
5289 false finally for function
5290 if in instanceof import
5295 this throw true try typeof
5300 ;; Token names aren't exactly the same as the keywords, unfortunately.
5301 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5302 (defconst js2-kwd-tokens
5303 (let ((table (make-vector js2-num-tokens nil))
5306 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5307 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5309 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5310 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5315 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5320 (aset table i 'font-lock-keyword-face))
5321 (aset table js2-STRING 'font-lock-string-face)
5322 (aset table js2-REGEXP 'font-lock-string-face)
5323 (aset table js2-COMMENT 'font-lock-comment-face)
5324 (aset table js2-THIS 'font-lock-builtin-face)
5325 (aset table js2-VOID 'font-lock-constant-face)
5326 (aset table js2-NULL 'font-lock-constant-face)
5327 (aset table js2-TRUE 'font-lock-constant-face)
5328 (aset table js2-FALSE 'font-lock-constant-face)
5329 (aset table js2-NOT 'font-lock-negation-char-face)
5331 "Vector whose values are non-nil for tokens that are keywords.
5332 The values are default faces to use for highlighting the keywords.")
5334 ;; FIXME: Support strict mode-only future reserved words, after we know
5335 ;; which parts scopes are in strict mode, and which are not.
5336 (defconst js2-reserved-words '(class export extends import super)
5337 "Future reserved keywords in ECMAScript 5.")
5339 (defconst js2-keyword-names
5340 (let ((table (make-hash-table :test 'equal)))
5341 (loop for k in js2-keywords
5343 (symbol-name k) ; instanceof
5344 (intern (concat "js2-"
5345 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5348 "JavaScript keywords by name, mapped to their symbols.")
5350 (defconst js2-reserved-word-names
5351 (let ((table (make-hash-table :test 'equal)))
5352 (loop for k in js2-reserved-words
5354 (puthash (symbol-name k) 'js2-RESERVED table))
5356 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5358 (defun js2-collect-string (buf)
5359 "Convert BUF, a list of chars, to a string.
5360 Reverses BUF before converting."
5362 (apply #'string (nreverse buf))
5365 (defun js2-string-to-keyword (s)
5366 "Return token for S, a string, if S is a keyword or reserved word.
5367 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5368 (or (gethash s js2-keyword-names)
5369 (gethash s js2-reserved-word-names)))
5371 (defsubst js2-ts-set-char-token-bounds (token)
5372 "Used when next token is one character."
5373 (setf (js2-token-beg token) (1- js2-ts-cursor)
5374 (js2-token-end token) js2-ts-cursor))
5376 (defsubst js2-ts-return (token type)
5377 "Update the `end' and `type' slots of TOKEN,
5378 then throw `return' with value TYPE."
5379 (setf (js2-token-end token) js2-ts-cursor
5380 (js2-token-type token) type)
5381 (throw 'return type))
5383 (defun js2-x-digit-to-int (c accumulator)
5384 "Build up a hex number.
5385 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5386 corresponding number. Otherwise return -1."
5389 ;; Use 0..9 < A..Z < a..z
5394 (throw 'check nil)))
5398 (throw 'check nil)))
5402 (throw 'check nil))))
5404 (logior c (lsh accumulator 4))))
5406 (defun js2-get-token ()
5407 "If `js2-ti-lookahead' is zero, call scanner to get new token.
5408 Otherwise, move `js2-ti-tokens-cursor' and return the type of
5411 This function will not return a newline (js2-EOL) - instead, it
5412 gobbles newlines until it finds a non-newline token. Call
5413 `js2-peek-token-or-eol' when you care about newlines.
5415 This function will also not return a js2-COMMENT. Instead, it
5416 records comments found in `js2-scanned-comments'. If the token
5417 returned by this function immediately follows a jsdoc comment,
5418 the token is flagged as such."
5419 (if (zerop js2-ti-lookahead)
5420 (js2-get-token-internal)
5421 (decf js2-ti-lookahead)
5422 (setq js2-ti-tokens-cursor (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens))
5423 (let ((tt (js2-current-token-type)))
5424 (assert (not (= tt js2-EOL)))
5427 (defun js2-unget-token ()
5428 (assert (< js2-ti-lookahead js2-ti-max-lookahead))
5429 (incf js2-ti-lookahead)
5430 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens)))
5432 (defun js2-get-token-internal ()
5433 (let* ((token (js2-get-token-internal-1)) ; call scanner
5434 (tt (js2-token-type token))
5438 (while (or (= tt js2-EOL) (= tt js2-COMMENT))
5442 (when js2-record-comments
5443 (js2-record-comment token)))
5444 (setq js2-ti-tokens-cursor (mod (1- js2-ti-tokens-cursor) js2-ti-ntokens))
5445 (setq token (js2-get-token-internal-1) ; call scanner again
5446 tt (js2-token-type token)))
5449 (setf (js2-token-follows-eol-p token) t))
5451 ;; perform lexical fontification as soon as token is scanned
5452 (when js2-parse-ide-mode
5455 (js2-record-face 'js2-error token))
5456 ((setq face (aref js2-kwd-tokens tt))
5457 (js2-record-face face token))
5458 ((and (= tt js2-NAME)
5459 (equal (js2-token-string token) "undefined"))
5460 (js2-record-face 'font-lock-constant-face token))))
5463 (defun js2-get-token-internal-1 ()
5464 "Return next JavaScript token type, an int such as js2-RETURN.
5465 During operation, creates an instance of `js2-token' struct, sets
5466 its relevant fields and puts it into `js2-ti-tokens'."
5467 (let (c c1 identifier-start is-unicode-escape-start
5468 contains-escape escape-val str result base
5469 quote-char val look-for-slash continue tt
5470 (token (js2-new-token 0)))
5475 ;; Eat whitespace, possibly sensitive to newlines.
5478 (setq c (js2-get-char))
5480 ((eq c js2-EOF_CHAR)
5482 (js2-ts-set-char-token-bounds token)
5483 (throw 'return js2-EOF))
5485 (js2-ts-set-char-token-bounds token)
5486 (setq js2-ts-dirty-line nil)
5487 (throw 'return js2-EOL))
5488 ((not (js2-js-space-p c))
5489 (if (/= c ?-) ; in case end of HTML comment
5490 (setq js2-ts-dirty-line t))
5491 (setq continue nil))))
5492 ;; Assume the token will be 1 char - fixed up below.
5493 (js2-ts-set-char-token-bounds token)
5495 (throw 'return js2-XMLATTR))
5496 ;; identifier/keyword/instanceof?
5497 ;; watch out for starting with a <backslash>
5500 (setq c (js2-get-char))
5502 (setq identifier-start t
5503 is-unicode-escape-start t
5504 js2-ts-string-buffer nil)
5505 (setq identifier-start nil)
5509 (when (setq identifier-start (js2-identifier-start-p c))
5510 (setq js2-ts-string-buffer nil)
5511 (js2-add-to-string c))))
5512 (when identifier-start
5513 (setq contains-escape is-unicode-escape-start)
5516 (if is-unicode-escape-start
5517 ;; strictly speaking we should probably push-back
5518 ;; all the bad characters if the <backslash>uXXXX
5519 ;; sequence is malformed. But since there isn't a
5520 ;; correct context(is there?) for a bad Unicode
5521 ;; escape sequence in an identifier, we can report
5526 (setq c (js2-get-char)
5527 escape-val (js2-x-digit-to-int c escape-val))
5528 ;; Next check takes care of c < 0 and bad escape
5529 (if (minusp escape-val)
5530 (throw 'break nil)))
5531 (if (minusp escape-val)
5532 (js2-report-scan-error "msg.invalid.escape" t))
5533 (js2-add-to-string escape-val)
5534 (setq is-unicode-escape-start nil))
5535 (setq c (js2-get-char))
5538 (setq c (js2-get-char))
5540 (setq is-unicode-escape-start t
5542 (js2-report-scan-error "msg.illegal.character" t)))
5544 (if (or (eq c js2-EOF_CHAR)
5545 (not (js2-identifier-part-p c)))
5547 (js2-add-to-string c))))))
5549 (setf str (js2-collect-string js2-ts-string-buffer)
5550 (js2-token-end token) js2-ts-cursor)
5551 ;; FIXME: Invalid in ES5 and ES6, see
5552 ;; https://bugzilla.mozilla.org/show_bug.cgi?id=694360
5553 ;; Probably should just drop this conditional.
5554 (unless contains-escape
5555 ;; OPT we shouldn't have to make a string (object!) to
5556 ;; check if it's a keyword.
5557 ;; Return the corresponding token if it's a keyword
5558 (when (setq result (js2-string-to-keyword str))
5559 (if (and (< js2-language-version 170)
5560 (memq result '(js2-LET js2-YIELD)))
5561 ;; LET and YIELD are tokens only in 1.7 and later
5562 (setq result 'js2-NAME))
5563 (when (eq result 'js2-RESERVED)
5564 (setf (js2-token-string token) str))
5565 (throw 'return (js2-tt-code result))))
5566 ;; If we want to intern these as Rhino does, just use (intern str)
5567 (setf (js2-token-string token) str)
5568 (throw 'return js2-NAME)) ; end identifier/kwd check
5570 (when (or (js2-digit-p c)
5571 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5572 (setq js2-ts-string-buffer nil
5575 (setq c (js2-get-char))
5577 ((or (eq c ?x) (eq c ?X))
5579 (setq c (js2-get-char)))
5580 ((and (or (eq c ?b) (eq c ?B))
5581 (>= js2-language-version 200))
5583 (setq c (js2-get-char)))
5584 ((and (or (eq c ?o) (eq c ?O))
5585 (>= js2-language-version 200))
5587 (setq c (js2-get-char)))
5589 (setq base 'maybe-8))
5591 (js2-add-to-string ?0))))
5594 (if (> 0 (js2-x-digit-to-int c 0))
5595 (js2-report-scan-error "msg.missing.hex.digits")
5596 (while (<= 0 (js2-x-digit-to-int c 0))
5597 (js2-add-to-string c)
5598 (setq c (js2-get-char)))))
5600 (if (not (memq c '(?0 ?1)))
5601 (js2-report-scan-error "msg.missing.binary.digits")
5602 (while (memq c '(?0 ?1))
5603 (js2-add-to-string c)
5604 (setq c (js2-get-char)))))
5606 (if (or (> ?0 c) (< ?7 c))
5607 (js2-report-scan-error "msg.missing.octal.digits")
5608 (while (and (<= ?0 c) (>= ?7 c))
5609 (js2-add-to-string c)
5610 (setq c (js2-get-char)))))
5612 (while (and (<= ?0 c) (<= c ?9))
5613 ;; We permit 08 and 09 as decimal numbers, which
5614 ;; makes our behavior a superset of the ECMA
5615 ;; numeric grammar. We might not always be so
5616 ;; permissive, so we warn about it.
5617 (when (and (eq base 'maybe-8) (>= c ?8))
5618 (js2-report-warning "msg.bad.octal.literal"
5619 (if (eq c ?8) "8" "9"))
5621 (js2-add-to-string c)
5622 (setq c (js2-get-char)))
5623 (when (eq base 'maybe-8)
5625 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5628 (js2-add-to-string c)
5629 (setq c (js2-get-char))
5630 while (js2-digit-p c)))
5631 (when (memq c '(?e ?E))
5632 (js2-add-to-string c)
5633 (setq c (js2-get-char))
5634 (when (memq c '(?+ ?-))
5635 (js2-add-to-string c)
5636 (setq c (js2-get-char)))
5637 (unless (js2-digit-p c)
5638 (js2-report-scan-error "msg.missing.exponent" t))
5640 (js2-add-to-string c)
5641 (setq c (js2-get-char))
5642 while (js2-digit-p c))))
5644 (let ((str (js2-set-string-from-buffer token)))
5645 (setf (js2-token-number token)
5646 (js2-string-to-number str base)))
5647 (throw 'return js2-NUMBER))
5649 (when (memq c '(?\" ?\'))
5650 ;; We attempt to accumulate a string the fast way, by
5651 ;; building it directly out of the reader. But if there
5652 ;; are any escaped characters in the string, we revert to
5653 ;; building it out of a string buffer.
5655 js2-ts-string-buffer nil
5658 (while (/= c quote-char)
5660 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5662 (setf (js2-token-end token) js2-ts-cursor)
5663 (js2-report-error "msg.unterminated.string.lit")
5664 (throw 'return js2-STRING))
5666 ;; We've hit an escaped character
5667 (setq c (js2-get-char))
5676 (setq c1 (js2-read-unicode-escape))
5677 (if js2-parse-ide-mode
5680 ;; just copy the string in IDE-mode
5681 (js2-add-to-string ?\\)
5682 (js2-add-to-string ?u)
5684 (js2-add-to-string (js2-get-char)))
5685 (setq c (js2-get-char))) ; added at end of loop
5686 ;; flag it as an invalid escape
5687 (js2-report-warning "msg.invalid.escape"
5688 nil (- js2-ts-cursor 2) 6))
5689 ;; Get 4 hex digits; if the u escape is not
5690 ;; followed by 4 hex digits, use 'u' + the
5691 ;; literal character sequence that follows.
5692 (js2-add-to-string ?u)
5695 (setq c (js2-get-char)
5696 escape-val (js2-x-digit-to-int c escape-val))
5697 (if (minusp escape-val)
5698 (throw 'continue nil))
5699 (js2-add-to-string c))
5700 ;; prepare for replace of stored 'u' sequence by escape value
5701 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5704 ;; Get 2 hex digits, defaulting to 'x'+literal
5705 ;; sequence, as above.
5706 (setq c (js2-get-char)
5707 escape-val (js2-x-digit-to-int c 0))
5708 (if (minusp escape-val)
5710 (js2-add-to-string ?x)
5711 (throw 'continue nil))
5714 escape-val (js2-x-digit-to-int c escape-val))
5715 (if (minusp escape-val)
5717 (js2-add-to-string ?x)
5718 (js2-add-to-string c1)
5719 (throw 'continue nil))
5721 (setq c escape-val))))
5723 ;; Remove line terminator after escape to follow
5724 ;; SpiderMonkey and C/C++
5725 (setq c (js2-get-char))
5726 (throw 'continue nil))
5728 (when (and (<= ?0 c) (< c ?8))
5731 (when (and (<= ?0 c) (< c ?8))
5732 (setq val (- (+ (* 8 val) c) ?0)
5734 (when (and (<= ?0 c)
5737 ;; c is 3rd char of octal sequence only
5738 ;; if the resulting val <= 0377
5739 (setq val (- (+ (* 8 val) c) ?0)
5743 (js2-add-to-string c)
5744 (setq c (js2-get-char)))))
5745 (js2-set-string-from-buffer token)
5746 (throw 'return js2-STRING))
5747 (js2-ts-return token
5750 (throw 'return js2-SEMI))
5752 (throw 'return js2-LB))
5754 (throw 'return js2-RB))
5756 (throw 'return js2-LC))
5758 (throw 'return js2-RC))
5760 (throw 'return js2-LP))
5762 (throw 'return js2-RP))
5764 (throw 'return js2-COMMA))
5766 (throw 'return js2-HOOK))
5768 (if (js2-match-char ?:)
5770 (throw 'return js2-COLON)))
5772 (if (js2-match-char ?.)
5773 (if (js2-match-char ?.)
5774 js2-TRIPLEDOT js2-DOTDOT)
5775 (if (js2-match-char ?\()
5777 (throw 'return js2-DOT))))
5779 (if (js2-match-char ?|)
5780 (throw 'return js2-OR)
5781 (if (js2-match-char ?=)
5783 (throw 'return js2-BITOR))))
5785 (if (js2-match-char ?=)
5787 (throw 'return js2-BITXOR)))
5789 (if (js2-match-char ?&)
5790 (throw 'return js2-AND)
5791 (if (js2-match-char ?=)
5793 (throw 'return js2-BITAND))))
5795 (if (js2-match-char ?=)
5796 (if (js2-match-char ?=)
5798 (throw 'return js2-EQ))
5799 (if (js2-match-char ?>)
5800 (js2-ts-return token js2-ARROW)
5801 (throw 'return js2-ASSIGN))))
5803 (if (js2-match-char ?=)
5804 (if (js2-match-char ?=)
5807 (throw 'return js2-NOT)))
5809 ;; NB:treat HTML begin-comment as comment-till-eol
5810 (when (js2-match-char ?!)
5811 (when (js2-match-char ?-)
5812 (when (js2-match-char ?-)
5814 (setf (js2-token-comment-type (js2-current-token)) 'html)
5815 (throw 'return js2-COMMENT)))
5817 (if (js2-match-char ?<)
5818 (if (js2-match-char ?=)
5821 (if (js2-match-char ?=)
5823 (throw 'return js2-LT))))
5825 (if (js2-match-char ?>)
5826 (if (js2-match-char ?>)
5827 (if (js2-match-char ?=)
5830 (if (js2-match-char ?=)
5833 (if (js2-match-char ?=)
5835 (throw 'return js2-GT))))
5837 (if (js2-match-char ?=)
5839 (throw 'return js2-MUL)))
5841 ;; is it a // comment?
5842 (when (js2-match-char ?/)
5843 (setf (js2-token-beg token) (- js2-ts-cursor 2))
5845 (setf (js2-token-comment-type token) 'line)
5846 ;; include newline so highlighting goes to end of window
5847 (incf (js2-token-end token))
5848 (throw 'return js2-COMMENT))
5849 ;; is it a /* comment?
5850 (when (js2-match-char ?*)
5851 (setf look-for-slash nil
5852 (js2-token-beg token) (- js2-ts-cursor 2)
5853 (js2-token-comment-type token)
5854 (if (js2-match-char ?*)
5856 (setq look-for-slash t)
5860 (setq c (js2-get-char))
5862 ((eq c js2-EOF_CHAR)
5863 (setf (js2-token-end token) (1- js2-ts-cursor))
5864 (js2-report-error "msg.unterminated.comment")
5865 (throw 'return js2-COMMENT))
5867 (setq look-for-slash t))
5870 (js2-ts-return token js2-COMMENT)))
5872 (setf look-for-slash nil
5873 (js2-token-end token) js2-ts-cursor)))))
5874 (if (js2-match-char ?=)
5876 (throw 'return js2-DIV)))
5878 (when js2-skip-preprocessor-directives
5880 (setf (js2-token-comment-type token) 'preprocessor
5881 (js2-token-end token) js2-ts-cursor)
5882 (throw 'return js2-COMMENT))
5883 (throw 'return js2-ERROR))
5885 (if (js2-match-char ?=)
5887 (throw 'return js2-MOD)))
5889 (throw 'return js2-BITNOT))
5891 (if (js2-match-char ?=)
5893 (if (js2-match-char ?+)
5895 (throw 'return js2-ADD))))
5898 ((js2-match-char ?=)
5899 (setq c js2-ASSIGN_SUB))
5900 ((js2-match-char ?-)
5901 (unless js2-ts-dirty-line
5902 ;; treat HTML end-comment after possible whitespace
5903 ;; after line start as comment-until-eol
5904 (when (js2-match-char ?>)
5906 (setf (js2-token-comment-type (js2-current-token)) 'html)
5907 (throw 'return js2-COMMENT)))
5911 (setq js2-ts-dirty-line t)
5914 (js2-report-scan-error "msg.illegal.character")))))))
5915 (setf (js2-token-type token) tt)
5918 (defsubst js2-string-to-number (str base)
5919 ;; TODO: Maybe port ScriptRuntime.stringToNumber.
5921 (string-to-number str base)
5922 (overflow-error -1)))
5924 (defun js2-read-regexp (start-tt)
5925 "Called by parser when it gets / or /= in literal context."
5927 in-class ; inside a '[' .. ']' character-class
5930 (token (js2-new-token 0)))
5931 (setq js2-ts-string-buffer nil)
5932 (if (eq start-tt js2-ASSIGN_DIV)
5934 (js2-add-to-string ?=)
5935 (if (not (eq start-tt js2-DIV))
5936 (error "failed assertion")))
5937 (while (and (not err)
5938 (or (/= (setq c (js2-get-char)) ?/)
5943 (setf (js2-token-end token) (1- js2-ts-cursor)
5945 (js2-token-string token) (js2-collect-string js2-ts-string-buffer))
5946 (js2-report-error "msg.unterminated.re.lit"))
5949 (js2-add-to-string c)
5950 (setq c (js2-get-char)))
5954 (setq in-class nil)))
5955 (js2-add-to-string c))))
5959 ((js2-match-char ?g)
5961 ((js2-match-char ?i)
5963 ((js2-match-char ?m)
5965 ((and (js2-match-char ?u)
5966 (>= js2-language-version 200))
5968 ((and (js2-match-char ?y)
5969 (>= js2-language-version 200))
5972 (setq continue nil))))
5973 (if (js2-alpha-p (js2-peek-char))
5974 (js2-report-scan-error "msg.invalid.re.flag" t
5976 (js2-set-string-from-buffer token))
5977 (js2-collect-string flags)))
5979 (defun js2-get-first-xml-token ()
5980 (setq js2-ts-xml-open-tags-count 0
5981 js2-ts-is-xml-attribute nil
5982 js2-ts-xml-is-tag-content nil)
5984 (js2-get-next-xml-token))
5986 (defun js2-xml-discard-string (token)
5987 "Throw away the string in progress and flag an XML parse error."
5988 (setf js2-ts-string-buffer nil
5989 (js2-token-string token) nil)
5990 (js2-report-scan-error "msg.XML.bad.form" t))
5992 (defun js2-get-next-xml-token ()
5993 (setq js2-ts-string-buffer nil) ; for recording the XML
5994 (let ((token (js2-new-token 0))
5999 (setq c (js2-get-char))
6002 (throw 'return js2-ERROR))
6003 (js2-ts-xml-is-tag-content
6006 (js2-add-to-string c)
6007 (setq js2-ts-xml-is-tag-content nil
6008 js2-ts-is-xml-attribute nil))
6010 (js2-add-to-string c)
6011 (when (eq ?> (js2-peek-char))
6012 (setq c (js2-get-char))
6013 (js2-add-to-string c)
6014 (setq js2-ts-xml-is-tag-content nil)
6015 (decf js2-ts-xml-open-tags-count)))
6018 (js2-set-string-from-buffer token)
6019 (throw 'return js2-XML))
6021 (js2-add-to-string c)
6022 (unless (js2-read-quoted-string c token)
6023 (throw 'return js2-ERROR)))
6025 (js2-add-to-string c)
6026 (setq js2-ts-is-xml-attribute t))
6028 (js2-add-to-string c))
6030 (js2-add-to-string c)
6031 (setq js2-ts-is-xml-attribute nil)))
6032 (when (and (not js2-ts-xml-is-tag-content)
6033 (zerop js2-ts-xml-open-tags-count))
6034 (js2-set-string-from-buffer token)
6035 (throw 'return js2-XMLEND)))
6037 ;; else not tag content
6040 (js2-add-to-string c)
6041 (setq c (js2-peek-char))
6044 (setq c (js2-get-char)) ;; skip !
6045 (js2-add-to-string c)
6046 (setq c (js2-peek-char))
6049 (setq c (js2-get-char)) ;; skip -
6050 (js2-add-to-string c)
6053 (js2-add-to-string c)
6054 (unless (js2-read-xml-comment token)
6055 (throw 'return js2-ERROR)))
6056 (js2-xml-discard-string token)
6057 (throw 'return js2-ERROR)))
6059 (setq c (js2-get-char)) ;; skip [
6060 (js2-add-to-string c)
6061 (if (and (= (js2-get-char) ?C)
6062 (= (js2-get-char) ?D)
6063 (= (js2-get-char) ?A)
6064 (= (js2-get-char) ?T)
6065 (= (js2-get-char) ?A)
6066 (= (js2-get-char) ?\[))
6068 (js2-add-to-string ?C)
6069 (js2-add-to-string ?D)
6070 (js2-add-to-string ?A)
6071 (js2-add-to-string ?T)
6072 (js2-add-to-string ?A)
6073 (js2-add-to-string ?\[)
6074 (unless (js2-read-cdata token)
6075 (throw 'return js2-ERROR)))
6076 (js2-xml-discard-string token)
6077 (throw 'return js2-ERROR)))
6079 (unless (js2-read-entity token)
6080 (throw 'return js2-ERROR))))
6081 ;; Allow bare CDATA section, e.g.:
6082 ;; let xml = <![CDATA[ foo bar baz ]]>;
6083 (when (zerop js2-ts-xml-open-tags-count)
6084 (throw 'return js2-XMLEND)))
6086 (setq c (js2-get-char)) ;; skip ?
6087 (js2-add-to-string c)
6088 (unless (js2-read-PI token)
6089 (throw 'return js2-ERROR)))
6092 (setq c (js2-get-char)) ;; skip /
6093 (js2-add-to-string c)
6094 (when (zerop js2-ts-xml-open-tags-count)
6095 (js2-xml-discard-string token)
6096 (throw 'return js2-ERROR))
6097 (setq js2-ts-xml-is-tag-content t)
6098 (decf js2-ts-xml-open-tags-count))
6101 (setq js2-ts-xml-is-tag-content t)
6102 (incf js2-ts-xml-open-tags-count))))
6105 (js2-set-string-from-buffer token)
6106 (throw 'return js2-XML))
6108 (js2-add-to-string c))))))))
6109 (setf (js2-token-end token) js2-ts-cursor)
6110 (setf (js2-token-type token) result)
6113 (defun js2-read-quoted-string (quote token)
6116 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6117 (js2-add-to-string c)
6120 (js2-xml-discard-string token) ;; throw away string in progress
6123 (defun js2-read-xml-comment (token)
6124 (let ((c (js2-get-char)))
6126 (while (/= c js2-EOF_CHAR)
6128 (js2-add-to-string c)
6129 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6130 (setq c (js2-get-char))
6131 (js2-add-to-string c)
6132 (if (eq (js2-peek-char) ?>)
6134 (setq c (js2-get-char)) ;; skip >
6135 (js2-add-to-string c)
6137 (throw 'continue nil)))
6138 (setq c (js2-get-char))))
6139 (js2-xml-discard-string token)
6142 (defun js2-read-cdata (token)
6143 (let ((c (js2-get-char)))
6145 (while (/= c js2-EOF_CHAR)
6147 (js2-add-to-string c)
6148 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6149 (setq c (js2-get-char))
6150 (js2-add-to-string c)
6151 (if (eq (js2-peek-char) ?>)
6153 (setq c (js2-get-char)) ;; Skip >
6154 (js2-add-to-string c)
6156 (throw 'continue nil)))
6157 (setq c (js2-get-char))))
6158 (js2-xml-discard-string token)
6161 (defun js2-read-entity (token)
6165 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6166 (js2-add-to-string c)
6172 (if (zerop decl-tags)
6173 (throw 'return t)))))
6174 (js2-xml-discard-string token)
6177 (defun js2-read-PI (token)
6178 "Scan an XML processing instruction."
6181 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6182 (js2-add-to-string c)
6183 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6184 (setq c (js2-get-char)) ;; Skip >
6185 (js2-add-to-string c)
6187 (js2-xml-discard-string token)
6192 (defun js2-set-face (beg end face &optional record)
6193 "Fontify a region. If RECORD is non-nil, record for later."
6194 (when (plusp js2-highlight-level)
6195 (setq beg (min (point-max) beg)
6196 beg (max (point-min) beg)
6197 end (min (point-max) end)
6198 end (max (point-min) end))
6200 (push (list beg end face) js2-mode-fontifications)
6201 (put-text-property beg end 'font-lock-face face))))
6203 (defsubst js2-clear-face (beg end)
6204 (remove-text-properties beg end '(font-lock-face nil
6209 (defconst js2-ecma-global-props
6212 '("Infinity" "NaN" "undefined" "arguments") t)
6214 "Value properties of the Ecma-262 Global Object.
6215 Shown at or above `js2-highlight-level' 2.")
6217 ;; might want to add the name "arguments" to this list?
6218 (defconst js2-ecma-object-props
6221 '("prototype" "__proto__" "__parent__") t)
6223 "Value properties of the Ecma-262 Object constructor.
6224 Shown at or above `js2-highlight-level' 2.")
6226 (defconst js2-ecma-global-funcs
6230 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6231 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6233 "Function properties of the Ecma-262 Global object.
6234 Shown at or above `js2-highlight-level' 2.")
6236 (defconst js2-ecma-number-props
6238 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6240 "POSITIVE_INFINITY") t)
6242 "Properties of the Ecma-262 Number constructor.
6243 Shown at or above `js2-highlight-level' 2.")
6245 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6246 "Properties of the Ecma-262 Date constructor.
6247 Shown at or above `js2-highlight-level' 2.")
6249 (defconst js2-ecma-math-props
6252 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6255 "Properties of the Ecma-262 Math object.
6256 Shown at or above `js2-highlight-level' 2.")
6258 (defconst js2-ecma-math-funcs
6261 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6262 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6264 "Function properties of the Ecma-262 Math object.
6265 Shown at or above `js2-highlight-level' 2.")
6267 (defconst js2-ecma-function-props
6271 '(;; properties of the Object prototype object
6272 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6273 "toLocaleString" "toString" "valueOf"
6274 ;; properties of the Function prototype object
6276 ;; properties of the Array prototype object
6277 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6279 ;; properties of the String prototype object
6280 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6281 "localeCompare" "match" "replace" "search" "split" "substring"
6282 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6284 ;; properties of the Number prototype object
6285 "toExponential" "toFixed" "toPrecision"
6286 ;; properties of the Date prototype object
6287 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6288 "getMinutes" "getMonth" "getSeconds" "getTime"
6289 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6290 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6291 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6292 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6293 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6294 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6295 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6296 "toTimeString" "toUTCString"
6297 ;; properties of the RegExp prototype object
6299 ;; properties of the JSON prototype object
6301 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6302 "toSource" "__defineGetter__" "__defineSetter__"
6303 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6304 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6307 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6308 Shown at or above `js2-highlight-level' 3.")
6310 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6311 (let ((target-name (and target
6312 (js2-name-node-p target)
6313 (js2-name-node-name target)))
6314 (prop-name (if prop (js2-name-node-name prop)))
6315 (level2 (>= js2-highlight-level 2))
6316 (level3 (>= js2-highlight-level 3)))
6323 ((and level3 (string-match js2-ecma-function-props prop-name))
6324 'font-lock-builtin-face)
6325 ((and target-name prop)
6327 ((string= target-name "Date")
6328 (if (string-match js2-ecma-date-props prop-name)
6329 'font-lock-builtin-face))
6330 ((string= target-name "Math")
6331 (if (string-match js2-ecma-math-funcs prop-name)
6332 'font-lock-builtin-face))))))
6334 (if (string-match js2-ecma-global-funcs prop-name)
6335 'font-lock-builtin-face)))
6339 ((string= target-name "Number")
6340 (if (string-match js2-ecma-number-props prop-name)
6341 'font-lock-constant-face))
6342 ((string= target-name "Math")
6343 (if (string-match js2-ecma-math-props prop-name)
6344 'font-lock-constant-face))))
6346 (if (string-match js2-ecma-object-props prop-name)
6347 'font-lock-constant-face))))))
6349 (let ((pos (+ (js2-node-pos parent) ; absolute
6350 (js2-node-pos prop)))) ; relative
6352 (+ pos (js2-node-len prop))
6355 (defun js2-parse-highlight-member-expr-node (node)
6356 "Perform syntax highlighting of EcmaScript built-in properties.
6357 The variable `js2-highlight-level' governs this highighting."
6358 (let (face target prop name pos end parent call-p callee)
6360 ;; case 1: simple name, e.g. foo
6361 ((js2-name-node-p node)
6362 (setq name (js2-name-node-name node))
6363 ;; possible for name to be nil in rare cases - saw it when
6364 ;; running js2-mode on an elisp buffer. Might as well try to
6365 ;; make it so js2-mode never barfs.
6367 (setq face (if (string-match js2-ecma-global-props name)
6368 'font-lock-constant-face))
6370 (setq pos (js2-node-pos node)
6371 end (+ pos (js2-node-len node)))
6372 (js2-set-face pos end face 'record))))
6373 ;; case 2: property access or function call
6374 ((or (js2-prop-get-node-p node)
6375 ;; highlight function call if expr is a prop-get node
6376 ;; or a plain name (i.e. unqualified function call)
6377 (and (setq call-p (js2-call-node-p node))
6378 (setq callee (js2-call-node-target node)) ; separate setq!
6379 (or (js2-prop-get-node-p callee)
6380 (js2-name-node-p callee))))
6382 node (if call-p callee node))
6383 (if (and call-p (js2-name-node-p callee))
6385 (setq target (js2-prop-get-node-left node)
6386 prop (js2-prop-get-node-right node)))
6388 ((js2-name-node-p prop)
6389 ;; case 2(a&c): simple or complex target, simple name, e.g. x[y].bar
6390 (js2-parse-highlight-prop-get parent target prop call-p))
6391 ((js2-name-node-p target)
6392 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6393 (js2-parse-highlight-prop-get parent target nil call-p)))))))
6395 (defun js2-parse-highlight-member-expr-fn-name (expr)
6396 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6397 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6398 We currently only handle the case where the last component is a prop-get
6399 of a simple name. Called before EXPR has a parent node."
6401 (name (and (js2-prop-get-node-p expr)
6402 (js2-prop-get-node-right expr))))
6403 (when (js2-name-node-p name)
6404 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6405 (js2-node-pos name)))
6406 (+ pos (js2-node-len name))
6407 'font-lock-function-name-face
6410 ;; source: http://jsdoc.sourceforge.net/
6411 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6412 ;; allows type specifications, and needs work before entering the wild.
6414 (defconst js2-jsdoc-param-tag-regexp
6415 (concat "^\\s-*\\*+\\s-*\\(@"
6416 "\\(?:param\\|argument\\)"
6418 "\\s-*\\({[^}]+}\\)?" ; optional type
6419 "\\s-*\\[?\\([[:alnum:]_$\.]+\\)?\\]?" ; name
6421 "Matches jsdoc tags with optional type and optional param name.")
6423 (defconst js2-jsdoc-typed-tag-regexp
6424 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6438 "\\)\\)\\s-*\\({[^}]+}\\)?")
6439 "Matches jsdoc tags with optional type.")
6441 (defconst js2-jsdoc-arg-tag-regexp
6442 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6465 "\\)\\)\\s-+\\([^ \t]+\\)")
6466 "Matches jsdoc tags with a single argument.")
6468 (defconst js2-jsdoc-empty-tag-regexp
6469 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6509 "Matches empty jsdoc tags.")
6511 (defconst js2-jsdoc-link-tag-regexp
6512 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6513 "Matches a jsdoc link or code tag.")
6515 (defconst js2-jsdoc-see-tag-regexp
6516 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6517 "Matches a jsdoc @see tag.")
6519 (defconst js2-jsdoc-html-tag-regexp
6520 "\\(</?\\)\\([[:alpha:]]+\\)\\s-*\\(/?>\\)"
6521 "Matches a simple (no attributes) html start- or end-tag.")
6523 (defun js2-jsdoc-highlight-helper ()
6524 (js2-set-face (match-beginning 1)
6527 (if (match-beginning 2)
6529 (goto-char (match-beginning 2))
6530 (= (char-after) ?{))
6531 (js2-set-face (1+ (match-beginning 2))
6534 (js2-set-face (match-beginning 2)
6537 (if (match-beginning 3)
6538 (js2-set-face (match-beginning 3)
6542 (defun js2-highlight-jsdoc (ast)
6543 "Highlight doc comment tags."
6544 (let ((comments (js2-ast-root-comments ast))
6547 (dolist (node comments)
6548 (when (eq (js2-comment-node-format node) 'jsdoc)
6549 (setq beg (js2-node-abs-pos node)
6550 end (+ beg (js2-node-len node)))
6552 (narrow-to-region beg end)
6553 (dolist (re (list js2-jsdoc-param-tag-regexp
6554 js2-jsdoc-typed-tag-regexp
6555 js2-jsdoc-arg-tag-regexp
6556 js2-jsdoc-link-tag-regexp
6557 js2-jsdoc-see-tag-regexp
6558 js2-jsdoc-empty-tag-regexp))
6560 (while (re-search-forward re nil t)
6561 (js2-jsdoc-highlight-helper)))
6562 ;; simple highlighting for html tags
6564 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6565 (js2-set-face (match-beginning 1)
6567 'js2-jsdoc-html-tag-delimiter)
6568 (js2-set-face (match-beginning 2)
6570 'js2-jsdoc-html-tag-name)
6571 (js2-set-face (match-beginning 3)
6573 'js2-jsdoc-html-tag-delimiter))))))))
6575 (defun js2-highlight-assign-targets (_node left right)
6576 "Highlight function properties and external variables."
6578 ;; highlight vars and props assigned function values
6579 (when (js2-function-node-p right)
6581 ;; var foo = function() {...}
6582 ((js2-name-node-p left)
6584 ;; foo.bar.baz = function() {...}
6585 ((and (js2-prop-get-node-p left)
6586 (js2-name-node-p (js2-prop-get-node-right left)))
6587 (setq name (js2-prop-get-node-right left))))
6589 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6590 (+ leftpos (js2-node-len name))
6591 'font-lock-function-name-face
6594 (defun js2-record-name-node (node)
6595 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6596 later. NODE must be a name node."
6597 (let ((leftpos (js2-node-abs-pos node)))
6598 (push (list node js2-current-scope
6600 (+ leftpos (js2-node-len node)))
6601 js2-recorded-identifiers)))
6603 (defun js2-highlight-undeclared-vars ()
6604 "After entire parse is finished, look for undeclared variable references.
6605 We have to wait until entire buffer is parsed, since JavaScript permits var
6606 decls to occur after they're used.
6608 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6609 it is considered declared."
6611 (dolist (entry js2-recorded-identifiers)
6612 (destructuring-bind (name-node scope pos end) entry
6613 (setq name (js2-name-node-name name-node))
6614 (unless (or (member name js2-global-externs)
6615 (member name js2-default-externs)
6616 (member name js2-additional-externs)
6617 (js2-get-defining-scope scope name))
6618 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6619 'js2-external-variable))))
6620 (setq js2-recorded-identifiers nil)))
6622 (defun js2-set-default-externs ()
6623 "Set the value of `js2-default-externs' based on the various
6624 `js2-include-?-externs' variables."
6625 (setq js2-default-externs
6626 (append js2-ecma-262-externs
6627 (if js2-include-browser-externs js2-browser-externs)
6628 (if (and js2-include-browser-externs
6629 (>= js2-language-version 200)) js2-harmony-externs)
6630 (if js2-include-rhino-externs js2-rhino-externs)
6631 (if js2-include-node-externs js2-node-externs)
6632 (if (or js2-include-browser-externs js2-include-node-externs)
6633 js2-typed-array-externs))))
6635 (defun js2-apply-jslint-globals ()
6636 (setq js2-additional-externs
6637 (nconc (js2-get-jslint-globals)
6638 js2-additional-externs)))
6640 (defun js2-get-jslint-globals ()
6641 (loop for node in (js2-ast-root-comments js2-mode-ast)
6642 when (and (eq 'block (js2-comment-node-format node))
6644 (goto-char (js2-node-abs-pos node))
6645 (looking-at "/\\*global ")))
6646 append (js2-get-jslint-globals-in
6648 (js2-node-abs-end node))))
6650 (defun js2-get-jslint-globals-in (beg end)
6654 (while (re-search-forward js2-mode-identifier-re end t)
6655 (let ((match (match-string 0)))
6656 (unless (member match '("true" "false"))
6657 (push match res)))))
6662 ;; We currently only support imenu, but eventually should support speedbar and
6663 ;; possibly other browsing mechanisms.
6665 ;; The basic strategy is to identify function assignment targets of the form
6666 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6667 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6668 ;; for imenu after parsing is finished.
6670 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6671 ;; JavaScript, and the general problem is undecidable. However, several forms
6672 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6675 ;; function foo() -- function declaration
6676 ;; foo = function() -- function expression assigned to variable
6677 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6678 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6679 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6680 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6681 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6682 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6683 ;; function foo() {function bar() {...}} -- nested function
6684 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6686 ;; This list boils down to a few forms that can be combined recursively.
6687 ;; Top-level named function declarations include both the left-hand (name)
6688 ;; and the right-hand (function value) expressions needed to produce an imenu
6689 ;; entry. The other "right-hand" forms we need to look for are:
6690 ;; - functions declared as props/getters/setters in object literals
6691 ;; - nested named function declarations
6692 ;; The "left-hand" expressions that functions can be assigned to include:
6693 ;; - local/global variables
6694 ;; - nested property-get expressions like a.b.c.d
6695 ;; - element gets like foo[10] or foo['bar'] where the index
6696 ;; expression can be trivially converted to a property name. They
6697 ;; effectively then become property gets.
6699 ;; All the different definition types are canonicalized into the form
6700 ;; foo.bar.baz = position-of-function-keyword
6702 ;; We need to build a trie-like structure for imenu. As an example,
6703 ;; consider the following JavaScript code:
6705 ;; a = function() {...} // function at position 5
6706 ;; b = function() {...} // function at position 25
6707 ;; foo = function() {...} // function at position 100
6708 ;; foo.bar = function() {...} // function at position 200
6709 ;; foo.bar.baz = function() {...} // function at position 300
6710 ;; foo.bar.zab = function() {...} // function at position 400
6712 ;; During parsing we accumulate an entry for each definition in
6713 ;; the variable `js2-imenu-recorder', like so:
6719 ;; (fn foo bar baz 300)
6720 ;; (fn foo bar zab 400))
6722 ;; Where 'fn' is the respective function node.
6723 ;; After parsing these entries are merged into this alist-trie:
6727 ;; (foo (<definition> . 3)
6728 ;; (bar (<definition> . 6)
6732 ;; Note the wacky need for a <definition> name. The token can be anything
6733 ;; that isn't a valid JavaScript identifier, because you might make foo
6734 ;; a function and then start setting properties on it that are also functions.
6736 (defun js2-prop-node-name (node)
6737 "Return the name of a node that may be a property-get/property-name.
6738 If NODE is not a valid name-node, string-node or integral number-node,
6739 returns nil. Otherwise returns the string name/value of the node."
6741 ((js2-name-node-p node)
6742 (js2-name-node-name node))
6743 ((js2-string-node-p node)
6744 (js2-string-node-value node))
6745 ((and (js2-number-node-p node)
6746 (string-match "^[0-9]+$" (js2-number-node-value node)))
6747 (js2-number-node-value node))
6748 ((js2-this-node-p node)
6751 (defun js2-node-qname-component (node)
6752 "Return the name of this node, if it contributes to a qname.
6753 Returns nil if the node doesn't contribute."
6755 (or (js2-prop-node-name node)
6756 (if (and (js2-function-node-p node)
6757 (js2-function-node-name node))
6758 (js2-name-node-name (js2-function-node-name node))))))
6760 (defun js2-record-imenu-entry (fn-node qname pos)
6761 "Add an entry to `js2-imenu-recorder'.
6762 FN-NODE should be the current item's function node.
6764 Associate FN-NODE with its QNAME for later lookup.
6765 This is used in postprocessing the chain list. For each chain, we find
6766 the parent function, look up its qname, then prepend a copy of it to the chain."
6767 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6768 (unless js2-imenu-function-map
6769 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6770 (puthash fn-node qname js2-imenu-function-map))
6772 (defun js2-record-imenu-functions (node &optional var)
6773 "Record function definitions for imenu.
6774 NODE is a function node or an object literal.
6775 VAR, if non-nil, is the expression that NODE is being assigned to.
6776 When passed arguments of wrong type, does nothing."
6777 (when js2-parse-ide-mode
6778 (let ((fun-p (js2-function-node-p node))
6781 ;; non-anonymous function declaration?
6784 (setq fname-node (js2-function-node-name node)))
6785 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6786 ;; for remaining forms, compute left-side tree branch first
6787 ((and var (setq qname (js2-compute-nested-prop-get var)))
6789 ;; foo.bar.baz = function
6791 (js2-record-imenu-entry node qname (js2-node-pos node)))
6792 ;; foo.bar.baz = object-literal
6793 ;; look for nested functions: {a: {b: function() {...} }}
6794 ((js2-object-node-p node)
6795 ;; Node position here is still absolute, since the parser
6796 ;; passes the assignment target and value expressions
6797 ;; to us before they are added as children of the assignment node.
6798 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6800 (defun js2-compute-nested-prop-get (node)
6801 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6802 component nodes as a list. Otherwise return nil. Element-gets are treated
6803 as property-gets if the index expression is a string, or a positive integer."
6804 (let (left right head)
6806 ((or (js2-name-node-p node)
6807 (js2-this-node-p node))
6809 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6810 ((js2-prop-get-node-p node) ; foo.bar
6811 (setq left (js2-prop-get-node-left node)
6812 right (js2-prop-get-node-right node))
6813 (if (setq head (js2-compute-nested-prop-get left))
6814 (nconc head (list right))))
6815 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6816 (setq left (js2-elem-get-node-target node)
6817 right (js2-elem-get-node-element node))
6818 (if (or (js2-string-node-p right) ; ['bar']
6819 (and (js2-number-node-p right) ; [10]
6820 (string-match "^[0-9]+$"
6821 (js2-number-node-value right))))
6822 (if (setq head (js2-compute-nested-prop-get left))
6823 (nconc head (list right))))))))
6825 (defun js2-record-object-literal (node qname pos)
6826 "Recursively process an object literal looking for functions.
6827 NODE is an object literal that is the right-hand child of an assignment
6828 expression. QNAME is a list of nodes representing the assignment target,
6829 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6830 POS is the absolute position of the node.
6831 We do a depth-first traversal of NODE. For any functions we find,
6832 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6834 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6835 (let ((left (js2-infix-node-left e))
6836 ;; Element positions are relative to the parent position.
6837 (pos (+ pos (js2-node-pos e))))
6839 ;; foo: function() {...}
6840 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6841 (when (js2-prop-node-name left)
6842 ;; As a policy decision, we record the position of the property,
6843 ;; not the position of the `function' keyword, since the property
6844 ;; is effectively the name of the function.
6845 (js2-record-imenu-entry right (append qname (list left)) pos)))
6846 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6847 ((js2-object-node-p right)
6848 (js2-record-object-literal right
6849 (append qname (list (js2-infix-node-left e)))
6850 (+ pos (js2-node-pos right)))))))))
6852 (defun js2-node-top-level-decl-p (node)
6853 "Return t if NODE's name is defined in the top-level scope.
6854 Also returns t if NODE's name is not defined in any scope, since it implies
6855 that it's an external variable, which must also be in the top-level scope."
6856 (let* ((name (js2-prop-node-name node))
6857 (this-scope (js2-node-get-enclosing-scope node))
6860 ((js2-this-node-p node)
6864 ((setq defining-scope (js2-get-defining-scope this-scope name))
6865 (js2-ast-root-p defining-scope))
6868 (defun js2-wrapper-function-p (node)
6869 "Return t if NODE is a function expression that's immediately invoked.
6870 NODE must be `js2-function-node'."
6871 (let ((parent (js2-node-parent node)))
6873 ;; function(){...}();
6874 (js2-call-node-p parent)
6875 (and (js2-paren-node-p parent)
6876 ;; (function(){...})();
6877 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6878 ;; (function(){...}).call(this);
6879 (and (js2-prop-get-node-p parent)
6880 (member (js2-name-node-name (js2-prop-get-node-right parent))
6882 (js2-call-node-p (js2-node-parent parent))))))))
6884 (defun js2-browse-postprocess-chains (entries)
6885 "Modify function-declaration name chains after parsing finishes.
6886 Some of the information is only available after the parse tree is complete.
6887 For instance, processing a nested scope requires a parent function node."
6888 (let (result fn parent-qname p elem)
6889 (dolist (entry entries)
6890 ;; function node goes first
6891 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6892 ;; Examine head's defining scope:
6893 ;; Pre-processed chain, or top-level/external, keep as-is.
6894 (if (or (stringp head) (js2-node-top-level-decl-p head))
6896 (when (js2-this-node-p head)
6897 (setq chain (cdr chain))) ; discard this-node
6898 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6899 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6900 (when (eq parent-qname 'not-found)
6901 ;; anonymous function expressions are not recorded
6902 ;; during the parse, so we need to handle this case here
6904 (if (js2-wrapper-function-p fn)
6905 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6906 (if (js2-ast-root-p grandparent)
6908 (gethash grandparent js2-imenu-function-map 'skip)))
6910 (puthash fn parent-qname js2-imenu-function-map))
6911 (unless (eq parent-qname 'skip)
6912 ;; prefix parent fn qname to this chain.
6913 (let ((qname (append parent-qname chain)))
6914 (puthash current-fn (butlast qname) js2-imenu-function-map)
6915 (push qname result)))))))
6916 ;; finally replace each node in each chain with its name.
6917 (dolist (chain result)
6920 (if (js2-node-p (setq elem (car p)))
6921 (setcar p (js2-node-qname-component elem)))
6925 ;; Merge name chains into a trie-like tree structure of nested lists.
6926 ;; To simplify construction of the trie, we first build it out using the rule
6927 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6928 ;; [key, num-or-list]. The second element can be a number; if so, this key
6929 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6930 ;; associated with the key at this level.) Otherwise the second element is
6931 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6932 ;; a simple recursive formulation.
6934 ;; js2-mode is building the data structure for imenu. The imenu documentation
6935 ;; claims that it's the structure above, but in practice it wants the children
6936 ;; at the same list level as the key for that level, which is how I've drawn
6937 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6938 ;; list wrapper around the children at each level.
6940 ;; A completed nested imenu-alist entry looks like this:
6942 ;; ("<definition>" . 7)
6947 ;; In particular, the documentation for `imenu--index-alist' says that
6948 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6949 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6951 (defun js2-treeify (lst)
6952 "Convert (a b c d) to (a ((b ((c d)))))."
6953 (if (null (cddr lst)) ; list length <= 2
6955 (list (car lst) (list (js2-treeify (cdr lst))))))
6957 (defun js2-build-alist-trie (chains trie)
6958 "Merge declaration name chains into a trie-like alist structure for imenu.
6959 CHAINS is the qname chain list produced during parsing. TRIE is a
6960 list of elements built up so far."
6961 (let (head tail pos branch kids)
6962 (dolist (chain chains)
6963 (setq head (car chain)
6965 pos (if (numberp (car tail)) (car tail))
6966 branch (js2-find-if (lambda (n)
6967 (string= (car n) head))
6969 kids (second branch))
6971 ;; case 1: this key isn't in the trie yet
6974 (setcdr (last trie) (list (js2-treeify chain)))
6975 (setq trie (list (js2-treeify chain)))))
6976 ;; case 2: key is present with a single number entry: replace w/ list
6977 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6978 ;; ("<definition>" 20)))
6980 (setcar (cdr branch)
6981 (list (list "<definition-1>" kids)
6983 (list "<definition-2>" pos)
6984 (js2-treeify tail)))))
6985 ;; case 3: key is there (with kids), and we're a number entry
6989 (list (format "<definition-%d>"
6990 (1+ (loop for kid in kids
6991 count (eq ?< (aref (car kid) 0)))))
6993 ;; case 4: key is there with kids, need to merge in our chain
6995 (js2-build-alist-trie (list tail) kids))))
6998 (defun js2-flatten-trie (trie)
6999 "Convert TRIE to imenu-format.
7000 Recurses through nodes, and for each one whose second element is a list,
7001 appends the list's flattened elements to the current element. Also
7002 changes the tails into conses. For instance, this pre-flattened trie
7014 Note that the root of the trie has no key, just a list of chains.
7015 This is also true for the value of any key with multiple children,
7016 e.g. key 'c' in the example above."
7019 (mapcar #'js2-flatten-trie trie))
7021 (if (numberp (second trie))
7022 (cons (car trie) (second trie))
7023 ;; else pop list and append its kids
7024 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7026 (defun js2-build-imenu-index ()
7027 "Turn `js2-imenu-recorder' into an imenu data structure."
7028 (unless (eq js2-imenu-recorder 'empty)
7029 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7030 (result (js2-build-alist-trie chains nil)))
7031 (js2-flatten-trie result))))
7033 (defun js2-test-print-chains (chains)
7034 "Print a list of qname chains.
7035 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7036 i.e. one or more nodes, and an integer position as the list tail."
7037 (mapconcat (lambda (chain)
7039 (mapconcat (lambda (elem)
7040 (if (js2-node-p elem)
7041 (or (js2-node-qname-component elem)
7043 (number-to-string elem)))
7052 (defconst js2-version "1.8.5"
7053 "Version of JavaScript supported.")
7055 (defun js2-record-face (face &optional token)
7056 "Record a style run of FACE for TOKEN or the current token."
7057 (unless token (setq token (js2-current-token)))
7058 (js2-set-face (js2-token-beg token) (js2-token-end token) face 'record))
7060 (defsubst js2-node-end (n)
7061 "Computes the absolute end of node N.
7062 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7063 is only true until the node is added to its parent; i.e., while parsing."
7067 (defun js2-record-comment (token)
7068 "Record a comment in `js2-scanned-comments'."
7069 (let ((ct (js2-token-comment-type token))
7070 (beg (js2-token-beg token))
7071 (end (js2-token-end token)))
7072 (push (make-js2-comment-node :len (- end beg)
7074 js2-scanned-comments)
7075 (when js2-parse-ide-mode
7076 (js2-record-face (if (eq ct 'jsdoc)
7078 'font-lock-comment-face)
7080 (when (memq ct '(html preprocessor))
7081 ;; Tell cc-engine the bounds of the comment.
7082 (js2-record-text-property beg (1- end) 'c-in-sws t)))))
7084 (defun js2-peek-token ()
7085 "Return the next token type without consuming it.
7086 If `js2-ti-lookahead' is positive, return the type of next token
7087 from `js2-ti-tokens'. Otherwise, call `js2-get-token'."
7088 (if (not (zerop js2-ti-lookahead))
7090 (aref js2-ti-tokens (mod (1+ js2-ti-tokens-cursor) js2-ti-ntokens)))
7091 (let ((tt (js2-get-token-internal)))
7095 (defalias 'js2-next-token 'js2-get-token)
7097 (defun js2-match-token (match &optional dont-unget)
7098 "Get next token and return t if it matches MATCH, a bytecode.
7099 Returns nil and consumes nothing if MATCH is not the next token."
7100 (if (/= (js2-get-token) match)
7101 (ignore (unless dont-unget (js2-unget-token)))
7104 (defun js2-match-contextual-kwd (name)
7105 "Consume and return t if next token is `js2-NAME', and its
7106 string is NAME. Returns nil and keeps current token otherwise."
7107 (if (or (/= (js2-get-token) js2-NAME)
7108 (not (string= (js2-current-token-string) name)))
7112 (js2-record-face 'font-lock-keyword-face)
7115 (defun js2-valid-prop-name-token (tt)
7117 (and js2-allow-keywords-as-property-names
7119 (or (= tt js2-RESERVED)
7120 (aref js2-kwd-tokens tt)))))
7122 (defun js2-match-prop-name ()
7123 "Consume token and return t if next token is a valid property name.
7124 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7125 is non-nil and it's a keyword token."
7126 (if (js2-valid-prop-name-token (js2-get-token))
7131 (defun js2-must-match-prop-name (msg-id &optional pos len)
7132 (if (js2-match-prop-name)
7134 (js2-report-error msg-id nil pos len)
7137 (defun js2-peek-token-or-eol ()
7138 "Return js2-EOL if the next token immediately follows a newline.
7139 Else returns the next token. Used in situations where we don't
7140 consider certain token types valid if they are preceded by a newline.
7141 One example is the postfix ++ or -- operator, which has to be on the
7142 same line as its operand."
7143 (let ((tt (js2-get-token))
7144 (follows-eol (js2-token-follows-eol-p (js2-current-token))))
7150 (defun js2-must-match (token msg-id &optional pos len)
7151 "Match next token to token code TOKEN, or record a syntax error.
7152 MSG-ID is the error message to report if the match fails.
7153 Returns t on match, nil if no match."
7154 (if (js2-match-token token t)
7156 (js2-report-error msg-id nil pos len)
7160 (defun js2-must-match-name (msg-id)
7161 (if (js2-match-token js2-NAME t)
7163 (if (eq (js2-current-token-type) js2-RESERVED)
7164 (js2-report-error "msg.reserved.id" (js2-current-token-string))
7165 (js2-report-error msg-id)
7169 (defsubst js2-inside-function ()
7170 (plusp js2-nesting-of-function))
7172 (defun js2-set-requires-activation ()
7173 (if (js2-function-node-p js2-current-script-or-fn)
7174 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7176 (defun js2-check-activation-name (name _token)
7177 (when (js2-inside-function)
7178 ;; skip language-version 1.2 check from Rhino
7179 (if (or (string= "arguments" name)
7180 (and js2-compiler-activation-names ; only used in codegen
7181 (gethash name js2-compiler-activation-names)))
7182 (js2-set-requires-activation))))
7184 (defun js2-set-is-generator ()
7185 (let ((fn-node js2-current-script-or-fn))
7186 (when (and (js2-function-node-p fn-node)
7187 (not (js2-function-node-generator-type fn-node)))
7188 (setf (js2-function-node-generator-type js2-current-script-or-fn) 'LEGACY))))
7190 (defun js2-must-have-xml ()
7191 (unless js2-compiler-xml-available
7192 (js2-report-error "msg.XML.not.available")))
7194 (defun js2-push-scope (scope)
7195 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7196 (assert (js2-scope-p scope))
7197 (assert (null (js2-scope-parent-scope scope)))
7198 (assert (not (eq js2-current-scope scope)))
7199 (setf (js2-scope-parent-scope scope) js2-current-scope
7200 js2-current-scope scope))
7202 (defsubst js2-pop-scope ()
7203 (setq js2-current-scope
7204 (js2-scope-parent-scope js2-current-scope)))
7206 (defun js2-enter-loop (loop-node)
7207 (push loop-node js2-loop-set)
7208 (push loop-node js2-loop-and-switch-set)
7209 (js2-push-scope loop-node)
7210 ;; Tell the current labeled statement (if any) its statement,
7211 ;; and set the jump target of the first label to the loop.
7212 ;; These are used in `js2-parse-continue' to verify that the
7213 ;; continue target is an actual labeled loop. (And for codegen.)
7214 (when js2-labeled-stmt
7215 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7216 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7217 js2-labeled-stmt))) loop-node)))
7219 (defun js2-exit-loop ()
7221 (pop js2-loop-and-switch-set)
7224 (defsubst js2-enter-switch (switch-node)
7225 (push switch-node js2-loop-and-switch-set))
7227 (defsubst js2-exit-switch ()
7228 (pop js2-loop-and-switch-set))
7230 (defun js2-parse (&optional buf cb)
7231 "Tell the js2 parser to parse a region of JavaScript.
7233 BUF is a buffer or buffer name containing the code to parse.
7234 Call `narrow-to-region' first to parse only part of the buffer.
7236 The returned AST root node is given some additional properties:
7237 `node-count' - total number of nodes in the AST
7238 `buffer' - BUF. The buffer it refers to may change or be killed,
7239 so the value is not necessarily reliable.
7241 An optional callback CB can be specified to report parsing
7242 progress. If `(functionp CB)' returns t, it will be called with
7243 the current line number once before parsing begins, then again
7244 each time the lexer reaches a new line number.
7246 CB can also be a list of the form `(symbol cb ...)' to specify
7247 multiple callbacks with different criteria. Each symbol is a
7248 criterion keyword, and the following element is the callback to
7251 :line - called whenever the line number changes
7252 :token - called for each new token consumed
7254 The list of criteria could be extended to include entering or
7255 leaving a statement, an expression, or a function definition."
7256 (if (and cb (not (functionp cb)))
7257 (error "criteria callbacks not yet implemented"))
7258 (let ((inhibit-point-motion-hooks t)
7259 (js2-compiler-xml-available (>= js2-language-version 160))
7260 ;; This is a recursive-descent parser, so give it a big stack.
7261 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7262 (max-specpdl-size (max max-specpdl-size 3000))
7263 (case-fold-search nil)
7265 (with-current-buffer (or buf (current-buffer))
7266 (setq js2-scanned-comments nil
7267 js2-parsed-errors nil
7268 js2-parsed-warnings nil
7269 js2-imenu-recorder nil
7270 js2-imenu-function-map nil
7273 (setq ast (with-silent-modifications
7275 (unless js2-ts-hit-eof
7276 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7277 (setf (js2-ast-root-errors ast) js2-parsed-errors
7278 (js2-ast-root-warnings ast) js2-parsed-warnings)
7279 ;; if we didn't find any declarations, put a dummy in this list so we
7280 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7281 (unless js2-imenu-recorder
7282 (setq js2-imenu-recorder 'empty))
7283 (run-hooks 'js2-parse-finished-hook)
7286 ;; Corresponds to Rhino's Parser.parse() method.
7287 (defun js2-do-parse ()
7288 "Parse current buffer starting from current point.
7289 Scanner should be initialized."
7290 (let ((pos js2-ts-cursor)
7291 (end js2-ts-cursor) ; in case file is empty
7293 ;; initialize buffer-local parsing vars
7294 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7295 js2-current-script-or-fn root
7296 js2-current-scope root
7297 js2-nesting-of-function 0
7298 js2-labeled-stmt nil
7299 js2-recorded-identifiers nil) ; for js2-highlight
7300 (while (/= (setq tt (js2-get-token)) js2-EOF)
7301 (if (= tt js2-FUNCTION)
7303 (setq n (if js2-called-by-compile-function
7304 (js2-parse-function-expr)
7305 (js2-parse-function-stmt))))
7306 ;; not a function - parse a statement
7308 (setq n (js2-parse-statement)))
7309 ;; add function or statement to script
7310 (setq end (js2-node-end n))
7311 (js2-block-node-push root n))
7312 ;; add comments to root in lexical order
7313 (when js2-scanned-comments
7314 ;; if we find a comment beyond end of normal kids, use its end
7315 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7316 (dolist (comment js2-scanned-comments)
7317 (push comment (js2-ast-root-comments root))
7318 (js2-node-add-children root comment)))
7319 (setf (js2-node-len root) (- end pos))
7320 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7321 ;; Give extensions a chance to muck with things before highlighting starts.
7322 (let ((js2-additional-externs js2-additional-externs))
7324 (run-hooks 'js2-post-parse-callbacks))
7325 (js2-highlight-undeclared-vars))
7328 (defun js2-parse-function-closure-body (fn-node)
7329 "Parse a JavaScript 1.8 function closure body."
7330 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7332 (js2-report-error "msg.no.brace.body" nil
7333 (js2-node-pos fn-node)
7334 (- js2-ts-cursor (js2-node-pos fn-node)))
7335 (js2-node-add-children fn-node
7336 (setf (js2-function-node-body fn-node)
7337 (js2-parse-expr t))))))
7339 (defun js2-parse-function-body (fn-node)
7340 (js2-must-match js2-LC "msg.no.brace.body"
7341 (js2-node-pos fn-node)
7342 (- js2-ts-cursor (js2-node-pos fn-node)))
7343 (let ((pos (js2-current-token-beg)) ; LC position
7344 (pn (make-js2-block-node)) ; starts at LC position
7347 (incf js2-nesting-of-function)
7349 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7352 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7353 (js2-parse-statement)
7355 (js2-parse-function-stmt))))
7356 (decf js2-nesting-of-function))
7357 (setq end (js2-current-token-end)) ; assume no curly and leave at current token
7358 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7359 (setq end (js2-current-token-end)))
7360 (setf (js2-node-pos pn) pos
7361 (js2-node-len pn) (- end pos))
7362 (setf (js2-function-node-body fn-node) pn)
7363 (js2-node-add-children fn-node pn)
7366 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7367 "Declare and fontify destructuring parameters inside NODE.
7368 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7370 ((js2-name-node-p node)
7372 (js2-define-symbol decl-type (js2-name-node-name node)
7373 node ignore-not-in-block)
7375 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7376 (+ leftpos (js2-node-len node))
7378 ((js2-object-node-p node)
7379 (dolist (elem (js2-object-node-elems node))
7380 (js2-define-destruct-symbols
7381 (if (js2-object-prop-node-p elem)
7382 (js2-object-prop-node-right elem)
7383 ;; abbreviated destructuring {a, b}
7385 decl-type face ignore-not-in-block)))
7386 ((js2-array-node-p node)
7387 (dolist (elem (js2-array-node-elems node))
7389 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7390 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7391 (js2-node-len node)))))
7393 (defun js2-parse-function-params (function-type fn-node pos)
7394 (if (js2-match-token js2-RP)
7395 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos))
7396 (let ((paren-free-arrow (and (eq function-type 'FUNCTION_ARROW)
7397 (eq (js2-current-token-type) js2-NAME)))
7398 params param default-found rest-param-at)
7399 (when paren-free-arrow
7401 (loop for tt = (js2-peek-token)
7404 ;; destructuring param
7405 ((and (not paren-free-arrow)
7406 (or (= tt js2-LB) (= tt js2-LC)))
7409 (js2-report-error "msg.no.default.after.default.param"))
7410 (setq param (js2-parse-destruct-primary-expr))
7411 (js2-define-destruct-symbols param
7413 'js2-function-param)
7414 (push param params))
7417 (when (and (>= js2-language-version 200)
7418 (not paren-free-arrow)
7419 (js2-match-token js2-TRIPLEDOT)
7420 (not rest-param-at))
7421 ;; to report errors if there are more parameters
7422 (setq rest-param-at (length params)))
7423 (js2-must-match-name "msg.no.parm")
7424 (js2-record-face 'js2-function-param)
7425 (setq param (js2-create-name-node))
7426 (js2-define-symbol js2-LP (js2-current-token-string) param)
7427 ;; default parameter value
7428 (when (or (and default-found
7430 (js2-must-match js2-ASSIGN
7431 "msg.no.default.after.default.param"
7432 (js2-node-pos param)
7433 (js2-node-len param)))
7434 (and (>= js2-language-version 200)
7435 (js2-match-token js2-ASSIGN)))
7436 (assert (not paren-free-arrow))
7437 (let* ((pos (js2-node-pos param))
7438 (tt (js2-current-token-type))
7439 (op-pos (- (js2-current-token-beg) pos))
7441 (right (js2-parse-assign-expr))
7442 (len (- (js2-node-end right) pos)))
7443 (setq param (make-js2-assign-node
7444 :type tt :pos pos :len len :op-pos op-pos
7445 :left left :right right)
7447 (js2-node-add-children param left right)))
7448 (push param params)))
7449 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7450 (js2-report-error "msg.param.after.rest" nil
7451 (js2-node-pos param) (js2-node-len param)))
7453 (js2-match-token js2-COMMA))
7454 (when (and (not paren-free-arrow)
7455 (js2-must-match js2-RP "msg.no.paren.after.parms"))
7456 (setf (js2-function-node-rp fn-node) (- (js2-current-token-beg) pos)))
7458 (setf (js2-function-node-rest-p fn-node) t))
7460 (js2-node-add-children fn-node p)
7461 (push p (js2-function-node-params fn-node))))))
7463 (defun js2-check-inconsistent-return-warning (fn-node name)
7464 "Possibly show inconsistent-return warning.
7465 Last token scanned is the close-curly for the function body."
7466 (when (and js2-mode-show-strict-warnings
7467 js2-strict-inconsistent-return-warning
7468 (not (js2-has-consistent-return-usage
7469 (js2-function-node-body fn-node))))
7470 ;; Have it extend from close-curly to bol or beginning of block.
7471 (let ((pos (save-excursion
7472 (goto-char (js2-current-token-end))
7473 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7475 (end (js2-current-token-end)))
7476 (if (plusp (js2-name-node-length name))
7477 (js2-add-strict-warning "msg.no.return.value"
7478 (js2-name-node-name name) pos end)
7479 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7481 (defun js2-parse-function-stmt ()
7482 (let ((pos (js2-current-token-beg))
7483 (star-p (js2-match-token js2-MUL)))
7484 (js2-must-match-name "msg.unnamed.function.stmt")
7485 (let ((name (js2-create-name-node t))
7488 ((js2-match-token js2-LP)
7489 (js2-parse-function 'FUNCTION_STATEMENT pos star-p name))
7490 (js2-allow-member-expr-as-function-name
7491 (setq member-expr (js2-parse-member-expr-tail nil name))
7492 (js2-parse-highlight-member-expr-fn-name member-expr)
7493 (js2-must-match js2-LP "msg.no.paren.parms")
7494 (setf pn (js2-parse-function 'FUNCTION_STATEMENT pos star-p)
7495 (js2-function-node-member-expr pn) member-expr)
7498 (js2-report-error "msg.no.paren.parms")
7499 (make-js2-error-node))))))
7501 (defun js2-parse-function-expr ()
7502 (let ((pos (js2-current-token-beg))
7503 (star-p (js2-match-token js2-MUL))
7505 (when (js2-match-token js2-NAME)
7506 (setq name (js2-create-name-node t)))
7507 (js2-must-match js2-LP "msg.no.paren.parms")
7508 (js2-parse-function 'FUNCTION_EXPRESSION pos star-p name)))
7510 (defun js2-parse-function (function-type pos star-p &optional name)
7511 "Function parser. FUNCTION-TYPE is a symbol, POS is the
7512 beginning of the first token (function keyword, unless it's an
7513 arrow function), NAME is js2-name-node."
7515 (if (= (js2-current-token-type) js2-LP) ; eventually matched LP?
7516 (setq lp (js2-current-token-beg)))
7517 (setf fn-node (make-js2-function-node :pos pos
7520 :lp (if lp (- lp pos))
7521 :generator-type (and star-p 'STAR)))
7523 (js2-set-face (js2-node-pos name) (js2-node-end name)
7524 'font-lock-function-name-face 'record)
7525 (when (plusp (js2-name-node-length name))
7526 ;; Function statements define a symbol in the enclosing scope
7527 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node)))
7528 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7529 ;; 1. Nested functions are not affected by the dynamic scope flag
7530 ;; as dynamic scope is already a parent of their scope.
7531 ;; 2. Functions defined under the with statement also immune to
7532 ;; this setup, in which case dynamic scope is ignored in favor
7533 ;; of the with object.
7534 (setf (js2-function-node-ignore-dynamic fn-node) t))
7535 ;; dynamically bind all the per-function variables
7536 (let ((js2-current-script-or-fn fn-node)
7537 (js2-current-scope fn-node)
7538 (js2-nesting-of-with 0)
7542 js2-loop-and-switch-set)
7543 (js2-parse-function-params function-type fn-node pos)
7544 (when (eq function-type 'FUNCTION_ARROW)
7545 (js2-must-match js2-ARROW "msg.bad.arrow.args"))
7546 (if (and (>= js2-language-version 180)
7547 (/= (js2-peek-token) js2-LC))
7548 (js2-parse-function-closure-body fn-node)
7549 (js2-parse-function-body fn-node))
7550 (js2-check-inconsistent-return-warning fn-node name)
7553 (js2-node-add-children fn-node name)
7554 ;; Function expressions define a name only in the body of the
7555 ;; function, and only if not hidden by a parameter name
7556 (when (and (eq function-type 'FUNCTION_EXPRESSION)
7557 (null (js2-scope-get-symbol js2-current-scope
7558 (js2-name-node-name name))))
7559 (js2-define-symbol js2-FUNCTION
7560 (js2-name-node-name name)
7562 (when (eq function-type 'FUNCTION_STATEMENT)
7563 (js2-record-imenu-functions fn-node))))
7565 (setf (js2-node-len fn-node) (- js2-ts-cursor pos))
7566 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7567 ;; We wait until after parsing the function to set its parent scope,
7568 ;; since `js2-define-symbol' needs the defining-scope check to stop
7569 ;; at the function boundary when checking for redeclarations.
7570 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7573 (defun js2-parse-statements (&optional parent)
7574 "Parse a statement list. Last token consumed must be js2-LC.
7576 PARENT can be a `js2-block-node', in which case the statements are
7577 appended to PARENT. Otherwise a new `js2-block-node' is created
7580 This function does not match the closing js2-RC: the caller
7581 matches the RC so it can provide a suitable error message if not
7582 matched. This means it's up to the caller to set the length of
7583 the node to include the closing RC. The node start pos is set to
7584 the absolute buffer start position, and the caller should fix it
7585 up to be relative to the parent node. All children of this block
7586 node are given relative start positions and correct lengths."
7587 (let ((pn (or parent (make-js2-block-node)))
7589 (setf (js2-node-pos pn) (js2-current-token-beg))
7590 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7592 (js2-block-node-push pn (js2-parse-statement)))
7595 (defun js2-parse-statement ()
7597 ;; coarse-grained user-interrupt check - needs work
7598 (and js2-parse-interruptable-p
7599 (zerop (% (incf js2-parse-stmt-count)
7600 js2-statements-per-pause))
7602 (throw 'interrupted t))
7603 (setq pn (js2-statement-helper))
7604 ;; no-side-effects warning check
7605 (unless (js2-node-has-side-effects pn)
7606 (setq end (js2-node-end pn))
7609 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7610 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7613 ;; These correspond to the switch cases in Parser.statementHelper
7614 (defconst js2-parsers
7615 (let ((parsers (make-vector js2-num-tokens
7616 #'js2-parse-expr-stmt)))
7617 (aset parsers js2-BREAK #'js2-parse-break)
7618 (aset parsers js2-CONST #'js2-parse-const-var)
7619 (aset parsers js2-CONTINUE #'js2-parse-continue)
7620 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7621 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7622 (aset parsers js2-DO #'js2-parse-do)
7623 (aset parsers js2-FOR #'js2-parse-for)
7624 (aset parsers js2-FUNCTION #'js2-parse-function-stmt)
7625 (aset parsers js2-IF #'js2-parse-if)
7626 (aset parsers js2-LC #'js2-parse-block)
7627 (aset parsers js2-LET #'js2-parse-let-stmt)
7628 (aset parsers js2-NAME #'js2-parse-name-or-label)
7629 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7630 (aset parsers js2-SEMI #'js2-parse-semi)
7631 (aset parsers js2-SWITCH #'js2-parse-switch)
7632 (aset parsers js2-THROW #'js2-parse-throw)
7633 (aset parsers js2-TRY #'js2-parse-try)
7634 (aset parsers js2-VAR #'js2-parse-const-var)
7635 (aset parsers js2-WHILE #'js2-parse-while)
7636 (aset parsers js2-WITH #'js2-parse-with)
7637 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7639 "A vector mapping token types to parser functions.")
7641 (defun js2-parse-warn-missing-semi (beg end)
7642 (and js2-mode-show-strict-warnings
7643 js2-strict-missing-semi-warning
7644 (js2-add-strict-warning
7645 "msg.missing.semi" nil
7646 ;; back up to beginning of statement or line
7647 (max beg (save-excursion
7652 (defconst js2-no-semi-insertion
7664 "List of tokens that don't do automatic semicolon insertion.")
7666 (defconst js2-autoinsert-semi-and-warn
7667 (list js2-ERROR js2-EOF js2-RC))
7669 (defun js2-statement-helper ()
7670 (let* ((tt (js2-get-token))
7672 (parser (if (= tt js2-ERROR)
7674 (aref js2-parsers tt)))
7676 ;; If the statement is set, then it's been told its label by now.
7677 (and js2-labeled-stmt
7678 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7679 (setq js2-labeled-stmt nil))
7680 (setq pn (funcall parser))
7681 ;; Don't do auto semi insertion for certain statement types.
7682 (unless (or (memq first-tt js2-no-semi-insertion)
7683 (js2-labeled-stmt-node-p pn))
7684 (js2-auto-insert-semicolon pn))
7687 (defun js2-auto-insert-semicolon (pn)
7688 (let* ((tt (js2-get-token))
7689 (pos (js2-node-pos pn)))
7692 ;; extend the node bounds to include the semicolon.
7693 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
7694 ((memq tt js2-autoinsert-semi-and-warn)
7695 (js2-unget-token) ; Not ';', do not consume.
7697 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7699 (if (not (js2-token-follows-eol-p (js2-current-token)))
7700 ;; Report error if no EOL or autoinsert ';' otherwise
7701 (js2-report-error "msg.no.semi.stmt")
7702 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7703 (js2-unget-token) ; Not ';', do not consume.
7706 (defun js2-parse-condition ()
7707 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7708 The parens are discarded and the expression node is returned.
7709 The `pos' field of the return value is set to an absolute position
7710 that must be fixed up by the caller.
7711 Return value is a list (EXPR LP RP), with absolute paren positions."
7713 (if (js2-must-match js2-LP "msg.no.paren.cond")
7714 (setq lp (js2-current-token-beg)))
7715 (setq pn (js2-parse-expr))
7716 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7717 (setq rp (js2-current-token-beg)))
7718 ;; Report strict warning on code like "if (a = 7) ..."
7719 (if (and js2-strict-cond-assign-warning
7720 (js2-assign-node-p pn))
7721 (js2-add-strict-warning "msg.equal.as.assign" nil
7723 (+ (js2-node-pos pn)
7724 (js2-node-len pn))))
7727 (defun js2-parse-if ()
7728 "Parser for if-statement. Last matched token must be js2-IF."
7729 (let ((pos (js2-current-token-beg))
7730 cond if-true if-false else-pos end pn)
7731 (setq cond (js2-parse-condition)
7732 if-true (js2-parse-statement)
7733 if-false (if (js2-match-token js2-ELSE)
7735 (setq else-pos (- (js2-current-token-beg) pos))
7736 (js2-parse-statement)))
7737 end (js2-node-end (or if-false if-true))
7738 pn (make-js2-if-node :pos pos
7740 :condition (car cond)
7744 :lp (js2-relpos (second cond) pos)
7745 :rp (js2-relpos (third cond) pos)))
7746 (js2-node-add-children pn (car cond) if-true if-false)
7749 (defun js2-parse-switch ()
7750 "Parser for switch-statement. Last matched token must be js2-SWITCH."
7751 (let ((pos (js2-current-token-beg))
7752 tt pn discriminant has-default case-expr case-node
7753 case-pos cases stmt lp)
7754 (if (js2-must-match js2-LP "msg.no.paren.switch")
7755 (setq lp (js2-current-token-beg)))
7756 (setq discriminant (js2-parse-expr)
7757 pn (make-js2-switch-node :discriminant discriminant
7759 :lp (js2-relpos lp pos)))
7760 (js2-node-add-children pn discriminant)
7761 (js2-enter-switch pn)
7764 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7765 (setf (js2-switch-node-rp pn) (- (js2-current-token-beg) pos)))
7766 (js2-must-match js2-LC "msg.no.brace.switch")
7769 (setq tt (js2-next-token)
7770 case-pos (js2-current-token-beg))
7773 (setf (js2-node-len pn) (- (js2-current-token-end) pos))
7774 (throw 'break nil)) ; done
7776 (setq case-expr (js2-parse-expr))
7777 (js2-must-match js2-COLON "msg.no.colon.case"))
7780 (js2-report-error "msg.double.switch.default"))
7783 (js2-must-match js2-COLON "msg.no.colon.case"))
7785 (js2-report-error "msg.bad.switch")
7786 (throw 'break nil)))
7787 (setq case-node (make-js2-case-node :pos case-pos
7788 :len (- (js2-current-token-end) case-pos)
7790 (js2-node-add-children case-node case-expr)
7791 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7795 (setf stmt (js2-parse-statement)
7796 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7797 (js2-block-node-push case-node stmt))
7798 (push case-node cases)))
7799 ;; add cases last, as pushing reverses the order to be correct
7801 (js2-node-add-children pn kid)
7802 (push kid (js2-switch-node-cases pn)))
7804 (js2-exit-switch))))
7806 (defun js2-parse-while ()
7807 "Parser for while-statement. Last matched token must be js2-WHILE."
7808 (let ((pos (js2-current-token-beg))
7809 (pn (make-js2-while-node))
7814 (setf cond (js2-parse-condition)
7815 (js2-while-node-condition pn) (car cond)
7816 body (js2-parse-statement)
7817 (js2-while-node-body pn) body
7818 (js2-node-len pn) (- (js2-node-end body) pos)
7819 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7820 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7821 (js2-node-add-children pn body (car cond)))
7825 (defun js2-parse-do ()
7826 "Parser for do-statement. Last matched token must be js2-DO."
7827 (let ((pos (js2-current-token-beg))
7828 (pn (make-js2-do-node))
7833 (setq body (js2-parse-statement))
7834 (js2-must-match js2-WHILE "msg.no.while.do")
7835 (setf (js2-do-node-while-pos pn) (- (js2-current-token-beg) pos)
7836 cond (js2-parse-condition)
7837 (js2-do-node-condition pn) (car cond)
7838 (js2-do-node-body pn) body
7840 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7841 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7842 (js2-node-add-children pn (car cond) body))
7844 ;; Always auto-insert semicolon to follow SpiderMonkey:
7845 ;; It is required by ECMAScript but is ignored by the rest of
7846 ;; world; see bug 238945
7847 (if (js2-match-token js2-SEMI)
7848 (setq end js2-ts-cursor))
7849 (setf (js2-node-len pn) (- end pos))
7852 (defun js2-parse-for ()
7853 "Parser for for-statement. Last matched token must be js2-FOR.
7854 Parses for, for-in, and for each-in statements."
7855 (let ((for-pos (js2-current-token-beg))
7856 pn is-for-each is-for-in-or-of is-for-of
7857 in-pos each-pos tmp-pos
7858 init ; Node init is also foo in 'foo in object'
7859 cond ; Node cond is also object in 'foo in object'
7860 incr ; 3rd section of for-loop initializer
7862 ;; See if this is a for each () instead of just a for ()
7863 (when (js2-match-token js2-NAME)
7864 (if (string= "each" (js2-current-token-string))
7867 each-pos (- (js2-current-token-beg) for-pos)) ; relative
7868 (js2-record-face 'font-lock-keyword-face))
7869 (js2-report-error "msg.no.paren.for")))
7870 (if (js2-must-match js2-LP "msg.no.paren.for")
7871 (setq lp (- (js2-current-token-beg) for-pos)))
7872 (setq tt (js2-get-token))
7873 ;; 'for' makes local scope
7874 (js2-push-scope (make-js2-scope))
7876 ;; parse init clause
7877 (let ((js2-in-for-init t)) ; set as dynamic variable
7881 (setq init (make-js2-empty-expr-node)))
7882 ((or (= tt js2-VAR) (= tt js2-LET))
7883 (setq init (js2-parse-variables tt (js2-current-token-beg))))
7886 (setq init (js2-parse-expr)))))
7887 (if (or (js2-match-token js2-IN)
7888 (and (>= js2-language-version 200)
7889 (js2-match-contextual-kwd "of")
7890 (setq is-for-of t)))
7891 (setq is-for-in-or-of t
7892 in-pos (- (js2-current-token-beg) for-pos)
7893 ;; scope of iteration target object is not the scope we've created above.
7894 ;; stash current scope temporary.
7895 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7896 (js2-parse-expr))) ; object over which we're iterating
7897 ;; else ordinary for loop - parse cond and incr
7898 (js2-must-match js2-SEMI "msg.no.semi.for")
7899 (setq cond (if (= (js2-peek-token) js2-SEMI)
7900 (make-js2-empty-expr-node) ; no loop condition
7902 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7903 (setq tmp-pos (js2-current-token-end)
7904 incr (if (= (js2-peek-token) js2-RP)
7905 (make-js2-empty-expr-node :pos tmp-pos)
7907 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7908 (setq rp (- (js2-current-token-beg) for-pos)))
7909 (if (not is-for-in-or-of)
7910 (setq pn (make-js2-for-node :init init
7915 ;; cond could be null if 'in obj' got eaten by the init node.
7916 (if (js2-infix-node-p init)
7917 ;; it was (foo in bar) instead of (var foo in bar)
7918 (setq cond (js2-infix-node-right init)
7919 init (js2-infix-node-left init))
7920 (if (and (js2-var-decl-node-p init)
7921 (> (length (js2-var-decl-node-kids init)) 1))
7922 (js2-report-error "msg.mult.index")))
7923 (setq pn (make-js2-for-in-node :iterator init
7926 :foreach-p is-for-each
7934 ;; We have to parse the body -after- creating the loop node,
7935 ;; so that the loop node appears in the js2-loop-set, allowing
7936 ;; break/continue statements to find the enclosing loop.
7937 (setf body (js2-parse-statement)
7938 (js2-loop-node-body pn) body
7939 (js2-node-pos pn) for-pos
7940 (js2-node-len pn) (- (js2-node-end body) for-pos))
7941 (js2-node-add-children pn init cond incr body))
7947 (defun js2-parse-try ()
7948 "Parser for try-statement. Last matched token must be js2-TRY."
7949 (let ((try-pos (js2-current-token-beg))
7966 (if (/= (js2-peek-token) js2-LC)
7967 (js2-report-error "msg.no.brace.try"))
7968 (setq try-block (js2-parse-statement)
7969 try-end (js2-node-end try-block)
7970 peek (js2-peek-token))
7973 (while (js2-match-token js2-CATCH)
7974 (setq catch-pos (js2-current-token-beg)
7979 (if saw-default-catch
7980 (js2-report-error "msg.catch.unreachable"))
7981 (if (js2-must-match js2-LP "msg.no.paren.catch")
7982 (setq lp (- (js2-current-token-beg) catch-pos)))
7983 (js2-push-scope (make-js2-scope))
7984 (let ((tt (js2-peek-token)))
7986 ;; destructuring pattern
7987 ;; catch ({ message, file }) { ... }
7988 ((or (= tt js2-LB) (= tt js2-LC))
7990 (setq param (js2-parse-destruct-primary-expr))
7991 (js2-define-destruct-symbols param js2-LET nil))
7994 (js2-must-match-name "msg.bad.catchcond")
7995 (setq param (js2-create-name-node))
7996 (js2-define-symbol js2-LET (js2-current-token-string) param))))
7998 (if (js2-match-token js2-IF)
7999 (setq guard-kwd (- (js2-current-token-beg) catch-pos)
8000 catch-cond (js2-parse-expr))
8001 (setq saw-default-catch t))
8002 (if (js2-must-match js2-RP "msg.bad.catchcond")
8003 (setq rp (- (js2-current-token-beg) catch-pos)))
8004 (js2-must-match js2-LC "msg.no.brace.catchblock")
8005 (setq block (js2-parse-statements)
8006 try-end (js2-node-end block)
8007 catch-node (make-js2-catch-node :pos catch-pos
8009 :guard-expr catch-cond
8010 :guard-kwd guard-kwd
8015 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8016 (setq try-end (js2-current-token-beg)))
8017 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8018 (js2-node-len catch-node) (- try-end catch-pos))
8019 (js2-node-add-children catch-node param catch-cond block)
8020 (push catch-node catch-blocks)))
8021 ((/= peek js2-FINALLY)
8022 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8023 (js2-node-pos try-block)
8024 (- (setq try-end (js2-node-end try-block))
8025 (js2-node-pos try-block)))))
8026 (when (js2-match-token js2-FINALLY)
8027 (setq finally-pos (js2-current-token-beg)
8028 block (js2-parse-statement)
8029 try-end (js2-node-end block)
8030 finally-block (make-js2-finally-node :pos finally-pos
8031 :len (- try-end finally-pos)
8033 (js2-node-add-children finally-block block))
8034 (setq pn (make-js2-try-node :pos try-pos
8035 :len (- try-end try-pos)
8036 :try-block try-block
8037 :finally-block finally-block))
8038 (js2-node-add-children pn try-block finally-block)
8039 ;; push them onto the try-node, which reverses and corrects their order
8040 (dolist (cb catch-blocks)
8041 (js2-node-add-children pn cb)
8042 (push cb (js2-try-node-catch-clauses pn)))
8045 (defun js2-parse-throw ()
8046 "Parser for throw-statement. Last matched token must be js2-THROW."
8047 (let ((pos (js2-current-token-beg))
8049 (if (= (js2-peek-token-or-eol) js2-EOL)
8050 ;; ECMAScript does not allow new lines before throw expression,
8052 (js2-report-error "msg.bad.throw.eol"))
8053 (setq expr (js2-parse-expr)
8054 pn (make-js2-throw-node :pos pos
8055 :len (- (js2-node-end expr) pos)
8057 (js2-node-add-children pn expr)
8060 (defun js2-match-jump-label-name (label-name)
8061 "If break/continue specified a label, return that label's labeled stmt.
8062 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8063 does not match an existing label, reports an error and returns nil."
8064 (let ((bundle (cdr (assoc label-name js2-label-set))))
8066 (js2-report-error "msg.undef.label"))
8069 (defun js2-parse-break ()
8070 "Parser for break-statement. Last matched token must be js2-BREAK."
8071 (let ((pos (js2-current-token-beg))
8072 (end (js2-current-token-end))
8073 break-target ; statement to break from
8074 break-label ; in "break foo", name-node representing the foo
8075 labels ; matching labeled statement to break to
8077 (when (eq (js2-peek-token-or-eol) js2-NAME)
8079 (setq break-label (js2-create-name-node)
8080 end (js2-node-end break-label)
8081 ;; matchJumpLabelName only matches if there is one
8082 labels (js2-match-jump-label-name (js2-current-token-string))
8083 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8084 (unless (or break-target break-label)
8085 ;; no break target specified - try for innermost enclosing loop/switch
8086 (if (null js2-loop-and-switch-set)
8088 (js2-report-error "msg.bad.break" nil pos (length "break")))
8089 (setq break-target (car js2-loop-and-switch-set))))
8090 (setq pn (make-js2-break-node :pos pos
8093 :target break-target))
8094 (js2-node-add-children pn break-label) ; but not break-target
8097 (defun js2-parse-continue ()
8098 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8099 (let ((pos (js2-current-token-beg))
8100 (end (js2-current-token-end))
8101 label ; optional user-specified label, a `js2-name-node'
8102 labels ; current matching labeled stmt, if any
8103 target ; the `js2-loop-node' target of this continue stmt
8105 (when (= (js2-peek-token-or-eol) js2-NAME)
8107 (setq label (js2-create-name-node)
8108 end (js2-node-end label)
8109 ;; matchJumpLabelName only matches if there is one
8110 labels (js2-match-jump-label-name (js2-current-token-string))))
8112 ((null labels) ; no current label to go to
8113 (if (null js2-loop-set) ; no loop to continue to
8114 (js2-report-error "msg.continue.outside" nil pos
8115 (length "continue"))
8116 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8118 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8119 (setq target (js2-labeled-stmt-node-stmt labels))
8120 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8121 (setq pn (make-js2-continue-node :pos pos
8125 (js2-node-add-children pn label) ; but not target - it's not our child
8128 (defun js2-parse-with ()
8129 "Parser for with-statement. Last matched token must be js2-WITH."
8130 (let ((pos (js2-current-token-beg))
8132 (if (js2-must-match js2-LP "msg.no.paren.with")
8133 (setq lp (js2-current-token-beg)))
8134 (setq obj (js2-parse-expr))
8135 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8136 (setq rp (js2-current-token-beg)))
8137 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8138 (setq body (js2-parse-statement)))
8139 (setq pn (make-js2-with-node :pos pos
8140 :len (- (js2-node-end body) pos)
8143 :lp (js2-relpos lp pos)
8144 :rp (js2-relpos rp pos)))
8145 (js2-node-add-children pn obj body)
8148 (defun js2-parse-const-var ()
8149 "Parser for var- or const-statement.
8150 Last matched token must be js2-CONST or js2-VAR."
8151 (let ((tt (js2-current-token-type))
8152 (pos (js2-current-token-beg))
8154 (setq expr (js2-parse-variables tt (js2-current-token-beg))
8155 pn (make-js2-expr-stmt-node :pos pos
8156 :len (- (js2-node-end expr) pos)
8158 (js2-node-add-children pn expr)
8161 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8162 (let ((pn (make-js2-expr-stmt-node :pos pos
8163 :len (js2-node-len expr)
8164 :type (if (js2-inside-function)
8169 (js2-node-add-children pn expr))
8172 (defun js2-parse-let-stmt ()
8173 "Parser for let-statement. Last matched token must be js2-LET."
8174 (let ((pos (js2-current-token-beg))
8176 (if (= (js2-peek-token) js2-LP)
8177 ;; let expression in statement context
8178 (setq expr (js2-parse-let pos 'statement)
8179 pn (js2-wrap-with-expr-stmt pos expr t))
8180 ;; else we're looking at a statement like let x=6, y=7;
8181 (setf expr (js2-parse-variables js2-LET pos)
8182 pn (js2-wrap-with-expr-stmt pos expr t)
8183 (js2-node-type pn) js2-EXPR_RESULT))
8186 (defun js2-parse-ret-yield ()
8187 (js2-parse-return-or-yield (js2-current-token-type) nil))
8189 (defconst js2-parse-return-stmt-enders
8190 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8192 (defsubst js2-now-all-set (before after mask)
8193 "Return whether or not the bits in the mask have changed to all set.
8194 BEFORE is bits before change, AFTER is bits after change, and MASK is
8195 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8197 (and (/= (logand before mask) mask)
8198 (= (logand after mask) mask)))
8200 (defun js2-parse-return-or-yield (tt expr-context)
8201 (let* ((pos (js2-current-token-beg))
8202 (end (js2-current-token-end))
8203 (before js2-end-flags)
8204 (inside-function (js2-inside-function))
8205 (gen-type (and inside-function (js2-function-node-generator-type
8206 js2-current-script-or-fn)))
8207 e ret name yield-star-p)
8208 (unless inside-function
8209 (js2-report-error (if (eq tt js2-RETURN)
8212 (when (and inside-function
8214 (js2-match-token js2-MUL))
8215 (setq yield-star-p t))
8216 ;; This is ugly, but we don't want to require a semicolon.
8217 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8218 (setq e (js2-parse-expr)
8219 end (js2-node-end e)))
8222 (js2-set-flag js2-end-flags (if (null e)
8224 js2-end-returns-value))
8225 (setq ret (make-js2-return-node :pos pos
8228 (js2-node-add-children ret e)
8229 ;; See if we need a strict mode warning.
8230 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8231 ;; more thorough and accurate than this before/after flag check.
8232 ;; E.g. if there's a finally-block that always returns, we shouldn't
8233 ;; show a warning generated by inconsistent returns in the catch blocks.
8234 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8235 ;; so we know which returns/yields to highlight, and we should get rid of
8236 ;; all the checking in `js2-parse-return-or-yield'.
8237 (if (and js2-strict-inconsistent-return-warning
8238 (js2-now-all-set before js2-end-flags
8239 (logior js2-end-returns js2-end-returns-value)))
8240 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8241 ((eq gen-type 'COMPREHENSION)
8242 ;; FIXME: We should probably switch to saving and using lastYieldOffset,
8243 ;; like SpiderMonkey does.
8244 (js2-report-error "msg.syntax" nil pos 5))
8246 (setq ret (make-js2-yield-node :pos pos
8249 :star-p yield-star-p))
8250 (js2-node-add-children ret e)
8251 (unless expr-context
8253 ret (js2-wrap-with-expr-stmt pos e t))
8254 (js2-set-requires-activation)
8255 (js2-set-is-generator))))
8256 ;; see if we are mixing yields and value returns.
8257 (when (and inside-function
8258 (js2-flag-set-p js2-end-flags js2-end-returns-value)
8259 (eq (js2-function-node-generator-type js2-current-script-or-fn)
8261 (setq name (js2-function-name js2-current-script-or-fn))
8262 (if (zerop (length name))
8263 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8264 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8267 (defun js2-parse-debugger ()
8268 (make-js2-keyword-node :type js2-DEBUGGER))
8270 (defun js2-parse-block ()
8271 "Parser for a curly-delimited statement block.
8272 Last token matched must be `js2-LC'."
8273 (let ((pos (js2-current-token-beg))
8274 (pn (make-js2-scope)))
8278 (js2-parse-statements pn)
8279 (js2-must-match js2-RC "msg.no.brace.block")
8280 (setf (js2-node-len pn) (- (js2-current-token-end) pos)))
8284 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8285 (defun js2-parse-semi ()
8286 "Parse a statement or handle an error.
8287 Current token type is `js2-SEMI' or `js2-ERROR'."
8288 (let ((tt (js2-current-token-type)) pos len)
8289 (if (eq tt js2-SEMI)
8290 (make-js2-empty-expr-node :len 1)
8291 (setq pos (js2-current-token-beg)
8292 len (- (js2-current-token-end) pos))
8293 (js2-report-error "msg.syntax" nil pos len)
8294 (make-js2-error-node :pos pos :len len))))
8296 (defun js2-parse-default-xml-namespace ()
8297 "Parse a `default xml namespace = <expr>' e4x statement."
8298 (let ((pos (js2-current-token-beg))
8301 (js2-set-requires-activation)
8302 (setq len (- js2-ts-cursor pos))
8303 (unless (and (js2-match-token js2-NAME)
8304 (string= (js2-current-token-string) "xml"))
8305 (js2-report-error "msg.bad.namespace" nil pos len))
8306 (unless (and (js2-match-token js2-NAME)
8307 (string= (js2-current-token-string) "namespace"))
8308 (js2-report-error "msg.bad.namespace" nil pos len))
8309 (unless (js2-match-token js2-ASSIGN)
8310 (js2-report-error "msg.bad.namespace" nil pos len))
8311 (setq expr (js2-parse-expr)
8312 end (js2-node-end expr)
8313 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8317 (js2-node-add-children unary expr)
8318 (make-js2-expr-stmt-node :pos pos
8322 (defun js2-record-label (label bundle)
8323 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8325 (let ((name (js2-label-node-name label))
8328 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8329 ;; flag both labels if possible when used in editing mode
8330 (if (and js2-parse-ide-mode
8331 (setq dup (js2-get-label-by-name labeled-stmt name)))
8332 (js2-report-error "msg.dup.label" nil
8333 (js2-node-abs-pos dup) (js2-node-len dup)))
8334 (js2-report-error "msg.dup.label" nil
8335 (js2-node-pos label) (js2-node-len label)))
8336 (js2-labeled-stmt-node-add-label bundle label)
8337 (js2-node-add-children bundle label)
8338 ;; Add one reference to the bundle per label in `js2-label-set'
8339 (push (cons name bundle) js2-label-set)))
8341 (defun js2-parse-name-or-label ()
8342 "Parser for identifier or label. Last token matched must be js2-NAME.
8343 Called when we found a name in a statement context. If it's a label, we gather
8344 up any following labels and the next non-label statement into a
8345 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8346 expression and return it wrapped in a `js2-expr-stmt-node'."
8347 (let ((pos (js2-current-token-beg))
8350 ;; set check for label and call down to `js2-parse-primary-expr'
8351 (setq expr (js2-maybe-parse-label))
8353 ;; Parse the non-label expression and wrap with expression stmt.
8354 (js2-wrap-with-expr-stmt pos (js2-parse-expr) t)
8355 ;; else parsed a label
8356 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8357 (js2-record-label expr bundle)
8358 ;; look for more labels
8359 (while (and continue (= (js2-get-token) js2-NAME))
8360 (if (setq expr (js2-maybe-parse-label))
8361 (js2-record-label expr bundle)
8362 (setq expr (js2-parse-expr)
8363 stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8365 (js2-auto-insert-semicolon stmt)))
8366 ;; no more labels; now parse the labeled statement
8369 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8371 (setq stmt (js2-statement-helper))))
8372 ;; remove the labels for this statement from the global set
8373 (dolist (label (js2-labeled-stmt-node-labels bundle))
8374 (setq js2-label-set (remove label js2-label-set))))
8375 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8376 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8377 (js2-node-add-children bundle stmt)
8380 (defun js2-maybe-parse-label ()
8381 (assert (= (js2-current-token-type) js2-NAME))
8383 (next-tt (js2-get-token))
8384 (label-end (js2-current-token-end)))
8385 ;; Do not consume colon, it is used as unwind indicator
8386 ;; to return to statementHelper.
8388 (if (= next-tt js2-COLON)
8390 (setq label-pos (js2-current-token-beg))
8391 (make-js2-label-node :pos label-pos
8392 :len (- label-end label-pos)
8393 :name (js2-current-token-string))
8394 (js2-set-face label-pos
8396 'font-lock-variable-name-face 'record))
8397 ;; Backtrack from the name token, too.
8401 (defun js2-parse-expr-stmt ()
8402 "Default parser in statement context, if no recognized statement found."
8403 (js2-wrap-with-expr-stmt (js2-current-token-beg)
8406 (js2-parse-expr)) t))
8408 (defun js2-parse-variables (decl-type pos)
8409 "Parse a comma-separated list of variable declarations.
8410 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8412 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8413 For 'var' or 'const', the keyword should be the token last scanned.
8415 POS is the position where the node should start. It's sometimes the
8416 var/const/let keyword, and other times the beginning of the first token
8417 in the first variable declaration.
8419 Returns the parsed `js2-var-decl-node' expression node."
8420 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8422 destructuring kid-pos tt init name end nbeg nend vi
8425 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8426 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8427 ;; var {a, b} = baz;
8429 (setq destructuring nil
8432 kid-pos (js2-current-token-beg)
8433 end (js2-current-token-end)
8435 (if (or (= tt js2-LB) (= tt js2-LC))
8436 ;; Destructuring assignment, e.g., var [a, b] = ...
8437 (setq destructuring (js2-parse-destruct-primary-expr)
8438 end (js2-node-end destructuring))
8439 ;; Simple variable name
8441 (when (js2-must-match-name "msg.bad.var")
8442 (setq name (js2-create-name-node)
8443 nbeg (js2-current-token-beg)
8444 nend (js2-current-token-end)
8446 (js2-define-symbol decl-type (js2-current-token-string) name js2-in-for-init)))
8447 (when (js2-match-token js2-ASSIGN)
8448 (setq init (js2-parse-assign-expr)
8449 end (js2-node-end init))
8450 (js2-record-imenu-functions init name))
8452 (js2-set-face nbeg nend (if (js2-function-node-p init)
8453 'font-lock-function-name-face
8454 'font-lock-variable-name-face)
8456 (setq vi (make-js2-var-init-node :pos kid-pos
8457 :len (- end kid-pos)
8461 (if (and (null init) (not js2-in-for-init))
8462 (js2-report-error "msg.destruct.assign.no.init"))
8463 (js2-define-destruct-symbols destructuring
8465 'font-lock-variable-name-face)
8466 (setf (js2-var-init-node-target vi) destructuring))
8467 (setf (js2-var-init-node-target vi) name))
8468 (setf (js2-var-init-node-initializer vi) init)
8469 (js2-node-add-children vi name destructuring init)
8470 (js2-block-node-push result vi)
8471 (unless (js2-match-token js2-COMMA)
8472 (setq continue nil)))
8473 (setf (js2-node-len result) (- end pos))
8476 (defun js2-parse-let (pos &optional stmt-p)
8477 "Parse a let expression or statement.
8478 A let-expression is of the form `let (vars) expr'.
8479 A let-statment is of the form `let (vars) {statements}'.
8480 The third form of let is a variable declaration list, handled
8481 by `js2-parse-variables'."
8482 (let ((pn (make-js2-let-node :pos pos))
8484 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8485 (setf (js2-let-node-lp pn) (- (js2-current-token-beg) pos)))
8489 (setq vars (js2-parse-variables js2-LET (js2-current-token-beg)))
8490 (if (js2-must-match js2-RP "msg.no.paren.let")
8491 (setf (js2-let-node-rp pn) (- (js2-current-token-beg) pos)))
8492 (if (and stmt-p (js2-match-token js2-LC))
8495 (setf beg (js2-current-token-beg) ; position stmt at LC
8496 body (js2-parse-statements))
8497 (js2-must-match js2-RC "msg.no.curly.let")
8498 (setf (js2-node-len body) (- (js2-current-token-end) beg)
8499 (js2-node-len pn) (- (js2-current-token-end) pos)
8500 (js2-let-node-body pn) body
8501 (js2-node-type pn) js2-LET))
8503 (setf body (js2-parse-expr)
8504 (js2-node-len pn) (- (js2-node-end body) pos)
8505 (js2-let-node-body pn) body))
8506 (setf (js2-let-node-vars pn) vars)
8507 (js2-node-add-children pn vars body))
8511 (defun js2-define-new-symbol (decl-type name node &optional scope)
8512 (js2-scope-put-symbol (or scope js2-current-scope)
8514 (make-js2-symbol decl-type name node)))
8516 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8517 "Define a symbol in the current scope.
8518 If NODE is non-nil, it is the AST node associated with the symbol."
8519 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8520 (symbol (if defining-scope
8521 (js2-scope-get-symbol defining-scope name)))
8522 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8524 ((and symbol ; already defined
8525 (or (= sdt js2-CONST) ; old version is const
8526 (= decl-type js2-CONST) ; new version is const
8527 ;; two let-bound vars in this block have same name
8528 (and (= sdt js2-LET)
8529 (eq defining-scope js2-current-scope))))
8532 ((= sdt js2-CONST) "msg.const.redecl")
8533 ((= sdt js2-LET) "msg.let.redecl")
8534 ((= sdt js2-VAR) "msg.var.redecl")
8535 ((= sdt js2-FUNCTION) "msg.function.redecl")
8536 (t "msg.parm.redecl"))
8538 ((= decl-type js2-LET)
8539 (if (and (not ignore-not-in-block)
8540 (or (= (js2-node-type js2-current-scope) js2-IF)
8541 (js2-loop-node-p js2-current-scope)))
8542 (js2-report-error "msg.let.decl.not.in.block")
8543 (js2-define-new-symbol decl-type name node)))
8544 ((or (= decl-type js2-VAR)
8545 (= decl-type js2-CONST)
8546 (= decl-type js2-FUNCTION))
8548 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8549 (js2-add-strict-warning "msg.var.redecl" name)
8550 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8551 (js2-add-strict-warning "msg.var.hides.arg" name)))
8552 (js2-define-new-symbol decl-type name node
8553 js2-current-script-or-fn)))
8554 ((= decl-type js2-LP)
8556 ;; must be duplicate parameter. Second parameter hides the
8557 ;; first, so go ahead and add the second pararameter
8558 (js2-report-warning "msg.dup.parms" name))
8559 (js2-define-new-symbol decl-type name node))
8560 (t (js2-code-bug)))))
8562 (defun js2-parse-paren-expr-or-generator-comp ()
8563 (let ((px-pos (js2-current-token-beg)))
8564 (if (and (>= js2-language-version 200)
8565 (js2-match-token js2-FOR))
8566 (js2-parse-generator-comp px-pos)
8567 (let* ((js2-in-for-init nil)
8568 (expr (js2-parse-expr))
8569 (pn (make-js2-paren-node :pos px-pos
8571 :len (- (js2-current-token-end)
8573 (js2-node-add-children pn (js2-paren-node-expr pn))
8574 (js2-must-match js2-RP "msg.no.paren")
8577 (defun js2-parse-expr (&optional oneshot)
8578 (let* ((pn (js2-parse-assign-expr))
8579 (pos (js2-node-pos pn))
8583 (while (and (not oneshot)
8584 (js2-match-token js2-COMMA))
8585 (setq op-pos (- (js2-current-token-beg) pos)) ; relative
8586 (if (= (js2-peek-token) js2-YIELD)
8587 (js2-report-error "msg.yield.parenthesized"))
8588 (setq right (js2-parse-assign-expr)
8590 pn (make-js2-infix-node :type js2-COMMA
8592 :len (- js2-ts-cursor pos)
8596 (js2-node-add-children pn left right))
8599 (defun js2-parse-assign-expr ()
8600 (let ((tt (js2-get-token))
8601 (pos (js2-current-token-beg))
8602 pn left right op-pos
8603 ts-state recorded-identifiers parsed-errors)
8604 (if (= tt js2-YIELD)
8605 (js2-parse-return-or-yield tt t)
8606 ;; Save the tokenizer state in case we find an arrow function
8607 ;; and have to rewind.
8608 (setq ts-state (make-js2-ts-state)
8609 recorded-identifiers js2-recorded-identifiers
8610 parsed-errors js2-parsed-errors)
8611 ;; not yield - parse assignment expression
8612 (setq pn (js2-parse-cond-expr)
8615 ((and (<= js2-first-assign tt)
8616 (<= tt js2-last-assign))
8617 ;; tt express assignment (=, |=, ^=, ..., %=)
8618 (setq op-pos (- (js2-current-token-beg) pos) ; relative
8620 (setq right (js2-parse-assign-expr)
8621 pn (make-js2-assign-node :type tt
8623 :len (- (js2-node-end right) pos)
8627 (when js2-parse-ide-mode
8628 (js2-highlight-assign-targets pn left right)
8629 (js2-record-imenu-functions right left))
8630 ;; do this last so ide checks above can use absolute positions
8631 (js2-node-add-children pn left right))
8632 ((and (= tt js2-ARROW)
8633 (>= js2-language-version 200))
8634 (js2-ts-seek ts-state)
8635 (setq js2-recorded-identifiers recorded-identifiers
8636 js2-parsed-errors parsed-errors)
8637 (setq pn (js2-parse-function 'FUNCTION_ARROW (js2-current-token-beg) nil)))
8642 (defun js2-parse-cond-expr ()
8643 (let ((pos (js2-current-token-beg))
8644 (pn (js2-parse-or-expr))
8650 (when (js2-match-token js2-HOOK)
8651 (setq q-pos (- (js2-current-token-beg) pos)
8652 if-true (let (js2-in-for-init) (js2-parse-assign-expr)))
8653 (js2-must-match js2-COLON "msg.no.colon.cond")
8654 (setq c-pos (- (js2-current-token-beg) pos)
8655 if-false (js2-parse-assign-expr)
8657 pn (make-js2-cond-node :pos pos
8658 :len (- (js2-node-end if-false) pos)
8659 :test-expr test-expr
8661 :false-expr if-false
8664 (js2-node-add-children pn test-expr if-true if-false))
8667 (defun js2-make-binary (type left parser)
8668 "Helper for constructing a binary-operator AST node.
8669 LEFT is the left-side-expression, already parsed, and the
8670 binary operator should have just been matched.
8671 PARSER is a function to call to parse the right operand,
8672 or a `js2-node' struct if it has already been parsed.
8673 FIXME: The latter option is unused?"
8674 (let* ((pos (js2-node-pos left))
8675 (op-pos (- (js2-current-token-beg) pos))
8676 (right (if (js2-node-p parser)
8680 (pn (make-js2-infix-node :type type
8682 :len (- (js2-node-end right) pos)
8686 (js2-node-add-children pn left right)
8689 (defun js2-parse-or-expr ()
8690 (let ((pn (js2-parse-and-expr)))
8691 (when (js2-match-token js2-OR)
8692 (setq pn (js2-make-binary js2-OR
8694 'js2-parse-or-expr)))
8697 (defun js2-parse-and-expr ()
8698 (let ((pn (js2-parse-bit-or-expr)))
8699 (when (js2-match-token js2-AND)
8700 (setq pn (js2-make-binary js2-AND
8702 'js2-parse-and-expr)))
8705 (defun js2-parse-bit-or-expr ()
8706 (let ((pn (js2-parse-bit-xor-expr)))
8707 (while (js2-match-token js2-BITOR)
8708 (setq pn (js2-make-binary js2-BITOR
8710 'js2-parse-bit-xor-expr)))
8713 (defun js2-parse-bit-xor-expr ()
8714 (let ((pn (js2-parse-bit-and-expr)))
8715 (while (js2-match-token js2-BITXOR)
8716 (setq pn (js2-make-binary js2-BITXOR
8718 'js2-parse-bit-and-expr)))
8721 (defun js2-parse-bit-and-expr ()
8722 (let ((pn (js2-parse-eq-expr)))
8723 (while (js2-match-token js2-BITAND)
8724 (setq pn (js2-make-binary js2-BITAND
8726 'js2-parse-eq-expr)))
8729 (defconst js2-parse-eq-ops
8730 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8732 (defun js2-parse-eq-expr ()
8733 (let ((pn (js2-parse-rel-expr))
8735 (while (memq (setq tt (js2-get-token)) js2-parse-eq-ops)
8736 (setq pn (js2-make-binary tt
8738 'js2-parse-rel-expr)))
8742 (defconst js2-parse-rel-ops
8743 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8745 (defun js2-parse-rel-expr ()
8746 (let ((pn (js2-parse-shift-expr))
8750 (setq tt (js2-get-token))
8752 ((and js2-in-for-init (= tt js2-IN))
8754 (setq continue nil))
8755 ((memq tt js2-parse-rel-ops)
8756 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8759 (setq continue nil))))
8762 (defconst js2-parse-shift-ops
8763 (list js2-LSH js2-URSH js2-RSH))
8765 (defun js2-parse-shift-expr ()
8766 (let ((pn (js2-parse-add-expr))
8770 (setq tt (js2-get-token))
8771 (if (memq tt js2-parse-shift-ops)
8772 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr))
8774 (setq continue nil)))
8777 (defun js2-parse-add-expr ()
8778 (let ((pn (js2-parse-mul-expr))
8782 (setq tt (js2-get-token))
8783 (if (or (= tt js2-ADD) (= tt js2-SUB))
8784 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr))
8786 (setq continue nil)))
8789 (defconst js2-parse-mul-ops
8790 (list js2-MUL js2-DIV js2-MOD))
8792 (defun js2-parse-mul-expr ()
8793 (let ((pn (js2-parse-unary-expr))
8797 (setq tt (js2-get-token))
8798 (if (memq tt js2-parse-mul-ops)
8799 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr))
8801 (setq continue nil)))
8804 (defun js2-make-unary (type parser &rest args)
8805 "Make a unary node of type TYPE.
8806 PARSER is either a node (for postfix operators) or a function to call
8807 to parse the operand (for prefix operators)."
8808 (let* ((pos (js2-current-token-beg))
8809 (postfix (js2-node-p parser))
8812 (apply parser args)))
8815 (if postfix ; e.g. i++
8816 (setq pos (js2-node-pos expr)
8817 end (js2-current-token-end))
8818 (setq end (js2-node-end expr)))
8819 (setq pn (make-js2-unary-node :type type
8823 (js2-node-add-children pn expr)
8826 (defconst js2-incrementable-node-types
8827 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8828 "Node types that can be the operand of a ++ or -- operator.")
8830 (defun js2-check-bad-inc-dec (tt beg end unary)
8831 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8832 js2-incrementable-node-types)
8833 (js2-report-error (if (= tt js2-INC)
8836 nil beg (- end beg))))
8838 (defun js2-parse-unary-expr ()
8839 (let ((tt (js2-current-token-type))
8842 ((or (= tt js2-VOID)
8847 (js2-make-unary tt 'js2-parse-unary-expr))
8850 ;; Convert to special POS token in decompiler and parse tree
8851 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8854 ;; Convert to special NEG token in decompiler and parse tree
8855 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8860 (setq beg (js2-current-token-beg)
8861 end (js2-current-token-end)
8862 expr (js2-make-unary tt 'js2-parse-member-expr t))
8863 (js2-check-bad-inc-dec tt beg end expr)))
8866 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8869 (make-js2-error-node)) ; try to continue
8871 js2-compiler-xml-available)
8872 ;; XML stream encountered in expression.
8873 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8875 (setq pn (js2-parse-member-expr t)
8876 ;; Don't look across a newline boundary for a postfix incop.
8877 tt (js2-peek-token-or-eol))
8878 (when (or (= tt js2-INC) (= tt js2-DEC))
8881 pn (js2-make-unary tt expr))
8882 (js2-node-set-prop pn 'postfix t)
8883 (js2-check-bad-inc-dec tt (js2-current-token-beg) (js2-current-token-end) pn))
8886 (defun js2-parse-xml-initializer ()
8887 "Parse an E4X XML initializer.
8888 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8889 Then I'll postprocess the result, depending on whether we're in IDE
8890 mode or codegen mode, and generate the appropriate rewritten AST.
8891 IDE mode uses a rich AST that models the XML structure. Codegen mode
8892 just concatenates everything and makes a new XML or XMLList out of it."
8893 (let ((tt (js2-get-first-xml-token))
8894 pn-xml pn expr kids expr-pos
8897 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8898 (js2-report-error "msg.syntax"))
8899 (setq pn-xml (make-js2-xml-node))
8902 (setq first-token nil)
8903 (setq tt (js2-get-next-xml-token)))
8905 ;; js2-XML means we found a {expr} in the XML stream.
8906 ;; The token string is the XML up to the left-curly.
8908 (push (make-js2-string-node :pos (js2-current-token-beg)
8909 :len (- js2-ts-cursor (js2-current-token-beg)))
8911 (js2-must-match js2-LC "msg.syntax")
8912 (setq expr-pos js2-ts-cursor
8913 expr (if (eq (js2-peek-token) js2-RC)
8914 (make-js2-empty-expr-node :pos expr-pos)
8916 (js2-must-match js2-RC "msg.syntax")
8917 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8918 :len (js2-node-len expr)
8920 (js2-node-add-children pn expr)
8922 ;; a js2-XMLEND token means we hit the final close-tag.
8924 (push (make-js2-string-node :pos (js2-current-token-beg)
8925 :len (- js2-ts-cursor (js2-current-token-beg)))
8927 (dolist (kid (nreverse kids))
8928 (js2-block-node-push pn-xml kid))
8929 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8930 (js2-node-pos pn-xml))
8933 (js2-report-error "msg.syntax")
8934 (setq continue nil))))
8938 (defun js2-parse-argument-list ()
8939 "Parse an argument list and return it as a Lisp list of nodes.
8940 Returns the list in reverse order. Consumes the right-paren token."
8942 (unless (js2-match-token js2-RP)
8944 (let ((tt (js2-get-token)))
8945 (if (= tt js2-YIELD)
8946 (js2-report-error "msg.yield.parenthesized"))
8947 (if (and (= tt js2-TRIPLEDOT)
8948 (>= js2-language-version 200))
8949 (push (js2-make-unary tt 'js2-parse-assign-expr) result)
8951 (push (js2-parse-assign-expr) result)))
8953 (js2-match-token js2-COMMA))
8954 (js2-must-match js2-RP "msg.no.paren.arg")
8957 (defun js2-parse-member-expr (&optional allow-call-syntax)
8958 (let ((tt (js2-current-token-type))
8959 pn pos target args beg end init)
8961 (setq pn (js2-parse-primary-expr))
8962 ;; parse a 'new' expression
8964 (setq pos (js2-current-token-beg)
8966 target (js2-parse-member-expr)
8967 end (js2-node-end target)
8968 pn (make-js2-new-node :pos pos
8971 (js2-highlight-function-call (js2-current-token))
8972 (js2-node-add-children pn target)
8973 (when (js2-match-token js2-LP)
8974 ;; Add the arguments to pn, if any are supplied.
8975 (setf beg pos ; start of "new" keyword
8976 pos (js2-current-token-beg)
8977 args (nreverse (js2-parse-argument-list))
8978 (js2-new-node-args pn) args
8979 end (js2-current-token-end)
8980 (js2-new-node-lp pn) (- pos beg)
8981 (js2-new-node-rp pn) (- end 1 beg))
8982 (apply #'js2-node-add-children pn args))
8983 (when (and js2-allow-rhino-new-expr-initializer
8984 (js2-match-token js2-LC))
8985 (setf init (js2-parse-object-literal)
8986 end (js2-node-end init)
8987 (js2-new-node-initializer pn) init)
8988 (js2-node-add-children pn init))
8989 (setf (js2-node-len pn) (- end beg))) ; end outer if
8990 (js2-parse-member-expr-tail allow-call-syntax pn)))
8992 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8993 "Parse a chain of property/array accesses or function calls.
8994 Includes parsing for E4X operators like `..' and `.@'.
8995 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8996 Returns an expression tree that includes PN, the parent node."
9000 (setq tt (js2-get-token))
9002 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9003 (setq pn (js2-parse-property-access tt pn)))
9004 ((= tt js2-DOTQUERY)
9005 (setq pn (js2-parse-dot-query pn)))
9007 (setq pn (js2-parse-element-get pn)))
9010 (if allow-call-syntax
9011 (setq pn (js2-parse-function-call pn))
9012 (setq continue nil)))
9015 (setq continue nil))))
9016 (if (>= js2-highlight-level 2)
9017 (js2-parse-highlight-member-expr-node pn))
9020 (defun js2-parse-dot-query (pn)
9021 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9022 Last token parsed must be `js2-DOTQUERY'."
9023 (let ((pos (js2-node-pos pn))
9026 (js2-set-requires-activation)
9027 (setq op-pos (js2-current-token-beg)
9028 expr (js2-parse-expr)
9029 end (js2-node-end expr)
9030 pn (make-js2-xml-dot-query-node :left pn
9034 (js2-node-add-children pn
9035 (js2-xml-dot-query-node-left pn)
9036 (js2-xml-dot-query-node-right pn))
9037 (if (js2-must-match js2-RP "msg.no.paren")
9038 (setf (js2-xml-dot-query-node-rp pn) (js2-current-token-beg)
9039 end (js2-current-token-end)))
9040 (setf (js2-node-len pn) (- end pos))
9043 (defun js2-parse-element-get (pn)
9044 "Parse an element-get expression, e.g. foo[bar].
9045 Last token parsed must be `js2-RB'."
9046 (let ((lb (js2-current-token-beg))
9047 (pos (js2-node-pos pn))
9049 (setq expr (js2-parse-expr))
9050 (if (js2-must-match js2-RB "msg.no.bracket.index")
9051 (setq rb (js2-current-token-beg)))
9052 (setq pn (make-js2-elem-get-node :target pn
9055 :lb (js2-relpos lb pos)
9056 :rb (js2-relpos rb pos)
9057 :len (- (js2-current-token-end) pos)))
9058 (js2-node-add-children pn
9059 (js2-elem-get-node-target pn)
9060 (js2-elem-get-node-element pn))
9063 (defun js2-highlight-function-call (token)
9064 (when (eq (js2-token-type token) js2-NAME)
9065 (js2-record-face 'js2-function-call token)))
9067 (defun js2-parse-function-call (pn)
9068 (js2-highlight-function-call (js2-current-token))
9071 (pos (js2-node-pos pn)))
9072 (setq pn (make-js2-call-node :pos pos
9074 :lp (- (js2-current-token-beg) pos)))
9075 (js2-node-add-children pn (js2-call-node-target pn))
9076 ;; Add the arguments to pn, if any are supplied.
9077 (setf args (nreverse (js2-parse-argument-list))
9078 (js2-call-node-rp pn) (- (js2-current-token-beg) pos)
9079 (js2-call-node-args pn) args)
9080 (apply #'js2-node-add-children pn args)
9081 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9084 (defun js2-parse-property-access (tt pn)
9085 "Parse a property access, XML descendants access, or XML attr access."
9086 (let ((member-type-flags 0)
9087 (dot-pos (js2-current-token-beg))
9088 (dot-len (if (= tt js2-DOTDOT) 2 1))
9090 ref ; right side of . or .. operator
9092 (when (= tt js2-DOTDOT)
9094 (setq member-type-flags js2-descendants-flag))
9095 (if (not js2-compiler-xml-available)
9097 (js2-must-match-prop-name "msg.no.name.after.dot")
9098 (setq name (js2-create-name-node t js2-GETPROP)
9099 result (make-js2-prop-get-node :left pn
9100 :pos (js2-current-token-beg)
9102 :len (js2-current-token-len)))
9103 (js2-node-add-children result pn name)
9105 ;; otherwise look for XML operators
9106 (setf result (if (= tt js2-DOT)
9107 (make-js2-prop-get-node)
9108 (make-js2-infix-node :type js2-DOTDOT))
9109 (js2-node-pos result) (js2-node-pos pn)
9110 (js2-infix-node-op-pos result) dot-pos
9111 (js2-infix-node-left result) pn ; do this after setting position
9112 tt (js2-next-token))
9114 ;; needed for generator.throw()
9116 (setq ref (js2-parse-property-name nil nil member-type-flags)))
9117 ;; handles: name, ns::name, ns::*, ns::[expr]
9118 ((js2-valid-prop-name-token tt)
9119 (setq ref (js2-parse-property-name -1 nil member-type-flags)))
9120 ;; handles: *, *::name, *::*, *::[expr]
9122 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9123 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9125 (setq result (js2-parse-attribute-access)))
9127 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9129 (setf (js2-node-len result) (- (js2-node-end ref)
9130 (js2-node-pos result))
9131 (js2-infix-node-right result) ref))
9132 (if (js2-infix-node-p result)
9133 (js2-node-add-children result
9134 (js2-infix-node-left result)
9135 (js2-infix-node-right result)))
9138 (defun js2-parse-attribute-access ()
9139 "Parse an E4X XML attribute expression.
9140 This includes expressions of the forms:
9142 @attr @ns::attr @ns::*
9144 @[expr] @*::[expr] @ns::[expr]
9146 Called if we peeked an '@' token."
9147 (let ((tt (js2-next-token))
9148 (at-pos (js2-current-token-beg)))
9150 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9151 ((js2-valid-prop-name-token tt)
9152 (js2-parse-property-name at-pos nil 0))
9153 ;; handles: @*, @*::name, @*::*, @*::[expr]
9155 (js2-parse-property-name (js2-current-token-beg) "*" 0))
9158 (js2-parse-xml-elem-ref at-pos))
9160 (js2-report-error "msg.no.name.after.xmlAttr")
9161 ;; Avoid cascaded errors that happen if we make an error node here.
9162 (js2-parse-property-name (js2-current-token-beg) "" 0)))))
9164 (defun js2-parse-property-name (at-pos s member-type-flags)
9165 "Check if :: follows name in which case it becomes qualified name.
9167 AT-POS is a natural number if we just read an '@' token, else nil.
9168 S is the name or string that was matched: an identifier, 'throw' or '*'.
9169 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9171 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9172 operator, or the name is followed by ::. For a plain name, returns a
9173 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9174 (let ((pos (or at-pos (js2-current-token-beg)))
9176 (name (js2-create-name-node t (js2-current-token-type) s))
9179 (when (js2-match-token js2-COLONCOLON)
9181 colon-pos (js2-current-token-beg)
9182 tt (js2-next-token))
9184 ;; handles name::name
9185 ((js2-valid-prop-name-token tt)
9186 (setq name (js2-create-name-node)))
9189 (setq name (js2-create-name-node nil nil "*")))
9190 ;; handles name::[expr]
9192 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9194 (js2-report-error "msg.no.name.after.coloncolon"))))
9195 (if (and (null ns) (zerop member-type-flags))
9199 (make-js2-xml-prop-ref-node :pos pos
9200 :len (- (js2-node-end name) pos)
9202 :colon-pos colon-pos
9204 (js2-node-add-children pn name))))))
9206 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9207 "Parse the [expr] portion of an xml element reference.
9208 For instance, @[expr], @*::[expr], or ns::[expr]."
9209 (let* ((lb (js2-current-token-beg))
9210 (pos (or at-pos lb))
9212 (expr (js2-parse-expr))
9213 (end (js2-node-end expr))
9215 (if (js2-must-match js2-RB "msg.no.bracket.index")
9216 (setq rb (js2-current-token-beg)
9217 end (js2-current-token-end)))
9220 (make-js2-xml-elem-ref-node :pos pos
9222 :namespace namespace
9223 :colon-pos colon-pos
9226 :lb (js2-relpos lb pos)
9227 :rb (js2-relpos rb pos)))
9228 (js2-node-add-children pn namespace expr))))
9230 (defun js2-parse-destruct-primary-expr ()
9231 (let ((js2-is-in-destructuring t))
9232 (js2-parse-primary-expr)))
9234 (defun js2-parse-primary-expr ()
9235 "Parse a literal (leaf) expression of some sort.
9236 Includes complex literals such as functions, object-literals,
9237 array-literals, array comprehensions and regular expressions."
9238 (let (pn ; parent node (usually return value)
9240 (setq tt (js2-current-token-type))
9242 ((= tt js2-FUNCTION)
9243 (js2-parse-function-expr))
9245 (js2-parse-array-comp-or-literal))
9247 (js2-parse-object-literal))
9249 (js2-parse-let (js2-current-token-beg)))
9251 (js2-parse-paren-expr-or-generator-comp))
9254 (js2-parse-attribute-access))
9256 (js2-parse-name tt))
9258 (make-js2-number-node))
9261 (make-js2-string-node)
9262 (js2-record-face 'font-lock-string-face)))
9263 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9264 ;; Got / or /= which in this context means a regexp literal
9265 (let ((px-pos (js2-current-token-beg))
9266 (flags (js2-read-regexp tt))
9267 (end (js2-current-token-end)))
9269 (make-js2-regexp-node :pos px-pos
9271 :value (js2-current-token-string)
9273 (js2-set-face px-pos end 'font-lock-string-face 'record)
9274 (js2-record-text-property px-pos end 'syntax-table '(2)))))
9275 ((or (= tt js2-NULL)
9279 (make-js2-keyword-node :type tt))
9281 ;; Not valid expression syntax, but this is valid in an arrow
9282 ;; function with no params: () => body.
9283 (if (eq (js2-peek-token) js2-ARROW)
9285 (js2-unget-token) ; Put back the right paren.
9286 ;; Return whatever, it will hopefully be rewinded and
9287 ;; reparsed when we reach the =>.
9288 (make-js2-keyword-node :type js2-NULL))
9289 (js2-report-error "msg.syntax")
9290 (make-js2-error-node)))
9291 ((= tt js2-TRIPLEDOT)
9292 ;; Likewise, only valid in an arrow function with a rest param.
9293 (if (and (js2-match-token js2-NAME)
9294 (js2-match-token js2-RP)
9295 (eq (js2-peek-token) js2-ARROW))
9297 (js2-unget-token) ; Put back the right paren.
9298 ;; See the previous case.
9299 (make-js2-keyword-node :type js2-NULL))
9300 (js2-report-error "msg.syntax")
9301 (make-js2-error-node)))
9302 ((= tt js2-RESERVED)
9303 (js2-report-error "msg.reserved.id")
9304 (make-js2-name-node))
9306 ;; the scanner or one of its subroutines reported the error.
9307 (make-js2-error-node))
9309 (let* ((px-pos (point-at-bol))
9310 (len (- js2-ts-cursor px-pos)))
9311 (js2-report-error "msg.unexpected.eof" nil px-pos len))
9312 (make-js2-error-node :pos (1- js2-ts-cursor)))
9314 (js2-report-error "msg.syntax")
9315 (make-js2-error-node)))))
9317 (defun js2-parse-name (_tt)
9318 (let ((name (js2-current-token-string))
9320 (setq node (if js2-compiler-xml-available
9321 (js2-parse-property-name nil name 0)
9322 (js2-create-name-node 'check-activation nil name)))
9323 (if js2-highlight-external-variables
9324 (js2-record-name-node node))
9327 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9328 (js2-add-strict-warning
9330 ;; back up from comma to beginning of line or array/objlit
9332 (js2-node-pos (car elems))
9335 (goto-char comma-pos)
9336 (back-to-indentation)
9340 (defun js2-parse-array-comp-or-literal ()
9341 (let ((pos (js2-current-token-beg)))
9342 (if (and (>= js2-language-version 200)
9343 (js2-match-token js2-FOR))
9344 (js2-parse-array-comp pos)
9345 (js2-parse-array-literal pos))))
9347 (defun js2-parse-array-literal (pos)
9348 (let ((after-lb-or-comma t)
9349 after-comma tt elems pn
9351 (unless js2-is-in-destructuring
9352 (js2-push-scope (make-js2-scope))) ; for the legacy array comp
9354 (setq tt (js2-get-token))
9358 (setq after-comma (js2-current-token-end))
9359 (if (not after-lb-or-comma)
9360 (setq after-lb-or-comma t)
9364 (= tt js2-EOF)) ; prevent infinite loop
9366 (js2-report-error "msg.no.bracket.arg" nil pos))
9367 (when (and after-comma (< js2-language-version 170))
9368 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9369 pos (remove nil elems) after-comma))
9371 pn (make-js2-array-node :pos pos
9372 :len (- js2-ts-cursor pos)
9373 :elems (nreverse elems)))
9374 (apply #'js2-node-add-children pn (js2-array-node-elems pn)))
9375 ;; destructuring binding
9376 (js2-is-in-destructuring
9377 (push (if (or (= tt js2-LC)
9380 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9381 (js2-parse-destruct-primary-expr)
9383 (js2-report-error "msg.bad.var")
9384 (make-js2-error-node))
9386 (setq after-lb-or-comma nil
9389 ((and (>= js2-language-version 170)
9390 (= tt js2-FOR) ; check for array comprehension
9391 (not after-lb-or-comma) ; "for" can't follow a comma
9392 elems ; must have at least 1 element
9393 (not (cdr elems))) ; but no 2nd element
9396 pn (js2-parse-legacy-array-comp (car elems) pos)))
9399 (unless after-lb-or-comma
9400 (js2-report-error "msg.no.bracket.arg"))
9401 (if (and (= tt js2-TRIPLEDOT)
9402 (>= js2-language-version 200))
9404 (push (js2-make-unary tt 'js2-parse-assign-expr)
9407 (push (js2-parse-assign-expr) elems))
9408 (setq after-lb-or-comma nil
9410 (unless js2-is-in-destructuring
9414 (defun js2-parse-legacy-array-comp (expr pos)
9415 "Parse a legacy array comprehension (JavaScript 1.7).
9416 EXPR is the first expression after the opening left-bracket.
9417 POS is the beginning of the LB token preceding EXPR.
9418 We should have just parsed the 'for' keyword before calling this function."
9419 (let ((current-scope js2-current-scope)
9420 loops first filter result)
9423 (while (js2-match-token js2-FOR)
9424 (let ((loop (make-js2-comp-loop-node)))
9425 (js2-push-scope loop)
9427 (js2-parse-comp-loop loop)))
9428 ;; First loop takes expr scope's parent.
9429 (setf (js2-scope-parent-scope (setq first (car (last loops))))
9430 (js2-scope-parent-scope current-scope))
9431 ;; Set expr scope's parent to the last loop.
9432 (setf (js2-scope-parent-scope current-scope) (car loops))
9433 (if (/= (js2-get-token) js2-IF)
9435 (setq filter (js2-parse-condition))))
9436 (dotimes (_ (1- (length loops)))
9438 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9439 (setq result (make-js2-comp-node :pos pos
9440 :len (- js2-ts-cursor pos)
9442 :loops (nreverse loops)
9443 :filters (and filter (list (car filter)))
9444 :form 'LEGACY_ARRAY))
9445 (apply #'js2-node-add-children result expr (car filter)
9446 (js2-comp-node-loops result))
9449 (defun js2-parse-array-comp (pos)
9450 "Parse an ES6 array comprehension.
9451 POS is the beginning of the LB token.
9452 We should have just parsed the 'for' keyword before calling this function."
9453 (let ((pn (js2-parse-comprehension pos 'ARRAY)))
9454 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9457 (defun js2-parse-generator-comp (pos)
9458 (let* ((js2-nesting-of-function (1+ js2-nesting-of-function))
9459 (js2-current-script-or-fn
9460 (make-js2-function-node :generator-type 'COMPREHENSION))
9461 (pn (js2-parse-comprehension pos 'STAR_GENERATOR)))
9462 (js2-must-match js2-RP "msg.no.paren" pos)
9465 (defun js2-parse-comprehension (pos form)
9466 (let (loops filters expr result)
9470 (while (js2-match-token js2-FOR)
9471 (let ((loop (make-js2-comp-loop-node)))
9472 (js2-push-scope loop)
9474 (js2-parse-comp-loop loop)))
9475 (while (js2-match-token js2-IF)
9476 (push (car (js2-parse-condition)) filters))
9477 (setq expr (js2-parse-assign-expr)))
9480 (setq result (make-js2-comp-node :pos pos
9481 :len (- js2-ts-cursor pos)
9483 :loops (nreverse loops)
9484 :filters (nreverse filters)
9486 (apply #'js2-node-add-children result (js2-comp-node-loops result))
9487 (apply #'js2-node-add-children result expr (js2-comp-node-filters result))
9490 (defun js2-parse-comp-loop (pn &optional only-of-p)
9491 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9492 The current token should be the initial FOR.
9493 If ONLY-OF-P is non-nil, only the 'for (foo of bar)' form is allowed."
9494 (let ((pos (js2-comp-loop-node-pos pn))
9495 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9496 (when (and (not only-of-p) (js2-match-token js2-NAME))
9497 (if (string= (js2-current-token-string) "each")
9500 each-pos (- (js2-current-token-beg) pos)) ; relative
9501 (js2-record-face 'font-lock-keyword-face))
9502 (js2-report-error "msg.no.paren.for")))
9503 (if (js2-must-match js2-LP "msg.no.paren.for")
9504 (setq lp (- (js2-current-token-beg) pos)))
9505 (setq tt (js2-peek-token))
9510 (setq iter (js2-parse-destruct-primary-expr))
9511 (js2-define-destruct-symbols iter js2-LET
9512 'font-lock-variable-name-face t))
9513 ((js2-match-token js2-NAME)
9514 (setq iter (js2-create-name-node)))
9516 (js2-report-error "msg.bad.var")))
9517 ;; Define as a let since we want the scope of the variable to
9518 ;; be restricted to the array comprehension
9519 (if (js2-name-node-p iter)
9520 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9521 (if (or (and (not only-of-p) (js2-match-token js2-IN))
9522 (and (>= js2-language-version 200)
9523 (js2-match-contextual-kwd "of")
9525 (setq in-pos (- (js2-current-token-beg) pos))
9526 (js2-report-error "msg.in.after.for.name"))
9527 (setq obj (js2-parse-expr))
9528 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9529 (setq rp (- (js2-current-token-beg) pos)))
9530 (setf (js2-node-pos pn) pos
9531 (js2-node-len pn) (- js2-ts-cursor pos)
9532 (js2-comp-loop-node-iterator pn) iter
9533 (js2-comp-loop-node-object pn) obj
9534 (js2-comp-loop-node-in-pos pn) in-pos
9535 (js2-comp-loop-node-each-pos pn) each-pos
9536 (js2-comp-loop-node-foreach-p pn) foreach-p
9537 (js2-comp-loop-node-forof-p pn) forof-p
9538 (js2-comp-loop-node-lp pn) lp
9539 (js2-comp-loop-node-rp pn) rp)
9540 (js2-node-add-children pn iter obj)
9543 (defun js2-parse-object-literal ()
9544 (let ((pos (js2-current-token-beg))
9545 tt elems result after-comma
9548 (setq tt (js2-get-token))
9550 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9551 ;; {get foo() {...}}, {set foo(x) {...}}, or {foo(x) {...}}
9552 ;; TODO(sdh): support *foo() {...}
9553 ((or (js2-valid-prop-name-token tt)
9555 (setq after-comma nil
9556 result (js2-parse-named-prop tt))
9557 (if (and (null result)
9558 (not js2-recover-from-parse-errors))
9560 (push result elems)))
9561 ;; {[Symbol.iterator]: ...}
9563 (>= js2-language-version 200))
9564 (let ((expr (js2-parse-expr)))
9565 (js2-must-match js2-RB "msg.missing.computed.rb")
9566 (setq after-comma nil)
9567 (push (js2-parse-plain-property expr) elems)))
9568 ;; {12: x} or {10.7: x}
9570 (setq after-comma nil)
9571 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9577 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9578 pos elems after-comma)))
9580 (js2-report-error "msg.bad.prop")
9581 (unless js2-recover-from-parse-errors
9582 (setq continue nil)))) ; end switch
9583 (if (js2-match-token js2-COMMA)
9584 (setq after-comma (js2-current-token-end))
9585 (setq continue nil))) ; end loop
9586 (js2-must-match js2-RC "msg.no.brace.prop")
9587 (setq result (make-js2-object-node :pos pos
9588 :len (- js2-ts-cursor pos)
9589 :elems (nreverse elems)))
9590 (apply #'js2-node-add-children result (js2-object-node-elems result))
9593 (defun js2-parse-named-prop (tt)
9594 "Parse a name, string, or getter/setter object property.
9595 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9596 (let ((string-prop (and (= tt js2-STRING)
9597 (make-js2-string-node)))
9599 (ppos (js2-current-token-beg))
9600 (pend (js2-current-token-end))
9601 (name (js2-create-name-node))
9602 (prop (js2-current-token-string)))
9604 ;; getter/setter prop
9605 ((and (= tt js2-NAME)
9606 (= (js2-peek-token) js2-NAME)
9607 (or (string= prop "get")
9608 (string= prop "set")))
9610 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9611 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9612 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9613 (js2-parse-getter-setter-prop ppos name prop))
9614 ;; method definition: {f() {...}}
9615 ((and (= (js2-peek-token) js2-LP)
9616 (>= js2-language-version 200))
9617 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; name
9618 (js2-parse-getter-setter-prop ppos name ""))
9619 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9620 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9621 ;; when patterns are used in variable declarations, function parameters,
9622 ;; catch-clause, and iterators.
9623 ;; We have to set `js2-is-in-destructuring' to t when the current
9624 ;; expressions are on the left side of any assignment, but it's difficult
9625 ;; because it requires looking ahead of expression.
9626 ((and js2-is-in-destructuring
9628 (let ((ctk (js2-peek-token)))
9629 (or (= ctk js2-COMMA)
9631 (js2-valid-prop-name-token ctk))))
9636 (setq expr (js2-parse-plain-property (or string-prop name)))
9637 (js2-set-face ppos pend
9638 (if (js2-function-node-p
9639 (js2-object-prop-node-right expr))
9640 'font-lock-function-name-face
9641 'font-lock-variable-name-face)
9644 (defun js2-parse-plain-property (prop)
9645 "Parse a non-getter/setter property in an object literal.
9646 PROP is the node representing the property: a number, name or string."
9647 (let* ((tt (js2-get-token))
9648 (pos (js2-node-pos prop))
9651 ;; Abbreviated property, as in {foo, bar}
9652 ((and (>= js2-language-version 200)
9653 (or (= tt js2-COMMA)
9656 (setq result (make-js2-object-prop-node
9660 :op-pos (js2-current-token-len)))
9661 (js2-node-add-children result prop)
9662 (js2-node-set-prop result 'SHORTHAND t)
9666 (if (= tt js2-COLON)
9667 (setq colon (- (js2-current-token-beg) pos)
9668 expr (js2-parse-assign-expr))
9669 (js2-report-error "msg.no.colon.prop")
9670 (setq expr (make-js2-error-node)))
9671 (setq result (make-js2-object-prop-node
9673 ;; don't include last consumed token in length
9674 :len (- (+ (js2-node-pos expr)
9675 (js2-node-len expr))
9680 (js2-node-add-children result prop expr)
9683 (defun js2-parse-getter-setter-prop (pos prop type-string)
9684 "Parse getter or setter property in an object literal.
9685 JavaScript syntax is:
9687 { get foo() {...}, set foo(x) {...} }
9689 and expression closure style is also supported
9691 { get foo() x, set foo(x) _x = x }
9693 POS is the start position of the `get' or `set' keyword.
9694 PROP is the `js2-name-node' representing the property name.
9695 GET-P is non-nil if the keyword was `get'."
9697 ((string= "get" type-string) js2-GET)
9698 ((string= "set" type-string) js2-SET)
9701 (fn (js2-parse-function-expr)))
9702 ;; it has to be an anonymous function, as we already parsed the name
9703 (if (/= (js2-node-type fn) js2-FUNCTION)
9704 (js2-report-error "msg.bad.prop")
9705 (if (plusp (length (js2-function-name fn)))
9706 (js2-report-error "msg.bad.prop")))
9707 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9708 (setq end (js2-node-end fn)
9709 result (make-js2-getter-setter-node :type type
9714 (js2-node-add-children result prop fn)
9717 (defun js2-create-name-node (&optional check-activation-p token string)
9718 "Create a name node using the current token and, optionally, STRING.
9719 And, if CHECK-ACTIVATION-P is non-nil, use the value of TOKEN."
9720 (let* ((beg (js2-current-token-beg))
9721 (tt (js2-current-token-type))
9724 (js2-current-token-string)
9727 (setq name (make-js2-name-node :pos beg
9730 (if check-activation-p
9731 (js2-check-activation-name s (or token js2-NAME)))
9734 ;;; Indentation support
9736 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9737 ;; Karl cleverly deduces that the desired indentation level is often a
9738 ;; function of paren/bracket/brace nesting depth, which can be determined
9739 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9740 ;; then does some equally clever checks to see if we're in the context of a
9741 ;; substatement of a possibly braceless statement keyword such as if, while,
9742 ;; or finally. This approach yields pretty good results.
9744 ;; The indenter is often "wrong", however, and needs to be overridden.
9745 ;; The right long-term solution is probably to emulate (or integrate
9746 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9747 ;; parse tree from `js2-parse' is present, which is not true at the
9748 ;; moment the user is typing, computing indentation is still thousands
9749 ;; of lines of code to handle every possible syntactic edge case.
9751 ;; In the meantime, the compromise solution is that we offer a "bounce
9752 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9753 ;; current line indent among various likely guess points. This approach
9754 ;; is far from perfect, but should at least make it slightly easier to
9755 ;; move the line towards its desired indentation when manually
9756 ;; overriding Karl's heuristic nesting guesser.
9758 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9759 ;; extensions such as `let' and Array comprehensions. Major kudos to
9760 ;; Karl for coming up with the initial approach, which packs a lot of
9761 ;; punch for so little code.
9763 (defconst js2-possibly-braceless-keywords-re
9764 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9765 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9766 "try" "while" "with" "let")))
9767 "Regular expression matching keywords that are optionally
9768 followed by an opening brace.")
9770 (defconst js2-indent-operator-re
9771 (concat "[-+*/%<>&^|?:.]\\([^-+*/]\\|$\\)\\|!?=\\|"
9772 (regexp-opt '("in" "instanceof") 'words))
9773 "Regular expression matching operators that affect indentation
9774 of continued expressions.")
9776 (defconst js2-declaration-keyword-re
9777 (regexp-opt '("var" "let" "const") 'words)
9778 "Regular expression matching variable declaration keywords.")
9780 (defun js2-re-search-forward-inner (regexp &optional bound count)
9781 "Auxiliary function for `js2-re-search-forward'."
9782 (let (parse saved-point)
9784 (re-search-forward regexp bound)
9785 (setq parse (if saved-point
9786 (parse-partial-sexp saved-point (point))
9787 (syntax-ppss (point))))
9788 (cond ((nth 3 parse)
9790 (concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
9791 (save-excursion (end-of-line) (point)) t))
9795 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9796 (re-search-forward "\\*/"))
9798 (setq count (1- count))))
9799 (setq saved-point (point))))
9802 (defun js2-re-search-forward (regexp &optional bound noerror count)
9803 "Search forward but ignore strings and comments.
9804 Invokes `re-search-forward' but treats the buffer as if strings
9805 and comments have been removed."
9806 (let ((saved-point (point)))
9809 (js2-re-search-forward-inner regexp bound 1))
9811 (js2-re-search-backward-inner regexp bound (- count)))
9813 (js2-re-search-forward-inner regexp bound count)))
9815 (goto-char saved-point)
9817 (error (error-message-string err)))))))
9819 (defun js2-re-search-backward-inner (regexp &optional bound count)
9820 "Auxiliary function for `js2-re-search-backward'."
9823 (re-search-backward regexp bound)
9824 (setq parse (syntax-ppss (point)))
9825 (cond ((nth 3 parse)
9827 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9828 (line-beginning-position) t))
9830 (goto-char (nth 8 parse)))
9832 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9833 (re-search-backward "/\\*"))
9835 (setq count (1- count))))))
9838 (defun js2-re-search-backward (regexp &optional bound noerror count)
9839 "Search backward but ignore strings and comments.
9840 Invokes `re-search-backward' but treats the buffer as if strings
9841 and comments have been removed."
9842 (let ((saved-point (point)))
9845 (js2-re-search-backward-inner regexp bound 1))
9847 (js2-re-search-forward-inner regexp bound (- count)))
9849 (js2-re-search-backward-inner regexp bound count)))
9851 (goto-char saved-point)
9853 (error (error-message-string err)))))))
9855 (defun js2-looking-at-operator-p ()
9856 "Return non-nil if text after point is a non-comma operator."
9857 (and (looking-at js2-indent-operator-re)
9858 (or (not (looking-at ":"))
9860 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9861 (looking-at "?"))))))
9863 (defun js2-continued-expression-p ()
9864 "Return non-nil if the current line continues an expression."
9866 (back-to-indentation)
9867 (or (js2-looking-at-operator-p)
9869 (while (and (re-search-backward "\n" nil t)
9870 (let ((state (syntax-ppss)))
9872 (goto-char (nth 8 state))) ;; skip comments
9873 (skip-chars-backward " \t")
9876 (throw 'found t))))))
9878 (when (js2-looking-at-operator-p)
9880 (not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]")))))))
9882 (defun js2-end-of-do-while-loop-p ()
9883 "Return non-nil if word after point is `while' of a do-while
9884 statement, else returns nil. A braceless do-while statement
9885 spanning several lines requires that the start of the loop is
9886 indented to the same column as the current line."
9889 (when (looking-at "\\s-*\\<while\\>")
9891 (skip-chars-backward "[ \t\n]*}")
9892 (looking-at "[ \t\n]*}"))
9894 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9895 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9896 (or (looking-at "\\<do\\>")
9897 (let ((saved-indent (current-indentation)))
9898 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9899 (/= (current-indentation) saved-indent)))
9900 (and (looking-at "[ \t]*\\<do\\>")
9901 (not (js2-re-search-forward
9902 "\\<while\\>" (point-at-eol) t))
9903 (= (current-indentation) saved-indent))))))))
9905 (defun js2-multiline-decl-indentation ()
9906 "Return the declaration indentation column if the current line belongs
9907 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9908 (let (forward-sexp-function ; use Lisp version
9911 (back-to-indentation)
9912 (when (not (looking-at js2-declaration-keyword-re))
9913 (when (looking-at js2-indent-operator-re)
9914 (goto-char (match-end 0))) ; continued expressions are ok
9915 (while (and (not at-opening-bracket)
9917 (let ((pos (point)))
9920 (or (eq (char-before) ?,)
9921 (and (not (eq (char-before) ?\;))
9922 (prog2 (skip-syntax-backward ".")
9923 (looking-at js2-indent-operator-re)
9925 (not (eq (char-before) ?\;)))
9926 (js2-same-line pos)))))
9929 (scan-error (setq at-opening-bracket t))))
9930 (when (looking-at js2-declaration-keyword-re)
9931 (goto-char (match-end 0))
9932 (1+ (current-column)))))))
9934 (defun js2-ctrl-statement-indentation ()
9935 "Return the proper indentation of current line if it is a control statement.
9936 Returns an indentation if this line starts the body of a control
9937 statement without braces, else returns nil."
9938 (let (forward-sexp-function)
9940 (back-to-indentation)
9941 (when (and (not (js2-same-line (point-min)))
9942 (not (looking-at "{"))
9943 (js2-re-search-backward "[[:graph:]]" nil t)
9944 (not (looking-at "[{([]"))
9947 (when (= (char-before) ?\))
9948 ;; scan-sexps sometimes throws an error
9949 (ignore-errors (backward-sexp))
9950 (skip-chars-backward " \t" (point-at-bol)))
9952 (back-to-indentation)
9953 (when (looking-at "}[ \t]*")
9954 (goto-char (match-end 0)))
9955 (and (looking-at js2-possibly-braceless-keywords-re)
9956 (= (match-end 0) pt)
9957 (not (js2-end-of-do-while-loop-p))))))
9958 (+ (current-indentation) js2-basic-offset)))))
9960 (defun js2-indent-in-array-comp (parse-status)
9961 "Return non-nil if we think we're in an array comprehension.
9962 In particular, return the buffer position of the first `for' kwd."
9963 (let ((bracket (nth 1 parse-status))
9968 (when (looking-at "\\[")
9971 (if (looking-at "[[{]")
9972 (let (forward-sexp-function) ; use Lisp version
9973 (forward-sexp) ; skip destructuring form
9975 (if (and (/= (char-after) ?,) ; regular array
9977 (match-beginning 0)))
9978 ;; to skip arbitrary expressions we need the parser,
9979 ;; so we'll just guess at it.
9980 (if (and (> end (point)) ; not empty literal
9981 (re-search-forward "[^,]]* \\(for\\) " end t)
9982 ;; not inside comment or string literal
9983 (let ((state (parse-partial-sexp bracket (point))))
9984 (not (or (nth 3 state) (nth 4 state)))))
9985 (match-beginning 1))))))))
9987 (defun js2-array-comp-indentation (parse-status for-kwd)
9988 (if (js2-same-line for-kwd)
9989 ;; first continuation line
9991 (goto-char (nth 1 parse-status))
9993 (skip-chars-forward " \t")
9999 (defun js2-proper-indentation (parse-status)
10000 "Return the proper indentation for the current line."
10002 (back-to-indentation)
10003 (let* ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10004 (at-closing-bracket (looking-at "[]})]"))
10005 (same-indent-p (or at-closing-bracket
10006 (looking-at "\\<case\\>[^:]")
10007 (and (looking-at "\\<default:")
10010 (not (memq (char-before) '(?, ?{)))))))
10011 (continued-expr-p (js2-continued-expression-p))
10012 (declaration-indent (and js2-pretty-multiline-declarations
10013 (js2-multiline-decl-indentation)))
10014 (bracket (nth 1 parse-status))
10017 ;; indent array comprehension continuation lines specially
10019 (>= js2-language-version 170)
10020 (not (js2-same-line bracket))
10021 (setq beg (js2-indent-in-array-comp parse-status))
10022 (>= (point) (save-excursion
10024 (point-at-bol)))) ; at or after first loop?
10025 (js2-array-comp-indentation parse-status beg))
10029 ((and declaration-indent continued-expr-p)
10030 (+ declaration-indent js2-basic-offset))
10032 (declaration-indent)
10035 (goto-char bracket)
10037 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10038 (when (save-excursion (skip-chars-backward " \t)")
10041 (back-to-indentation)
10042 (and (eq js2-pretty-multiline-declarations 'all)
10043 (looking-at js2-declaration-keyword-re)
10044 (goto-char (1+ (match-end 0))))
10046 (cond (same-indent-p
10049 (+ (current-column) (* 2 js2-basic-offset)))
10051 (+ (current-column) js2-basic-offset))))
10052 (if (and js2-indent-switch-body
10053 (not at-closing-bracket)
10054 (looking-at "\\_<switch\\_>"))
10055 (+ indent js2-basic-offset)
10058 (unless same-indent-p
10060 (skip-chars-forward " \t"))
10061 (current-column))))
10063 (continued-expr-p js2-basic-offset)
10067 (defun js2-lineup-comment (parse-status)
10068 "Indent a multi-line block comment continuation line."
10069 (let* ((beg (nth 8 parse-status))
10070 (first-line (js2-same-line beg))
10071 (offset (save-excursion
10073 (if (looking-at "/\\*")
10074 (+ 1 (current-column))
10077 (indent-line-to offset))))
10079 (defun js2-backward-sws ()
10080 "Move backward through whitespace and comments."
10082 (while (forward-comment -1)))
10084 (defun js2-forward-sws ()
10085 "Move forward through whitespace and comments."
10087 (while (forward-comment 1)))
10089 (defun js2-current-indent (&optional pos)
10090 "Return column of indentation on current line.
10091 If POS is non-nil, go to that point and return indentation for that line."
10095 (back-to-indentation)
10098 (defun js2-arglist-close ()
10099 "Return non-nil if we're on a line beginning with a close-paren/brace."
10101 (goto-char (point-at-bol))
10103 (looking-at "[])}]")))
10105 (defun js2-indent-looks-like-label-p ()
10106 (goto-char (point-at-bol))
10108 (looking-at (concat js2-mode-identifier-re ":")))
10110 (defun js2-indent-in-objlit-p (parse-status)
10111 "Return non-nil if this looks like an object-literal entry."
10112 (let ((start (nth 1 parse-status)))
10116 (and (zerop (forward-line -1))
10117 (not (< (point) start)) ; crossed a {} boundary
10118 (js2-indent-looks-like-label-p)))
10120 (js2-indent-looks-like-label-p)))))
10122 ;; If prev line looks like foobar({ then we're passing an object
10123 ;; literal to a function call, and people pretty much always want to
10124 ;; de-dent back to the previous line, so move the 'basic-offset'
10125 ;; position to the front.
10126 (defun js2-indent-objlit-arg-p (parse-status)
10128 (back-to-indentation)
10130 (and (eq (1- (point)) (nth 1 parse-status))
10131 (eq (char-before) ?{)
10134 (skip-chars-backward " \t")
10135 (eq (char-before) ?\()))))
10137 (defun js2-indent-case-block-p ()
10139 (back-to-indentation)
10141 (goto-char (point-at-bol))
10142 (skip-chars-forward " \t")
10143 (looking-at "case\\s-.+:")))
10145 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
10146 "Cycle among alternate computed indentation positions.
10147 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10148 of the buffer to the current point. NORMAL-COL is the indentation
10149 column computed by the heuristic guesser based on current paren,
10150 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10152 (let ((cur-indent (js2-current-indent))
10153 (old-buffer-undo-list buffer-undo-list)
10154 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10155 (current-line (save-excursion
10156 (forward-line 0) ; move to bol
10157 (1+ (count-lines (point-min) (point)))))
10158 positions pos main-pos anchor arglist-cont same-indent
10159 basic-offset computed-pos)
10160 ;; temporarily don't record undo info, if user requested this
10161 (when js2-mode-indent-inhibit-undo
10162 (setq buffer-undo-list t))
10165 ;; First likely point: indent from beginning of previous code line
10166 (push (setq basic-offset
10168 (back-to-indentation)
10170 (back-to-indentation)
10175 ;; (First + epsilon) likely point: indent 2x from beginning of
10176 ;; previous code line. Google does it this way.
10177 (push (setq basic-offset
10179 (back-to-indentation)
10181 (back-to-indentation)
10183 (* 2 js2-basic-offset)))
10186 ;; Second likely point: indent from assign-expr RHS. This
10187 ;; is just a crude guess based on finding " = " on the previous
10188 ;; line containing actual code.
10189 (setq pos (save-excursion
10191 (goto-char (point-at-bol))
10192 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10194 (goto-char (match-end 1))
10195 (skip-chars-forward " \t\r\n")
10196 (current-column))))
10198 (incf pos js2-basic-offset)
10199 (push pos positions))
10201 ;; Third likely point: same indent as previous line of code.
10202 ;; Make it the first likely point if we're not on an
10203 ;; arglist-close line and previous line ends in a comma, or
10204 ;; both this line and prev line look like object-literal
10206 (setq pos (save-excursion
10207 (goto-char (point-at-bol))
10209 (back-to-indentation)
10212 ;; while we're here, look for trailing comma
10213 (if (save-excursion
10214 (goto-char (point-at-eol))
10216 (eq (char-before) ?,))
10217 (setq arglist-cont (1- (point)))))))
10219 (if (and (or arglist-cont
10220 (js2-indent-in-objlit-p parse-status))
10221 (not (js2-arglist-close)))
10222 (setq same-indent pos))
10223 (push pos positions))
10225 ;; Fourth likely point: first preceding code with less indentation.
10226 ;; than the immediately preceding code line.
10227 (setq pos (save-excursion
10228 (back-to-indentation)
10230 (back-to-indentation)
10231 (setq anchor (current-column))
10232 (while (and (zerop (forward-line -1))
10234 (back-to-indentation)
10237 (setq pos (current-column))))
10238 (push pos positions)
10240 ;; nesting-heuristic position, main by default
10241 (push (setq main-pos normal-col) positions)
10243 ;; delete duplicates and sort positions list
10244 (setq positions (sort (delete-dups positions) '<))
10246 ;; comma-list continuation lines: prev line indent takes precedence
10248 (setq main-pos same-indent))
10250 ;; common special cases where we want to indent in from previous line
10251 (if (or (js2-indent-case-block-p)
10252 (js2-indent-objlit-arg-p parse-status))
10253 (setq main-pos basic-offset))
10255 ;; if bouncing backwards, reverse positions list
10257 (setq positions (reverse positions)))
10259 ;; record whether we're already sitting on one of the alternatives
10260 (setq pos (member cur-indent positions))
10263 ;; case 0: we're one one of the alternatives and this is the
10264 ;; first time they've pressed TAB on this line (best-guess).
10265 ((and js2-mode-indent-ignore-first-tab
10267 ;; first time pressing TAB on this line?
10268 (not (eq js2-mode-last-indented-line current-line)))
10270 (setq computed-pos nil))
10271 ;; case 1: only one computed position => use it
10272 ((null (cdr positions))
10273 (setq computed-pos 0))
10274 ;; case 2: not on any of the computed spots => use main spot
10276 (setq computed-pos (js2-position main-pos positions)))
10277 ;; case 3: on last position: cycle to first position
10279 (setq computed-pos 0))
10280 ;; case 4: on intermediate position: cycle to next position
10282 (setq computed-pos (js2-position (second pos) positions))))
10284 ;; see if any hooks want to indent; otherwise we do it
10285 (loop with result = nil
10286 for hook in js2-indent-hook
10287 while (null result)
10289 (setq result (funcall hook positions computed-pos))
10291 (unless (or result (null computed-pos))
10292 (indent-line-to (nth computed-pos positions)))))
10295 (if js2-mode-indent-inhibit-undo
10296 (setq buffer-undo-list old-buffer-undo-list))
10297 ;; see commentary for `js2-mode-last-indented-line'
10298 (setq js2-mode-last-indented-line current-line))))
10300 (defun js2-indent-bounce-backwards ()
10301 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10302 cycles between the computed indentation positions in reverse order."
10304 (js2-indent-line t))
10306 (defun js2-1-line-comment-continuation-p ()
10307 "Return t if we're in a 1-line comment continuation.
10308 If so, we don't ever want to use bounce-indent."
10312 (looking-at "\\s-*//"))
10316 (when (looking-at "\\s-*$")
10319 (looking-at "\\s-*//")))))
10321 (defun js2-indent-line (&optional bounce-backwards)
10322 "Indent the current line as JavaScript source text."
10324 (let (parse-status offset indent-col
10325 ;; Don't whine about errors/warnings when we're indenting.
10326 ;; This has to be set before calling parse-partial-sexp below.
10327 (inhibit-point-motion-hooks t))
10328 (setq parse-status (save-excursion
10329 (syntax-ppss (point-at-bol)))
10330 offset (- (point) (save-excursion
10331 (back-to-indentation)
10333 (js2-with-underscore-as-word-syntax
10334 (if (nth 4 parse-status)
10335 (js2-lineup-comment parse-status)
10336 (setq indent-col (js2-proper-indentation parse-status))
10337 ;; See comments below about `js2-mode-last-indented-line'.
10339 ;; bounce-indenting is disabled during electric-key indent.
10340 ;; It doesn't work well on first line of buffer.
10341 ((and js2-bounce-indent-p
10342 (not (js2-same-line (point-min)))
10343 (not (js2-1-line-comment-continuation-p)))
10344 (js2-bounce-indent indent-col parse-status bounce-backwards))
10345 ;; just indent to the guesser's likely spot
10346 (t (indent-line-to indent-col))))
10347 (when (plusp offset)
10348 (forward-char offset)))))
10350 (defun js2-indent-region (start end)
10351 "Indent the region, but don't use bounce indenting."
10352 (let ((js2-bounce-indent-p nil)
10353 (indent-region-function nil)
10354 (after-change-functions (remq 'js2-mode-edit
10355 after-change-functions)))
10356 (indent-region start end nil) ; nil for byte-compiler
10357 (js2-mode-edit start end (- end start))))
10359 (defvar js2-minor-mode-map
10360 (let ((map (make-sparse-keymap)))
10361 (define-key map (kbd "C-c C-`") #'js2-next-error)
10362 (define-key map [mouse-1] #'js2-mode-show-node)
10364 "Keymap used when `js2-minor-mode' is active.")
10367 (define-minor-mode js2-minor-mode
10368 "Minor mode for running js2 as a background linter.
10369 This allows you to use a different major mode for JavaScript editing,
10370 such as `js-mode', while retaining the asynchronous error/warning
10371 highlighting features of `js2-mode'."
10373 :lighter " js-lint"
10375 (js2-minor-mode-enter)
10376 (js2-minor-mode-exit)))
10378 (defun js2-minor-mode-enter ()
10379 "Initialization for `js2-minor-mode'."
10380 (set (make-local-variable 'max-lisp-eval-depth)
10381 (max max-lisp-eval-depth 3000))
10382 (setq next-error-function #'js2-next-error)
10383 (js2-set-default-externs)
10384 ;; Experiment: make reparse-delay longer for longer files.
10385 (if (plusp js2-dynamic-idle-timer-adjust)
10386 (setq js2-idle-timer-delay
10387 (* js2-idle-timer-delay
10388 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10389 (setq js2-mode-buffer-dirty-p t
10390 js2-mode-parsing nil)
10391 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10392 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10393 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10394 (when js2-include-jslint-globals
10395 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10396 (run-hooks 'js2-init-hook)
10399 (defun js2-minor-mode-exit ()
10400 "Turn off `js2-minor-mode'."
10401 (setq next-error-function nil)
10402 (remove-hook 'after-change-functions #'js2-mode-edit t)
10403 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10404 (when js2-mode-node-overlay
10405 (delete-overlay js2-mode-node-overlay)
10406 (setq js2-mode-node-overlay nil))
10407 (js2-remove-overlays)
10408 (remove-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals t)
10409 (setq js2-mode-ast nil))
10411 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10412 (make-variable-buffer-local 'js2-source-buffer)
10414 (defun* js2-display-error-list ()
10415 "Display a navigable buffer listing parse errors/warnings."
10417 (unless (js2-have-errors-p)
10418 (message "No errors")
10419 (return-from js2-display-error-list))
10420 (labels ((annotate-list
10422 "Add diagnostic TYPE and line number to errs list"
10423 (mapcar (lambda (err)
10424 (list err type (line-number-at-pos (nth 1 err))))
10426 (let* ((srcbuf (current-buffer))
10427 (errbuf (get-buffer-create "*js-lint*"))
10428 (errors (annotate-list
10429 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10430 'js2-error)) ; must be a valid face name
10431 (warnings (annotate-list
10432 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10433 'js2-warning)) ; must be a valid face name
10434 (all-errs (sort (append errors warnings)
10435 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10436 (with-current-buffer errbuf
10437 (let ((inhibit-read-only t))
10439 (dolist (err all-errs)
10440 (destructuring-bind ((msg-key beg _end &rest) type line) err
10441 (insert-text-button
10442 (format "line %d: %s" line (js2-get-msg msg-key))
10444 'follow-link "\C-m"
10445 'action 'js2-error-buffer-jump
10446 'js2-msg (js2-get-msg msg-key)
10449 (js2-error-buffer-mode)
10450 (setq js2-source-buffer srcbuf)
10451 (pop-to-buffer errbuf)
10452 (goto-char (point-min))
10454 (js2-error-buffer-view))))))
10456 (defvar js2-error-buffer-mode-map
10457 (let ((map (make-sparse-keymap)))
10458 (define-key map "n" #'js2-error-buffer-next)
10459 (define-key map "p" #'js2-error-buffer-prev)
10460 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10461 (define-key map "o" #'js2-error-buffer-view)
10462 (define-key map "q" #'js2-error-buffer-quit)
10464 "Keymap used for js2 diagnostics buffers.")
10466 (defun js2-error-buffer-mode ()
10467 "Major mode for js2 diagnostics buffers.
10468 Selecting an error will jump it to the corresponding source-buffer error.
10469 \\{js2-error-buffer-mode-map}"
10471 (setq major-mode 'js2-error-buffer-mode
10472 mode-name "JS Lint Diagnostics")
10473 (use-local-map js2-error-buffer-mode-map)
10474 (setq truncate-lines t)
10475 (set-buffer-modified-p nil)
10476 (setq buffer-read-only t)
10477 (run-hooks 'js2-error-buffer-mode-hook))
10479 (defun js2-error-buffer-next ()
10480 "Move to next error and view it."
10482 (when (zerop (forward-line 1))
10483 (js2-error-buffer-view)))
10485 (defun js2-error-buffer-prev ()
10486 "Move to previous error and view it."
10488 (when (zerop (forward-line -1))
10489 (js2-error-buffer-view)))
10491 (defun js2-error-buffer-quit ()
10492 "Kill the current buffer."
10496 (defun js2-error-buffer-jump (&rest ignored)
10497 "Jump cursor to current error in source buffer."
10499 (when (js2-error-buffer-view)
10500 (pop-to-buffer js2-source-buffer)))
10502 (defun js2-error-buffer-view ()
10503 "Scroll source buffer to show error at current line."
10506 ((not (eq major-mode 'js2-error-buffer-mode))
10507 (message "Not in a js2 errors buffer"))
10508 ((not (buffer-live-p js2-source-buffer))
10509 (message "Source buffer has been killed"))
10510 ((not (wholenump (get-text-property (point) 'js2-pos)))
10511 (message "There does not seem to be an error here"))
10513 (let ((pos (get-text-property (point) 'js2-pos))
10514 (msg (get-text-property (point) 'js2-msg)))
10515 (save-selected-window
10516 (pop-to-buffer js2-source-buffer)
10521 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10522 ;; FIXME: Should derive from js-mode.
10523 "Major mode for editing JavaScript code."
10524 ;; Used by comment-region; don't change it.
10525 (set (make-local-variable 'comment-start) "//")
10526 (set (make-local-variable 'comment-end) "")
10527 (set (make-local-variable 'comment-start-skip) js2-comment-start-skip)
10528 (set (make-local-variable 'max-lisp-eval-depth)
10529 (max max-lisp-eval-depth 3000))
10530 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10531 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10532 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10533 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10534 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10535 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10536 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10537 ;; for characters inside regexp literals.
10538 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10539 ;; this is necessary to make `show-paren-function' work properly
10540 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10541 ;; needed for M-x rgrep, among other things
10542 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10544 (set (make-local-variable 'electric-indent-chars)
10545 (append "{}()[]:;,*." electric-indent-chars))
10546 (set (make-local-variable 'electric-layout-rules)
10547 '((?\; . after) (?\{ . after) (?\} . before)))
10549 ;; some variables needed by cc-engine for paragraph-fill, etc.
10550 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10551 c-comment-start-regexp "/[*/]\\|\\s|"
10552 c-line-comment-starter "//"
10553 c-paragraph-start js2-paragraph-start
10554 c-paragraph-separate "$"
10555 c-syntactic-ws-start js2-syntactic-ws-start
10556 c-syntactic-ws-end js2-syntactic-ws-end
10557 c-syntactic-eol js2-syntactic-eol)
10559 (let ((c-buffer-is-cc-mode t))
10560 ;; Copied from `js-mode'. Also see Bug#6071.
10561 (make-local-variable 'paragraph-start)
10562 (make-local-variable 'paragraph-separate)
10563 (make-local-variable 'paragraph-ignore-fill-prefix)
10564 (make-local-variable 'adaptive-fill-mode)
10565 (make-local-variable 'adaptive-fill-regexp)
10566 (c-setup-paragraph-variables))
10568 (setq font-lock-defaults '(nil t))
10570 ;; Experiment: make reparse-delay longer for longer files.
10571 (when (plusp js2-dynamic-idle-timer-adjust)
10572 (setq js2-idle-timer-delay
10573 (* js2-idle-timer-delay
10574 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10576 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10577 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10578 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10579 (setq next-error-function #'js2-next-error)
10580 (imenu-add-to-menubar (concat "IM-" mode-name))
10581 (add-to-invisibility-spec '(js2-outline . t))
10582 (set (make-local-variable 'line-move-ignore-invisible) t)
10583 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10585 (setq js2-mode-functions-hidden nil
10586 js2-mode-comments-hidden nil
10587 js2-mode-buffer-dirty-p t
10588 js2-mode-parsing nil)
10590 (js2-set-default-externs)
10592 (when js2-include-jslint-globals
10593 (add-hook 'js2-post-parse-callbacks 'js2-apply-jslint-globals nil t))
10595 (run-hooks 'js2-init-hook)
10599 (defun js2-mode-exit ()
10600 "Exit `js2-mode' and clean up."
10602 (when js2-mode-node-overlay
10603 (delete-overlay js2-mode-node-overlay)
10604 (setq js2-mode-node-overlay nil))
10605 (js2-remove-overlays)
10606 (setq js2-mode-ast nil)
10607 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10608 (remove-from-invisibility-spec '(js2-outline . t))
10609 (js2-mode-show-all)
10610 (with-silent-modifications
10611 (js2-clear-face (point-min) (point-max))))
10613 (defun js2-mode-reset-timer ()
10614 "Cancel any existing parse timer and schedule a new one."
10615 (if js2-mode-parse-timer
10616 (cancel-timer js2-mode-parse-timer))
10617 (setq js2-mode-parsing nil)
10618 (let ((timer (timer-create)))
10619 (setq js2-mode-parse-timer timer)
10620 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10621 (timer-set-idle-time timer js2-idle-timer-delay)
10622 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10623 (timer-activate-when-idle timer nil)))
10625 (defun js2-mode-idle-reparse (buffer)
10626 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10627 it to be reparsed when the buffer is selected."
10628 (cond ((eq buffer (current-buffer))
10630 ((buffer-live-p buffer)
10631 ;; reparse when the buffer is selected again
10632 (with-current-buffer buffer
10633 (add-hook 'window-configuration-change-hook
10634 #'js2-mode-idle-reparse-inner
10637 (defun js2-mode-idle-reparse-inner ()
10638 (remove-hook 'window-configuration-change-hook
10639 #'js2-mode-idle-reparse-inner
10643 (defun js2-mode-edit (_beg _end _len)
10644 "Schedule a new parse after buffer is edited.
10645 Buffer edit spans from BEG to END and is of length LEN."
10646 (setq js2-mode-buffer-dirty-p t)
10647 (js2-mode-hide-overlay)
10648 (js2-mode-reset-timer))
10650 (defun js2-minor-mode-edit (_beg _end _len)
10651 "Callback for buffer edits in `js2-mode'.
10652 Schedules a new parse after buffer is edited.
10653 Buffer edit spans from BEG to END and is of length LEN."
10654 (setq js2-mode-buffer-dirty-p t)
10655 (js2-mode-hide-overlay)
10656 (js2-mode-reset-timer))
10658 (defun js2-reparse (&optional force)
10659 "Re-parse current buffer after user finishes some data entry.
10660 If we get any user input while parsing, including cursor motion,
10661 we discard the parse and reschedule it. If FORCE is nil, then the
10662 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10665 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10666 (unless js2-mode-parsing
10667 (setq js2-mode-parsing t)
10669 (when (or js2-mode-buffer-dirty-p force)
10670 (js2-remove-overlays)
10671 (with-silent-modifications
10672 (setq js2-mode-buffer-dirty-p nil
10673 js2-mode-fontifications nil
10674 js2-mode-deferred-properties nil)
10675 (if js2-mode-verbose-parse-p
10676 (message "parsing..."))
10679 (setq interrupted-p
10680 (catch 'interrupted
10682 ;; if parsing is interrupted, comments and regex
10683 ;; literals stay ignored by `parse-partial-sexp'
10684 (remove-text-properties (point-min) (point-max)
10686 (js2-mode-apply-deferred-properties)
10687 (js2-mode-remove-suppressed-warnings)
10688 (js2-mode-show-warnings)
10689 (js2-mode-show-errors)
10690 (if (>= js2-highlight-level 1)
10691 (js2-highlight-jsdoc js2-mode-ast))
10695 ;; unfinished parse => try again
10696 (setq js2-mode-buffer-dirty-p t)
10697 (js2-mode-reset-timer))
10698 (if js2-mode-verbose-parse-p
10699 (message "Parse time: %s" time)))))
10700 (setq js2-mode-parsing nil)
10701 (unless interrupted-p
10702 (setq js2-mode-parse-timer nil))))))
10704 (defun js2-mode-show-node (event)
10705 "Debugging aid: highlight selected AST node on mouse click."
10707 (mouse-set-point event)
10708 (setq deactivate-mark t)
10709 (when js2-mode-show-overlay
10710 (let ((node (js2-node-at-point))
10713 (message "No node found at location %s" (point))
10714 (setq beg (js2-node-abs-pos node)
10715 end (+ beg (js2-node-len node)))
10716 (if js2-mode-node-overlay
10717 (move-overlay js2-mode-node-overlay beg end)
10718 (setq js2-mode-node-overlay (make-overlay beg end))
10719 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10720 (with-silent-modifications
10721 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10722 (message "%s, parent: %s"
10723 (js2-node-short-name node)
10724 (if (js2-node-parent node)
10725 (js2-node-short-name (js2-node-parent node))
10728 (defun js2-mode-hide-overlay (&optional _p1 p2)
10729 "Remove the debugging overlay when the point moves.
10730 P1 and P2 are the old and new values of point, respectively."
10731 (when js2-mode-node-overlay
10732 (let ((beg (overlay-start js2-mode-node-overlay))
10733 (end (overlay-end js2-mode-node-overlay)))
10734 ;; Sometimes we're called spuriously.
10738 (with-silent-modifications
10739 (remove-text-properties beg end '(point-left nil)))
10740 (delete-overlay js2-mode-node-overlay)
10741 (setq js2-mode-node-overlay nil)))))
10743 (defun js2-mode-reset ()
10744 "Debugging helper: reset everything."
10749 (defun js2-mode-show-warn-or-err (e face)
10750 "Highlight a warning or error E with FACE.
10751 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10752 The last element is optional. When present, use instead of FACE."
10753 (let* ((key (first e))
10755 (end (+ beg (third e)))
10756 ;; Don't inadvertently go out of bounds.
10757 (beg (max (point-min) (min beg (point-max))))
10758 (end (max (point-min) (min end (point-max))))
10759 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10760 (ovl (make-overlay beg end)))
10761 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10762 (overlay-put ovl 'js2-error t)
10763 (put-text-property beg end 'help-echo (js2-get-msg key))
10764 (put-text-property beg end 'point-entered #'js2-echo-error)))
10766 (defun js2-remove-overlays ()
10767 "Remove overlays from buffer that have a `js2-error' property."
10768 (let ((beg (point-min))
10771 (dolist (o (overlays-in beg end))
10772 (when (overlay-get o 'js2-error)
10773 (delete-overlay o))))))
10775 (defun js2-error-at-point (&optional pos)
10776 "Return non-nil if there's an error overlay at POS.
10777 Defaults to point."
10778 (loop with pos = (or pos (point))
10779 for o in (overlays-at pos)
10780 thereis (overlay-get o 'js2-error)))
10782 (defun js2-mode-apply-deferred-properties ()
10783 "Apply fontifications and other text properties recorded during parsing."
10784 (when (plusp js2-highlight-level)
10785 ;; We defer clearing faces as long as possible to eliminate flashing.
10786 (js2-clear-face (point-min) (point-max))
10787 ;; Have to reverse the recorded fontifications list so that errors
10788 ;; and warnings overwrite the normal fontifications.
10789 (dolist (f (nreverse js2-mode-fontifications))
10790 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10791 (setq js2-mode-fontifications nil))
10792 (dolist (p js2-mode-deferred-properties)
10793 (apply #'put-text-property p))
10794 (setq js2-mode-deferred-properties nil))
10796 (defun js2-mode-show-errors ()
10797 "Highlight syntax errors."
10798 (when js2-mode-show-parse-errors
10799 (dolist (e (js2-ast-root-errors js2-mode-ast))
10800 (js2-mode-show-warn-or-err e 'js2-error))))
10802 (defun js2-mode-remove-suppressed-warnings ()
10803 "Take suppressed warnings out of the AST warnings list.
10804 This ensures that the counts and `next-error' are correct."
10805 (setf (js2-ast-root-warnings js2-mode-ast)
10808 (let ((key (caar e)))
10810 (and (not js2-strict-trailing-comma-warning)
10811 (string-match "trailing\\.comma" key))
10812 (and (not js2-strict-cond-assign-warning)
10813 (string= key "msg.equal.as.assign"))
10814 (and js2-missing-semi-one-line-override
10815 (string= key "msg.missing.semi")
10816 (let* ((beg (second e))
10817 (node (js2-node-at-point beg))
10818 (fn (js2-mode-find-parent-fn node))
10819 (body (and fn (js2-function-node-body fn)))
10820 (lc (and body (js2-node-abs-pos body)))
10821 (rc (and lc (+ lc (js2-node-len body)))))
10826 (and (js2-same-line lc)
10827 (js2-same-line rc))))))))))
10828 (js2-ast-root-warnings js2-mode-ast))))
10830 (defun js2-mode-show-warnings ()
10831 "Highlight strict-mode warnings."
10832 (when js2-mode-show-strict-warnings
10833 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10834 (js2-mode-show-warn-or-err e 'js2-warning))))
10836 (defun js2-echo-error (_old-point new-point)
10837 "Called by point-motion hooks."
10838 (let ((msg (get-text-property new-point 'help-echo)))
10839 (when (and (stringp msg)
10840 (not (active-minibuffer-window))
10841 (not (current-message)))
10844 (defalias 'js2-echo-help #'js2-echo-error)
10846 (defun js2-line-break (&optional _soft)
10847 "Break line at point and indent, continuing comment if within one.
10848 If inside a string, and `js2-concat-multiline-strings' is not
10849 nil, turn it into concatenation."
10851 (let ((parse-status (syntax-ppss)))
10853 ;; Check if we're inside a string.
10854 ((nth 3 parse-status)
10855 (if js2-concat-multiline-strings
10856 (js2-mode-split-string parse-status)
10858 ;; Check if inside a block comment.
10859 ((nth 4 parse-status)
10860 (js2-mode-extend-comment (nth 8 parse-status)))
10862 (newline-and-indent)))))
10864 (defun js2-mode-split-string (parse-status)
10865 "Turn a newline in mid-string into a string concatenation.
10866 PARSE-STATUS is as documented in `parse-partial-sexp'."
10867 (let* ((quote-char (nth 3 parse-status))
10868 (at-eol (eq js2-concat-multiline-strings 'eol)))
10869 (insert quote-char)
10870 (insert (if at-eol " +\n" "\n"))
10874 (insert quote-char)
10876 (insert quote-char)
10877 (backward-char 1))))
10879 (defun js2-mode-extend-comment (start-pos)
10880 "Indent the line and, when inside a comment block, add comment prefix."
10881 (let (star single col first-line needs-close)
10883 (back-to-indentation)
10884 (when (< (point) start-pos)
10885 (goto-char start-pos))
10887 ((looking-at "\\*[^/]")
10889 col (current-column)))
10890 ((looking-at "/\\*")
10893 col (1+ (current-column))))
10896 col (current-column)))))
10897 ;; Heuristic for whether we need to close the comment:
10898 ;; if we've got a parse error here, assume it's an unterminated
10902 (eq (get-text-property (1- (point)) 'point-entered)
10904 ;; The heuristic above doesn't work well when we're
10905 ;; creating a comment and there's another one downstream,
10906 ;; as our parser thinks this one ends at the end of the
10907 ;; next one. (You can have a /* inside a js block comment.)
10908 ;; So just close it if the next non-ws char isn't a *.
10912 (skip-chars-forward " \t\r\n")
10913 (not (eq (char-after) ?*))))))
10914 (delete-horizontal-space)
10920 (if (and first-line needs-close)
10927 (and (zerop (forward-line 1))
10928 (looking-at "\\s-*//"))))
10931 ;; Don't need to extend the comment after all.
10932 (js2-indent-line)))
10934 (defun js2-beginning-of-line ()
10935 "Toggle point between bol and first non-whitespace char in line.
10936 Also moves past comment delimiters when inside comments."
10941 (back-to-indentation))
10943 (skip-chars-forward "/ \t"))
10944 ((and (eq (char-after) ?*)
10945 (setq node (js2-comment-at-point))
10946 (memq (js2-comment-node-format node) '(jsdoc block))
10948 (skip-chars-backward " \t")
10950 (skip-chars-forward "\* \t"))
10952 (goto-char (point-at-bol))))))
10954 (defun js2-end-of-line ()
10955 "Toggle point between eol and last non-whitespace char in line."
10958 (skip-chars-backward " \t")
10959 (goto-char (point-at-eol))))
10961 (defun js2-mode-wait-for-parse (callback)
10962 "Invoke CALLBACK when parsing is finished.
10963 If parsing is already finished, calls CALLBACK immediately."
10964 (if (not js2-mode-buffer-dirty-p)
10966 (push callback js2-mode-pending-parse-callbacks)
10967 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10969 (defun js2-mode-parse-finished ()
10970 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10971 ;; We can't let errors propagate up, since it prevents the
10972 ;; `js2-parse' method from completing normally and returning
10973 ;; the ast, which makes things mysteriously not work right.
10975 (dolist (cb js2-mode-pending-parse-callbacks)
10976 (condition-case err
10978 (error (message "%s" err))))
10979 (setq js2-mode-pending-parse-callbacks nil)))
10981 (defun js2-mode-flag-region (from to flag)
10982 "Hide or show text from FROM to TO, according to FLAG.
10983 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10984 Returns the created overlay if FLAG is non-nil."
10985 (remove-overlays from to 'invisible 'js2-outline)
10987 (let ((o (make-overlay from to)))
10988 (overlay-put o 'invisible 'js2-outline)
10989 (overlay-put o 'isearch-open-invisible
10990 'js2-isearch-open-invisible)
10993 ;; Function to be set as an outline-isearch-open-invisible' property
10994 ;; to the overlay that makes the outline invisible (see
10995 ;; `js2-mode-flag-region').
10996 (defun js2-isearch-open-invisible (_overlay)
10997 ;; We rely on the fact that isearch places point on the matched text.
10998 (js2-mode-show-element))
11000 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11001 "Return cons cell of bounds of folding overlay at POS.
11002 Returns nil if not found."
11003 (let ((overlays (overlays-at (or pos (point))))
11005 (while (and overlays
11007 (if (overlay-get (car overlays) 'invisible)
11008 (setq o (car overlays))
11009 (setq overlays (cdr overlays))))
11011 (cons (overlay-start o) (overlay-end o)))))
11013 (defun js2-mode-function-at-point (&optional pos)
11014 "Return the innermost function node enclosing current point.
11015 Returns nil if point is not in a function."
11016 (let ((node (js2-node-at-point pos)))
11017 (while (and node (not (js2-function-node-p node)))
11018 (setq node (js2-node-parent node)))
11019 (if (js2-function-node-p node)
11022 (defun js2-mode-toggle-element ()
11023 "Hide or show the foldable element at the point."
11025 (let (comment fn pos)
11028 ;; /* ... */ comment?
11029 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11030 (if (js2-mode-invisible-overlay-bounds
11031 (setq pos (+ 3 (js2-node-abs-pos comment))))
11034 (js2-mode-show-element))
11035 (js2-mode-hide-element)))
11038 (back-to-indentation)
11039 (looking-at js2-mode-//-comment-re))
11040 (js2-mode-toggle-//-comment))
11042 ((setq fn (js2-mode-function-at-point))
11043 (setq pos (and (js2-function-node-body fn)
11044 (js2-node-abs-pos (js2-function-node-body fn))))
11045 (goto-char (1+ pos))
11046 (if (js2-mode-invisible-overlay-bounds)
11047 (js2-mode-show-element)
11048 (js2-mode-hide-element)))
11050 (message "Nothing at point to hide or show"))))))
11052 (defun js2-mode-hide-element ()
11053 "Fold/hide contents of a block, showing ellipses.
11054 Show the hidden text with \\[js2-mode-show-element]."
11056 (if js2-mode-buffer-dirty-p
11057 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11058 (let (node body beg end)
11060 ((js2-mode-invisible-overlay-bounds)
11061 (message "already hidden"))
11063 (setq node (js2-node-at-point))
11065 ((js2-block-comment-p node)
11066 (js2-mode-hide-comment node))
11068 (while (and node (not (js2-function-node-p node)))
11069 (setq node (js2-node-parent node)))
11071 (setq body (js2-function-node-body node)))
11073 (setq beg (js2-node-abs-pos body)
11074 end (+ beg (js2-node-len body)))
11075 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11076 (message "No collapsable element found at point"))))))))
11078 (defun js2-mode-show-element ()
11079 "Show the hidden element at current point."
11081 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11083 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11084 (message "Nothing to un-hide"))))
11086 (defun js2-mode-show-all ()
11087 "Show all of the text in the buffer."
11089 (js2-mode-flag-region (point-min) (point-max) nil))
11091 (defun js2-mode-toggle-hide-functions ()
11093 (if js2-mode-functions-hidden
11094 (js2-mode-show-functions)
11095 (js2-mode-hide-functions)))
11097 (defun js2-mode-hide-functions ()
11098 "Hides all non-nested function bodies in the buffer.
11099 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11100 to open an individual entry."
11102 (if js2-mode-buffer-dirty-p
11103 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11104 (if (null js2-mode-ast)
11105 (message "Oops - parsing failed")
11106 (setq js2-mode-functions-hidden t)
11107 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11109 (defun js2-mode-function-hider (n endp)
11111 (let ((tt (js2-node-type n))
11114 ((and (= tt js2-FUNCTION)
11115 (setq body (js2-function-node-body n)))
11116 (setq beg (js2-node-abs-pos body)
11117 end (+ beg (js2-node-len body)))
11118 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11119 nil) ; don't process children of function
11121 t))))) ; keep processing other AST nodes
11123 (defun js2-mode-show-functions ()
11124 "Un-hide any folded function bodies in the buffer."
11126 (setq js2-mode-functions-hidden nil)
11128 (goto-char (point-min))
11129 (while (/= (goto-char (next-overlay-change (point)))
11131 (dolist (o (overlays-at (point)))
11132 (when (and (overlay-get o 'invisible)
11133 (not (overlay-get o 'comment)))
11134 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11136 (defun js2-mode-hide-comment (n)
11137 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11140 (beg (+ (js2-node-abs-pos n) head))
11141 (end (- (+ beg (js2-node-len n)) head 2))
11142 (o (js2-mode-flag-region beg end 'hide)))
11143 (overlay-put o 'comment t)))
11145 (defun js2-mode-toggle-hide-comments ()
11146 "Folds all block comments in the buffer.
11147 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11148 to open an individual entry."
11150 (if js2-mode-comments-hidden
11151 (js2-mode-show-comments)
11152 (js2-mode-hide-comments)))
11154 (defun js2-mode-hide-comments ()
11156 (if js2-mode-buffer-dirty-p
11157 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11158 (if (null js2-mode-ast)
11159 (message "Oops - parsing failed")
11160 (setq js2-mode-comments-hidden t)
11161 (dolist (n (js2-ast-root-comments js2-mode-ast))
11162 (when (js2-block-comment-p n)
11163 (js2-mode-hide-comment n)))
11164 (js2-mode-hide-//-comments)))
11166 (defun js2-mode-extend-//-comment (direction)
11167 "Find start or end of a block of similar //-comment lines.
11168 DIRECTION is -1 to look back, 1 to look forward.
11169 INDENT is the indentation level to match.
11170 Returns the end-of-line position of the furthest adjacent
11171 //-comment line with the same indentation as the current line.
11172 If there is no such matching line, returns current end of line."
11173 (let ((pos (point-at-eol))
11174 (indent (current-indentation)))
11176 (while (and (zerop (forward-line direction))
11177 (looking-at js2-mode-//-comment-re)
11178 (eq indent (length (match-string 1))))
11179 (setq pos (point-at-eol))
11182 (defun js2-mode-hide-//-comments ()
11183 "Fold adjacent 1-line comments, showing only snippet of first one."
11186 (goto-char (point-min))
11187 (while (re-search-forward js2-mode-//-comment-re nil t)
11189 end (js2-mode-extend-//-comment 1))
11190 (unless (eq beg end)
11191 (overlay-put (js2-mode-flag-region beg end 'hide)
11194 (forward-char 1)))))
11196 (defun js2-mode-toggle-//-comment ()
11197 "Fold or un-fold any multi-line //-comment at point.
11198 Caller should have determined that this line starts with a //-comment."
11199 (let* ((beg (point-at-eol))
11203 (if (js2-mode-invisible-overlay-bounds)
11204 (js2-mode-show-element)
11205 ;; else hide the comment
11206 (setq beg (js2-mode-extend-//-comment -1)
11207 end (js2-mode-extend-//-comment 1))
11208 (unless (eq beg end)
11209 (overlay-put (js2-mode-flag-region beg end 'hide)
11212 (defun js2-mode-show-comments ()
11213 "Un-hide any hidden comments, leaving other hidden elements alone."
11215 (setq js2-mode-comments-hidden nil)
11217 (goto-char (point-min))
11218 (while (/= (goto-char (next-overlay-change (point)))
11220 (dolist (o (overlays-at (point)))
11221 (when (overlay-get o 'comment)
11222 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11224 (defun js2-mode-display-warnings-and-errors ()
11225 "Turn on display of warnings and errors."
11227 (setq js2-mode-show-parse-errors t
11228 js2-mode-show-strict-warnings t)
11229 (js2-reparse 'force))
11231 (defun js2-mode-hide-warnings-and-errors ()
11232 "Turn off display of warnings and errors."
11234 (setq js2-mode-show-parse-errors nil
11235 js2-mode-show-strict-warnings nil)
11236 (js2-reparse 'force))
11238 (defun js2-mode-toggle-warnings-and-errors ()
11239 "Toggle the display of warnings and errors.
11240 Some users don't like having warnings/errors reported while they type."
11242 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11243 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11244 (if (called-interactively-p 'any)
11245 (message "warnings and errors %s"
11246 (if js2-mode-show-parse-errors
11249 (js2-reparse 'force))
11251 (defun js2-mode-customize ()
11253 (customize-group 'js2-mode))
11255 (defun js2-mode-forward-sexp (&optional arg)
11256 "Move forward across one statement or balanced expression.
11257 With ARG, do it that many times. Negative arg -N means
11258 move backward across N balanced expressions."
11260 (setq arg (or arg 1))
11262 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11264 (let (forward-sexp-function
11265 node (start (point)) pos lp rp child)
11268 ;; could probably make this better for some cases:
11269 ;; - if in statement block (e.g. function body), go to parent
11270 ;; - infix exprs like (foo in bar) - maybe go to beginning
11271 ;; of infix expr if in the right-side expression?
11272 ((and arg (minusp arg))
11273 (dotimes (_ (- arg))
11275 (forward-char -1) ; Enter the node we backed up to.
11276 (when (setq node (js2-node-at-point (point) t))
11277 (setq pos (js2-node-abs-pos node))
11278 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11279 (setq lp (car parens)
11281 (when (and lp (> start lp))
11282 (if (and rp (<= start rp))
11283 ;; Between parens, check if there's a child node we can jump.
11284 (when (setq child (js2-node-closest-child node (point) lp t))
11285 (setq pos (js2-node-abs-pos child)))
11286 ;; Before both parens.
11288 (let ((state (parse-partial-sexp start pos)))
11289 (goto-char (if (not (zerop (car state)))
11290 ;; Stumble at the unbalanced paren if < 0, or
11291 ;; jump a bit further if > 0.
11292 (scan-sexps start -1)
11294 (unless pos (goto-char (point-min)))))
11299 (when (setq node (js2-node-at-point (point) t))
11300 (setq pos (js2-node-abs-pos node))
11301 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11302 (setq lp (car parens)
11305 (when (and rp (<= start rp))
11307 (when (setq child (js2-node-closest-child node (point) rp))
11308 (setq pos (js2-node-abs-end child)))
11309 (setq pos (1+ rp))))
11310 ;; No parens or child nodes, looks for the end of the curren node.
11311 (incf pos (js2-node-len
11312 (if (js2-expr-stmt-node-p (js2-node-parent node))
11313 ;; Stop after the semicolon.
11314 (js2-node-parent node)
11316 (let ((state (save-excursion (parse-partial-sexp start pos))))
11317 (goto-char (if (not (zerop (car state)))
11318 (scan-sexps start 1)
11320 (unless pos (goto-char (point-max)))))))))
11322 (defun js2-mode-forward-sexp-parens (node abs-pos)
11323 "Return a cons cell with positions of main parens in NODE."
11325 ((or (js2-array-node-p node)
11326 (js2-object-node-p node)
11327 (js2-comp-node-p node)
11328 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11329 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11330 ((js2-paren-expr-node-p node)
11331 (let ((lp (js2-node-lp node))
11332 (rp (js2-node-rp node)))
11333 (cons (when lp (+ abs-pos lp))
11334 (when rp (+ abs-pos rp)))))))
11336 (defun js2-node-closest-child (parent point limit &optional before)
11337 (let* ((parent-pos (js2-node-abs-pos parent))
11338 (rpoint (- point parent-pos))
11339 (rlimit (- limit parent-pos))
11340 (min (min rpoint rlimit))
11341 (max (max rpoint rlimit))
11346 (lambda (node _end-p)
11347 (if (eq node parent)
11349 (let ((pos (js2-node-pos node)) ;; Both relative values.
11350 (end (+ (js2-node-pos node) (js2-node-len node))))
11351 (when (and (>= pos min) (<= end max)
11352 (if before (< pos rpoint) (> end rpoint)))
11354 (when (> end rpoint)
11355 (throw 'done nil)))
11359 (defun js2-errors ()
11360 "Return a list of errors found."
11362 (js2-ast-root-errors js2-mode-ast)))
11364 (defun js2-warnings ()
11365 "Return a list of warnings found."
11367 (js2-ast-root-warnings js2-mode-ast)))
11369 (defun js2-have-errors-p ()
11370 "Return non-nil if any parse errors or warnings were found."
11371 (or (js2-errors) (js2-warnings)))
11373 (defun js2-errors-and-warnings ()
11374 "Return a copy of the concatenated errors and warnings lists.
11375 They are appended: first the errors, then the warnings.
11376 Entries are of the form (MSG BEG END)."
11378 (append (js2-ast-root-errors js2-mode-ast)
11379 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11381 (defun js2-next-error (&optional arg reset)
11382 "Move to next parse error.
11383 Typically invoked via \\[next-error].
11384 ARG is the number of errors, forward or backward, to move.
11385 RESET means start over from the beginning."
11387 (if (not (or (js2-errors) (js2-warnings)))
11388 (message "No errors")
11390 (goto-char (point-min)))
11391 (let* ((errs (js2-errors-and-warnings))
11395 (backward (minusp count))
11396 (sorter (if backward '> '<))
11397 (stopper (if backward '< '>))
11398 (count (abs count))
11400 ;; Sort by start position.
11401 (setq errs (sort errs (lambda (e1 e2)
11402 (funcall sorter (second e1) (second e2))))
11404 ;; Find nth error with pos > start.
11405 (while (and errs continue)
11406 (when (funcall stopper (cadar errs) start)
11407 (setq err (car errs))
11408 (if (zerop (decf count))
11409 (setq continue nil)))
11410 (setq errs (cdr errs)))
11411 ;; Clear for `js2-echo-error'.
11414 (goto-char (second err))
11415 ;; Wrap around to first error.
11416 (goto-char (second (car all-errs)))
11417 ;; If we were already on it, echo msg again.
11418 (if (= (point) start)
11419 (js2-echo-error (point) (point)))))))
11421 (defun js2-down-mouse-3 ()
11422 "Make right-click move the point to the click location.
11423 This makes right-click context menu operations a bit more intuitive.
11424 The point will not move if the region is active, however, to avoid
11425 destroying the region selection."
11427 (when (and js2-move-point-on-right-click
11429 (let ((e last-input-event))
11431 (goto-char (cadadr e))))))
11433 (defun js2-mode-create-imenu-index ()
11434 "Return an alist for `imenu--index-alist'."
11435 ;; This is built up in `js2-parse-record-imenu' during parsing.
11437 ;; if we have an ast but no recorder, they're requesting a rescan
11438 (unless js2-imenu-recorder
11439 (js2-reparse 'force))
11441 (js2-build-imenu-index)
11442 (setq js2-imenu-recorder nil
11443 js2-imenu-function-map nil))))
11445 (defun js2-mode-find-tag ()
11446 "Replacement for `find-tag-default'.
11447 `find-tag-default' returns a ridiculous answer inside comments."
11449 (js2-with-underscore-as-word-syntax
11451 (if (and (not (looking-at "[[:alnum:]_$]"))
11452 (looking-back "[[:alnum:]_$]"))
11453 (setq beg (progn (forward-word -1) (point))
11454 end (progn (forward-word 1) (point)))
11455 (setq beg (progn (forward-word 1) (point))
11456 end (progn (forward-word -1) (point))))
11457 (replace-regexp-in-string
11459 (buffer-substring-no-properties beg end))))))
11461 (defun js2-mode-forward-sibling ()
11462 "Move to the end of the sibling following point in parent.
11463 Returns non-nil if successful, or nil if there was no following sibling."
11464 (let* ((node (js2-node-at-point))
11465 (parent (js2-mode-find-enclosing-fn node))
11467 (when (setq sib (js2-node-find-child-after (point) parent))
11468 (goto-char (+ (js2-node-abs-pos sib)
11469 (js2-node-len sib))))))
11471 (defun js2-mode-backward-sibling ()
11472 "Move to the beginning of the sibling node preceding point in parent.
11473 Parent is defined as the enclosing script or function."
11474 (let* ((node (js2-node-at-point))
11475 (parent (js2-mode-find-enclosing-fn node))
11477 (when (setq sib (js2-node-find-child-before (point) parent))
11478 (goto-char (js2-node-abs-pos sib)))))
11480 (defun js2-beginning-of-defun (&optional arg)
11481 "Go to line on which current function starts, and return t on success.
11482 If we're not in a function or already at the beginning of one, go
11483 to beginning of previous script-level element.
11484 With ARG N, do that N times. If N is negative, move forward."
11485 (setq arg (or arg 1))
11487 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11489 ((js2-function-node-p parent)
11490 (goto-char (js2-node-abs-pos parent)))
11492 (js2-mode-backward-sibling)))
11494 (js2-beginning-of-defun (1- arg))
11496 (when (js2-end-of-defun)
11497 (js2-beginning-of-defun (if (>= arg -1) 1 (1+ arg))))))
11499 (defun js2-end-of-defun ()
11500 "Go to the char after the last position of the current function
11501 or script-level element."
11502 (let* ((node (js2-node-at-point))
11503 (parent (or (and (js2-function-node-p node) node)
11504 (js2-node-parent-script-or-fn node)))
11506 (unless (js2-function-node-p parent)
11507 ;; Use current script-level node, or, if none, the next one.
11508 (setq script (or parent node)
11509 parent (js2-node-find-child-before (point) script))
11510 (when (or (null parent)
11511 (>= (point) (+ (js2-node-abs-pos parent)
11512 (js2-node-len parent))))
11513 (setq parent (js2-node-find-child-after (point) script))))
11515 (goto-char (+ (js2-node-abs-pos parent)
11516 (js2-node-len parent))))))
11518 (defun js2-mark-defun (&optional allow-extend)
11519 "Put mark at end of this function, point at beginning.
11520 The function marked is the one that contains point.
11522 Interactively, if this command is repeated,
11523 or (in Transient Mark mode) if the mark is active,
11524 it marks the next defun after the ones already marked."
11527 (when (and allow-extend
11528 (or (and (eq last-command this-command) (mark t))
11529 (and transient-mark-mode mark-active)))
11530 (let ((sib (save-excursion
11532 (if (js2-mode-forward-sibling)
11538 ;; no more siblings - try extending to enclosing node
11539 (goto-char (mark t)))))
11540 (when (not extended)
11541 (let ((node (js2-node-at-point (point) t)) ; skip comments
11542 ast fn stmt parent beg end)
11543 (when (js2-ast-root-p node)
11545 node (or (js2-node-find-child-after (point) node)
11546 (js2-node-find-child-before (point) node))))
11547 ;; only mark whole buffer if we can't find any children
11550 (if (js2-function-node-p node)
11552 (setq fn (js2-mode-find-enclosing-fn node)
11553 stmt (if (or (null fn)
11554 (js2-ast-root-p fn))
11555 (js2-mode-find-first-stmt node))
11556 parent (or stmt fn)))
11557 (setq beg (js2-node-abs-pos parent)
11558 end (+ beg (js2-node-len parent)))
11561 (exchange-point-and-mark)))))
11563 (defun js2-narrow-to-defun ()
11564 "Narrow to the function enclosing point."
11566 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11567 (fn (if (js2-script-node-p node)
11569 (js2-mode-find-enclosing-fn node)))
11570 (beg (js2-node-abs-pos fn)))
11571 (unless (js2-ast-root-p fn)
11572 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11574 (provide 'js2-mode)
11576 ;;; js2-mode.el ends here