1 ;;; js2-mode.el --- an improved JavaScript editing mode
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; This JavaScript editing mode supports:
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
71 (require 'cc-cmds) ; for `c-fill-paragraph'
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
78 ;;; Externs (variables presumed to be defined by the host system)
80 (defvar js2-ecma-262-externs
82 '(Array Boolean Date Error EvalError Function Infinity
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
90 (defvar js2-browser-externs
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
129 window alert confirm document java navigator prompt screen
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
147 DocumentRange Range RangeException
150 XPathResult XMLHttpRequest))
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
155 (defvar js2-rhino-externs
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
165 (defvar js2-gears-externs
168 ;; TODO(stevey): add these
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
175 (defun js2-mark-safe-local (name pred)
176 "Make the variable NAME buffer-local and mark it as safe file-local
177 variable with predicate PRED."
178 (make-variable-buffer-local name)
179 (put name 'safe-local-variable pred))
181 (defvar js2-emacs22 (>= emacs-major-version 22))
183 (defcustom js2-highlight-level 2
184 "Amount of syntax highlighting to perform.
185 0 or a negative value means do no highlighting.
186 1 adds basic syntax highlighting.
187 2 adds highlighting of some Ecma built-in properties.
188 3 adds highlighting of many Ecma built-in functions."
190 :type '(choice (const :tag "None" 0)
191 (const :tag "Basic" 1)
192 (const :tag "Include Properties" 2)
193 (const :tag "Include Functions" 3)))
195 (defvar js2-mode-dev-mode-p nil
196 "Non-nil if running in development mode. Normally nil.")
198 (defgroup js2-mode nil
199 "An improved JavaScript mode."
202 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
203 (numberp c-basic-offset))
206 "Number of spaces to indent nested statements.
207 Similar to `c-basic-offset'."
210 (js2-mark-safe-local 'js2-basic-offset 'integerp)
212 ;; TODO(stevey): move this code into a separate minor mode.
213 (defcustom js2-mirror-mode nil
214 "Non-nil to insert closing brackets, parens, etc. automatically."
218 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
237 (defcustom js2-consistent-level-indent-inner-bracket-p t
238 "Non-nil to make indentation level inner bracket consistent,
239 regardless of the beginning bracket position."
242 (js2-mark-safe-local 'js2-consistent-level-indent-inner-bracket-p 'booleanp)
244 (defcustom js2-pretty-multiline-decl-indentation-p t
245 "Non-nil to line up multiline declarations vertically. See the
246 function `js-multiline-decl-indentation' for details."
249 (js2-mark-safe-local 'js2-pretty-multiline-decl-indentation-p 'booleanp)
251 (defcustom js2-always-indent-assigned-expr-in-decls-p nil
252 "If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
253 always additionally indent function expression or array/object literal
254 assigned in a declaration, even when only one var is declared."
257 (js2-mark-safe-local 'js2-always-indent-assigned-expr-in-decls-p 'booleanp)
259 (defcustom js2-indent-on-enter-key nil
260 "Non-nil to have Enter/Return key indent the line.
261 This is unusual for Emacs modes but common in IDEs like Eclipse."
265 (defcustom js2-enter-indents-newline nil
266 "Non-nil to have Enter/Return key indent the newly-inserted line.
267 This is unusual for Emacs modes but common in IDEs like Eclipse."
271 (defcustom js2-rebind-eol-bol-keys t
272 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
273 If non-nil, bounce between bol/eol and first/last non-whitespace char."
277 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
278 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
279 Each value in the list is passed to `define-key'."
283 (defcustom js2-idle-timer-delay 0.2
284 "Delay in secs before re-parsing after user makes changes.
285 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
288 (make-variable-buffer-local 'js2-idle-timer-delay)
290 (defcustom js2-dynamic-idle-timer-adjust 0
291 "Positive to adjust `js2-idle-timer-delay' based on file size.
292 The idea is that for short files, parsing is faster so we can be
293 more responsive to user edits without interfering with editing.
294 The buffer length in characters (typically bytes) is divided by
295 this value and used to multiply `js2-idle-timer-delay' for the
296 buffer. For example, a 21k file and 10k adjust yields 21k/10k
297 == 2, so js2-idle-timer-delay is multiplied by 2.
298 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
299 `js2-idle-timer-delay' is not dependent on the file size."
303 (defcustom js2-mode-escape-quotes t
304 "Non-nil to disable automatic quote-escaping inside strings."
308 (defcustom js2-concat-multiline-strings t
309 "Non-nil to automatically turn a newline in mid-string
310 into a string concatenation."
314 (defcustom js2-mode-squeeze-spaces t
315 "Non-nil to normalize whitespace when filling in comments.
316 Multiple runs of spaces are converted to a single space."
320 (defcustom js2-mode-show-parse-errors t
321 "True to highlight parse errors."
325 (defcustom js2-mode-show-strict-warnings t
326 "Non-nil to emit Ecma strict-mode warnings.
327 Some of the warnings can be individually disabled by other flags,
328 even if this flag is non-nil."
332 (defcustom js2-strict-trailing-comma-warning t
333 "Non-nil to warn about trailing commas in array literals.
334 Ecma-262 forbids them, but many browsers permit them. IE is the
335 big exception, and can produce bugs if you have trailing commas."
339 (defcustom js2-strict-missing-semi-warning t
340 "Non-nil to warn about semicolon auto-insertion after statement.
341 Technically this is legal per Ecma-262, but some style guides disallow
346 (defcustom js2-missing-semi-one-line-override nil
347 "Non-nil to permit missing semicolons in one-line functions.
348 In one-liner functions such as `function identity(x) {return x}'
349 people often omit the semicolon for a cleaner look. If you are
350 such a person, you can suppress the missing-semicolon warning
351 by setting this variable to t."
355 (defcustom js2-strict-inconsistent-return-warning t
356 "Non-nil to warn about mixing returns with value-returns.
357 It's perfectly legal to have a `return' and a `return foo' in the
358 same function, but it's often an indicator of a bug, and it also
359 interferes with type inference (in systems that support it.)"
363 (defcustom js2-strict-cond-assign-warning t
364 "Non-nil to warn about expressions like if (a = b).
365 This often should have been '==' instead of '='. If the warning
366 is enabled, you can suppress it on a per-expression basis by
367 parenthesizing the expression, e.g. if ((a = b)) ..."
371 (defcustom js2-strict-cond-assign-warning t
372 "Non-nil to warn about expressions like if (a = b).
373 This often should have been '==' instead of '='. If the warning
374 is enabled, you can suppress it on a per-expression basis by
375 parenthesizing the expression, e.g. if ((a = b)) ..."
379 (defcustom js2-strict-var-redeclaration-warning t
380 "Non-nil to warn about redeclaring variables in a script or function."
384 (defcustom js2-strict-var-hides-function-arg-warning t
385 "Non-nil to warn about a var decl hiding a function argument."
389 (defcustom js2-skip-preprocessor-directives nil
390 "Non-nil to treat lines beginning with # as comments.
391 Useful for viewing Mozilla JavaScript source code."
395 (defcustom js2-language-version 180
396 "Configures what JavaScript language version to recognize.
397 Currently versions 150, 160, 170 and 180 are supported, corresponding
398 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
399 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
400 and 1.8 adds function closures."
404 (defcustom js2-allow-keywords-as-property-names t
405 "If non-nil, you can use JavaScript keywords as object property names.
408 var foo = {int: 5, while: 6, continue: 7};
411 Ecma-262 forbids this syntax, but many browsers support it."
415 (defcustom js2-instanceof-has-side-effects nil
416 "If non-nil, treats the instanceof operator as having side effects.
417 This is useful for xulrunner apps."
421 (defcustom js2-cleanup-whitespace nil
422 "Non-nil to invoke `delete-trailing-whitespace' before saves."
426 (defcustom js2-move-point-on-right-click t
427 "Non-nil to move insertion point when you right-click.
428 This makes right-click context menu behavior a bit more intuitive,
429 since menu operations generally apply to the point. The exception
430 is if there is a region selection, in which case the point does -not-
431 move, so cut/copy/paste etc. can work properly.
433 Note that IntelliJ moves the point, and Eclipse leaves it alone,
434 so this behavior is customizable."
438 (defcustom js2-allow-rhino-new-expr-initializer t
439 "Non-nil to support a Rhino's experimental syntactic construct.
441 Rhino supports the ability to follow a `new' expression with an object
442 literal, which is used to set additional properties on the new object
443 after calling its constructor. Syntax:
445 new <expr> [ ( arglist ) ] [initializer]
447 Hence, this expression:
449 new Object {a: 1, b: 2}
451 results in an Object with properties a=1 and b=2. This syntax is
452 apparently not configurable in Rhino - it's currently always enabled,
453 as of Rhino version 1.7R2."
457 (defcustom js2-allow-member-expr-as-function-name nil
458 "Non-nil to support experimental Rhino syntax for function names.
460 Rhino supports an experimental syntax configured via the Rhino Context
461 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
463 function <member-expr> ( [ arg-list ] ) { <body> }
465 Where member-expr is a non-parenthesized 'member expression', which
466 is anything at the grammar level of a new-expression or lower, meaning
467 any expression that does not involve infix or unary operators.
469 When <member-expr> is not a simple identifier, then it is syntactic
470 sugar for assigning the anonymous function to the <member-expr>. Hence,
473 function a.b().c[2] (x, y) { ... }
477 a.b().c[2] = function(x, y) {...}
479 which doesn't seem particularly useful, but Rhino permits it."
483 (defvar js2-mode-version 20101228
484 "Release number for `js2-mode'.")
488 (defmacro js2-deflocal (name value &optional comment)
489 "Define a buffer-local variable NAME with VALUE and COMMENT."
491 (defvar ,name ,value ,comment)
492 (make-variable-buffer-local ',name)))
494 ;; We record the start and end position of each token.
495 (js2-deflocal js2-token-beg 1)
496 (js2-deflocal js2-token-end -1)
498 (defvar js2-EOF_CHAR -1
499 "Represents end of stream. Distinct from js2-EOF token type.")
501 ;; I originally used symbols to represent tokens, but Rhino uses
502 ;; ints and then sets various flag bits in them, so ints it is.
503 ;; The upshot is that we need a `js2-' prefix in front of each name.
504 (defvar js2-ERROR -1)
507 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
508 (defvar js2-LEAVEWITH 3)
509 (defvar js2-RETURN 4)
513 (defvar js2-SETNAME 8)
515 (defvar js2-BITXOR 10)
516 (defvar js2-BITAND 11)
526 (defvar js2-ADD 21) ; infix plus
527 (defvar js2-SUB 22) ; infix minus
532 (defvar js2-BITNOT 27)
533 (defvar js2-POS 28) ; unary plus
534 (defvar js2-NEG 29) ; unary minus
536 (defvar js2-DELPROP 31)
537 (defvar js2-TYPEOF 32)
538 (defvar js2-GETPROP 33)
539 (defvar js2-GETPROPNOWARN 34)
540 (defvar js2-SETPROP 35)
541 (defvar js2-GETELEM 36)
542 (defvar js2-SETELEM 37)
544 (defvar js2-NAME 39) ; an identifier
545 (defvar js2-NUMBER 40)
546 (defvar js2-STRING 41)
549 (defvar js2-FALSE 44)
551 (defvar js2-SHEQ 46) ; shallow equality (===)
552 (defvar js2-SHNE 47) ; shallow inequality (!==)
553 (defvar js2-REGEXP 48)
554 (defvar js2-BINDNAME 49)
555 (defvar js2-THROW 50)
556 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
558 (defvar js2-INSTANCEOF 53)
559 (defvar js2-LOCAL_LOAD 54)
560 (defvar js2-GETVAR 55)
561 (defvar js2-SETVAR 56)
562 (defvar js2-CATCH_SCOPE 57)
563 (defvar js2-ENUM_INIT_KEYS 58)
564 (defvar js2-ENUM_INIT_VALUES 59)
565 (defvar js2-ENUM_INIT_ARRAY 60)
566 (defvar js2-ENUM_NEXT 61)
567 (defvar js2-ENUM_ID 62)
568 (defvar js2-THISFN 63)
569 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
570 (defvar js2-ARRAYLIT 65) ; array literal
571 (defvar js2-OBJECTLIT 66) ; object literal
572 (defvar js2-GET_REF 67) ; *reference
573 (defvar js2-SET_REF 68) ; *reference = something
574 (defvar js2-DEL_REF 69) ; delete reference
575 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
576 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
577 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
580 (defvar js2-DEFAULTNAMESPACE 73)
581 (defvar js2-ESCXMLATTR 74)
582 (defvar js2-ESCXMLTEXT 75)
583 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
584 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
585 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
586 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
588 (defvar js2-first-bytecode js2-ENTERWITH)
589 (defvar js2-last-bytecode js2-REF_NS_NAME)
592 (defvar js2-SEMI 81) ; semicolon
593 (defvar js2-LB 82) ; left and right brackets
595 (defvar js2-LC 84) ; left and right curly-braces
597 (defvar js2-LP 86) ; left and right parens
599 (defvar js2-COMMA 88) ; comma operator
601 (defvar js2-ASSIGN 89) ; simple assignment (=)
602 (defvar js2-ASSIGN_BITOR 90) ; |=
603 (defvar js2-ASSIGN_BITXOR 91) ; ^=
604 (defvar js2-ASSIGN_BITAND 92) ; &=
605 (defvar js2-ASSIGN_LSH 93) ; <<=
606 (defvar js2-ASSIGN_RSH 94) ; >>=
607 (defvar js2-ASSIGN_URSH 95) ; >>>=
608 (defvar js2-ASSIGN_ADD 96) ; +=
609 (defvar js2-ASSIGN_SUB 97) ; -=
610 (defvar js2-ASSIGN_MUL 98) ; *=
611 (defvar js2-ASSIGN_DIV 99) ; /=
612 (defvar js2-ASSIGN_MOD 100) ; %=
614 (defvar js2-first-assign js2-ASSIGN)
615 (defvar js2-last-assign js2-ASSIGN_MOD)
617 (defvar js2-HOOK 101) ; conditional (?:)
618 (defvar js2-COLON 102)
619 (defvar js2-OR 103) ; logical or (||)
620 (defvar js2-AND 104) ; logical and (&&)
621 (defvar js2-INC 105) ; increment/decrement (++ --)
623 (defvar js2-DOT 107) ; member operator (.)
624 (defvar js2-FUNCTION 108) ; function keyword
625 (defvar js2-EXPORT 109) ; export keyword
626 (defvar js2-IMPORT 110) ; import keyword
627 (defvar js2-IF 111) ; if keyword
628 (defvar js2-ELSE 112) ; else keyword
629 (defvar js2-SWITCH 113) ; switch keyword
630 (defvar js2-CASE 114) ; case keyword
631 (defvar js2-DEFAULT 115) ; default keyword
632 (defvar js2-WHILE 116) ; while keyword
633 (defvar js2-DO 117) ; do keyword
634 (defvar js2-FOR 118) ; for keyword
635 (defvar js2-BREAK 119) ; break keyword
636 (defvar js2-CONTINUE 120) ; continue keyword
637 (defvar js2-VAR 121) ; var keyword
638 (defvar js2-WITH 122) ; with keyword
639 (defvar js2-CATCH 123) ; catch keyword
640 (defvar js2-FINALLY 124) ; finally keyword
641 (defvar js2-VOID 125) ; void keyword
642 (defvar js2-RESERVED 126) ; reserved keywords
644 (defvar js2-EMPTY 127)
646 ;; Types used for the parse tree - never returned by scanner.
648 (defvar js2-BLOCK 128) ; statement block
649 (defvar js2-LABEL 129) ; label
650 (defvar js2-TARGET 130)
651 (defvar js2-LOOP 131)
652 (defvar js2-EXPR_VOID 132) ; expression statement in functions
653 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
655 (defvar js2-SCRIPT 135) ; top-level node for entire script
656 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
657 (defvar js2-USE_STACK 137)
658 (defvar js2-SETPROP_OP 138) ; x.y op= something
659 (defvar js2-SETELEM_OP 139) ; x[y] op= something
660 (defvar js2-LOCAL_BLOCK 140)
661 (defvar js2-SET_REF_OP 141) ; *reference op= something
664 (defvar js2-DOTDOT 142) ; member operator (..)
665 (defvar js2-COLONCOLON 143) ; namespace::name
666 (defvar js2-XML 144) ; XML type
667 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
668 (defvar js2-XMLATTR 146) ; @
669 (defvar js2-XMLEND 147)
671 ;; Optimizer-only tokens
672 (defvar js2-TO_OBJECT 148)
673 (defvar js2-TO_DOUBLE 149)
675 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
676 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
677 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
678 (defvar js2-CONST 153)
679 (defvar js2-SETCONST 154)
680 (defvar js2-SETCONSTVAR 155)
681 (defvar js2-ARRAYCOMP 156)
682 (defvar js2-LETEXPR 157)
683 (defvar js2-WITHEXPR 158)
684 (defvar js2-DEBUGGER 159)
686 (defvar js2-COMMENT 160)
687 (defvar js2-ENUM 161) ; for "enum" reserved word
689 (defconst js2-num-tokens (1+ js2-ENUM))
691 (defconst js2-debug-print-trees nil)
693 ;; Rhino accepts any string or stream as input. Emacs character
694 ;; processing works best in buffers, so we'll assume the input is a
695 ;; buffer. JavaScript strings can be copied into temp buffers before
698 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
699 ;; They're the Emacs equivalent of instance variables, more or less.
701 (js2-deflocal js2-ts-dirty-line nil
702 "Token stream buffer-local variable.
703 Indicates stuff other than whitespace since start of line.")
705 (js2-deflocal js2-ts-regexp-flags nil
706 "Token stream buffer-local variable.")
708 (js2-deflocal js2-ts-string ""
709 "Token stream buffer-local variable.
710 Last string scanned.")
712 (js2-deflocal js2-ts-number nil
713 "Token stream buffer-local variable.
714 Last literal number scanned.")
716 (js2-deflocal js2-ts-hit-eof nil
717 "Token stream buffer-local variable.")
719 (js2-deflocal js2-ts-line-start 0
720 "Token stream buffer-local variable.")
722 (js2-deflocal js2-ts-lineno 1
723 "Token stream buffer-local variable.")
725 (js2-deflocal js2-ts-line-end-char -1
726 "Token stream buffer-local variable.")
728 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
729 "Token stream buffer-local variable.
730 Current scan position.")
732 (js2-deflocal js2-ts-is-xml-attribute nil
733 "Token stream buffer-local variable.")
735 (js2-deflocal js2-ts-xml-is-tag-content nil
736 "Token stream buffer-local variable.")
738 (js2-deflocal js2-ts-xml-open-tags-count 0
739 "Token stream buffer-local variable.")
741 (js2-deflocal js2-ts-string-buffer nil
742 "Token stream buffer-local variable.
743 List of chars built up while scanning various tokens.")
745 (js2-deflocal js2-ts-comment-type nil
746 "Token stream buffer-local variable.")
750 (js2-deflocal js2-parsed-errors nil
751 "List of errors produced during scanning/parsing.")
753 (js2-deflocal js2-parsed-warnings nil
754 "List of warnings produced during scanning/parsing.")
756 (js2-deflocal js2-recover-from-parse-errors t
757 "Non-nil to continue parsing after a syntax error.
759 In recovery mode, the AST will be built in full, and any error
760 nodes will be flagged with appropriate error information. If
761 this flag is nil, a syntax error will result in an error being
764 The variable is automatically buffer-local, because different
765 modes that use the parser will need different settings.")
767 (js2-deflocal js2-parse-hook nil
768 "List of callbacks for receiving parsing progress.")
770 (defvar js2-parse-finished-hook nil
771 "List of callbacks to notify when parsing finishes.
772 Not called if parsing was interrupted.")
774 (js2-deflocal js2-is-eval-code nil
775 "True if we're evaluating code in a string.
776 If non-nil, the tokenizer will record the token text, and the AST nodes
777 will record their source text. Off by default for IDE modes, since the
778 text is available in the buffer.")
780 (defvar js2-parse-ide-mode t
781 "Non-nil if the parser is being used for `js2-mode'.
782 If non-nil, the parser will set text properties for fontification
783 and the syntax table. The value should be nil when using the
784 parser as a frontend to an interpreter or byte compiler.")
786 ;;; Parser instance variables (buffer-local vars for js2-parse)
788 (defconst js2-clear-ti-mask #xFFFF
789 "Mask to clear token information bits.")
791 (defconst js2-ti-after-eol (lsh 1 16)
792 "Flag: first token of the source line.")
794 (defconst js2-ti-check-label (lsh 1 17)
795 "Flag: indicates to check for label.")
797 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
799 (js2-deflocal js2-compiler-generate-debug-info t)
800 (js2-deflocal js2-compiler-use-dynamic-scope nil)
801 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
802 (js2-deflocal js2-compiler-xml-available t)
803 (js2-deflocal js2-compiler-optimization-level 0)
804 (js2-deflocal js2-compiler-generating-source t)
805 (js2-deflocal js2-compiler-strict-mode nil)
806 (js2-deflocal js2-compiler-report-warning-as-error nil)
807 (js2-deflocal js2-compiler-generate-observer-count nil)
808 (js2-deflocal js2-compiler-activation-names nil)
812 ;; There's a compileFunction method in Context.java - may need it.
813 (js2-deflocal js2-called-by-compile-function nil
814 "True if `js2-parse' was called by `js2-compile-function'.
815 Will only be used when we finish implementing the interpreter.")
817 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
819 (js2-deflocal js2-current-flagged-token js2-EOF)
820 (js2-deflocal js2-current-token js2-EOF)
822 ;; SKIP: node factory - we're going to just call functions directly,
823 ;; and eventually go to a unified AST format.
825 (js2-deflocal js2-nesting-of-function 0)
827 (js2-deflocal js2-recorded-identifiers nil
828 "Tracks identifiers found during parsing.")
830 (defmacro js2-in-lhs (body)
831 `(let ((js2-is-in-lhs t))
834 (defmacro js2-in-rhs (body)
835 `(let ((js2-is-in-lhs nil))
838 (js2-deflocal js2-is-in-lhs nil
839 "True while parsing lhs statement")
841 (defcustom js2-global-externs nil
842 "A list of any extern names you'd like to consider always declared.
843 This list is global and is used by all js2-mode files.
844 You can create buffer-local externs list using `js2-additional-externs'.
846 There is also a buffer-local variable `js2-default-externs',
847 which is initialized by default to include the Ecma-262 externs
848 and the standard browser externs. The three lists are all
849 checked during highlighting."
853 (js2-deflocal js2-default-externs nil
854 "Default external declarations.
856 These are currently only used for highlighting undeclared variables,
857 which only worries about top-level (unqualified) references.
858 As js2-mode's processing improves, we will flesh out this list.
860 The initial value is set to `js2-ecma-262-externs', unless you
861 have set `js2-include-browser-externs', in which case the browser
862 externs are also included.
864 See `js2-additional-externs' for more information.")
866 (defcustom js2-include-browser-externs t
867 "Non-nil to include browser externs in the master externs list.
868 If you work on JavaScript files that are not intended for browsers,
869 such as Mozilla Rhino server-side JavaScript, set this to nil.
870 You can always include them on a per-file basis by calling
871 `js2-add-browser-externs' from a function on `js2-mode-hook'.
873 See `js2-additional-externs' for more information about externs."
877 (defcustom js2-include-rhino-externs t
878 "Non-nil to include Mozilla Rhino externs in the master externs list.
879 See `js2-additional-externs' for more information about externs."
883 (defcustom js2-include-gears-externs t
884 "Non-nil to include Google Gears externs in the master externs list.
885 See `js2-additional-externs' for more information about externs."
889 (js2-deflocal js2-additional-externs nil
890 "A buffer-local list of additional external declarations.
891 It is used to decide whether variables are considered undeclared
892 for purposes of highlighting.
894 Each entry is a lisp string. The string should be the fully qualified
895 name of an external entity. All externs should be added to this list,
896 so that as js2-mode's processing improves it can take advantage of them.
898 You may want to declare your externs in three ways.
899 First, you can add externs that are valid for all your JavaScript files.
900 You should probably do this by adding them to `js2-global-externs', which
901 is a global list used for all js2-mode files.
903 Next, you can add a function to `js2-mode-hook' that adds additional
904 externs appropriate for the specific file, perhaps based on its path.
905 These should go in `js2-additional-externs', which is buffer-local.
907 Finally, you can add a function to `js2-post-parse-callbacks',
908 which is called after parsing completes, and `root' is bound to
909 the root of the parse tree. At this stage you can set up an AST
910 node visitor using `js2-visit-ast' and examine the parse tree
911 for specific import patterns that may imply the existence of
912 other externs, possibly tied to your build system. These should also
913 be added to `js2-additional-externs'.
915 Your post-parse callback may of course also use the simpler and
916 faster (but perhaps less robust) approach of simply scanning the
917 buffer text for your imports, using regular expressions.")
920 ;; SKIP: encoded-source
922 ;;; The following variables are per-function and should be saved/restored
923 ;;; during function parsing...
925 (js2-deflocal js2-current-script-or-fn nil)
926 (js2-deflocal js2-current-scope nil)
927 (js2-deflocal js2-nesting-of-with 0)
928 (js2-deflocal js2-label-set nil
929 "An alist mapping label names to nodes.")
931 (js2-deflocal js2-loop-set nil)
932 (js2-deflocal js2-loop-and-switch-set nil)
933 (js2-deflocal js2-has-return-value nil)
934 (js2-deflocal js2-end-flags 0)
936 ;;; ...end of per function variables
938 ;; Without 2-token lookahead, labels are a problem.
939 ;; These vars store the token info of the last matched name,
940 ;; iff it wasn't the last matched token. Only valid in some contexts.
941 (defvar js2-prev-name-token-start nil)
942 (defvar js2-prev-name-token-string nil)
944 (defsubst js2-save-name-token-data (pos name)
945 (setq js2-prev-name-token-start pos
946 js2-prev-name-token-string name))
948 ;; These flags enumerate the possible ways a statement/function can
949 ;; terminate. These flags are used by endCheck() and by the Parser to
950 ;; detect inconsistent return usage.
952 ;; END_UNREACHED is reserved for code paths that are assumed to always be
953 ;; able to execute (example: throw, continue)
955 ;; END_DROPS_OFF indicates if the statement can transfer control to the
956 ;; next one. Statement such as return dont. A compound statement may have
957 ;; some branch that drops off control to the next statement.
959 ;; END_RETURNS indicates that the statement can return (without arguments)
960 ;; END_RETURNS_VALUE indicates that the statement can return a value.
962 ;; A compound statement such as
966 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
968 (defconst js2-end-unreached #x0)
969 (defconst js2-end-drops-off #x1)
970 (defconst js2-end-returns #x2)
971 (defconst js2-end-returns-value #x4)
972 (defconst js2-end-yields #x8)
974 ;; Rhino awkwardly passes a statementLabel parameter to the
975 ;; statementHelper() function, the main statement parser, which
976 ;; is then used by quite a few of the sub-parsers. We just make
977 ;; it a buffer-local variable and make sure it's cleaned up properly.
978 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
980 ;; Similarly, Rhino passes an inForInit boolean through about half
981 ;; the expression parsers. We use a dynamically-scoped variable,
982 ;; which makes it easier to funcall the parsers individually without
983 ;; worrying about whether they take the parameter or not.
984 (js2-deflocal js2-in-for-init nil)
985 (js2-deflocal js2-temp-name-counter 0)
986 (js2-deflocal js2-parse-stmt-count 0)
988 (defsubst js2-get-next-temp-name ()
989 (format "$%d" (incf js2-temp-name-counter)))
991 (defvar js2-parse-interruptable-p t
992 "Set this to nil to force parse to continue until finished.
993 This will mostly be useful for interpreters.")
995 (defvar js2-statements-per-pause 50
996 "Pause after this many statements to check for user input.
997 If user input is pending, stop the parse and discard the tree.
998 This makes for a smoother user experience for large files.
999 You may have to wait a second or two before the highlighting
1000 and error-reporting appear, but you can always type ahead if
1001 you wish. This appears to be more or less how Eclipse, IntelliJ
1002 and other editors work.")
1004 (js2-deflocal js2-record-comments t
1005 "Instructs the scanner to record comments in `js2-scanned-comments'.")
1007 (js2-deflocal js2-scanned-comments nil
1008 "List of all comments from the current parse.")
1010 (defcustom js2-mode-indent-inhibit-undo nil
1011 "Non-nil to disable collection of Undo information when indenting lines.
1012 Some users have requested this behavior. It's nil by default because
1013 other Emacs modes don't work this way."
1017 (defcustom js2-mode-indent-ignore-first-tab nil
1018 "If non-nil, ignore first TAB keypress if we look indented properly.
1019 It's fairly common for users to navigate to an already-indented line
1020 and press TAB for reassurance that it's been indented. For this class
1021 of users, we want the first TAB press on a line to be ignored if the
1022 line is already indented to one of the precomputed alternatives.
1024 This behavior is only partly implemented. If you TAB-indent a line,
1025 navigate to another line, and then navigate back, it fails to clear
1026 the last-indented variable, so it thinks you've already hit TAB once,
1027 and performs the indent. A full solution would involve getting on the
1028 point-motion hooks for the entire buffer. If we come across another
1029 use cases that requires watching point motion, I'll consider doing it.
1031 If you set this variable to nil, then the TAB key will always change
1032 the indentation of the current line, if more than one alternative
1033 indentation spot exists."
1037 (defvar js2-indent-hook nil
1038 "A hook for user-defined indentation rules.
1040 Functions on this hook should expect two arguments: (LIST INDEX)
1041 The LIST argument is the list of computed indentation points for
1042 the current line. INDEX is the list index of the indentation point
1043 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1044 indent function is not going to change the current line indentation.
1046 If a hook function on this list returns a non-nil value, then
1047 `js2-bounce-indent' assumes the hook function has performed its own
1048 indentation, and will do nothing. If all hook functions on the list
1049 return nil, then `js2-bounce-indent' will use its computed indentation
1050 and reindent the line.
1052 When hook functions on this hook list are called, the variable
1053 `js2-mode-ast' may or may not be set, depending on whether the
1054 parse tree is available. If the variable is nil, you can pass a
1055 callback to `js2-mode-wait-for-parse', and your callback will be
1056 called after the new parse tree is built. This can take some time
1059 (defface js2-warning-face
1060 `((((class color) (background light))
1061 (:underline "orange"))
1062 (((class color) (background dark))
1063 (:underline "orange"))
1065 "Face for JavaScript warnings."
1068 (defface js2-error-face
1069 `((((class color) (background light))
1070 (:foreground "red"))
1071 (((class color) (background dark))
1072 (:foreground "red"))
1073 (t (:foreground "red")))
1074 "Face for JavaScript errors."
1077 (defface js2-jsdoc-tag-face
1078 '((t :foreground "SlateGray"))
1079 "Face used to highlight @whatever tags in jsdoc comments."
1082 (defface js2-jsdoc-type-face
1083 '((t :foreground "SteelBlue"))
1084 "Face used to highlight {FooBar} types in jsdoc comments."
1087 (defface js2-jsdoc-value-face
1088 '((t :foreground "PeachPuff3"))
1089 "Face used to highlight tag values in jsdoc comments."
1092 (defface js2-function-param-face
1093 '((t :foreground "SeaGreen"))
1094 "Face used to highlight function parameters in javascript."
1097 (defface js2-instance-member-face
1098 '((t :foreground "DarkOrchid"))
1099 "Face used to highlight instance variables in javascript.
1100 Not currently used."
1103 (defface js2-private-member-face
1104 '((t :foreground "PeachPuff3"))
1105 "Face used to highlight calls to private methods in javascript.
1106 Not currently used."
1109 (defface js2-private-function-call-face
1110 '((t :foreground "goldenrod"))
1111 "Face used to highlight calls to private functions in javascript.
1112 Not currently used."
1115 (defface js2-jsdoc-html-tag-name-face
1117 '((((class color) (min-colors 88) (background light))
1118 (:foreground "rosybrown"))
1119 (((class color) (min-colors 8) (background dark))
1120 (:foreground "yellow"))
1121 (((class color) (min-colors 8) (background light))
1122 (:foreground "magenta")))
1123 '((((type tty pc) (class color) (background light))
1124 (:foreground "magenta"))
1125 (((type tty pc) (class color) (background dark))
1126 (:foreground "yellow"))
1127 (t (:foreground "RosyBrown"))))
1128 "Face used to highlight jsdoc html tag names"
1131 (defface js2-jsdoc-html-tag-delimiter-face
1133 '((((class color) (min-colors 88) (background light))
1134 (:foreground "dark khaki"))
1135 (((class color) (min-colors 8) (background dark))
1136 (:foreground "green"))
1137 (((class color) (min-colors 8) (background light))
1138 (:foreground "green")))
1139 '((((type tty pc) (class color) (background light))
1140 (:foreground "green"))
1141 (((type tty pc) (class color) (background dark))
1142 (:foreground "green"))
1143 (t (:foreground "dark khaki"))))
1144 "Face used to highlight brackets in jsdoc html tags."
1147 (defface js2-magic-paren-face
1149 "Face used to color parens that will be auto-overwritten."
1152 (defcustom js2-post-parse-callbacks nil
1153 "A list of callback functions invoked after parsing finishes.
1154 Currently, the main use for this function is to add synthetic
1155 declarations to `js2-recorded-identifiers', which see."
1159 (defface js2-external-variable-face
1160 '((t :foreground "orange"))
1161 "Face used to highlight undeclared variable identifiers.
1162 An undeclared variable is any variable not declared with var or let
1163 in the current scope or any lexically enclosing scope. If you use
1164 such a variable, then you are either expecting it to originate from
1165 another file, or you've got a potential bug."
1168 (defcustom js2-highlight-external-variables t
1169 "Non-nil to highlight undeclared variable identifiers."
1173 (defcustom js2-auto-insert-catch-block t
1174 "Non-nil to insert matching catch block on open-curly after `try'."
1178 (defvar js2-mode-map
1179 (let ((map (make-sparse-keymap))
1181 (define-key map [mouse-1] #'js2-mode-show-node)
1182 (define-key map (kbd "C-m") #'js2-enter-key)
1183 (when js2-rebind-eol-bol-keys
1184 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1185 (define-key map (kbd "C-e") #'js2-end-of-line))
1186 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1187 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1188 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1189 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1190 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1191 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1192 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1193 (define-key map (kbd "C-c C-`") #'js2-next-error)
1194 ;; also define user's preference for next-error, if available
1195 (if (setq keys (where-is-internal #'next-error))
1196 (define-key map (car keys) #'js2-next-error))
1197 (define-key map (or (car (where-is-internal #'mark-defun))
1200 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1202 #'js2-narrow-to-defun)
1203 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1204 (when js2-auto-indent-p
1206 (define-key map key #'js2-insert-and-indent))
1208 (when js2-bounce-indent-p
1209 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1211 (define-key map [menu-bar javascript]
1212 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1214 (define-key map [menu-bar javascript customize-js2-mode]
1215 '(menu-item "Customize js2-mode" js2-mode-customize
1216 :help "Customize the behavior of this mode"))
1218 (define-key map [menu-bar javascript js2-force-refresh]
1219 '(menu-item "Force buffer refresh" js2-mode-reset
1220 :help "Re-parse the buffer from scratch"))
1222 (define-key map [menu-bar javascript separator-2]
1225 (define-key map [menu-bar javascript next-error]
1226 '(menu-item "Next warning or error" js2-next-error
1227 :enabled (and js2-mode-ast
1228 (or (js2-ast-root-errors js2-mode-ast)
1229 (js2-ast-root-warnings js2-mode-ast)))
1230 :help "Move to next warning or error"))
1232 (define-key map [menu-bar javascript display-errors]
1233 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1234 :visible (not js2-mode-show-parse-errors)
1235 :help "Turn on display of warnings and errors"))
1237 (define-key map [menu-bar javascript hide-errors]
1238 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1239 :visible js2-mode-show-parse-errors
1240 :help "Turn off display of warnings and errors"))
1242 (define-key map [menu-bar javascript separator-1]
1245 (define-key map [menu-bar javascript js2-toggle-function]
1246 '(menu-item "Show/collapse element" js2-mode-toggle-element
1247 :help "Hide or show function body or comment"))
1249 (define-key map [menu-bar javascript show-comments]
1250 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1251 :visible js2-mode-comments-hidden
1252 :help "Expand all hidden block comments"))
1254 (define-key map [menu-bar javascript hide-comments]
1255 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1256 :visible (not js2-mode-comments-hidden)
1257 :help "Show block comments as /*...*/"))
1259 (define-key map [menu-bar javascript show-all-functions]
1260 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1261 :visible js2-mode-functions-hidden
1262 :help "Expand all hidden function bodies"))
1264 (define-key map [menu-bar javascript hide-all-functions]
1265 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1266 :visible (not js2-mode-functions-hidden)
1267 :help "Show {...} for all top-level function bodies"))
1270 "Keymap used in `js2-mode' buffers.")
1272 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1274 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1275 "Matches a //-comment line. Must be first non-whitespace on line.
1276 First match-group is the leading whitespace.")
1278 (defvar js2-mode-hook nil)
1280 (js2-deflocal js2-mode-ast nil "Private variable.")
1281 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1282 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1283 (js2-deflocal js2-mode-parsing nil "Private variable.")
1284 (js2-deflocal js2-mode-node-overlay nil)
1286 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1287 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1289 (js2-deflocal js2-mode-fontifications nil "Private variable")
1290 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1291 (js2-deflocal js2-imenu-recorder nil "Private variable")
1292 (js2-deflocal js2-imenu-function-map nil "Private variable")
1294 (defvar js2-paragraph-start
1295 "\\(@[a-zA-Z]+\\>\\|$\\)")
1297 ;; Note that we also set a 'c-in-sws text property in html comments,
1298 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1299 (defvar js2-syntactic-ws-start
1300 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1302 (defvar js2-syntactic-ws-end
1303 "\\s \\|[\n\r/]\\|\\s!")
1305 (defvar js2-syntactic-eol
1306 (concat "\\s *\\(/\\*[^*\n\r]*"
1307 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1309 "\\(//\\|/\\*[^*\n\r]*"
1310 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1312 "Copied from `java-mode'. Needed for some cc-engine functions.")
1314 (defvar js2-comment-prefix-regexp
1317 (defvar js2-comment-start-skip
1318 "\\(//+\\|/\\*+\\)\\s *")
1320 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1321 "Non-nil to emit status messages during parsing.")
1323 (defvar js2-mode-functions-hidden nil "private variable")
1324 (defvar js2-mode-comments-hidden nil "private variable")
1326 (defvar js2-mode-syntax-table
1327 (let ((table (make-syntax-table)))
1328 (c-populate-syntax-table table)
1330 "Syntax table used in js2-mode buffers.")
1332 (defvar js2-mode-abbrev-table nil
1333 "Abbrev table in use in `js2-mode' buffers.")
1334 (define-abbrev-table 'js2-mode-abbrev-table ())
1336 (defvar js2-mode-pending-parse-callbacks nil
1337 "List of functions waiting to be notified that parse is finished.")
1339 (defvar js2-mode-last-indented-line -1)
1341 ;;; Localizable error and warning messages
1343 ;; Messages are copied from Rhino's Messages.properties.
1344 ;; Many of the Java-specific messages have been elided.
1345 ;; Add any js2-specific ones at the end, so we can keep
1346 ;; this file synced with changes to Rhino's.
1348 (defvar js2-message-table
1349 (make-hash-table :test 'equal :size 250)
1350 "Contains localized messages for js2-mode.")
1352 ;; TODO(stevey): construct this table at compile-time.
1353 (defmacro js2-msg (key &rest strings)
1354 `(puthash ,key (funcall #'concat ,@strings)
1357 (defun js2-get-msg (msg-key)
1358 "Look up a localized message.
1359 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1360 the correct number of ARGS must be provided."
1361 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1362 (args (if (listp msg-key) (cdr msg-key)))
1363 (msg (gethash key js2-message-table)))
1365 (apply #'format msg args)
1366 key))) ; default to showing the key
1368 (js2-msg "msg.dup.parms"
1369 "Duplicate parameter name '%s'.")
1371 (js2-msg "msg.too.big.jump"
1372 "Program too complex: jump offset too big.")
1374 (js2-msg "msg.too.big.index"
1375 "Program too complex: internal index exceeds 64K limit.")
1377 (js2-msg "msg.while.compiling.fn"
1378 "Encountered code generation error while compiling function '%s': %s")
1380 (js2-msg "msg.while.compiling.script"
1381 "Encountered code generation error while compiling script: %s")
1384 (js2-msg "msg.ctor.not.found"
1385 "Constructor for '%s' not found.")
1387 (js2-msg "msg.not.ctor"
1388 "'%s' is not a constructor.")
1391 (js2-msg "msg.varargs.ctor"
1392 "Method or constructor '%s' must be static "
1393 "with the signature (Context cx, Object[] args, "
1394 "Function ctorObj, boolean inNewExpr) "
1395 "to define a variable arguments constructor.")
1397 (js2-msg "msg.varargs.fun"
1398 "Method '%s' must be static with the signature "
1399 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1400 "to define a variable arguments function.")
1402 (js2-msg "msg.incompat.call"
1403 "Method '%s' called on incompatible object.")
1405 (js2-msg "msg.bad.parms"
1406 "Unsupported parameter type '%s' in method '%s'.")
1408 (js2-msg "msg.bad.method.return"
1409 "Unsupported return type '%s' in method '%s'.")
1411 (js2-msg "msg.bad.ctor.return"
1412 "Construction of objects of type '%s' is not supported.")
1414 (js2-msg "msg.no.overload"
1415 "Method '%s' occurs multiple times in class '%s'.")
1417 (js2-msg "msg.method.not.found"
1418 "Method '%s' not found in '%s'.")
1422 (js2-msg "msg.bad.for.in.lhs"
1423 "Invalid left-hand side of for..in loop.")
1425 (js2-msg "msg.mult.index"
1426 "Only one variable allowed in for..in loop.")
1428 (js2-msg "msg.bad.for.in.destruct"
1429 "Left hand side of for..in loop must be an array of "
1430 "length 2 to accept key/value pair.")
1432 (js2-msg "msg.cant.convert"
1433 "Can't convert to type '%s'.")
1435 (js2-msg "msg.bad.assign.left"
1436 "Invalid assignment left-hand side.")
1438 (js2-msg "msg.bad.decr"
1439 "Invalid decerement operand.")
1441 (js2-msg "msg.bad.incr"
1442 "Invalid increment operand.")
1444 (js2-msg "msg.bad.yield"
1445 "yield must be in a function.")
1447 (js2-msg "msg.yield.parenthesized"
1448 "yield expression must be parenthesized.")
1451 (js2-msg "msg.cant.call.indirect"
1452 "Function '%s' must be called directly, and not by way of a "
1453 "function of another name.")
1455 (js2-msg "msg.eval.nonstring"
1456 "Calling eval() with anything other than a primitive "
1457 "string value will simply return the value. "
1458 "Is this what you intended?")
1460 (js2-msg "msg.eval.nonstring.strict"
1461 "Calling eval() with anything other than a primitive "
1462 "string value is not allowed in strict mode.")
1464 (js2-msg "msg.bad.destruct.op"
1465 "Invalid destructuring assignment operator")
1468 (js2-msg "msg.only.from.new"
1469 "'%s' may only be invoked from a `new' expression.")
1471 (js2-msg "msg.deprec.ctor"
1472 "The '%s' constructor is deprecated.")
1475 (js2-msg "msg.no.function.ref.found"
1476 "no source found to decompile function reference %s")
1478 (js2-msg "msg.arg.isnt.array"
1479 "second argument to Function.prototype.apply must be an array")
1482 (js2-msg "msg.bad.esc.mask"
1483 "invalid string escape mask")
1486 (js2-msg "msg.bad.quant"
1487 "Invalid quantifier %s")
1489 (js2-msg "msg.overlarge.backref"
1490 "Overly large back reference %s")
1492 (js2-msg "msg.overlarge.min"
1493 "Overly large minimum %s")
1495 (js2-msg "msg.overlarge.max"
1496 "Overly large maximum %s")
1498 (js2-msg "msg.zero.quant"
1499 "Zero quantifier %s")
1501 (js2-msg "msg.max.lt.min"
1502 "Maximum %s less than minimum")
1504 (js2-msg "msg.unterm.quant"
1505 "Unterminated quantifier %s")
1507 (js2-msg "msg.unterm.paren"
1508 "Unterminated parenthetical %s")
1510 (js2-msg "msg.unterm.class"
1511 "Unterminated character class %s")
1513 (js2-msg "msg.bad.range"
1514 "Invalid range in character class.")
1516 (js2-msg "msg.trail.backslash"
1517 "Trailing \\ in regular expression.")
1519 (js2-msg "msg.re.unmatched.right.paren"
1520 "unmatched ) in regular expression.")
1522 (js2-msg "msg.no.regexp"
1523 "Regular expressions are not available.")
1525 (js2-msg "msg.bad.backref"
1526 "back-reference exceeds number of capturing parentheses.")
1528 (js2-msg "msg.bad.regexp.compile"
1529 "Only one argument may be specified if the first "
1530 "argument to RegExp.prototype.compile is a RegExp object.")
1533 (js2-msg "msg.got.syntax.errors"
1534 "Compilation produced %s syntax errors.")
1536 (js2-msg "msg.var.redecl"
1537 "TypeError: redeclaration of var %s.")
1539 (js2-msg "msg.const.redecl"
1540 "TypeError: redeclaration of const %s.")
1542 (js2-msg "msg.let.redecl"
1543 "TypeError: redeclaration of variable %s.")
1545 (js2-msg "msg.parm.redecl"
1546 "TypeError: redeclaration of formal parameter %s.")
1548 (js2-msg "msg.fn.redecl"
1549 "TypeError: redeclaration of function %s.")
1551 (js2-msg "msg.let.decl.not.in.block"
1552 "SyntaxError: let declaration not directly within block")
1555 (js2-msg "msg.dup.label"
1558 (js2-msg "msg.undef.label"
1561 (js2-msg "msg.bad.break"
1562 "unlabelled break must be inside loop or switch")
1564 (js2-msg "msg.continue.outside"
1565 "continue must be inside loop")
1567 (js2-msg "msg.continue.nonloop"
1568 "continue can only use labels of iteration statements")
1570 (js2-msg "msg.bad.throw.eol"
1571 "Line terminator is not allowed between the throw "
1572 "keyword and throw expression.")
1574 (js2-msg "msg.no.paren.parms"
1575 "missing ( before function parameters.")
1577 (js2-msg "msg.no.parm"
1578 "missing formal parameter")
1580 (js2-msg "msg.no.paren.after.parms"
1581 "missing ) after formal parameters")
1583 (js2-msg "msg.no.brace.body"
1584 "missing '{' before function body")
1586 (js2-msg "msg.no.brace.after.body"
1587 "missing } after function body")
1589 (js2-msg "msg.no.paren.cond"
1590 "missing ( before condition")
1592 (js2-msg "msg.no.paren.after.cond"
1593 "missing ) after condition")
1595 (js2-msg "msg.no.semi.stmt"
1596 "missing ; before statement")
1598 (js2-msg "msg.missing.semi"
1599 "missing ; after statement")
1601 (js2-msg "msg.no.name.after.dot"
1602 "missing name after . operator")
1604 (js2-msg "msg.no.name.after.coloncolon"
1605 "missing name after :: operator")
1607 (js2-msg "msg.no.name.after.dotdot"
1608 "missing name after .. operator")
1610 (js2-msg "msg.no.name.after.xmlAttr"
1611 "missing name after .@")
1613 (js2-msg "msg.no.bracket.index"
1614 "missing ] in index expression")
1616 (js2-msg "msg.no.paren.switch"
1617 "missing ( before switch expression")
1619 (js2-msg "msg.no.paren.after.switch"
1620 "missing ) after switch expression")
1622 (js2-msg "msg.no.brace.switch"
1623 "missing '{' before switch body")
1625 (js2-msg "msg.bad.switch"
1626 "invalid switch statement")
1628 (js2-msg "msg.no.colon.case"
1629 "missing : after case expression")
1631 (js2-msg "msg.double.switch.default"
1632 "double default label in the switch statement")
1634 (js2-msg "msg.no.while.do"
1635 "missing while after do-loop body")
1637 (js2-msg "msg.no.paren.for"
1638 "missing ( after for")
1640 (js2-msg "msg.no.semi.for"
1641 "missing ; after for-loop initializer")
1643 (js2-msg "msg.no.semi.for.cond"
1644 "missing ; after for-loop condition")
1646 (js2-msg "msg.in.after.for.name"
1647 "missing in after for")
1649 (js2-msg "msg.no.paren.for.ctrl"
1650 "missing ) after for-loop control")
1652 (js2-msg "msg.no.paren.with"
1653 "missing ( before with-statement object")
1655 (js2-msg "msg.no.paren.after.with"
1656 "missing ) after with-statement object")
1658 (js2-msg "msg.no.paren.after.let"
1659 "missing ( after let")
1661 (js2-msg "msg.no.paren.let"
1662 "missing ) after variable list")
1664 (js2-msg "msg.no.curly.let"
1665 "missing } after let statement")
1667 (js2-msg "msg.bad.return"
1670 (js2-msg "msg.no.brace.block"
1671 "missing } in compound statement")
1673 (js2-msg "msg.bad.label"
1676 (js2-msg "msg.bad.var"
1677 "missing variable name")
1679 (js2-msg "msg.bad.var.init"
1680 "invalid variable initialization")
1682 (js2-msg "msg.no.colon.cond"
1683 "missing : in conditional expression")
1685 (js2-msg "msg.no.paren.arg"
1686 "missing ) after argument list")
1688 (js2-msg "msg.no.bracket.arg"
1689 "missing ] after element list")
1691 (js2-msg "msg.bad.prop"
1692 "invalid property id")
1694 (js2-msg "msg.no.colon.prop"
1695 "missing : after property id")
1697 (js2-msg "msg.no.brace.prop"
1698 "missing } after property list")
1700 (js2-msg "msg.no.paren"
1701 "missing ) in parenthetical")
1703 (js2-msg "msg.reserved.id"
1704 "identifier is a reserved word")
1706 (js2-msg "msg.no.paren.catch"
1707 "missing ( before catch-block condition")
1709 (js2-msg "msg.bad.catchcond"
1710 "invalid catch block condition")
1712 (js2-msg "msg.catch.unreachable"
1713 "any catch clauses following an unqualified catch are unreachable")
1715 (js2-msg "msg.no.brace.try"
1716 "missing '{' before try block")
1718 (js2-msg "msg.no.brace.catchblock"
1719 "missing '{' before catch-block body")
1721 (js2-msg "msg.try.no.catchfinally"
1722 "'try' without 'catch' or 'finally'")
1724 (js2-msg "msg.no.return.value"
1725 "function %s does not always return a value")
1727 (js2-msg "msg.anon.no.return.value"
1728 "anonymous function does not always return a value")
1730 (js2-msg "msg.return.inconsistent"
1731 "return statement is inconsistent with previous usage")
1733 (js2-msg "msg.generator.returns"
1734 "TypeError: generator function '%s' returns a value")
1736 (js2-msg "msg.anon.generator.returns"
1737 "TypeError: anonymous generator function returns a value")
1739 (js2-msg "msg.syntax"
1742 (js2-msg "msg.unexpected.eof"
1743 "Unexpected end of file")
1745 (js2-msg "msg.XML.bad.form"
1746 "illegally formed XML syntax")
1748 (js2-msg "msg.XML.not.available"
1749 "XML runtime not available")
1751 (js2-msg "msg.too.deep.parser.recursion"
1752 "Too deep recursion while parsing")
1754 (js2-msg "msg.no.side.effects"
1755 "Code has no side effects")
1757 (js2-msg "msg.extra.trailing.comma"
1758 "Trailing comma is not legal in an ECMA-262 object initializer")
1760 (js2-msg "msg.array.trailing.comma"
1761 "Trailing comma yields different behavior across browsers")
1763 (js2-msg "msg.equal.as.assign"
1764 (concat "Test for equality (==) mistyped as assignment (=)?"
1765 " (parenthesize to suppress warning)"))
1767 (js2-msg "msg.var.hides.arg"
1768 "Variable %s hides argument")
1770 (js2-msg "msg.destruct.assign.no.init"
1771 "Missing = in destructuring declaration")
1774 (js2-msg "msg.no.properties"
1775 "%s has no properties.")
1777 (js2-msg "msg.invalid.iterator"
1778 "Invalid iterator value")
1780 (js2-msg "msg.iterator.primitive"
1781 "__iterator__ returned a primitive value")
1783 (js2-msg "msg.assn.create.strict"
1784 "Assignment to undeclared variable %s")
1786 (js2-msg "msg.ref.undefined.prop"
1787 "Reference to undefined property '%s'")
1789 (js2-msg "msg.prop.not.found"
1790 "Property %s not found.")
1792 (js2-msg "msg.invalid.type"
1793 "Invalid JavaScript value of type %s")
1795 (js2-msg "msg.primitive.expected"
1796 "Primitive type expected (had %s instead)")
1798 (js2-msg "msg.namespace.expected"
1799 "Namespace object expected to left of :: (found %s instead)")
1801 (js2-msg "msg.null.to.object"
1802 "Cannot convert null to an object.")
1804 (js2-msg "msg.undef.to.object"
1805 "Cannot convert undefined to an object.")
1807 (js2-msg "msg.cyclic.value"
1808 "Cyclic %s value not allowed.")
1810 (js2-msg "msg.is.not.defined"
1811 "'%s' is not defined.")
1813 (js2-msg "msg.undef.prop.read"
1814 "Cannot read property '%s' from %s")
1816 (js2-msg "msg.undef.prop.write"
1817 "Cannot set property '%s' of %s to '%s'")
1819 (js2-msg "msg.undef.prop.delete"
1820 "Cannot delete property '%s' of %s")
1822 (js2-msg "msg.undef.method.call"
1823 "Cannot call method '%s' of %s")
1825 (js2-msg "msg.undef.with"
1826 "Cannot apply 'with' to %s")
1828 (js2-msg "msg.isnt.function"
1829 "%s is not a function, it is %s.")
1831 (js2-msg "msg.isnt.function.in"
1832 "Cannot call property %s in object %s. "
1833 "It is not a function, it is '%s'.")
1835 (js2-msg "msg.function.not.found"
1836 "Cannot find function %s.")
1838 (js2-msg "msg.function.not.found.in"
1839 "Cannot find function %s in object %s.")
1841 (js2-msg "msg.isnt.xml.object"
1842 "%s is not an xml object.")
1844 (js2-msg "msg.no.ref.to.get"
1845 "%s is not a reference to read reference value.")
1847 (js2-msg "msg.no.ref.to.set"
1848 "%s is not a reference to set reference value to %s.")
1850 (js2-msg "msg.no.ref.from.function"
1851 "Function %s can not be used as the left-hand "
1852 "side of assignment or as an operand of ++ or -- operator.")
1854 (js2-msg "msg.bad.default.value"
1855 "Object's getDefaultValue() method returned an object.")
1857 (js2-msg "msg.instanceof.not.object"
1858 "Can't use instanceof on a non-object.")
1860 (js2-msg "msg.instanceof.bad.prototype"
1861 "'prototype' property of %s is not an object.")
1863 (js2-msg "msg.bad.radix"
1864 "illegal radix %s.")
1867 (js2-msg "msg.default.value"
1868 "Cannot find default value for object.")
1870 (js2-msg "msg.zero.arg.ctor"
1871 "Cannot load class '%s' which has no zero-parameter constructor.")
1873 (js2-msg "msg.ctor.multiple.parms"
1874 "Can't define constructor or class %s since more than "
1875 "one constructor has multiple parameters.")
1877 (js2-msg "msg.extend.scriptable"
1878 "%s must extend ScriptableObject in order to define property %s.")
1880 (js2-msg "msg.bad.getter.parms"
1881 "In order to define a property, getter %s must have zero "
1882 "parameters or a single ScriptableObject parameter.")
1884 (js2-msg "msg.obj.getter.parms"
1885 "Expected static or delegated getter %s to take "
1886 "a ScriptableObject parameter.")
1888 (js2-msg "msg.getter.static"
1889 "Getter and setter must both be static or neither be static.")
1891 (js2-msg "msg.setter.return"
1892 "Setter must have void return type: %s")
1894 (js2-msg "msg.setter2.parms"
1895 "Two-parameter setter must take a ScriptableObject as "
1896 "its first parameter.")
1898 (js2-msg "msg.setter1.parms"
1899 "Expected single parameter setter for %s")
1901 (js2-msg "msg.setter2.expected"
1902 "Expected static or delegated setter %s to take two parameters.")
1904 (js2-msg "msg.setter.parms"
1905 "Expected either one or two parameters for setter.")
1907 (js2-msg "msg.setter.bad.type"
1908 "Unsupported parameter type '%s' in setter '%s'.")
1910 (js2-msg "msg.add.sealed"
1911 "Cannot add a property to a sealed object: %s.")
1913 (js2-msg "msg.remove.sealed"
1914 "Cannot remove a property from a sealed object: %s.")
1916 (js2-msg "msg.modify.sealed"
1917 "Cannot modify a property of a sealed object: %s.")
1919 (js2-msg "msg.modify.readonly"
1920 "Cannot modify readonly property: %s.")
1923 (js2-msg "msg.missing.exponent"
1926 (js2-msg "msg.caught.nfe"
1927 "number format error")
1929 (js2-msg "msg.unterminated.string.lit"
1930 "unterminated string literal")
1932 (js2-msg "msg.unterminated.comment"
1933 "unterminated comment")
1935 (js2-msg "msg.unterminated.re.lit"
1936 "unterminated regular expression literal")
1938 (js2-msg "msg.invalid.re.flag"
1939 "invalid flag after regular expression")
1941 (js2-msg "msg.no.re.input.for"
1944 (js2-msg "msg.illegal.character"
1945 "illegal character")
1947 (js2-msg "msg.invalid.escape"
1948 "invalid Unicode escape sequence")
1950 (js2-msg "msg.bad.namespace"
1951 "not a valid default namespace statement. "
1952 "Syntax is: default xml namespace = EXPRESSION;")
1954 ;; TokensStream warnings
1955 (js2-msg "msg.bad.octal.literal"
1956 "illegal octal literal digit %s; "
1957 "interpreting it as a decimal digit")
1959 (js2-msg "msg.reserved.keyword"
1960 "illegal usage of future reserved keyword %s; "
1961 "interpreting it as ordinary identifier")
1963 (js2-msg "msg.script.is.not.constructor"
1964 "Script objects are not constructors.")
1967 (js2-msg "msg.arraylength.bad"
1968 "Inappropriate array length.")
1971 (js2-msg "msg.arraylength.too.big"
1972 "Array length %s exceeds supported capacity limit.")
1975 (js2-msg "msg.bad.uri"
1976 "Malformed URI sequence.")
1979 (js2-msg "msg.bad.precision"
1980 "Precision %s out of range.")
1983 (js2-msg "msg.send.newborn"
1984 "Attempt to send value to newborn generator")
1986 (js2-msg "msg.already.exec.gen"
1987 "Already executing generator")
1989 (js2-msg "msg.StopIteration.invalid"
1990 "StopIteration may not be changed to an arbitrary object.")
1993 (js2-msg "msg.yield.closing"
1994 "Yield from closing generator")
1998 (defun js2-delete-if (predicate list)
1999 "Remove all items satisfying PREDICATE in LIST."
2000 (loop for item in list
2001 if (not (funcall predicate item))
2004 (defun js2-position (element list)
2005 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2006 Returns nil if element is not found in the list."
2009 (while (and list (not found))
2010 (if (eq element (car list))
2012 (setq count (1+ count)
2016 (defun js2-find-if (predicate list)
2017 "Find first item satisfying PREDICATE in LIST."
2019 (while (and list (not result))
2020 (if (funcall predicate (car list))
2021 (setq result (car list)))
2022 (setq list (cdr list)))
2025 (defmacro js2-time (form)
2026 "Evaluate FORM, discard result, and return elapsed time in sec"
2028 (let ((beg (make-symbol "--js2-time-beg--"))
2029 (delta (make-symbol "--js2-time-end--")))
2030 `(let ((,beg (current-time))
2033 (/ (truncate (* (- (float-time (current-time))
2038 (defsubst js2-same-line (pos)
2039 "Return t if POS is on the same line as current point."
2040 (and (>= pos (point-at-bol))
2041 (<= pos (point-at-eol))))
2043 (defsubst js2-same-line-2 (p1 p2)
2044 "Return t if p1 is on the same line as p2."
2047 (js2-same-line p2)))
2049 (defun js2-code-bug ()
2050 "Signal an error when we encounter an unexpected code path."
2051 (error "failed assertion"))
2053 (defsubst js2-record-text-property (beg end prop value)
2054 "Record a text property to set when parsing finishes."
2055 (push (list beg end prop value) js2-mode-deferred-properties))
2057 ;; I'd like to associate errors with nodes, but for now the
2058 ;; easiest thing to do is get the context info from the last token.
2059 (defsubst js2-record-parse-error (msg &optional arg pos len)
2060 (push (list (list msg arg)
2061 (or pos js2-token-beg)
2062 (or len (- js2-token-end js2-token-beg)))
2065 (defsubst js2-report-error (msg &optional msg-arg pos len)
2066 "Signal a syntax error or record a parse error."
2067 (if js2-recover-from-parse-errors
2068 (js2-record-parse-error msg msg-arg pos len)
2069 (signal 'js2-syntax-error
2073 (goto-char js2-ts-cursor)
2077 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2078 (if js2-compiler-report-warning-as-error
2079 (js2-report-error msg msg-arg pos len)
2080 (push (list (list msg msg-arg)
2081 (or pos js2-token-beg)
2082 (or len (- js2-token-end js2-token-beg)))
2083 js2-parsed-warnings)))
2085 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2086 (if js2-compiler-strict-mode
2087 (js2-report-warning msg-id msg-arg beg
2088 (and beg end (- end beg)))))
2090 (put 'js2-syntax-error 'error-conditions
2091 '(error syntax-error js2-syntax-error))
2092 (put 'js2-syntax-error 'error-message "Syntax error")
2094 (put 'js2-parse-error 'error-conditions
2095 '(error parse-error js2-parse-error))
2096 (put 'js2-parse-error 'error-message "Parse error")
2098 (defmacro js2-clear-flag (flags flag)
2099 `(setq ,flags (logand ,flags (lognot ,flag))))
2101 (defmacro js2-set-flag (flags flag)
2102 "Logical-or FLAG into FLAGS."
2103 `(setq ,flags (logior ,flags ,flag)))
2105 (defsubst js2-flag-set-p (flags flag)
2106 (/= 0 (logand flags flag)))
2108 (defsubst js2-flag-not-set-p (flags flag)
2109 (zerop (logand flags flag)))
2111 ;; Stolen shamelessly from James Clark's nxml-mode.
2112 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2113 "Evaluate BODY without any text property changes modifying the buffer.
2114 Any text properties changes happen as usual but the changes are not treated as
2115 modifications to the buffer."
2116 (declare (indent 0) (debug t))
2117 (let ((modified (make-symbol "modified")))
2118 `(let ((,modified (buffer-modified-p))
2119 (inhibit-read-only t)
2120 (inhibit-modification-hooks t)
2121 (buffer-undo-list t)
2122 (deactivate-mark nil)
2123 ;; Apparently these avoid file locking problems.
2124 (buffer-file-name nil)
2125 (buffer-file-truename nil))
2129 (restore-buffer-modified-p nil))))))
2131 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2132 "Evaluate BODY with the _ character set to be word-syntax."
2133 (declare (indent 0) (debug t))
2134 (let ((old-syntax (make-symbol "old-syntax")))
2135 `(let ((,old-syntax (string (char-syntax ?_))))
2138 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2140 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2142 (defsubst js2-char-uppercase-p (c)
2143 "Return t if C is an uppercase character.
2144 Handles unicode and latin chars properly."
2145 (/= c (downcase c)))
2147 (defsubst js2-char-lowercase-p (c)
2148 "Return t if C is an uppercase character.
2149 Handles unicode and latin chars properly."
2152 ;;; AST struct and function definitions
2154 ;; flags for ast node property 'member-type (used for e4x operators)
2155 (defvar js2-property-flag #x1 "property access: element is valid name")
2156 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2157 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2159 (defsubst js2-relpos (pos anchor)
2160 "Convert POS to be relative to ANCHOR.
2161 If POS is nil, returns nil."
2162 (and pos (- pos anchor)))
2164 (defsubst js2-make-pad (indent)
2167 (make-string (* indent js2-basic-offset) ? )))
2169 (defsubst js2-visit-ast (node callback)
2170 "Visit every node in ast NODE with visitor CALLBACK.
2172 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2173 called twice: once to visit the node, and again after all the node's
2174 children have been processed. The END-P argument is nil on the first
2175 call and non-nil on the second call. The return value of the callback
2176 affects the traversal: if non-nil, the children of NODE are processed.
2177 If the callback returns nil, or if the node has no children, then the
2178 callback is called immediately with a non-nil END-P argument.
2180 The node traversal is approximately lexical-order, although there
2181 are currently no guarantees around this."
2183 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2185 (when (funcall callback node nil)
2188 ((eq vfunc 'js2-visit-none)
2189 nil) ; don't even bother calling it
2190 ;; Each AST node type has to define a `js2-visitor' function
2191 ;; that takes a node and a callback, and calls `js2-visit-ast'
2192 ;; on each child of the node.
2194 (funcall vfunc node callback))
2196 (error "%s does not define a visitor-traversal function"
2198 ;; call the end-visit
2199 (funcall callback node t))))
2201 (defstruct (js2-node
2202 (:constructor nil)) ; abstract
2203 "Base AST node type."
2204 (type -1) ; token type
2205 (pos -1) ; start position of this AST node in parsed input
2206 (len 1) ; num characters spanned by the node
2207 props ; optional node property list (an alist)
2208 parent) ; link to parent node; null for root
2210 (defsubst js2-node-get-prop (node prop &optional default)
2211 (or (cadr (assoc prop (js2-node-props node))) default))
2213 (defsubst js2-node-set-prop (node prop value)
2214 (setf (js2-node-props node)
2215 (cons (list prop value) (js2-node-props node))))
2217 (defsubst js2-fixup-starts (n nodes)
2218 "Adjust the start positions of NODES to be relative to N.
2219 Any node in the list may be nil, for convenience."
2220 (dolist (node nodes)
2222 (setf (js2-node-pos node) (- (js2-node-pos node)
2223 (js2-node-pos n))))))
2225 (defsubst js2-node-add-children (parent &rest nodes)
2226 "Set parent node of NODES to PARENT, and return PARENT.
2227 Does nothing if we're not recording parent links.
2228 If any given node in NODES is nil, doesn't record that link."
2229 (js2-fixup-starts parent nodes)
2230 (dolist (node nodes)
2232 (setf (js2-node-parent node) parent))))
2234 ;; Non-recursive since it's called a frightening number of times.
2235 (defsubst js2-node-abs-pos (n)
2236 (let ((pos (js2-node-pos n)))
2237 (while (setq n (js2-node-parent n))
2238 (setq pos (+ pos (js2-node-pos n))))
2241 (defsubst js2-node-abs-end (n)
2242 "Return absolute buffer position of end of N."
2243 (+ (js2-node-abs-pos n) (js2-node-len n)))
2245 ;; It's important to make sure block nodes have a lisp list for the
2246 ;; child nodes, to limit printing recursion depth in an AST that
2247 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2248 ;; a sufficiently large vector tree.
2250 (defstruct (js2-block-node
2253 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2258 "A block of statements."
2259 kids) ; a lisp list of the child statement nodes
2261 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2262 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2264 (defsubst js2-visit-block (ast callback)
2265 "Visit the `js2-block-node' children of AST."
2266 (dolist (kid (js2-block-node-kids ast))
2267 (js2-visit-ast kid callback)))
2269 (defun js2-print-block (n i)
2270 (let ((pad (js2-make-pad i)))
2272 (dolist (kid (js2-block-node-kids n))
2273 (js2-print-ast kid (1+ i)))
2276 (defstruct (js2-scope
2277 (:include js2-block-node)
2279 (:constructor make-js2-scope (&key (type js2-BLOCK)
2283 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2284 ;; I don't have one of those handy, so I'll use an alist for now.
2285 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2286 ;; and is much lighter-weight to construct (both CPU and mem).
2287 ;; The keys are interned strings (symbols) for faster lookup.
2288 ;; Should switch to hybrid alist/hashtable eventually.
2289 symbol-table ; an alist of (symbol . js2-symbol)
2290 parent-scope ; a `js2-scope'
2291 top) ; top-level `js2-scope' (script/function)
2293 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2294 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2296 (defun js2-scope-set-parent-scope (scope parent)
2297 (setf (js2-scope-parent-scope scope) parent
2298 (js2-scope-top scope) (if (null parent)
2300 (js2-scope-top parent))))
2302 (defun js2-node-get-enclosing-scope (node)
2303 "Return the innermost `js2-scope' node surrounding NODE.
2304 Returns nil if there is no enclosing scope node."
2305 (let ((parent (js2-node-parent node)))
2306 (while (not (js2-scope-p parent))
2307 (setq parent (js2-node-parent parent)))
2310 (defun js2-get-defining-scope (scope name)
2311 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2312 Returns `js2-scope' in which NAME is defined, or nil if not found."
2313 (let ((sym (if (symbolp name)
2319 (while (and scope continue)
2320 (if (and (setq table (js2-scope-symbol-table scope))
2324 (setq scope (js2-scope-parent-scope scope))))
2327 (defsubst js2-scope-get-symbol (scope name)
2328 "Return symbol table entry for NAME in SCOPE.
2329 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2330 (and (js2-scope-symbol-table scope)
2331 (cdr (assq (if (symbolp name)
2334 (js2-scope-symbol-table scope)))))
2336 (defsubst js2-scope-put-symbol (scope name symbol)
2337 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2338 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2339 (let* ((table (js2-scope-symbol-table scope))
2340 (sym (if (symbolp name) name (intern name)))
2341 (entry (assq sym table)))
2343 (setcdr entry symbol)
2344 (push (cons sym symbol)
2345 (js2-scope-symbol-table scope)))))
2347 (defstruct (js2-symbol
2349 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2350 "A symbol table entry."
2351 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2352 ;; js2-LET, or js2-CONST
2355 ast-node) ; a `js2-node'
2357 (defstruct (js2-error-node
2359 (:constructor nil) ; silence emacs21 byte-compiler
2360 (:constructor make-js2-error-node (&key (type js2-ERROR)
2363 "AST node representing a parse error.")
2365 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2366 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2368 (defstruct (js2-script-node
2369 (:include js2-scope)
2371 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2376 functions ; lisp list of nested functions
2377 regexps ; lisp list of (string . flags)
2378 symbols ; alist (every symbol gets unique index)
2380 var-names ; vector of string names
2381 consts ; bool-vector matching var-decls
2382 (temp-number 0)) ; for generating temp variables
2384 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2385 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2387 (defun js2-print-script (node indent)
2388 (dolist (kid (js2-block-node-kids node))
2389 (js2-print-ast kid indent)))
2391 (defstruct (js2-ast-root
2392 (:include js2-script-node)
2394 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2398 "The root node of a js2 AST."
2399 buffer ; the source buffer from which the code was parsed
2400 comments ; a lisp list of comments, ordered by start position
2401 errors ; a lisp list of errors found during parsing
2402 warnings ; a lisp list of warnings found during parsing
2403 node-count) ; number of nodes in the tree, including the root
2405 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2406 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2408 (defun js2-visit-ast-root (ast callback)
2409 (dolist (kid (js2-ast-root-kids ast))
2410 (js2-visit-ast kid callback))
2411 (dolist (comment (js2-ast-root-comments ast))
2412 (js2-visit-ast comment callback)))
2414 (defstruct (js2-comment-node
2417 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2420 (format js2-ts-comment-type))))
2421 format) ; 'line, 'block, 'jsdoc or 'html
2423 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2424 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2426 (defun js2-print-comment (n i)
2427 ;; We really ought to link end-of-line comments to their nodes.
2428 ;; Or maybe we could add a new comment type, 'endline.
2429 (insert (js2-make-pad i)
2430 (js2-node-string n)))
2432 (defstruct (js2-expr-stmt-node
2435 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2439 "An expression statement."
2442 (defsubst js2-expr-stmt-node-set-has-result (node)
2443 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2444 (setf (js2-node-type node) js2-EXPR_RESULT))
2446 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2447 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2449 (defun js2-visit-expr-stmt-node (n v)
2450 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2452 (defun js2-print-expr-stmt-node (n indent)
2453 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2456 (defstruct (js2-loop-node
2457 (:include js2-scope)
2459 "Abstract supertype of loop nodes."
2460 body ; a `js2-block-node'
2461 lp ; position of left-paren, nil if omitted
2462 rp) ; position of right-paren, nil if omitted
2464 (defstruct (js2-do-node
2465 (:include js2-loop-node)
2467 (:constructor make-js2-do-node (&key (type js2-DO)
2475 "AST node for do-loop."
2476 condition ; while (expression)
2477 while-pos) ; buffer position of 'while' keyword
2479 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2480 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2482 (defun js2-visit-do-node (n v)
2483 (js2-visit-ast (js2-do-node-body n) v)
2484 (js2-visit-ast (js2-do-node-condition n) v))
2486 (defun js2-print-do-node (n i)
2487 (let ((pad (js2-make-pad i)))
2488 (insert pad "do {\n")
2489 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2490 (js2-print-ast kid (1+ i)))
2491 (insert pad "} while (")
2492 (js2-print-ast (js2-do-node-condition n) 0)
2495 (defstruct (js2-while-node
2496 (:include js2-loop-node)
2498 (:constructor make-js2-while-node (&key (type js2-WHILE)
2505 "AST node for while-loop."
2506 condition) ; while-condition
2508 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2509 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2511 (defun js2-visit-while-node (n v)
2512 (js2-visit-ast (js2-while-node-condition n) v)
2513 (js2-visit-ast (js2-while-node-body n) v))
2515 (defun js2-print-while-node (n i)
2516 (let ((pad (js2-make-pad i)))
2517 (insert pad "while (")
2518 (js2-print-ast (js2-while-node-condition n) 0)
2520 (js2-print-body (js2-while-node-body n) (1+ i))
2521 (insert pad "}\n")))
2523 (defstruct (js2-for-node
2524 (:include js2-loop-node)
2526 (:constructor make-js2-for-node (&key (type js2-FOR)
2535 "AST node for a C-style for-loop."
2536 init ; initialization expression
2537 condition ; loop condition
2538 update) ; update clause
2540 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2541 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2543 (defun js2-visit-for-node (n v)
2544 (js2-visit-ast (js2-for-node-init n) v)
2545 (js2-visit-ast (js2-for-node-condition n) v)
2546 (js2-visit-ast (js2-for-node-update n) v)
2547 (js2-visit-ast (js2-for-node-body n) v))
2549 (defun js2-print-for-node (n i)
2550 (let ((pad (js2-make-pad i)))
2551 (insert pad "for (")
2552 (js2-print-ast (js2-for-node-init n) 0)
2554 (js2-print-ast (js2-for-node-condition n) 0)
2556 (js2-print-ast (js2-for-node-update n) 0)
2558 (js2-print-body (js2-for-node-body n) (1+ i))
2559 (insert pad "}\n")))
2561 (defstruct (js2-for-in-node
2562 (:include js2-loop-node)
2564 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2575 "AST node for a for..in loop."
2576 iterator ; [var] foo in ...
2577 object ; object over which we're iterating
2578 in-pos ; buffer position of 'in' keyword
2579 each-pos ; buffer position of 'each' keyword, if foreach-p
2580 foreach-p) ; t if it's a for-each loop
2582 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2583 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2585 (defun js2-visit-for-in-node (n v)
2586 (js2-visit-ast (js2-for-in-node-iterator n) v)
2587 (js2-visit-ast (js2-for-in-node-object n) v)
2588 (js2-visit-ast (js2-for-in-node-body n) v))
2590 (defun js2-print-for-in-node (n i)
2591 (let ((pad (js2-make-pad i))
2592 (foreach (js2-for-in-node-foreach-p n)))
2597 (js2-print-ast (js2-for-in-node-iterator n) 0)
2599 (js2-print-ast (js2-for-in-node-object n) 0)
2601 (js2-print-body (js2-for-in-node-body n) (1+ i))
2602 (insert pad "}\n")))
2604 (defstruct (js2-return-node
2607 (:constructor make-js2-return-node (&key (type js2-RETURN)
2611 "AST node for a return statement."
2612 retval) ; expression to return, or 'undefined
2614 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2615 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2617 (defun js2-visit-return-node (n v)
2618 (js2-visit-ast (js2-return-node-retval n) v))
2620 (defun js2-print-return-node (n i)
2621 (insert (js2-make-pad i) "return")
2622 (when (js2-return-node-retval n)
2624 (js2-print-ast (js2-return-node-retval n) 0))
2627 (defstruct (js2-if-node
2630 (:constructor make-js2-if-node (&key (type js2-IF)
2639 "AST node for an if-statement."
2640 condition ; expression
2641 then-part ; statement or block
2642 else-pos ; optional buffer position of 'else' keyword
2643 else-part ; optional statement or block
2644 lp ; position of left-paren, nil if omitted
2645 rp) ; position of right-paren, nil if omitted
2647 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2648 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2650 (defun js2-visit-if-node (n v)
2651 (js2-visit-ast (js2-if-node-condition n) v)
2652 (js2-visit-ast (js2-if-node-then-part n) v)
2653 (js2-visit-ast (js2-if-node-else-part n) v))
2655 (defun js2-print-if-node (n i)
2656 (let ((pad (js2-make-pad i))
2657 (then-part (js2-if-node-then-part n))
2658 (else-part (js2-if-node-else-part n)))
2660 (js2-print-ast (js2-if-node-condition n) 0)
2662 (js2-print-body then-part (1+ i))
2667 ((js2-if-node-p else-part)
2669 (js2-print-body else-part i))
2671 (insert " else {\n")
2672 (js2-print-body else-part (1+ i))
2673 (insert pad "}\n")))))
2675 (defstruct (js2-try-node
2678 (:constructor make-js2-try-node (&key (type js2-TRY)
2684 "AST node for a try-statement."
2686 catch-clauses ; a lisp list of `js2-catch-node'
2687 finally-block) ; a `js2-finally-node'
2689 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2690 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2692 (defun js2-visit-try-node (n v)
2693 (js2-visit-ast (js2-try-node-try-block n) v)
2694 (dolist (clause (js2-try-node-catch-clauses n))
2695 (js2-visit-ast clause v))
2696 (js2-visit-ast (js2-try-node-finally-block n) v))
2698 (defun js2-print-try-node (n i)
2699 (let ((pad (js2-make-pad i))
2700 (catches (js2-try-node-catch-clauses n))
2701 (finally (js2-try-node-finally-block n)))
2702 (insert pad "try {\n")
2703 (js2-print-body (js2-try-node-try-block n) (1+ i))
2706 (dolist (catch catches)
2707 (js2-print-ast catch i)))
2709 (js2-print-ast finally i)
2712 (defstruct (js2-catch-node
2715 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2724 "AST node for a catch clause."
2725 param ; destructuring form or simple name node
2726 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2727 guard-expr ; catch condition, a `js2-node'
2728 block ; statements, a `js2-block-node'
2729 lp ; buffer position of left-paren, nil if omitted
2730 rp) ; buffer position of right-paren, nil if omitted
2732 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2733 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2735 (defun js2-visit-catch-node (n v)
2736 (js2-visit-ast (js2-catch-node-param n) v)
2737 (when (js2-catch-node-guard-kwd n)
2738 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2739 (js2-visit-ast (js2-catch-node-block n) v))
2741 (defun js2-print-catch-node (n i)
2742 (let ((pad (js2-make-pad i))
2743 (guard-kwd (js2-catch-node-guard-kwd n))
2744 (guard-expr (js2-catch-node-guard-expr n)))
2746 (js2-print-ast (js2-catch-node-param n) 0)
2749 (js2-print-ast guard-expr 0))
2751 (js2-print-body (js2-catch-node-block n) (1+ i))
2754 (defstruct (js2-finally-node
2757 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2761 "AST node for a finally clause."
2762 body) ; a `js2-node', often but not always a block node
2764 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2765 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2767 (defun js2-visit-finally-node (n v)
2768 (js2-visit-ast (js2-finally-node-body n) v))
2770 (defun js2-print-finally-node (n i)
2771 (let ((pad (js2-make-pad i)))
2772 (insert " finally {\n")
2773 (js2-print-body (js2-finally-node-body n) (1+ i))
2774 (insert pad "}\n")))
2776 (defstruct (js2-switch-node
2779 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2786 "AST node for a switch statement."
2787 discriminant ; a `js2-node' (switch expression)
2788 cases ; a lisp list of `js2-case-node'
2789 lp ; position of open-paren for discriminant, nil if omitted
2790 rp) ; position of close-paren for discriminant, nil if omitted
2792 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2793 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2795 (defun js2-visit-switch-node (n v)
2796 (js2-visit-ast (js2-switch-node-discriminant n) v)
2797 (dolist (c (js2-switch-node-cases n))
2798 (js2-visit-ast c v)))
2800 (defun js2-print-switch-node (n i)
2801 (let ((pad (js2-make-pad i))
2802 (cases (js2-switch-node-cases n)))
2803 (insert pad "switch (")
2804 (js2-print-ast (js2-switch-node-discriminant n) 0)
2806 (dolist (case cases)
2807 (js2-print-ast case i))
2808 (insert pad "}\n")))
2810 (defstruct (js2-case-node
2811 (:include js2-block-node)
2813 (:constructor make-js2-case-node (&key (type js2-CASE)
2818 "AST node for a case clause of a switch statement."
2819 expr) ; the case expression (nil for default)
2821 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2822 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2824 (defun js2-visit-case-node (n v)
2825 (js2-visit-ast (js2-case-node-expr n) v)
2826 (js2-visit-block n v))
2828 (defun js2-print-case-node (n i)
2829 (let ((pad (js2-make-pad i))
2830 (expr (js2-case-node-expr n)))
2833 (insert "default:\n")
2835 (js2-print-ast expr 0)
2837 (dolist (kid (js2-case-node-kids n))
2838 (js2-print-ast kid (1+ i)))))
2840 (defstruct (js2-throw-node
2843 (:constructor make-js2-throw-node (&key (type js2-THROW)
2847 "AST node for a throw statement."
2848 expr) ; the expression to throw
2850 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2851 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2853 (defun js2-visit-throw-node (n v)
2854 (js2-visit-ast (js2-throw-node-expr n) v))
2856 (defun js2-print-throw-node (n i)
2857 (insert (js2-make-pad i) "throw ")
2858 (js2-print-ast (js2-throw-node-expr n) 0)
2861 (defstruct (js2-with-node
2864 (:constructor make-js2-with-node (&key (type js2-WITH)
2871 "AST node for a with-statement."
2874 lp ; buffer position of left-paren around object, nil if omitted
2875 rp) ; buffer position of right-paren around object, nil if omitted
2877 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2878 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2880 (defun js2-visit-with-node (n v)
2881 (js2-visit-ast (js2-with-node-object n) v)
2882 (js2-visit-ast (js2-with-node-body n) v))
2884 (defun js2-print-with-node (n i)
2885 (let ((pad (js2-make-pad i)))
2886 (insert pad "with (")
2887 (js2-print-ast (js2-with-node-object n) 0)
2889 (js2-print-body (js2-with-node-body n) (1+ i))
2890 (insert pad "}\n")))
2892 (defstruct (js2-label-node
2895 (:constructor make-js2-label-node (&key (type js2-LABEL)
2899 "AST node for a statement label or case label."
2901 loop) ; for validating and code-generating continue-to-label
2903 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2904 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2906 (defun js2-print-label (n i)
2907 (insert (js2-make-pad i)
2908 (js2-label-node-name n)
2911 (defstruct (js2-labeled-stmt-node
2914 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2915 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2916 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2921 "AST node for a statement with one or more labels.
2922 Multiple labels for a statement are collapsed into the labels field."
2923 labels ; lisp list of `js2-label-node'
2924 stmt) ; the statement these labels are for
2926 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2927 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2929 (defun js2-get-label-by-name (lbl-stmt name)
2930 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2931 Returns nil if no such label is in the list."
2932 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2934 (while (and label-list (not result))
2935 (if (string= (js2-label-node-name (car label-list)) name)
2936 (setq result (car label-list))
2937 (setq label-list (cdr label-list))))
2940 (defun js2-visit-labeled-stmt (n v)
2941 (dolist (label (js2-labeled-stmt-node-labels n))
2942 (js2-visit-ast label v))
2943 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2945 (defun js2-print-labeled-stmt (n i)
2946 (dolist (label (js2-labeled-stmt-node-labels n))
2947 (js2-print-ast label i))
2948 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2950 (defun js2-labeled-stmt-node-contains (node label)
2951 "Return t if NODE contains LABEL in its label set.
2952 NODE is a `js2-labels-node'. LABEL is an identifier."
2953 (loop for nl in (js2-labeled-stmt-node-labels node)
2954 if (string= label (js2-label-node-name nl))
2956 finally return nil))
2958 (defsubst js2-labeled-stmt-node-add-label (node label)
2959 "Add a `js2-label-node' to the label set for this statement."
2960 (setf (js2-labeled-stmt-node-labels node)
2961 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2963 (defstruct (js2-jump-node
2966 "Abstract supertype of break and continue nodes."
2967 label ; `js2-name-node' for location of label identifier, if present
2968 target) ; target js2-labels-node or loop/switch statement
2970 (defun js2-visit-jump-node (n v)
2971 (js2-visit-ast (js2-jump-node-label n) v))
2973 (defstruct (js2-break-node
2974 (:include js2-jump-node)
2976 (:constructor make-js2-break-node (&key (type js2-BREAK)
2981 "AST node for a break statement.
2982 The label field is a `js2-name-node', possibly nil, for the named label
2983 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2984 is the target of the break - a label node or enclosing loop/switch statement.")
2986 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2987 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2989 (defun js2-print-break-node (n i)
2990 (insert (js2-make-pad i) "break")
2991 (when (js2-break-node-label n)
2993 (js2-print-ast (js2-break-node-label n) 0))
2996 (defstruct (js2-continue-node
2997 (:include js2-jump-node)
2999 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
3004 "AST node for a continue statement.
3005 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3006 It is nil if continue specifies no label. The target field is the jump target:
3007 a `js2-label-node' or the innermost enclosing loop.")
3009 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3010 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3012 (defun js2-print-continue-node (n i)
3013 (insert (js2-make-pad i) "continue")
3014 (when (js2-continue-node-label n)
3016 (js2-print-ast (js2-continue-node-label n) 0))
3019 (defstruct (js2-function-node
3020 (:include js2-script-node)
3022 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3026 (form 'FUNCTION_STATEMENT)
3032 "AST node for a function declaration.
3033 The `params' field is a lisp list of nodes. Each node is either a simple
3034 `js2-name-node', or if it's a destructuring-assignment parameter, a
3035 `js2-array-node' or `js2-object-node'."
3036 ftype ; FUNCTION, GETTER or SETTER
3037 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3038 name ; function name (a `js2-name-node', or nil if anonymous)
3039 params ; a lisp list of destructuring forms or simple name nodes
3040 body ; a `js2-block-node' or expression node (1.8 only)
3041 lp ; position of arg-list open-paren, or nil if omitted
3042 rp ; position of arg-list close-paren, or nil if omitted
3043 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3044 needs-activation ; t if we need an activation object for this frame
3045 is-generator ; t if this function contains a yield
3046 member-expr) ; nonstandard Ecma extension from Rhino
3048 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3049 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3051 (defun js2-visit-function-node (n v)
3052 (js2-visit-ast (js2-function-node-name n) v)
3053 (dolist (p (js2-function-node-params n))
3054 (js2-visit-ast p v))
3055 (js2-visit-ast (js2-function-node-body n) v))
3057 (defun js2-print-function-node (n i)
3058 (let ((pad (js2-make-pad i))
3059 (getter (js2-node-get-prop n 'GETTER_SETTER))
3060 (name (js2-function-node-name n))
3061 (params (js2-function-node-params n))
3062 (body (js2-function-node-body n))
3063 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3065 (insert pad "function"))
3068 (js2-print-ast name 0))
3070 (loop with len = (length params)
3074 (js2-print-ast param 0)
3080 ;; TODO: fix this to be smarter about indenting, etc.
3081 (js2-print-body body (1+ i))
3086 (defsubst js2-function-name (node)
3087 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3088 (and (js2-function-node-name node)
3089 (js2-name-node-name (js2-function-node-name node))))
3091 ;; Having this be an expression node makes it more flexible.
3092 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3093 ;; that work better if you assume it's an expression. Whenever we have
3094 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3095 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3096 (defstruct (js2-var-decl-node
3099 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3104 "AST node for a variable declaration list (VAR, CONST or LET).
3105 The node bounds differ depending on the declaration type. For VAR or
3106 CONST declarations, the bounds include the var/const keyword. For LET
3107 declarations, the node begins at the position of the first child."
3108 kids ; a lisp list of `js2-var-init-node' structs.
3109 decl-type) ; js2-VAR, js2-CONST or js2-LET
3111 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3112 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3114 (defun js2-visit-var-decl (n v)
3115 (dolist (kid (js2-var-decl-node-kids n))
3116 (js2-visit-ast kid v)))
3118 (defun js2-print-var-decl (n i)
3119 (let ((pad (js2-make-pad i))
3120 (tt (js2-var-decl-node-decl-type n)))
3123 ((= tt js2-VAR) "var ")
3124 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3125 ((= tt js2-CONST) "const ")
3127 (error "malformed var-decl node"))))
3128 (loop with kids = (js2-var-decl-node-kids n)
3129 with len = (length kids)
3133 (js2-print-ast kid 0)
3137 (defstruct (js2-var-init-node
3140 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3145 "AST node for a variable declaration.
3146 The type field will be js2-CONST for a const decl."
3147 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3148 initializer) ; initializer expression, a `js2-node'
3150 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3151 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3153 (defun js2-visit-var-init-node (n v)
3154 (js2-visit-ast (js2-var-init-node-target n) v)
3155 (js2-visit-ast (js2-var-init-node-initializer n) v))
3157 (defun js2-print-var-init-node (n i)
3158 (let ((pad (js2-make-pad i))
3159 (name (js2-var-init-node-target n))
3160 (init (js2-var-init-node-initializer n)))
3162 (js2-print-ast name 0)
3165 (js2-print-ast init 0))))
3167 (defstruct (js2-cond-node
3170 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3178 "AST node for the ternary operator"
3182 q-pos ; buffer position of ?
3183 c-pos) ; buffer position of :
3185 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3186 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3188 (defun js2-visit-cond-node (n v)
3189 (js2-visit-ast (js2-cond-node-test-expr n) v)
3190 (js2-visit-ast (js2-cond-node-true-expr n) v)
3191 (js2-visit-ast (js2-cond-node-false-expr n) v))
3193 (defun js2-print-cond-node (n i)
3194 (let ((pad (js2-make-pad i)))
3196 (js2-print-ast (js2-cond-node-test-expr n) 0)
3198 (js2-print-ast (js2-cond-node-true-expr n) 0)
3200 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3202 (defstruct (js2-infix-node
3205 (:constructor make-js2-infix-node (&key type
3211 "Represents infix expressions.
3212 Includes assignment ops like `|=', and the comma operator.
3213 The type field inherited from `js2-node' holds the operator."
3214 op-pos ; buffer position where operator begins
3215 left ; any `js2-node'
3216 right) ; any `js2-node'
3218 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3219 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3221 (defun js2-visit-infix-node (n v)
3222 (js2-visit-ast (js2-infix-node-left n) v)
3223 (js2-visit-ast (js2-infix-node-right n) v))
3225 (defconst js2-operator-tokens
3226 (let ((table (make-hash-table :test 'eq))
3228 (list (cons js2-IN "in")
3229 (cons js2-TYPEOF "typeof")
3230 (cons js2-INSTANCEOF "instanceof")
3231 (cons js2-DELPROP "delete")
3232 (cons js2-COMMA ",")
3233 (cons js2-COLON ":")
3238 (cons js2-BITOR "|")
3239 (cons js2-BITXOR "^")
3240 (cons js2-BITAND "&")
3249 (cons js2-URSH ">>>")
3250 (cons js2-ADD "+") ; infix plus
3251 (cons js2-SUB "-") ; infix minus
3256 (cons js2-BITNOT "~")
3257 (cons js2-POS "+") ; unary plus
3258 (cons js2-NEG "-") ; unary minus
3259 (cons js2-SHEQ "===") ; shallow equality
3260 (cons js2-SHNE "!==") ; shallow inequality
3261 (cons js2-ASSIGN "=")
3262 (cons js2-ASSIGN_BITOR "|=")
3263 (cons js2-ASSIGN_BITXOR "^=")
3264 (cons js2-ASSIGN_BITAND "&=")
3265 (cons js2-ASSIGN_LSH "<<=")
3266 (cons js2-ASSIGN_RSH ">>=")
3267 (cons js2-ASSIGN_URSH ">>>=")
3268 (cons js2-ASSIGN_ADD "+=")
3269 (cons js2-ASSIGN_SUB "-=")
3270 (cons js2-ASSIGN_MUL "*=")
3271 (cons js2-ASSIGN_DIV "/=")
3272 (cons js2-ASSIGN_MOD "%="))))
3273 (loop for (k . v) in tokens do
3274 (puthash k v table))
3277 (defun js2-print-infix-node (n i)
3278 (let* ((tt (js2-node-type n))
3279 (op (gethash tt js2-operator-tokens)))
3281 (error "unrecognized infix operator %s" (js2-node-type n)))
3282 (insert (js2-make-pad i))
3283 (js2-print-ast (js2-infix-node-left n) 0)
3284 (unless (= tt js2-COMMA)
3288 (js2-print-ast (js2-infix-node-right n) 0)))
3290 (defstruct (js2-assign-node
3291 (:include js2-infix-node)
3293 (:constructor make-js2-assign-node (&key type
3299 "Represents any assignment.
3300 The type field holds the actual assignment operator.")
3302 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3303 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3305 (defstruct (js2-unary-node
3308 (:constructor make-js2-unary-node (&key type ; required
3312 "AST node type for unary operator nodes.
3313 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3314 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3315 property is added if the operator follows the operand."
3316 operand) ; a `js2-node' expression
3318 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3319 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3321 (defun js2-visit-unary-node (n v)
3322 (js2-visit-ast (js2-unary-node-operand n) v))
3324 (defun js2-print-unary-node (n i)
3325 (let* ((tt (js2-node-type n))
3326 (op (gethash tt js2-operator-tokens))
3327 (postfix (js2-node-get-prop n 'postfix)))
3329 (error "unrecognized unary operator %s" tt))
3330 (insert (js2-make-pad i))
3333 (if (or (= tt js2-TYPEOF)
3336 (js2-print-ast (js2-unary-node-operand n) 0)
3340 (defstruct (js2-let-node
3341 (:include js2-scope)
3343 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3350 "AST node for a let expression or a let statement.
3351 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3352 vars ; a `js2-var-decl-node'
3353 body ; a `js2-node' representing the expression or body block
3357 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3358 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3360 (defun js2-visit-let-node (n v)
3361 (js2-visit-ast (js2-let-node-vars n) v)
3362 (js2-visit-ast (js2-let-node-body n) v))
3364 (defun js2-print-let-node (n i)
3365 (insert (js2-make-pad i) "let (")
3366 (js2-print-ast (js2-let-node-vars n) 0)
3368 (js2-print-ast (js2-let-node-body n) i))
3370 (defstruct (js2-keyword-node
3373 (:constructor make-js2-keyword-node (&key type
3375 (len (- js2-ts-cursor pos)))))
3376 "AST node representing a literal keyword such as `null'.
3377 Used for `null', `this', `true', `false' and `debugger'.
3378 The node type is set to js2-NULL, js2-THIS, etc.")
3380 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3381 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3383 (defun js2-print-keyword-node (n i)
3384 (insert (js2-make-pad i)
3385 (let ((tt (js2-node-type n)))
3387 ((= tt js2-THIS) "this")
3388 ((= tt js2-NULL) "null")
3389 ((= tt js2-TRUE) "true")
3390 ((= tt js2-FALSE) "false")
3391 ((= tt js2-DEBUGGER) "debugger")
3392 (t (error "Invalid keyword literal type: %d" tt))))))
3394 (defsubst js2-this-node-p (node)
3395 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3396 (eq (js2-node-type node) js2-THIS))
3398 (defstruct (js2-new-node
3401 (:constructor make-js2-new-node (&key (type js2-NEW)
3409 "AST node for new-expression such as new Foo()."
3410 target ; an identifier or reference
3411 args ; a lisp list of argument nodes
3412 lp ; position of left-paren, nil if omitted
3413 rp ; position of right-paren, nil if omitted
3414 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3416 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3417 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3419 (defun js2-visit-new-node (n v)
3420 (js2-visit-ast (js2-new-node-target n) v)
3421 (dolist (arg (js2-new-node-args n))
3422 (js2-visit-ast arg v))
3423 (js2-visit-ast (js2-new-node-initializer n) v))
3425 (defun js2-print-new-node (n i)
3426 (insert (js2-make-pad i) "new ")
3427 (js2-print-ast (js2-new-node-target n))
3429 (js2-print-list (js2-new-node-args n))
3431 (when (js2-new-node-initializer n)
3433 (js2-print-ast (js2-new-node-initializer n))))
3435 (defstruct (js2-name-node
3438 (:constructor make-js2-name-node (&key (type js2-NAME)
3440 (len (- js2-ts-cursor
3442 (name js2-ts-string))))
3443 "AST node for a JavaScript identifier"
3445 scope) ; a `js2-scope' (optional, used for codegen)
3447 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3448 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3450 (defun js2-print-name-node (n i)
3451 (insert (js2-make-pad i)
3452 (js2-name-node-name n)))
3454 (defsubst js2-name-node-length (node)
3455 "Return identifier length of NODE, a `js2-name-node'.
3456 Returns 0 if NODE is nil or its identifier field is nil."
3458 (length (js2-name-node-name node))
3461 (defstruct (js2-number-node
3464 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3466 (len (- js2-ts-cursor
3468 (value js2-ts-string)
3469 (num-value js2-ts-number))))
3470 "AST node for a number literal."
3471 value ; the original string, e.g. "6.02e23"
3472 num-value) ; the parsed number value
3474 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3475 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3477 (defun js2-print-number-node (n i)
3478 (insert (js2-make-pad i)
3479 (number-to-string (js2-number-node-num-value n))))
3481 (defstruct (js2-regexp-node
3484 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3486 (len (- js2-ts-cursor
3490 "AST node for a regular expression literal."
3491 value ; the regexp string, without // delimiters
3492 flags) ; a string of flags, e.g. `mi'.
3494 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3495 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3497 (defun js2-print-regexp (n i)
3498 (insert (js2-make-pad i)
3500 (js2-regexp-node-value n)
3502 (if (js2-regexp-node-flags n)
3503 (insert (js2-regexp-node-flags n))))
3505 (defstruct (js2-string-node
3508 (:constructor make-js2-string-node (&key (type js2-STRING)
3510 (len (- js2-ts-cursor
3512 (value js2-ts-string))))
3514 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3515 You can tell the quote type by looking at the first character."
3516 value) ; the characters of the string, including the quotes
3518 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3519 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3521 (defun js2-print-string-node (n i)
3522 (insert (js2-make-pad i)
3523 (js2-node-string n)))
3525 (defstruct (js2-array-node
3528 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3532 "AST node for an array literal."
3533 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3535 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3536 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3538 (defun js2-visit-array-node (n v)
3539 (dolist (e (js2-array-node-elems n))
3540 (js2-visit-ast e v)))
3542 (defun js2-print-array-node (n i)
3543 (insert (js2-make-pad i) "[")
3544 (js2-print-list (js2-array-node-elems n))
3547 (defstruct (js2-object-node
3550 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3554 "AST node for an object literal expression.
3555 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3556 the latter represents abbreviation in destructuring expressions."
3559 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3560 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3562 (defun js2-visit-object-node (n v)
3563 (dolist (e (js2-object-node-elems n))
3564 (js2-visit-ast e v)))
3566 (defun js2-print-object-node (n i)
3567 (insert (js2-make-pad i) "{")
3568 (js2-print-list (js2-object-node-elems n))
3571 (defstruct (js2-object-prop-node
3572 (:include js2-infix-node)
3574 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3580 "AST node for an object literal prop:value entry.
3581 The `left' field is the property: a name node, string node or number node.
3582 The `right' field is a `js2-node' representing the initializer value.")
3584 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3585 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3587 (defun js2-print-object-prop-node (n i)
3588 (insert (js2-make-pad i))
3589 (js2-print-ast (js2-object-prop-node-left n) 0)
3591 (js2-print-ast (js2-object-prop-node-right n) 0))
3593 (defstruct (js2-getter-setter-node
3594 (:include js2-infix-node)
3596 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3601 "AST node for a getter/setter property in an object literal.
3602 The `left' field is the `js2-name-node' naming the getter/setter prop.
3603 The `right' field is always an anonymous `js2-function-node' with a node
3604 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3606 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3607 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3609 (defun js2-print-getter-setter (n i)
3610 (let ((pad (js2-make-pad i))
3611 (left (js2-getter-setter-node-left n))
3612 (right (js2-getter-setter-node-right n)))
3614 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3615 (js2-print-ast left 0)
3616 (js2-print-ast right 0)))
3618 (defstruct (js2-prop-get-node
3619 (:include js2-infix-node)
3621 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3626 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3628 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3629 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3631 (defun js2-visit-prop-get-node (n v)
3632 (js2-visit-ast (js2-prop-get-node-left n) v)
3633 (js2-visit-ast (js2-prop-get-node-right n) v))
3635 (defun js2-print-prop-get-node (n i)
3636 (insert (js2-make-pad i))
3637 (js2-print-ast (js2-prop-get-node-left n) 0)
3639 (js2-print-ast (js2-prop-get-node-right n) 0))
3641 (defstruct (js2-elem-get-node
3644 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3651 "AST node for an array index expression such as foo[bar]."
3652 target ; a `js2-node' - the expression preceding the "."
3653 element ; a `js2-node' - the expression in brackets
3654 lb ; position of left-bracket, nil if omitted
3655 rb) ; position of right-bracket, nil if omitted
3657 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3658 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3660 (defun js2-visit-elem-get-node (n v)
3661 (js2-visit-ast (js2-elem-get-node-target n) v)
3662 (js2-visit-ast (js2-elem-get-node-element n) v))
3664 (defun js2-print-elem-get-node (n i)
3665 (insert (js2-make-pad i))
3666 (js2-print-ast (js2-elem-get-node-target n) 0)
3668 (js2-print-ast (js2-elem-get-node-element n) 0)
3671 (defstruct (js2-call-node
3674 (:constructor make-js2-call-node (&key (type js2-CALL)
3681 "AST node for a JavaScript function call."
3682 target ; a `js2-node' evaluating to the function to call
3683 args ; a lisp list of `js2-node' arguments
3684 lp ; position of open-paren, or nil if missing
3685 rp) ; position of close-paren, or nil if missing
3687 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3688 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3690 (defun js2-visit-call-node (n v)
3691 (js2-visit-ast (js2-call-node-target n) v)
3692 (dolist (arg (js2-call-node-args n))
3693 (js2-visit-ast arg v)))
3695 (defun js2-print-call-node (n i)
3696 (insert (js2-make-pad i))
3697 (js2-print-ast (js2-call-node-target n) 0)
3699 (js2-print-list (js2-call-node-args n))
3702 (defstruct (js2-yield-node
3705 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3709 "AST node for yield statement or expression."
3710 value) ; optional: value to be yielded
3712 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3713 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3715 (defun js2-visit-yield-node (n v)
3716 (js2-visit-ast (js2-yield-node-value n) v))
3718 (defun js2-print-yield-node (n i)
3719 (insert (js2-make-pad i))
3721 (when (js2-yield-node-value n)
3723 (js2-print-ast (js2-yield-node-value n) 0)))
3725 (defstruct (js2-paren-node
3728 (:constructor make-js2-paren-node (&key (type js2-LP)
3732 "AST node for a parenthesized expression.
3733 In particular, used when the parens are syntactically optional,
3734 as opposed to required parens such as those enclosing an if-conditional."
3737 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3738 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3740 (defun js2-visit-paren-node (n v)
3741 (js2-visit-ast (js2-paren-node-expr n) v))
3743 (defun js2-print-paren-node (n i)
3744 (insert (js2-make-pad i))
3746 (js2-print-ast (js2-paren-node-expr n) 0)
3749 (defstruct (js2-array-comp-node
3750 (:include js2-scope)
3752 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3761 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3762 result ; result expression (just after left-bracket)
3763 loops ; a lisp list of `js2-array-comp-loop-node'
3764 filter ; guard/filter expression
3765 if-pos ; buffer pos of 'if' keyword, if present, else nil
3766 lp ; buffer position of if-guard left-paren, or nil if not present
3767 rp) ; buffer position of if-guard right-paren, or nil if not present
3769 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3770 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3772 (defun js2-visit-array-comp-node (n v)
3773 (js2-visit-ast (js2-array-comp-node-result n) v)
3774 (dolist (l (js2-array-comp-node-loops n))
3775 (js2-visit-ast l v))
3776 (js2-visit-ast (js2-array-comp-node-filter n) v))
3778 (defun js2-print-array-comp-node (n i)
3779 (let ((pad (js2-make-pad i))
3780 (result (js2-array-comp-node-result n))
3781 (loops (js2-array-comp-node-loops n))
3782 (filter (js2-array-comp-node-filter n)))
3784 (js2-print-ast result 0)
3787 (js2-print-ast l 0))
3790 (js2-print-ast filter 0))
3793 (defstruct (js2-array-comp-loop-node
3794 (:include js2-for-in-node)
3796 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3806 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3808 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3809 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3811 (defun js2-visit-array-comp-loop (n v)
3812 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3813 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3815 (defun js2-print-array-comp-loop (n i)
3817 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3819 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3822 (defstruct (js2-empty-expr-node
3825 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3828 "AST node for an empty expression.")
3830 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3831 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3833 (defstruct (js2-xml-node
3834 (:include js2-block-node)
3836 (:constructor make-js2-xml-node (&key (type js2-XML)
3840 "AST node for initial parse of E4X literals.
3841 The kids field is a list of XML fragments, each a `js2-string-node' or
3842 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3844 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3845 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3847 (defun js2-print-xml-node (n i)
3848 (dolist (kid (js2-xml-node-kids n))
3849 (js2-print-ast kid i)))
3851 (defstruct (js2-xml-js-expr-node
3852 (:include js2-xml-node)
3854 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3858 "AST node for an embedded JavaScript {expression} in an E4X literal.
3859 The start and end fields correspond to the curly-braces."
3860 expr) ; a `js2-expr-node' of some sort
3862 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3863 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3865 (defun js2-visit-xml-js-expr (n v)
3866 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3868 (defun js2-print-xml-js-expr (n i)
3869 (insert (js2-make-pad i))
3871 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3874 (defstruct (js2-xml-dot-query-node
3875 (:include js2-infix-node)
3877 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3884 "AST node for an E4X foo.(bar) filter expression.
3885 Note that the left-paren is automatically the character immediately
3886 following the dot (.) in the operator. No whitespace is permitted
3887 between the dot and the lp by the scanner."
3890 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3891 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3893 (defun js2-print-xml-dot-query (n i)
3894 (insert (js2-make-pad i))
3895 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3897 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3900 (defstruct (js2-xml-ref-node
3902 (:constructor nil)) ; abstract
3903 "Base type for E4X XML attribute-access or property-get expressions.
3904 Such expressions can take a variety of forms. The general syntax has
3907 - (optional) an @ (specifying an attribute access)
3908 - (optional) a namespace (a `js2-name-node') and double-colon
3909 - (required) either a `js2-name-node' or a bracketed [expression]
3911 The property-name expressions (examples: ns::name, @name) are
3912 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3913 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3915 This node type (or more specifically, its subclasses) will sometimes
3916 be the right-hand child of a `js2-prop-get-node' or a
3917 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3918 The `js2-xml-ref-node' may also be a standalone primary expression with
3919 no explicit target, which is valid in certain expression contexts such as
3921 company..employee.(@id < 100)
3923 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3924 expression whose parent is a `js2-xml-dot-query-node'."
3929 (defsubst js2-xml-ref-node-attr-access-p (node)
3930 "Return non-nil if this expression began with an @-token."
3931 (and (numberp (js2-xml-ref-node-at-pos node))
3932 (plusp (js2-xml-ref-node-at-pos node))))
3934 (defstruct (js2-xml-prop-ref-node
3935 (:include js2-xml-ref-node)
3937 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3944 "AST node for an E4X XML [expr] property-ref expression.
3945 The JavaScript syntax is an optional @, an optional ns::, and a name.
3947 [ '@' ] [ name '::' ] name
3949 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3950 @ns::*, @*::attr, @*::*, and @*.
3952 The node starts at the @ token, if present. Otherwise it starts at the
3953 namespace name. The node bounds extend through the closing right-bracket,
3954 or if it is missing due to a syntax error, through the end of the index
3958 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3959 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3961 (defun js2-visit-xml-prop-ref-node (n v)
3962 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3963 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3965 (defun js2-print-xml-prop-ref-node (n i)
3966 (insert (js2-make-pad i))
3967 (if (js2-xml-ref-node-attr-access-p n)
3969 (when (js2-xml-prop-ref-node-namespace n)
3970 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3972 (if (js2-xml-prop-ref-node-propname n)
3973 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3975 (defstruct (js2-xml-elem-ref-node
3976 (:include js2-xml-ref-node)
3978 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3987 "AST node for an E4X XML [expr] member-ref expression.
3990 [ '@' ] [ name '::' ] '[' expr ']'
3992 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3994 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3995 is not a legal E4X XML element-ref expression, since it's already used
3996 for standard JavaScript element-get array indexing. Hence, a
3997 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3998 non-nil namespace node, or both.
4000 The node starts at the @ token, if present. Otherwise it starts
4001 at the namespace name. The node bounds extend through the closing
4002 right-bracket, or if it is missing due to a syntax error, through the
4003 end of the index expression."
4004 expr ; the bracketed index expression
4008 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4009 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4011 (defun js2-visit-xml-elem-ref-node (n v)
4012 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4013 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4015 (defun js2-print-xml-elem-ref-node (n i)
4016 (insert (js2-make-pad i))
4017 (if (js2-xml-ref-node-attr-access-p n)
4019 (when (js2-xml-elem-ref-node-namespace n)
4020 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4023 (if (js2-xml-elem-ref-node-expr n)
4024 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4027 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4029 (defstruct (js2-xml-start-tag-node
4030 (:include js2-xml-node)
4032 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4039 "AST node for an XML start-tag. Not currently used.
4040 The `kids' field is a lisp list of child content nodes."
4041 name ; a `js2-xml-name-node'
4042 attrs ; a lisp list of `js2-xml-attr-node'
4043 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4045 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4046 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4048 (defun js2-visit-xml-start-tag (n v)
4049 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4050 (dolist (attr (js2-xml-start-tag-node-attrs n))
4051 (js2-visit-ast attr v))
4052 (js2-visit-block n v))
4054 (defun js2-print-xml-start-tag (n i)
4055 (insert (js2-make-pad i) "<")
4056 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4057 (when (js2-xml-start-tag-node-attrs n)
4059 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4062 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4063 ;; and add the end-tag to the kids list of the parent as well.
4064 (defstruct (js2-xml-end-tag-node
4065 (:include js2-xml-node)
4067 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4071 "AST node for an XML end-tag. Not currently used."
4072 name) ; a `js2-xml-name-node'
4074 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4075 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4077 (defun js2-visit-xml-end-tag (n v)
4078 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4080 (defun js2-print-xml-end-tag (n i)
4081 (insert (js2-make-pad i))
4083 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4086 (defstruct (js2-xml-name-node
4087 (:include js2-xml-node)
4089 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4094 "AST node for an E4X XML name. Not currently used.
4095 Any XML name can be qualified with a namespace, hence the namespace field.
4096 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4097 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4098 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4099 namespace) ; a `js2-string-node'
4101 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4102 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4104 (defun js2-visit-xml-name-node (n v)
4105 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4107 (defun js2-print-xml-name-node (n i)
4108 (insert (js2-make-pad i))
4109 (when (js2-xml-name-node-namespace n)
4110 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4112 (dolist (kid (js2-xml-name-node-kids n))
4113 (js2-print-ast kid 0)))
4115 (defstruct (js2-xml-pi-node
4116 (:include js2-xml-node)
4118 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4123 "AST node for an E4X XML processing instruction. Not currently used."
4124 name ; a `js2-xml-name-node'
4125 attrs) ; a list of `js2-xml-attr-node'
4127 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4128 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4130 (defun js2-visit-xml-pi-node (n v)
4131 (js2-visit-ast (js2-xml-pi-node-name n) v)
4132 (dolist (attr (js2-xml-pi-node-attrs n))
4133 (js2-visit-ast attr v)))
4135 (defun js2-print-xml-pi-node (n i)
4136 (insert (js2-make-pad i) "<?")
4137 (js2-print-ast (js2-xml-pi-node-name n))
4138 (when (js2-xml-pi-node-attrs n)
4140 (js2-print-list (js2-xml-pi-node-attrs n)))
4143 (defstruct (js2-xml-cdata-node
4144 (:include js2-xml-node)
4146 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4150 "AST node for a CDATA escape section. Not currently used."
4151 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4153 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4154 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4156 (defun js2-visit-xml-cdata-node (n v)
4157 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4159 (defun js2-print-xml-cdata-node (n i)
4160 (insert (js2-make-pad i))
4161 (js2-print-ast (js2-xml-cdata-node-content n)))
4163 (defstruct (js2-xml-attr-node
4164 (:include js2-xml-node)
4166 (:constructor make-js2-attr-node (&key (type js2-XML)
4173 "AST node representing a foo='bar' XML attribute value. Not yet used."
4174 name ; a `js2-xml-name-node'
4175 value ; a `js2-xml-name-node'
4176 eq-pos ; buffer position of "=" sign
4177 quote-type) ; 'single or 'double
4179 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4180 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4182 (defun js2-visit-xml-attr-node (n v)
4183 (js2-visit-ast (js2-xml-attr-node-name n) v)
4184 (js2-visit-ast (js2-xml-attr-node-value n) v))
4186 (defun js2-print-xml-attr-node (n i)
4187 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4190 (insert (js2-make-pad i))
4191 (js2-print-ast (js2-xml-attr-node-name n) 0)
4193 (js2-print-ast (js2-xml-attr-node-value n) 0)
4196 (defstruct (js2-xml-text-node
4197 (:include js2-xml-node)
4199 (:constructor make-js2-text-node (&key (type js2-XML)
4203 "AST node for an E4X XML text node. Not currently used."
4204 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4206 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4207 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4209 (defun js2-visit-xml-text-node (n v)
4210 (js2-visit-ast (js2-xml-text-node-content n) v))
4212 (defun js2-print-xml-text-node (n i)
4213 (insert (js2-make-pad i))
4214 (dolist (kid (js2-xml-text-node-content n))
4215 (js2-print-ast kid)))
4217 (defstruct (js2-xml-comment-node
4218 (:include js2-xml-node)
4220 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4223 "AST node for E4X XML comment. Not currently used.")
4225 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4226 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4228 (defun js2-print-xml-comment (n i)
4229 (insert (js2-make-pad i)
4230 (js2-node-string n)))
4234 (defsubst js2-node-line (n)
4235 "Fetch the source line number at the start of node N.
4236 This is O(n) in the length of the source buffer; use prudently."
4237 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4239 (defsubst js2-block-node-kid (n i)
4240 "Return child I of node N, or nil if there aren't that many."
4241 (nth i (js2-block-node-kids n)))
4243 (defsubst js2-block-node-first (n)
4244 "Return first child of block node N, or nil if there is none."
4245 (first (js2-block-node-kids n)))
4247 (defun js2-node-root (n)
4248 "Return the root of the AST containing N.
4249 If N has no parent pointer, returns N."
4250 (let ((parent (js2-node-parent n)))
4252 (js2-node-root parent)
4255 (defun js2-node-position-in-parent (node &optional parent)
4256 "Return the position of NODE in parent's block-kids list.
4257 PARENT can be supplied if known. Positioned returned is zero-indexed.
4258 Returns 0 if NODE is not a child of a block statement, or if NODE
4259 is not a statement node."
4260 (let ((p (or parent (js2-node-parent node)))
4262 (if (not (js2-block-node-p p))
4264 (or (js2-position node (js2-block-node-kids p))
4267 (defsubst js2-node-short-name (n)
4268 "Return the short name of node N as a string, e.g. `js2-if-node'."
4269 (substring (symbol-name (aref n 0))
4270 (length "cl-struct-")))
4272 (defsubst js2-node-child-list (node)
4273 "Return the child list for NODE, a lisp list of nodes.
4274 Works for block nodes, array nodes, obj literals, funarg lists,
4275 var decls and try nodes (for catch clauses). Note that you should call
4276 `js2-block-node-kids' on the function body for the body statements.
4277 Returns nil for zero-length child lists or unsupported nodes."
4279 ((js2-function-node-p node)
4280 (js2-function-node-params node))
4281 ((js2-block-node-p node)
4282 (js2-block-node-kids node))
4283 ((js2-try-node-p node)
4284 (js2-try-node-catch-clauses node))
4285 ((js2-array-node-p node)
4286 (js2-array-node-elems node))
4287 ((js2-object-node-p node)
4288 (js2-object-node-elems node))
4289 ((js2-call-node-p node)
4290 (js2-call-node-args node))
4291 ((js2-new-node-p node)
4292 (js2-new-node-args node))
4293 ((js2-var-decl-node-p node)
4294 (js2-var-decl-node-kids node))
4298 (defsubst js2-node-set-child-list (node kids)
4299 "Set the child list for NODE to KIDS."
4301 ((js2-function-node-p node)
4302 (setf (js2-function-node-params node) kids))
4303 ((js2-block-node-p node)
4304 (setf (js2-block-node-kids node) kids))
4305 ((js2-try-node-p node)
4306 (setf (js2-try-node-catch-clauses node) kids))
4307 ((js2-array-node-p node)
4308 (setf (js2-array-node-elems node) kids))
4309 ((js2-object-node-p node)
4310 (setf (js2-object-node-elems node) kids))
4311 ((js2-call-node-p node)
4312 (setf (js2-call-node-args node) kids))
4313 ((js2-new-node-p node)
4314 (setf (js2-new-node-args node) kids))
4315 ((js2-var-decl-node-p node)
4316 (setf (js2-var-decl-node-kids node) kids))
4318 (error "Unsupported node type: %s" (js2-node-short-name node))))
4321 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4322 (defconst js2-paren-expr-nodes
4323 '(cl-struct-js2-array-comp-loop-node
4324 cl-struct-js2-array-comp-node
4325 cl-struct-js2-call-node
4326 cl-struct-js2-catch-node
4327 cl-struct-js2-do-node
4328 cl-struct-js2-elem-get-node
4329 cl-struct-js2-for-in-node
4330 cl-struct-js2-for-node
4331 cl-struct-js2-function-node
4332 cl-struct-js2-if-node
4333 cl-struct-js2-let-node
4334 cl-struct-js2-new-node
4335 cl-struct-js2-paren-node
4336 cl-struct-js2-switch-node
4337 cl-struct-js2-while-node
4338 cl-struct-js2-with-node
4339 cl-struct-js2-xml-dot-query-node)
4340 "Node types that can have a parenthesized child expression.
4341 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4343 (defsubst js2-paren-expr-node-p (node)
4344 "Return t for nodes that typically have a parenthesized child expression.
4345 Useful for computing the indentation anchors for arg-lists and conditions.
4346 Note that it may return a false positive, for instance when NODE is
4347 a `js2-new-node' and there are no arguments or parentheses."
4348 (memq (aref node 0) js2-paren-expr-nodes))
4350 ;; Fake polymorphism... yech.
4351 (defsubst js2-node-lp (node)
4352 "Return relative left-paren position for NODE, if applicable.
4353 For `js2-elem-get-node' structs, returns left-bracket position.
4354 Note that the position may be nil in the case of a parse error."
4356 ((js2-elem-get-node-p node)
4357 (js2-elem-get-node-lb node))
4358 ((js2-loop-node-p node)
4359 (js2-loop-node-lp node))
4360 ((js2-function-node-p node)
4361 (js2-function-node-lp node))
4362 ((js2-if-node-p node)
4363 (js2-if-node-lp node))
4364 ((js2-new-node-p node)
4365 (js2-new-node-lp node))
4366 ((js2-call-node-p node)
4367 (js2-call-node-lp node))
4368 ((js2-paren-node-p node)
4369 (js2-node-pos node))
4370 ((js2-switch-node-p node)
4371 (js2-switch-node-lp node))
4372 ((js2-catch-node-p node)
4373 (js2-catch-node-lp node))
4374 ((js2-let-node-p node)
4375 (js2-let-node-lp node))
4376 ((js2-array-comp-node-p node)
4377 (js2-array-comp-node-lp node))
4378 ((js2-with-node-p node)
4379 (js2-with-node-lp node))
4380 ((js2-xml-dot-query-node-p node)
4381 (1+ (js2-infix-node-op-pos node)))
4383 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4385 ;; Fake polymorphism... blech.
4386 (defsubst js2-node-rp (node)
4387 "Return relative right-paren position for NODE, if applicable.
4388 For `js2-elem-get-node' structs, returns right-bracket position.
4389 Note that the position may be nil in the case of a parse error."
4391 ((js2-elem-get-node-p node)
4392 (js2-elem-get-node-lb node))
4393 ((js2-loop-node-p node)
4394 (js2-loop-node-rp node))
4395 ((js2-function-node-p node)
4396 (js2-function-node-rp node))
4397 ((js2-if-node-p node)
4398 (js2-if-node-rp node))
4399 ((js2-new-node-p node)
4400 (js2-new-node-rp node))
4401 ((js2-call-node-p node)
4402 (js2-call-node-rp node))
4403 ((js2-paren-node-p node)
4404 (+ (js2-node-pos node) (js2-node-len node)))
4405 ((js2-switch-node-p node)
4406 (js2-switch-node-rp node))
4407 ((js2-catch-node-p node)
4408 (js2-catch-node-rp node))
4409 ((js2-let-node-p node)
4410 (js2-let-node-rp node))
4411 ((js2-array-comp-node-p node)
4412 (js2-array-comp-node-rp node))
4413 ((js2-with-node-p node)
4414 (js2-with-node-rp node))
4415 ((js2-xml-dot-query-node-p node)
4416 (1+ (js2-xml-dot-query-node-rp node)))
4418 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4420 (defsubst js2-node-first-child (node)
4421 "Returns the first element of `js2-node-child-list' for NODE."
4422 (car (js2-node-child-list node)))
4424 (defsubst js2-node-last-child (node)
4425 "Returns the last element of `js2-node-last-child' for NODE."
4426 (car (last (js2-node-child-list node))))
4428 (defun js2-node-prev-sibling (node)
4429 "Return the previous statement in parent.
4430 Works for parents supported by `js2-node-child-list'.
4431 Returns nil if NODE is not in the parent, or PARENT is
4432 not a supported node, or if NODE is the first child."
4433 (let* ((p (js2-node-parent node))
4434 (kids (js2-node-child-list p))
4437 (not (eq node (cadr kids))))
4438 (setq kids (cdr kids)
4442 (defun js2-node-next-sibling (node)
4443 "Return the next statement in parent block.
4444 Returns nil if NODE is not in the block, or PARENT is not
4445 a block node, or if NODE is the last statement."
4446 (let* ((p (js2-node-parent node))
4447 (kids (js2-node-child-list p)))
4449 (not (eq node (car kids))))
4450 (setq kids (cdr kids)))
4453 (defun js2-node-find-child-before (pos parent &optional after)
4454 "Find the last child that starts before POS in parent.
4455 If AFTER is non-nil, returns first child starting after POS.
4456 POS is an absolute buffer position. PARENT is any node
4457 supported by `js2-node-child-list'.
4458 Returns nil if no applicable child is found."
4459 (let ((kids (if (js2-function-node-p parent)
4460 (js2-block-node-kids (js2-function-node-body parent))
4461 (js2-node-child-list parent)))
4462 (beg (if (js2-function-node-p parent)
4463 (js2-node-abs-pos (js2-function-node-body parent))
4464 (js2-node-abs-pos parent)))
4469 (setq fn (if after '>= '<))
4470 (while (and kids continue)
4471 (setq kid (car kids))
4472 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4474 continue (if after nil t))
4475 (setq continue (if after t nil)))
4476 (setq kids (cdr kids)))
4479 (defun js2-node-find-child-after (pos parent)
4480 "Find first child that starts after POS in parent.
4481 POS is an absolute buffer position. PARENT is any node
4482 supported by `js2-node-child-list'.
4483 Returns nil if no applicable child is found."
4484 (js2-node-find-child-before pos parent 'after))
4486 (defun js2-node-replace-child (pos parent new-node)
4487 "Replace node at index POS in PARENT with NEW-NODE.
4488 Only works for parents supported by `js2-node-child-list'."
4489 (let ((kids (js2-node-child-list parent))
4492 (setq kids (cdr kids)
4494 (setcar kids new-node)
4495 (js2-node-add-children parent new-node)))
4497 (defun js2-node-buffer (n)
4498 "Return the buffer associated with AST N.
4499 Returns nil if the buffer is not set as a property on the root
4500 node, or if parent links were not recorded during parsing."
4501 (let ((root (js2-node-root n)))
4503 (js2-ast-root-p root)
4504 (js2-ast-root-buffer root))))
4506 (defsubst js2-block-node-push (n kid)
4507 "Push js2-node KID onto the end of js2-block-node N's child list.
4508 KID is always added to the -end- of the kids list.
4509 Function also calls `js2-node-add-children' to add the parent link."
4510 (let ((kids (js2-node-child-list n)))
4512 (setcdr kids (nconc (cdr kids) (list kid)))
4513 (js2-node-set-child-list n (list kid)))
4514 (js2-node-add-children n kid)))
4516 (defun js2-node-string (node)
4517 (let ((buf (js2-node-buffer node))
4520 (error "No buffer available for node %s" node))
4521 (with-current-buffer buf
4522 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4523 (+ pos (js2-node-len node))))))
4525 ;; Container for storing the node we're looking for in a traversal.
4526 (js2-deflocal js2-discovered-node nil)
4528 ;; Keep track of absolute node position during traversals.
4529 (js2-deflocal js2-visitor-offset nil)
4531 (js2-deflocal js2-node-search-point nil)
4533 (when js2-mode-dev-mode-p
4534 (defun js2-find-node-at-point ()
4536 (let ((node (js2-node-at-point)))
4537 (message "%s" (or node "No node found at point"))))
4538 (defun js2-node-name-at-point ()
4540 (let ((node (js2-node-at-point)))
4541 (message "%s" (if node
4542 (js2-node-short-name node)
4543 "No node found at point.")))))
4545 (defun js2-node-at-point (&optional pos skip-comments)
4546 "Return AST node at POS, a buffer position, defaulting to current point.
4547 The `js2-mode-ast' variable must be set to the current parse tree.
4548 Signals an error if the AST (`js2-mode-ast') is nil.
4549 Always returns a node - if it can't find one, it returns the root.
4550 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4551 (let ((ast js2-mode-ast)
4554 (error "No JavaScript AST available"))
4555 ;; Look through comments first, since they may be inside nodes that
4556 ;; would otherwise report a match.
4557 (setq pos (or pos (point))
4558 result (if (> pos (js2-node-abs-end ast))
4560 (if (not skip-comments)
4561 (js2-comment-at-point pos))))
4563 (setq js2-discovered-node nil
4564 js2-visitor-offset 0
4565 js2-node-search-point pos)
4567 (catch 'js2-visit-done
4568 (js2-visit-ast ast #'js2-node-at-point-visitor))
4569 (setq js2-visitor-offset nil
4570 js2-node-search-point nil))
4571 (setq result js2-discovered-node))
4572 ;; may have found a comment beyond end of last child node,
4573 ;; since visiting the ast-root looks at the comment-list last.
4574 (if (and skip-comments
4575 (js2-comment-node-p result))
4577 (or result js2-mode-ast)))
4579 (defun js2-node-at-point-visitor (node end-p)
4580 (let ((rel-pos (js2-node-pos node))
4583 (point js2-node-search-point))
4586 ;; this evaluates to a non-nil return value, even if it's zero
4587 (decf js2-visitor-offset rel-pos))
4588 ;; we already looked for comments before visiting, and don't want them now
4589 ((js2-comment-node-p node)
4592 (setq abs-pos (incf js2-visitor-offset rel-pos)
4593 ;; we only want to use the node if the point is before
4594 ;; the last character position in the node, so we decrement
4595 ;; the absolute end by 1.
4596 abs-end (+ abs-pos (js2-node-len node) -1))
4598 ;; If this node starts after search-point, stop the search.
4600 (throw 'js2-visit-done nil))
4601 ;; If this node ends before the search-point, don't check kids.
4605 ;; Otherwise point is within this node, possibly in a child.
4606 (setq js2-discovered-node node)
4607 t)))))) ; keep processing kids to look for more specific match
4609 (defsubst js2-block-comment-p (node)
4610 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4611 (and (js2-comment-node-p node)
4612 (memq (js2-comment-node-format node) '(jsdoc block))))
4614 ;; TODO: put the comments in a vector and binary-search them instead
4615 (defun js2-comment-at-point (&optional pos)
4616 "Look through scanned comment nodes for one containing POS.
4617 POS is a buffer position that defaults to current point.
4618 Function returns nil if POS was not in any comment node."
4619 (let ((ast js2-mode-ast)
4620 (x (or pos (point)))
4624 (error "No JavaScript AST available"))
4626 ;; Comments are stored in lexical order.
4627 (dolist (comment (js2-ast-root-comments ast) nil)
4628 (setq beg (js2-node-abs-pos comment)
4629 end (+ beg (js2-node-len comment)))
4632 (throw 'done comment))))))
4634 (defun js2-mode-find-parent-fn (node)
4635 "Find function enclosing NODE.
4636 Returns nil if NODE is not inside a function."
4637 (setq node (js2-node-parent node))
4638 (while (and node (not (js2-function-node-p node)))
4639 (setq node (js2-node-parent node)))
4640 (and (js2-function-node-p node) node))
4642 (defun js2-mode-find-enclosing-fn (node)
4643 "Find function or root enclosing NODE."
4644 (if (js2-ast-root-p node)
4646 (setq node (js2-node-parent node))
4647 (while (not (or (js2-ast-root-p node)
4648 (js2-function-node-p node)))
4649 (setq node (js2-node-parent node)))
4652 (defun js2-mode-find-enclosing-node (beg end)
4653 "Find script or function fully enclosing BEG and END."
4654 (let ((node (js2-node-at-point beg))
4658 (if (or (js2-ast-root-p node)
4659 (and (js2-function-node-p node)
4660 (<= (setq pos (js2-node-abs-pos node)) beg)
4661 (>= (+ pos (js2-node-len node)) end)))
4663 (setq node (js2-node-parent node))))
4666 (defun js2-node-parent-script-or-fn (node)
4667 "Find script or function immediately enclosing NODE.
4668 If NODE is the ast-root, returns nil."
4669 (if (js2-ast-root-p node)
4671 (setq node (js2-node-parent node))
4672 (while (and node (not (or (js2-function-node-p node)
4673 (js2-script-node-p node))))
4674 (setq node (js2-node-parent node)))
4677 (defsubst js2-nested-function-p (node)
4678 "Return t if NODE is a nested function, or is inside a nested function."
4679 (unless (js2-ast-root-p node)
4680 (js2-function-node-p (if (js2-function-node-p node)
4681 (js2-node-parent-script-or-fn node)
4682 (js2-node-parent-script-or-fn
4683 (js2-node-parent-script-or-fn node))))))
4685 (defsubst js2-function-param-node-p (node)
4686 "Return non-nil if NODE is a param node of a `js2-function-node'."
4687 (let ((parent (js2-node-parent node)))
4689 (js2-function-node-p parent)
4690 (memq node (js2-function-node-params parent)))))
4692 (defsubst js2-mode-shift-kids (kids start offset)
4694 (if (> (js2-node-pos kid) start)
4695 (incf (js2-node-pos kid) offset))))
4697 (defsubst js2-mode-shift-children (parent start offset)
4698 "Update start-positions of all children of PARENT beyond START."
4699 (let ((root (js2-node-root parent)))
4700 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4701 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4703 (defsubst js2-node-is-descendant (node ancestor)
4704 "Return t if NODE is a descendant of ANCESTOR."
4706 (not (eq node ancestor)))
4707 (setq node (js2-node-parent node)))
4710 ;;; visitor infrastructure
4712 (defun js2-visit-none (node callback)
4713 "Visitor for AST node that have no node children."
4716 (defun js2-print-none (node indent)
4717 "Visitor for AST node with no printed representation.")
4719 (defun js2-print-body (node indent)
4720 "Print a statement, or a block without braces."
4721 (if (js2-block-node-p node)
4722 (dolist (kid (js2-block-node-kids node))
4723 (js2-print-ast kid indent))
4724 (js2-print-ast node indent)))
4726 (defun js2-print-list (args &optional delimiter)
4727 (loop with len = (length args)
4731 (js2-print-ast arg 0)
4733 (insert (or delimiter ", ")))))
4735 (defun js2-print-tree (ast)
4736 "Prints an AST to the current buffer.
4737 Makes `js2-ast-parent-nodes' available to the printer functions."
4738 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4739 (js2-print-ast ast)))
4741 (defun js2-print-ast (node &optional indent)
4742 "Helper function for printing AST nodes.
4743 Requires `js2-ast-parent-nodes' to be non-nil.
4744 You should use `js2-print-tree' instead of this function."
4745 (let ((printer (get (aref node 0) 'js2-printer))
4747 (pos (js2-node-abs-pos node)))
4748 ;; TODO: wedge comments in here somewhere
4750 (funcall printer node i))))
4752 (defconst js2-side-effecting-tokens
4753 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4754 (dolist (tt (list js2-ASSIGN
4823 (if js2-instanceof-has-side-effects
4824 (aset tokens js2-INSTANCEOF t))
4827 (defun js2-node-has-side-effects (node)
4828 "Return t if NODE has side effects."
4829 (when node ; makes it easier to handle malformed expressions
4830 (let ((tt (js2-node-type node)))
4832 ;; This doubtless needs some work, since EXPR_VOID is used
4833 ;; in several ways in Rhino, and I may not have caught them all.
4834 ;; I'll wait for people to notice incorrect warnings.
4835 ((and (= tt js2-EXPR_VOID)
4836 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4837 (let ((expr (js2-expr-stmt-node-expr node)))
4838 (or (js2-node-has-side-effects expr)
4839 (when (js2-string-node-p expr)
4840 (string= "use strict" (js2-string-node-value expr))))))
4842 (js2-node-has-side-effects (js2-infix-node-right node)))
4845 (or (js2-node-has-side-effects (js2-infix-node-right node))
4846 (js2-node-has-side-effects (js2-infix-node-left node))))
4848 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4849 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4850 ((js2-paren-node-p node)
4851 (js2-node-has-side-effects (js2-paren-node-expr node)))
4852 ((= tt js2-ERROR) ; avoid cascaded error messages
4855 (aref js2-side-effecting-tokens tt))))))
4857 (defun js2-member-expr-leftmost-name (node)
4858 "For an expr such as foo.bar.baz, return leftmost node foo.
4859 NODE is any `js2-node' object. If it represents a member expression,
4860 which is any sequence of property gets, element-gets, function calls,
4861 or xml descendants/filter operators, then we look at the lexically
4862 leftmost (first) node in the chain. If it is a name-node we return it.
4863 Note that NODE can be a raw name-node and it will be returned as well.
4864 If NODE is not a name-node or member expression, or if it is a member
4865 expression whose leftmost target is not a name node, returns nil."
4868 (while (and continue (not result))
4870 ((js2-name-node-p node)
4872 ((js2-prop-get-node-p node)
4873 (setq node (js2-prop-get-node-left node)))
4874 ;; TODO: handle call-nodes, xml-nodes, others?
4876 (setq continue nil))))
4879 (defconst js2-stmt-node-types
4883 js2-DEFAULT ; e4x "default xml namespace" statement
4895 "Node types that only appear in statement contexts.
4896 The list does not include nodes that always appear as the child
4897 of another specific statement type, such as switch-cases,
4898 catch and finally blocks, and else-clauses. The list also excludes
4899 nodes like yield, let and var, which may appear in either expression
4900 or statement context, and in the latter context always have a
4901 `js2-expr-stmt-node' parent. Finally, the list does not include
4902 functions or scripts, which are treated separately from statements
4903 by the JavaScript parser and runtime.")
4905 (defun js2-stmt-node-p (node)
4906 "Heuristic for figuring out if NODE is a statement.
4907 Some node types can appear in either an expression context or a
4908 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4909 For these node types in a statement context, the parent will be a
4910 `js2-expr-stmt-node'.
4911 Functions aren't included in the check."
4912 (memq (js2-node-type node) js2-stmt-node-types))
4914 (defsubst js2-mode-find-first-stmt (node)
4915 "Search upward starting from NODE looking for a statement.
4916 For purposes of this function, a `js2-function-node' counts."
4917 (while (not (or (js2-stmt-node-p node)
4918 (js2-function-node-p node)))
4919 (setq node (js2-node-parent node)))
4922 (defun js2-node-parent-stmt (node)
4923 "Return the node's first ancestor that is a statement.
4924 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4925 appearing in a statement context will have a parent that is a
4926 `js2-expr-stmt-node' that will be returned by this function."
4927 (let ((parent (js2-node-parent node)))
4928 (if (or (null parent)
4929 (js2-stmt-node-p parent)
4930 (and (js2-function-node-p parent)
4931 (not (eq (js2-function-node-form parent)
4932 'FUNCTION_EXPRESSION))))
4934 (js2-node-parent-stmt parent))))
4936 ;; In the Mozilla Rhino sources, Roshan James writes:
4937 ;; Does consistent-return analysis on the function body when strict mode is
4940 ;; function (x) { return (x+1) }
4944 ;; function (x) { if (x < 0) return (x+1); }
4946 ;; is not because the function can potentially return a value when the
4947 ;; condition is satisfied and if not, the function does not explicitly
4950 ;; This extends to checking mismatches such as "return" and "return <value>"
4951 ;; used in the same function. Warnings are not emitted if inconsistent
4952 ;; returns exist in code that can be statically shown to be unreachable.
4954 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4956 ;; emits no warning. However if the loop had a break statement, then a
4957 ;; warning would be emitted.
4959 ;; The consistency analysis looks at control structures such as loops, ifs,
4960 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4961 ;; warns the user about an inconsistent set of termination possibilities.
4963 ;; These flags enumerate the possible ways a statement/function can
4964 ;; terminate. These flags are used by endCheck() and by the Parser to
4965 ;; detect inconsistent return usage.
4967 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4968 ;; able to execute (example: throw, continue)
4970 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4971 ;; next one. Statement such as return dont. A compound statement may have
4972 ;; some branch that drops off control to the next statement.
4974 ;; END_RETURNS indicates that the statement can return with no value.
4975 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4977 ;; A compound statement such as
4981 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4983 (defconst js2-END_UNREACHED 0)
4984 (defconst js2-END_DROPS_OFF 1)
4985 (defconst js2-END_RETURNS 2)
4986 (defconst js2-END_RETURNS_VALUE 4)
4987 (defconst js2-END_YIELDS 8)
4989 (defun js2-has-consistent-return-usage (node)
4990 "Check that every return usage in a function body is consistent.
4991 Returns t if the function satisfies strict mode requirement."
4992 (let ((n (js2-end-check node)))
4993 ;; either it doesn't return a value in any branch...
4994 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4995 ;; or it returns a value (or is unreached) at every branch
4996 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5000 (defun js2-end-check-if (node)
5001 "Returns in the then and else blocks must be consistent with each other.
5002 If there is no else block, then the return statement can fall through.
5003 Returns logical OR of END_* flags"
5004 (let ((th (js2-if-node-then-part node))
5005 (el (js2-if-node-else-part node)))
5008 (logior (js2-end-check th) (if el
5010 js2-END_DROPS_OFF)))))
5012 (defun js2-end-check-switch (node)
5013 "Consistency of return statements is checked between the case statements.
5014 If there is no default, then the switch can fall through. If there is a
5015 default, we check to see if all code paths in the default return or if
5016 there is a code path that can fall through.
5017 Returns logical OR of END_* flags."
5018 (let ((rv js2-END_UNREACHED)
5020 ;; examine the cases
5022 (dolist (c (js2-switch-node-cases node))
5023 (if (js2-case-node-expr c)
5024 (js2-set-flag rv (js2-end-check-block c))
5025 (setq default-case c)
5026 (throw 'break nil))))
5027 ;; we don't care how the cases drop into each other
5028 (js2-clear-flag rv js2-END_DROPS_OFF)
5029 ;; examine the default
5030 (js2-set-flag rv (if default-case
5031 (js2-end-check default-case)
5035 (defun js2-end-check-try (node)
5036 "If the block has a finally, return consistency is checked in the
5037 finally block. If all code paths in the finally return, then the
5038 returns in the try-catch blocks don't matter. If there is a code path
5039 that does not return or if there is no finally block, the returns
5040 of the try and catch blocks are checked for mismatch.
5041 Returns logical OR of END_* flags."
5042 (let ((finally (js2-try-node-finally-block node))
5044 ;; check the finally if it exists
5045 (setq rv (if finally
5046 (js2-end-check (js2-finally-node-body finally))
5048 ;; If the finally block always returns, then none of the returns
5049 ;; in the try or catch blocks matter.
5050 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5051 (js2-clear-flag rv js2-END_DROPS_OFF)
5052 ;; examine the try block
5053 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5054 ;; check each catch block
5055 (dolist (cb (js2-try-node-catch-clauses node))
5056 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5059 (defun js2-end-check-loop (node)
5060 "Return statement in the loop body must be consistent. The default
5061 assumption for any kind of a loop is that it will eventually terminate.
5062 The only exception is a loop with a constant true condition. Code that
5063 follows such a loop is examined only if one can statically determine
5064 that there is a break out of the loop.
5066 for(... ; ... ; ...) {}
5071 Returns logical OR of END_* flags."
5072 (let ((rv (js2-end-check (js2-loop-node-body node)))
5074 ((js2-while-node-p node)
5075 (js2-while-node-condition node))
5076 ((js2-do-node-p node)
5077 (js2-do-node-condition node))
5078 ((js2-for-node-p node)
5079 (js2-for-node-condition node)))))
5081 ;; check to see if the loop condition is always true
5083 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5084 (js2-clear-flag rv js2-END_DROPS_OFF))
5086 ;; look for effect of breaks
5087 (js2-set-flag rv (js2-node-get-prop node
5092 (defun js2-end-check-block (node)
5093 "A general block of code is examined statement by statement.
5094 If any statement (even a compound one) returns in all branches, then
5095 subsequent statements are not examined.
5096 Returns logical OR of END_* flags."
5097 (let* ((rv js2-END_DROPS_OFF)
5098 (kids (js2-block-node-kids node))
5100 ;; Check each statment. If the statement can continue onto the next
5101 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5102 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5103 (js2-clear-flag rv js2-END_DROPS_OFF)
5104 (js2-set-flag rv (js2-end-check n))
5105 (setq kids (cdr kids)
5109 (defun js2-end-check-label (node)
5110 "A labeled statement implies that there may be a break to the label.
5111 The function processes the labeled statement and then checks the
5112 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5114 Returns logical OR of END_* flags."
5115 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5116 (logior rv (js2-node-get-prop node
5118 js2-END_UNREACHED))))
5120 (defun js2-end-check-break (node)
5121 "When a break is encountered annotate the statement being broken
5122 out of by setting its CONTROL_BLOCK_PROP property.
5123 Returns logical OR of END_* flags."
5124 (and (js2-break-node-target node)
5125 (js2-node-set-prop (js2-break-node-target node)
5130 (defun js2-end-check (node)
5131 "Examine the body of a function, doing a basic reachability analysis.
5132 Returns a combination of flags END_* flags that indicate
5133 how the function execution can terminate. These constitute only the
5134 pessimistic set of termination conditions. It is possible that at
5135 runtime certain code paths will never be actually taken. Hence this
5136 analysis will flag errors in cases where there may not be errors.
5137 Returns logical OR of END_* flags"
5140 ((js2-break-node-p node)
5141 (js2-end-check-break node))
5142 ((js2-expr-stmt-node-p node)
5143 (if (setq kid (js2-expr-stmt-node-expr node))
5146 ((or (js2-continue-node-p node)
5147 (js2-throw-node-p node))
5149 ((js2-return-node-p node)
5150 (if (setq kid (js2-return-node-retval node))
5151 js2-END_RETURNS_VALUE
5153 ((js2-loop-node-p node)
5154 (js2-end-check-loop node))
5155 ((js2-switch-node-p node)
5156 (js2-end-check-switch node))
5157 ((js2-labeled-stmt-node-p node)
5158 (js2-end-check-label node))
5159 ((js2-if-node-p node)
5160 (js2-end-check-if node))
5161 ((js2-try-node-p node)
5162 (js2-end-check-try node))
5163 ((js2-block-node-p node)
5164 (if (null (js2-block-node-kids node))
5166 (js2-end-check-block node)))
5167 ((js2-yield-node-p node)
5170 js2-END_DROPS_OFF))))
5172 (defun js2-always-defined-boolean-p (node)
5173 "Check if NODE always evaluates to true or false in boolean context.
5174 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5176 (let ((tt (js2-node-type node))
5179 ((or (= tt js2-FALSE) (= tt js2-NULL))
5184 (setq num (js2-number-node-num-value node))
5185 (if (and (not (eq num 0.0e+NaN))
5192 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5193 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5195 (defvar js2-tokens nil
5196 "List of all defined token names.") ; initialized in `js2-token-names'
5198 (defconst js2-token-names
5199 (let* ((names (make-vector js2-num-tokens -1))
5200 (case-fold-search nil) ; only match js2-UPPER_CASE
5201 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5202 (loop for sym in syms
5205 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5207 (aset names (symbol-value sym) ; code, e.g. 152
5208 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5209 (push sym js2-tokens)))
5211 "Vector mapping int values to token string names, sans `js2-' prefix.")
5213 (defun js2-token-name (tok)
5214 "Return a string name for TOK, a token symbol or code.
5215 Signals an error if it's not a recognized token."
5218 (setq code (symbol-value tok)))
5221 (if (and (numberp code)
5223 (< code js2-num-tokens))
5224 (aref js2-token-names code)
5225 (error "Invalid token: %s" code)))))
5227 (defsubst js2-token-sym (tok)
5228 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5229 (intern (js2-token-name tok)))
5231 (defconst js2-token-codes
5232 (let ((table (make-hash-table :test 'eq :size 256)))
5233 (loop for name across js2-token-names
5234 for sym = (intern (concat "js2-" name))
5236 (puthash sym (symbol-value sym) table))
5237 ;; clean up a few that are "wrong" in Rhino's token codes
5238 (puthash 'js2-DELETE js2-DELPROP table)
5240 "Hashtable mapping token symbols to their bytecodes.")
5242 (defsubst js2-token-code (sym)
5243 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5244 (or (gethash sym js2-token-codes)
5245 (error "Invalid token symbol: %s " sym))) ; signal code bug
5247 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5248 (setq js2-token-end js2-ts-cursor)
5249 (js2-report-error msg nil
5250 (or beg js2-token-beg)
5251 (or len (- js2-token-end js2-token-beg)))
5253 (throw 'return js2-ERROR)))
5255 (defsubst js2-get-string-from-buffer ()
5256 "Reverse the char accumulator and return it as a string."
5257 (setq js2-token-end js2-ts-cursor)
5258 (if js2-ts-string-buffer
5259 (apply #'string (nreverse js2-ts-string-buffer))
5262 ;; TODO: could potentially avoid a lot of consing by allocating a
5263 ;; char buffer the way Rhino does.
5264 (defsubst js2-add-to-string (c)
5265 (push c js2-ts-string-buffer))
5267 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5268 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5269 ;; any other character: when it's not part of the current token, we
5270 ;; unget it, allowing it to be read again by the following call.
5271 (defsubst js2-unget-char ()
5272 (decf js2-ts-cursor))
5274 ;; Rhino distinguishes \r and \n line endings. We don't need to
5275 ;; because we only scan from Emacs buffers, which always use \n.
5276 (defsubst js2-get-char ()
5277 "Read and return the next character from the input buffer.
5278 Increments `js2-ts-lineno' if the return value is a newline char.
5279 Updates `js2-ts-cursor' to the point after the returned char.
5280 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5281 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5283 ;; check for end of buffer
5284 (if (>= js2-ts-cursor (point-max))
5285 (setq js2-ts-hit-eof t
5286 js2-ts-cursor (1+ js2-ts-cursor)
5287 c js2-EOF_CHAR) ; return value
5288 ;; otherwise read next char
5289 (setq c (char-before (incf js2-ts-cursor)))
5290 ;; if we read a newline, update counters
5292 (setq js2-ts-line-start js2-ts-cursor
5293 js2-ts-lineno (1+ js2-ts-lineno)))
5294 ;; TODO: skip over format characters
5297 (defsubst js2-read-unicode-escape ()
5298 "Read a \\uNNNN sequence from the input.
5299 Assumes the ?\ and ?u have already been read.
5300 Returns the unicode character, or nil if it wasn't a valid character.
5301 Doesn't change the values of any scanner variables."
5302 ;; I really wish I knew a better way to do this, but I can't
5303 ;; find the Emacs function that takes a 16-bit int and converts
5304 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5305 ;; Have to first check that it's 4 hex characters or it may stop
5308 (let ((s (buffer-substring-no-properties js2-ts-cursor
5309 (+ 4 js2-ts-cursor))))
5310 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5311 (read (concat "?\\u" s))))))
5313 (defsubst js2-match-char (test)
5314 "Consume and return next character if it matches TEST, a character.
5315 Returns nil and consumes nothing if TEST is not the next character."
5316 (let ((c (js2-get-char)))
5322 (defsubst js2-peek-char ()
5327 (defsubst js2-java-identifier-start-p (c)
5330 (js2-char-uppercase-p c)
5331 (js2-char-lowercase-p c)))
5333 (defsubst js2-java-identifier-part-p (c)
5334 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5335 ;; TODO: make me Unicode-friendly. See comments above.
5338 (js2-char-uppercase-p c)
5339 (js2-char-lowercase-p c)
5340 (and (>= c ?0) (<= c ?9))))
5342 (defsubst js2-alpha-p (c)
5343 (cond ((and (<= ?A c) (<= c ?Z)) t)
5344 ((and (<= ?a c) (<= c ?z)) t)
5347 (defsubst js2-digit-p (c)
5348 (and (<= ?0 c) (<= c ?9)))
5350 (defsubst js2-js-space-p (c)
5352 (memq c '(#x20 #x9 #xB #xC #xD))
5355 ;; TODO: change this nil to check for Unicode space character
5358 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5360 (defsubst js2-skip-line ()
5361 "Skip to end of line"
5363 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5365 (setq js2-token-end js2-ts-cursor)))
5367 (defun js2-init-scanner (&optional buf line)
5368 "Create token stream for BUF starting on LINE.
5369 BUF defaults to current-buffer and line defaults to 1.
5371 A buffer can only have one scanner active at a time, which yields
5372 dramatically simpler code than using a defstruct. If you need to
5373 have simultaneous scanners in a buffer, copy the regions to scan
5378 (setq js2-ts-dirty-line nil
5379 js2-ts-regexp-flags nil
5384 js2-ts-lineno (or line 1)
5385 js2-ts-line-end-char -1
5386 js2-ts-cursor (point-min)
5387 js2-ts-is-xml-attribute nil
5388 js2-ts-xml-is-tag-content nil
5389 js2-ts-xml-open-tags-count 0
5390 js2-ts-string-buffer nil)))
5392 ;; This function uses the cached op, string and number fields in
5393 ;; TokenStream; if getToken has been called since the passed token
5394 ;; was scanned, the op or string printed may be incorrect.
5395 (defun js2-token-to-string (token)
5396 ;; Not sure where this function is used in Rhino. Not tested.
5397 (if (not js2-debug-print-trees)
5399 (let ((name (js2-token-name token)))
5401 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5402 (concat name " `" js2-ts-string "'"))
5403 ((eq token js2-NUMBER)
5404 (format "NUMBER %g" js2-ts-number))
5408 (defconst js2-keywords
5410 case catch const continue
5411 debugger default delete do
5413 false finally for function
5414 if in instanceof import
5419 this throw true try typeof
5424 ;; Token names aren't exactly the same as the keywords, unfortunately.
5425 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5426 (defconst js2-kwd-tokens
5427 (let ((table (make-vector js2-num-tokens nil))
5430 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5431 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5433 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5434 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5439 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5444 (aset table i 'font-lock-keyword-face))
5445 (aset table js2-STRING 'font-lock-string-face)
5446 (aset table js2-REGEXP 'font-lock-string-face)
5447 (aset table js2-COMMENT 'font-lock-comment-face)
5448 (aset table js2-THIS 'font-lock-builtin-face)
5449 (aset table js2-VOID 'font-lock-constant-face)
5450 (aset table js2-NULL 'font-lock-constant-face)
5451 (aset table js2-TRUE 'font-lock-constant-face)
5452 (aset table js2-FALSE 'font-lock-constant-face)
5454 "Vector whose values are non-nil for tokens that are keywords.
5455 The values are default faces to use for highlighting the keywords.")
5457 (defconst js2-reserved-words
5465 implements import int interface
5468 package private protected public
5469 short static super synchronized
5473 (defconst js2-keyword-names
5474 (let ((table (make-hash-table :test 'equal)))
5475 (loop for k in js2-keywords
5477 (symbol-name k) ; instanceof
5478 (intern (concat "js2-"
5479 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5482 "JavaScript keywords by name, mapped to their symbols.")
5484 (defconst js2-reserved-word-names
5485 (let ((table (make-hash-table :test 'equal)))
5486 (loop for k in js2-reserved-words
5488 (puthash (symbol-name k) 'js2-RESERVED table))
5490 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5492 (defsubst js2-collect-string (buf)
5493 "Convert BUF, a list of chars, to a string.
5494 Reverses BUF before converting."
5498 ((null buf) ; for emacs21 compat
5502 (apply #'string (nreverse buf))
5505 (defun js2-string-to-keyword (s)
5506 "Return token for S, a string, if S is a keyword or reserved word.
5507 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5508 (or (gethash s js2-keyword-names)
5509 (gethash s js2-reserved-word-names)))
5511 (defsubst js2-ts-set-char-token-bounds ()
5512 "Used when next token is one character."
5513 (setq js2-token-beg (1- js2-ts-cursor)
5514 js2-token-end js2-ts-cursor))
5516 (defsubst js2-ts-return (token)
5517 "Return an N-character TOKEN from `js2-get-token'.
5518 Updates `js2-token-end' accordingly."
5519 (setq js2-token-end js2-ts-cursor)
5520 (throw 'return token))
5522 (defsubst js2-x-digit-to-int (c accumulator)
5523 "Build up a hex number.
5524 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5525 corresponding number. Otherwise return -1."
5528 ;; Use 0..9 < A..Z < a..z
5533 (throw 'check nil)))
5537 (throw 'check nil)))
5541 (throw 'check nil))))
5543 (logior c (lsh accumulator 4))))
5545 (defun js2-get-token ()
5546 "Return next JavaScript token, an int such as js2-RETURN."
5550 is-unicode-escape-start
5564 ;; Eat whitespace, possibly sensitive to newlines.
5567 (setq c (js2-get-char))
5569 ((eq c js2-EOF_CHAR)
5570 (js2-ts-set-char-token-bounds)
5571 (throw 'return js2-EOF))
5573 (js2-ts-set-char-token-bounds)
5574 (setq js2-ts-dirty-line nil)
5575 (throw 'return js2-EOL))
5576 ((not (js2-js-space-p c))
5577 (if (/= c ?-) ; in case end of HTML comment
5578 (setq js2-ts-dirty-line t))
5579 (setq continue nil))))
5580 ;; Assume the token will be 1 char - fixed up below.
5581 (js2-ts-set-char-token-bounds)
5583 (throw 'return js2-XMLATTR))
5584 ;; identifier/keyword/instanceof?
5585 ;; watch out for starting with a <backslash>
5588 (setq c (js2-get-char))
5590 (setq identifier-start t
5591 is-unicode-escape-start t
5592 js2-ts-string-buffer nil)
5593 (setq identifier-start nil)
5597 (when (setq identifier-start (js2-java-identifier-start-p c))
5598 (setq js2-ts-string-buffer nil)
5599 (js2-add-to-string c))))
5600 (when identifier-start
5601 (setq contains-escape is-unicode-escape-start)
5604 (if is-unicode-escape-start
5605 ;; strictly speaking we should probably push-back
5606 ;; all the bad characters if the <backslash>uXXXX
5607 ;; sequence is malformed. But since there isn't a
5608 ;; correct context(is there?) for a bad Unicode
5609 ;; escape sequence in an identifier, we can report
5614 (setq c (js2-get-char)
5615 escape-val (js2-x-digit-to-int c escape-val))
5616 ;; Next check takes care of c < 0 and bad escape
5617 (if (minusp escape-val)
5618 (throw 'break nil)))
5619 (if (minusp escape-val)
5620 (js2-report-scan-error "msg.invalid.escape" t))
5621 (js2-add-to-string escape-val)
5622 (setq is-unicode-escape-start nil))
5623 (setq c (js2-get-char))
5626 (setq c (js2-get-char))
5628 (setq is-unicode-escape-start t
5630 (js2-report-scan-error "msg.illegal.character" t)))
5632 (if (or (eq c js2-EOF_CHAR)
5633 (not (js2-java-identifier-part-p c)))
5635 (js2-add-to-string c))))))
5637 (setq str (js2-get-string-from-buffer))
5638 (unless contains-escape
5639 ;; OPT we shouldn't have to make a string (object!) to
5640 ;; check if it's a keyword.
5641 ;; Return the corresponding token if it's a keyword
5642 (when (setq result (js2-string-to-keyword str))
5643 (if (and (< js2-language-version 170)
5644 (memq result '(js2-LET js2-YIELD)))
5645 ;; LET and YIELD are tokens only in 1.7 and later
5646 (setq result 'js2-NAME))
5647 (if (not (eq result 'js2-RESERVED))
5648 (throw 'return (js2-token-code result)))
5649 (js2-report-warning "msg.reserved.keyword" str)))
5650 ;; If we want to intern these as Rhino does, just use (intern str)
5651 (setq js2-ts-string str)
5652 (throw 'return js2-NAME)) ; end identifier/kwd check
5654 (when (or (js2-digit-p c)
5655 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5656 (setq js2-ts-string-buffer nil
5659 (setq c (js2-get-char))
5661 ((or (eq c ?x) (eq c ?X))
5663 (setq c (js2-get-char)))
5667 (js2-add-to-string ?0))))
5669 (while (<= 0 (js2-x-digit-to-int c 0))
5670 (js2-add-to-string c)
5671 (setq c (js2-get-char)))
5672 (while (and (<= ?0 c) (<= c ?9))
5673 ;; We permit 08 and 09 as decimal numbers, which
5674 ;; makes our behavior a superset of the ECMA
5675 ;; numeric grammar. We might not always be so
5676 ;; permissive, so we warn about it.
5677 (when (and (eq base 8) (>= c ?8))
5678 (js2-report-warning "msg.bad.octal.literal"
5679 (if (eq c ?8) "8" "9"))
5681 (js2-add-to-string c)
5682 (setq c (js2-get-char))))
5684 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5685 (setq is-integer nil)
5688 (js2-add-to-string c)
5689 (setq c (js2-get-char))
5690 while (js2-digit-p c)))
5691 (when (memq c '(?e ?E))
5692 (js2-add-to-string c)
5693 (setq c (js2-get-char))
5694 (when (memq c '(?+ ?-))
5695 (js2-add-to-string c)
5696 (setq c (js2-get-char)))
5697 (unless (js2-digit-p c)
5698 (js2-report-scan-error "msg.missing.exponent" t))
5700 (js2-add-to-string c)
5701 (setq c (js2-get-char))
5702 while (js2-digit-p c))))
5704 (setq js2-ts-string (js2-get-string-from-buffer)
5706 (if (and (eq base 10) (not is-integer))
5707 (string-to-number js2-ts-string)
5708 ;; TODO: call runtime number-parser. Some of it is in
5709 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5710 (string-to-number js2-ts-string)))
5711 (throw 'return js2-NUMBER))
5713 (when (memq c '(?\" ?\'))
5714 ;; We attempt to accumulate a string the fast way, by
5715 ;; building it directly out of the reader. But if there
5716 ;; are any escaped characters in the string, we revert to
5717 ;; building it out of a string buffer.
5719 js2-ts-string-buffer nil
5722 (while (/= c quote-char)
5724 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5726 (setq js2-token-end js2-ts-cursor)
5727 (js2-report-error "msg.unterminated.string.lit")
5728 (throw 'return js2-STRING))
5730 ;; We've hit an escaped character
5731 (setq c (js2-get-char))
5740 (setq c1 (js2-read-unicode-escape))
5741 (if js2-parse-ide-mode
5744 ;; just copy the string in IDE-mode
5745 (js2-add-to-string ?\\)
5746 (js2-add-to-string ?u)
5748 (js2-add-to-string (js2-get-char)))
5749 (setq c (js2-get-char))) ; added at end of loop
5750 ;; flag it as an invalid escape
5751 (js2-report-warning "msg.invalid.escape"
5752 nil (- js2-ts-cursor 2) 6))
5753 ;; Get 4 hex digits; if the u escape is not
5754 ;; followed by 4 hex digits, use 'u' + the
5755 ;; literal character sequence that follows.
5756 (js2-add-to-string ?u)
5759 (setq c (js2-get-char)
5760 escape-val (js2-x-digit-to-int c escape-val))
5761 (if (minusp escape-val)
5762 (throw 'continue nil))
5763 (js2-add-to-string c))
5764 ;; prepare for replace of stored 'u' sequence by escape value
5765 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5768 ;; Get 2 hex digits, defaulting to 'x'+literal
5769 ;; sequence, as above.
5770 (setq c (js2-get-char)
5771 escape-val (js2-x-digit-to-int c 0))
5772 (if (minusp escape-val)
5774 (js2-add-to-string ?x)
5775 (throw 'continue nil))
5778 escape-val (js2-x-digit-to-int c escape-val))
5779 (if (minusp escape-val)
5781 (js2-add-to-string ?x)
5782 (js2-add-to-string c1)
5783 (throw 'continue nil))
5785 (setq c escape-val))))
5787 ;; Remove line terminator after escape to follow
5788 ;; SpiderMonkey and C/C++
5789 (setq c (js2-get-char))
5790 (throw 'continue nil))
5792 (when (and (<= ?0 c) (< c ?8))
5795 (when (and (<= ?0 c) (< c ?8))
5796 (setq val (- (+ (* 8 val) c) ?0)
5798 (when (and (<= ?0 c)
5801 ;; c is 3rd char of octal sequence only
5802 ;; if the resulting val <= 0377
5803 (setq val (- (+ (* 8 val) c) ?0)
5807 (js2-add-to-string c)
5808 (setq c (js2-get-char)))))
5809 (setq js2-ts-string (js2-get-string-from-buffer))
5810 (throw 'return js2-STRING))
5813 (throw 'return js2-SEMI))
5815 (throw 'return js2-LB))
5817 (throw 'return js2-RB))
5819 (throw 'return js2-LC))
5821 (throw 'return js2-RC))
5823 (throw 'return js2-LP))
5825 (throw 'return js2-RP))
5827 (throw 'return js2-COMMA))
5829 (throw 'return js2-HOOK))
5831 (if (js2-match-char ?:)
5832 (js2-ts-return js2-COLONCOLON)
5833 (throw 'return js2-COLON)))
5835 (if (js2-match-char ?.)
5836 (js2-ts-return js2-DOTDOT)
5837 (if (js2-match-char ?\()
5838 (js2-ts-return js2-DOTQUERY)
5839 (throw 'return js2-DOT))))
5841 (if (js2-match-char ?|)
5842 (throw 'return js2-OR)
5843 (if (js2-match-char ?=)
5844 (js2-ts-return js2-ASSIGN_BITOR)
5845 (throw 'return js2-BITOR))))
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-ASSIGN_BITOR)
5849 (throw 'return js2-BITXOR)))
5851 (if (js2-match-char ?&)
5852 (throw 'return js2-AND)
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-ASSIGN_BITAND)
5855 (throw 'return js2-BITAND))))
5857 (if (js2-match-char ?=)
5858 (if (js2-match-char ?=)
5859 (js2-ts-return js2-SHEQ)
5860 (throw 'return js2-EQ))
5861 (throw 'return js2-ASSIGN)))
5863 (if (js2-match-char ?=)
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-SHNE)
5866 (js2-ts-return js2-NE))
5867 (throw 'return js2-NOT)))
5869 ;; NB:treat HTML begin-comment as comment-till-eol
5870 (when (js2-match-char ?!)
5871 (when (js2-match-char ?-)
5872 (when (js2-match-char ?-)
5874 (setq js2-ts-comment-type 'html)
5875 (throw 'return js2-COMMENT)))
5877 (if (js2-match-char ?<)
5878 (if (js2-match-char ?=)
5879 (js2-ts-return js2-ASSIGN_LSH)
5880 (js2-ts-return js2-LSH))
5881 (if (js2-match-char ?=)
5882 (js2-ts-return js2-LE)
5883 (throw 'return js2-LT))))
5885 (if (js2-match-char ?>)
5886 (if (js2-match-char ?>)
5887 (if (js2-match-char ?=)
5888 (js2-ts-return js2-ASSIGN_URSH)
5889 (js2-ts-return js2-URSH))
5890 (if (js2-match-char ?=)
5891 (js2-ts-return js2-ASSIGN_RSH)
5892 (js2-ts-return js2-RSH)))
5893 (if (js2-match-char ?=)
5894 (js2-ts-return js2-GE)
5895 (throw 'return js2-GT))))
5897 (if (js2-match-char ?=)
5898 (js2-ts-return js2-ASSIGN_MUL)
5899 (throw 'return js2-MUL)))
5901 ;; is it a // comment?
5902 (when (js2-match-char ?/)
5903 (setq js2-token-beg (- js2-ts-cursor 2))
5905 (setq js2-ts-comment-type 'line)
5906 ;; include newline so highlighting goes to end of window
5907 (incf js2-token-end)
5908 (throw 'return js2-COMMENT))
5909 ;; is it a /* comment?
5910 (when (js2-match-char ?*)
5911 (setq look-for-slash nil
5912 js2-token-beg (- js2-ts-cursor 2)
5914 (if (js2-match-char ?*)
5916 (setq look-for-slash t)
5920 (setq c (js2-get-char))
5922 ((eq c js2-EOF_CHAR)
5923 (setq js2-token-end (1- js2-ts-cursor))
5924 (js2-report-error "msg.unterminated.comment")
5925 (throw 'return js2-COMMENT))
5927 (setq look-for-slash t))
5930 (js2-ts-return js2-COMMENT)))
5932 (setq look-for-slash nil
5933 js2-token-end js2-ts-cursor)))))
5934 (if (js2-match-char ?=)
5935 (js2-ts-return js2-ASSIGN_DIV)
5936 (throw 'return js2-DIV)))
5938 (when js2-skip-preprocessor-directives
5940 (setq js2-ts-comment-type 'preprocessor
5941 js2-token-end js2-ts-cursor)
5942 (throw 'return js2-COMMENT))
5943 (throw 'return js2-ERROR))
5945 (if (js2-match-char ?=)
5946 (js2-ts-return js2-ASSIGN_MOD)
5947 (throw 'return js2-MOD)))
5949 (throw 'return js2-BITNOT))
5951 (if (js2-match-char ?=)
5952 (js2-ts-return js2-ASSIGN_ADD)
5953 (if (js2-match-char ?+)
5954 (js2-ts-return js2-INC)
5955 (throw 'return js2-ADD))))
5958 ((js2-match-char ?=)
5959 (setq c js2-ASSIGN_SUB))
5960 ((js2-match-char ?-)
5961 (unless js2-ts-dirty-line
5962 ;; treat HTML end-comment after possible whitespace
5963 ;; after line start as comment-until-eol
5964 (when (js2-match-char ?>)
5966 (setq js2-ts-comment-type 'html)
5967 (throw 'return js2-COMMENT)))
5971 (setq js2-ts-dirty-line t)
5974 (js2-report-scan-error "msg.illegal.character")))))))
5976 (defun js2-read-regexp (start-token)
5977 "Called by parser when it gets / or /= in literal context."
5980 in-class ; inside a '[' .. ']' character-class
5983 (setq js2-token-beg js2-ts-cursor
5984 js2-ts-string-buffer nil
5985 js2-ts-regexp-flags nil)
5986 (if (eq start-token js2-ASSIGN_DIV)
5988 (js2-add-to-string ?=)
5989 (if (not (eq start-token js2-DIV))
5990 (error "failed assertion")))
5991 (while (and (not err)
5992 (or (/= (setq c (js2-get-char)) ?/)
5997 (setq js2-token-end (1- js2-ts-cursor)
5999 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6000 (js2-report-error "msg.unterminated.re.lit"))
6003 (js2-add-to-string c)
6004 (setq c (js2-get-char)))
6008 (setq in-class nil)))
6009 (js2-add-to-string c))))
6013 ((js2-match-char ?g)
6015 ((js2-match-char ?i)
6017 ((js2-match-char ?m)
6020 (setq continue nil))))
6021 (if (js2-alpha-p (js2-peek-char))
6022 (js2-report-scan-error "msg.invalid.re.flag" t
6024 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6025 js2-ts-regexp-flags (js2-collect-string flags)
6026 js2-token-end js2-ts-cursor)
6027 ;; tell `parse-partial-sexp' to ignore this range of chars
6028 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6030 (defun js2-get-first-xml-token ()
6031 (setq js2-ts-xml-open-tags-count 0
6032 js2-ts-is-xml-attribute nil
6033 js2-ts-xml-is-tag-content nil)
6035 (js2-get-next-xml-token))
6037 (defsubst js2-xml-discard-string ()
6038 "Throw away the string in progress and flag an XML parse error."
6039 (setq js2-ts-string-buffer nil
6041 (js2-report-scan-error "msg.XML.bad.form" t))
6043 (defun js2-get-next-xml-token ()
6044 (setq js2-ts-string-buffer nil ; for recording the XML
6045 js2-token-beg js2-ts-cursor)
6050 (setq c (js2-get-char))
6053 (throw 'return js2-ERROR))
6054 (js2-ts-xml-is-tag-content
6057 (js2-add-to-string c)
6058 (setq js2-ts-xml-is-tag-content nil
6059 js2-ts-is-xml-attribute nil))
6061 (js2-add-to-string c)
6062 (when (eq ?> (js2-peek-char))
6063 (setq c (js2-get-char))
6064 (js2-add-to-string c)
6065 (setq js2-ts-xml-is-tag-content nil)
6066 (decf js2-ts-xml-open-tags-count)))
6069 (setq js2-ts-string (js2-get-string-from-buffer))
6070 (throw 'return js2-XML))
6072 (js2-add-to-string c)
6073 (unless (js2-read-quoted-string c)
6074 (throw 'return js2-ERROR)))
6076 (js2-add-to-string c)
6077 (setq js2-ts-is-xml-attribute t))
6079 (js2-add-to-string c))
6081 (js2-add-to-string c)
6082 (setq js2-ts-is-xml-attribute nil)))
6083 (when (and (not js2-ts-xml-is-tag-content)
6084 (zerop js2-ts-xml-open-tags-count))
6085 (setq js2-ts-string (js2-get-string-from-buffer))
6086 (throw 'return js2-XMLEND)))
6088 ;; else not tag content
6091 (js2-add-to-string c)
6092 (setq c (js2-peek-char))
6095 (setq c (js2-get-char)) ;; skip !
6096 (js2-add-to-string c)
6097 (setq c (js2-peek-char))
6100 (setq c (js2-get-char)) ;; skip -
6101 (js2-add-to-string c)
6104 (js2-add-to-string c)
6105 (unless (js2-read-xml-comment)
6106 (throw 'return js2-ERROR)))
6107 (js2-xml-discard-string)
6108 (throw 'return js2-ERROR)))
6110 (setq c (js2-get-char)) ;; skip [
6111 (js2-add-to-string c)
6112 (if (and (= (js2-get-char) ?C)
6113 (= (js2-get-char) ?D)
6114 (= (js2-get-char) ?A)
6115 (= (js2-get-char) ?T)
6116 (= (js2-get-char) ?A)
6117 (= (js2-get-char) ?\[))
6119 (js2-add-to-string ?C)
6120 (js2-add-to-string ?D)
6121 (js2-add-to-string ?A)
6122 (js2-add-to-string ?T)
6123 (js2-add-to-string ?A)
6124 (js2-add-to-string ?\[)
6125 (unless (js2-read-cdata)
6126 (throw 'return js2-ERROR)))
6127 (js2-xml-discard-string)
6128 (throw 'return js2-ERROR)))
6130 (unless (js2-read-entity)
6131 (throw 'return js2-ERROR))))
6132 ;; allow bare CDATA section
6133 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6134 (when (zerop js2-ts-xml-open-tags-count)
6135 (throw 'return js2-XMLEND)))
6137 (setq c (js2-get-char)) ;; skip ?
6138 (js2-add-to-string c)
6139 (unless (js2-read-PI)
6140 (throw 'return js2-ERROR)))
6143 (setq c (js2-get-char)) ;; skip /
6144 (js2-add-to-string c)
6145 (when (zerop js2-ts-xml-open-tags-count)
6146 (js2-xml-discard-string)
6147 (throw 'return js2-ERROR))
6148 (setq js2-ts-xml-is-tag-content t)
6149 (decf js2-ts-xml-open-tags-count))
6152 (setq js2-ts-xml-is-tag-content t)
6153 (incf js2-ts-xml-open-tags-count))))
6156 (setq js2-ts-string (js2-get-string-from-buffer))
6157 (throw 'return js2-XML))
6159 (js2-add-to-string c))))))))
6160 (setq js2-token-end js2-ts-cursor)
6163 (defun js2-read-quoted-string (quote)
6166 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6167 (js2-add-to-string c)
6170 (js2-xml-discard-string) ;; throw away string in progress
6173 (defun js2-read-xml-comment ()
6174 (let ((c (js2-get-char)))
6176 (while (/= c js2-EOF_CHAR)
6178 (js2-add-to-string c)
6179 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6180 (setq c (js2-get-char))
6181 (js2-add-to-string c)
6182 (if (eq (js2-peek-char) ?>)
6184 (setq c (js2-get-char)) ;; skip >
6185 (js2-add-to-string c)
6187 (throw 'continue nil)))
6188 (setq c (js2-get-char))))
6189 (js2-xml-discard-string)
6192 (defun js2-read-cdata ()
6193 (let ((c (js2-get-char)))
6195 (while (/= c js2-EOF_CHAR)
6197 (js2-add-to-string c)
6198 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6199 (setq c (js2-get-char))
6200 (js2-add-to-string c)
6201 (if (eq (js2-peek-char) ?>)
6203 (setq c (js2-get-char)) ;; Skip >
6204 (js2-add-to-string c)
6206 (throw 'continue nil)))
6207 (setq c (js2-get-char))))
6208 (js2-xml-discard-string)
6211 (defun js2-read-entity ()
6215 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6216 (js2-add-to-string c)
6222 (if (zerop decl-tags)
6223 (throw 'return t)))))
6224 (js2-xml-discard-string)
6227 (defun js2-read-PI ()
6228 "Scan an XML processing instruction."
6231 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6232 (js2-add-to-string c)
6233 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6234 (setq c (js2-get-char)) ;; Skip >
6235 (js2-add-to-string c)
6237 (js2-xml-discard-string)
6240 (defun js2-scanner-get-line ()
6241 "Return the text of the current scan line."
6242 (buffer-substring (point-at-bol) (point-at-eol)))
6246 (defsubst js2-set-face (beg end face &optional record)
6247 "Fontify a region. If RECORD is non-nil, record for later."
6248 (when (plusp js2-highlight-level)
6249 (setq beg (min (point-max) beg)
6250 beg (max (point-min) beg)
6251 end (min (point-max) end)
6252 end (max (point-min) end))
6254 (push (list beg end face) js2-mode-fontifications)
6255 (put-text-property beg end 'font-lock-face face))))
6257 (defsubst js2-set-kid-face (pos kid len face)
6258 "Set-face on a child node.
6259 POS is absolute buffer position of parent.
6260 KID is the child node.
6261 LEN is the length to fontify.
6262 FACE is the face to fontify with."
6263 (js2-set-face (+ pos (js2-node-pos kid))
6264 (+ pos (js2-node-pos kid) (js2-node-len kid))
6267 (defsubst js2-fontify-kwd (start length)
6268 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6270 (defsubst js2-clear-face (beg end)
6271 (remove-text-properties beg end '(font-lock-face nil
6276 (defconst js2-ecma-global-props
6279 '("Infinity" "NaN" "undefined" "arguments") t)
6281 "Value properties of the Ecma-262 Global Object.
6282 Shown at or above `js2-highlight-level' 2.")
6284 ;; might want to add the name "arguments" to this list?
6285 (defconst js2-ecma-object-props
6288 '("prototype" "__proto__" "__parent__") t)
6290 "Value properties of the Ecma-262 Object constructor.
6291 Shown at or above `js2-highlight-level' 2.")
6293 (defconst js2-ecma-global-funcs
6297 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6298 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6300 "Function properties of the Ecma-262 Global object.
6301 Shown at or above `js2-highlight-level' 2.")
6303 (defconst js2-ecma-number-props
6305 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6307 "POSITIVE_INFINITY") t)
6309 "Properties of the Ecma-262 Number constructor.
6310 Shown at or above `js2-highlight-level' 2.")
6312 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6313 "Properties of the Ecma-262 Date constructor.
6314 Shown at or above `js2-highlight-level' 2.")
6316 (defconst js2-ecma-math-props
6319 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6322 "Properties of the Ecma-262 Math object.
6323 Shown at or above `js2-highlight-level' 2.")
6325 (defconst js2-ecma-math-funcs
6328 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6329 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6331 "Function properties of the Ecma-262 Math object.
6332 Shown at or above `js2-highlight-level' 2.")
6334 (defconst js2-ecma-function-props
6338 '(;; properties of the Object prototype object
6339 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6340 "toLocaleString" "toString" "valueOf"
6341 ;; properties of the Function prototype object
6343 ;; properties of the Array prototype object
6344 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6346 ;; properties of the String prototype object
6347 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6348 "localeCompare" "match" "replace" "search" "split" "substring"
6349 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6351 ;; properties of the Number prototype object
6352 "toExponential" "toFixed" "toPrecision"
6353 ;; properties of the Date prototype object
6354 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6355 "getMinutes" "getMonth" "getSeconds" "getTime"
6356 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6357 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6358 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6359 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6360 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6361 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6362 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6363 "toTimeString" "toUTCString"
6364 ;; properties of the RegExp prototype object
6366 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6367 "toSource" "__defineGetter__" "__defineSetter__"
6368 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6369 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6372 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6373 Shown at or above `js2-highlight-level' 3.")
6375 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6376 (let ((target-name (and target
6377 (js2-name-node-p target)
6378 (js2-name-node-name target)))
6379 (prop-name (if prop (js2-name-node-name prop)))
6380 (level1 (>= js2-highlight-level 1))
6381 (level2 (>= js2-highlight-level 2))
6382 (level3 (>= js2-highlight-level 3))
6390 ((and level3 (string-match js2-ecma-function-props prop-name))
6391 (setq face 'font-lock-builtin-face))
6392 ((and target-name prop)
6394 ((string= target-name "Date")
6395 (if (string-match js2-ecma-date-props prop-name)
6396 (setq face 'font-lock-builtin-face)))
6397 ((string= target-name "Math")
6398 (if (string-match js2-ecma-math-funcs prop-name)
6399 (setq face 'font-lock-builtin-face)))))))
6401 (if (string-match js2-ecma-global-funcs prop-name)
6402 (setq face 'font-lock-builtin-face))))
6406 ((string= target-name "Number")
6407 (if (string-match js2-ecma-number-props prop-name)
6408 (setq face 'font-lock-constant-face)))
6409 ((string= target-name "Math")
6410 (if (string-match js2-ecma-math-props prop-name)
6411 (setq face 'font-lock-constant-face)))))
6413 (if (string-match js2-ecma-object-props prop-name)
6414 (setq face 'font-lock-constant-face)))))
6416 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6417 (js2-node-pos prop))) ; relative
6418 (+ pos (js2-node-len prop))
6421 (defun js2-parse-highlight-member-expr-node (node)
6422 "Perform syntax highlighting of EcmaScript built-in properties.
6423 The variable `js2-highlight-level' governs this highighting."
6424 (let (face target prop name pos end parent call-p callee)
6426 ;; case 1: simple name, e.g. foo
6427 ((js2-name-node-p node)
6428 (setq name (js2-name-node-name node))
6429 ;; possible for name to be nil in rare cases - saw it when
6430 ;; running js2-mode on an elisp buffer. Might as well try to
6431 ;; make it so js2-mode never barfs.
6433 (setq face (if (string-match js2-ecma-global-props name)
6434 'font-lock-constant-face))
6436 (setq pos (js2-node-pos node)
6437 end (+ pos (js2-node-len node)))
6438 (js2-set-face pos end face))))
6439 ;; case 2: property access or function call
6440 ((or (js2-prop-get-node-p node)
6441 ;; highlight function call if expr is a prop-get node
6442 ;; or a plain name (i.e. unqualified function call)
6443 (and (setq call-p (js2-call-node-p node))
6444 (setq callee (js2-call-node-target node)) ; separate setq!
6445 (or (js2-prop-get-node-p callee)
6446 (js2-name-node-p callee))))
6448 node (if call-p callee node))
6449 (if (and call-p (js2-name-node-p callee))
6451 (setq target (js2-prop-get-node-left node)
6452 prop (js2-prop-get-node-right node)))
6454 ((js2-name-node-p target)
6455 (if (js2-name-node-p prop)
6456 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6457 (js2-parse-highlight-prop-get parent target prop call-p)
6458 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6459 (js2-parse-highlight-prop-get parent target nil call-p)))
6460 ((js2-name-node-p prop)
6461 ;; case 2c: complex target, simple name, e.g. x[y].bar
6462 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6464 (defun js2-parse-highlight-member-expr-fn-name (expr)
6465 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6466 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6467 We currently only handle the case where the last component is a prop-get
6468 of a simple name. Called before EXPR has a parent node."
6470 (name (and (js2-prop-get-node-p expr)
6471 (js2-prop-get-node-right expr))))
6472 (when (js2-name-node-p name)
6473 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6474 (js2-node-pos name)))
6475 (+ pos (js2-node-len name))
6476 'font-lock-function-name-face
6479 ;; source: http://jsdoc.sourceforge.net/
6480 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6481 ;; allows type specifications, and needs work before entering the wild.
6483 (defconst js2-jsdoc-param-tag-regexp
6484 (concat "^\\s-*\\*+\\s-*\\(@"
6485 "\\(?:param\\|argument\\)"
6487 "\\s-*\\({[^}]+}\\)?" ; optional type
6488 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6490 "Matches jsdoc tags with optional type and optional param name.")
6492 (defconst js2-jsdoc-typed-tag-regexp
6493 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6507 "\\)\\)\\s-*\\({[^}]+}\\)?")
6508 "Matches jsdoc tags with optional type.")
6510 (defconst js2-jsdoc-arg-tag-regexp
6511 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6534 "\\)\\)\\s-+\\([^ \t]+\\)")
6535 "Matches jsdoc tags with a single argument.")
6537 (defconst js2-jsdoc-empty-tag-regexp
6538 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6578 "Matches empty jsdoc tags.")
6580 (defconst js2-jsdoc-link-tag-regexp
6581 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6582 "Matches a jsdoc link or code tag.")
6584 (defconst js2-jsdoc-see-tag-regexp
6585 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6586 "Matches a jsdoc @see tag.")
6588 (defconst js2-jsdoc-html-tag-regexp
6589 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6590 "Matches a simple (no attributes) html start- or end-tag.")
6592 (defsubst js2-jsdoc-highlight-helper ()
6593 (js2-set-face (match-beginning 1)
6595 'js2-jsdoc-tag-face)
6596 (if (match-beginning 2)
6598 (goto-char (match-beginning 2))
6599 (= (char-after) ?{))
6600 (js2-set-face (1+ (match-beginning 2))
6602 'js2-jsdoc-type-face)
6603 (js2-set-face (match-beginning 2)
6605 'js2-jsdoc-value-face)))
6606 (if (match-beginning 3)
6607 (js2-set-face (match-beginning 3)
6609 'js2-jsdoc-value-face)))
6611 (defun js2-highlight-jsdoc (ast)
6612 "Highlight doc comment tags."
6613 (let ((comments (js2-ast-root-comments ast))
6616 (dolist (node comments)
6617 (when (eq (js2-comment-node-format node) 'jsdoc)
6618 (setq beg (js2-node-abs-pos node)
6619 end (+ beg (js2-node-len node)))
6621 (narrow-to-region beg end)
6622 (dolist (re (list js2-jsdoc-param-tag-regexp
6623 js2-jsdoc-typed-tag-regexp
6624 js2-jsdoc-arg-tag-regexp
6625 js2-jsdoc-link-tag-regexp
6626 js2-jsdoc-see-tag-regexp
6627 js2-jsdoc-empty-tag-regexp))
6629 (while (re-search-forward re nil t)
6630 (js2-jsdoc-highlight-helper)))
6631 ;; simple highlighting for html tags
6633 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6634 (js2-set-face (match-beginning 1)
6636 'js2-jsdoc-html-tag-delimiter-face)
6637 (js2-set-face (match-beginning 2)
6639 'js2-jsdoc-html-tag-name-face)
6640 (js2-set-face (match-beginning 3)
6642 'js2-jsdoc-html-tag-delimiter-face))))))))
6644 (defun js2-highlight-assign-targets (node left right)
6645 "Highlight function properties and external variables."
6646 (let (leftpos end name)
6647 ;; highlight vars and props assigned function values
6648 (when (js2-function-node-p right)
6650 ;; var foo = function() {...}
6651 ((js2-name-node-p left)
6653 ;; foo.bar.baz = function() {...}
6654 ((and (js2-prop-get-node-p left)
6655 (js2-name-node-p (js2-prop-get-node-right left)))
6656 (setq name (js2-prop-get-node-right left))))
6658 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6659 (+ leftpos (js2-node-len name))
6660 'font-lock-function-name-face
6663 (defun js2-record-name-node (node)
6664 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6665 later. NODE must be a name node."
6667 (push (list node js2-current-scope
6668 (setq leftpos (js2-node-abs-pos node))
6669 (setq end (+ leftpos (js2-node-len node))))
6670 js2-recorded-identifiers)))
6672 (defun js2-highlight-undeclared-vars ()
6673 "After entire parse is finished, look for undeclared variable references.
6674 We have to wait until entire buffer is parsed, since JavaScript permits var
6675 decls to occur after they're used.
6677 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6678 it is considered declared."
6680 (dolist (entry js2-recorded-identifiers)
6681 (destructuring-bind (name-node scope pos end) entry
6682 (setq name (js2-name-node-name name-node))
6683 (unless (or (member name js2-global-externs)
6684 (member name js2-default-externs)
6685 (member name js2-additional-externs)
6686 (js2-get-defining-scope scope name))
6687 (js2-set-face pos end 'js2-external-variable-face 'record)
6688 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6689 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6690 (setq js2-recorded-identifiers nil)))
6694 ;; We currently only support imenu, but eventually should support speedbar and
6695 ;; possibly other browsing mechanisms.
6697 ;; The basic strategy is to identify function assignment targets of the form
6698 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6699 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6700 ;; for imenu after parsing is finished.
6702 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6703 ;; JavaScript, and the general problem is undecidable. However, several forms
6704 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6707 ;; function foo() -- function declaration
6708 ;; foo = function() -- function expression assigned to variable
6709 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6710 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6711 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6712 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6713 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6714 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6715 ;; function foo() {function bar() {...}} -- nested function
6716 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6718 ;; This list boils down to a few forms that can be combined recursively.
6719 ;; Top-level named function declarations include both the left-hand (name)
6720 ;; and the right-hand (function value) expressions needed to produce an imenu
6721 ;; entry. The other "right-hand" forms we need to look for are:
6722 ;; - functions declared as props/getters/setters in object literals
6723 ;; - nested named function declarations
6724 ;; The "left-hand" expressions that functions can be assigned to include:
6725 ;; - local/global variables
6726 ;; - nested property-get expressions like a.b.c.d
6727 ;; - element gets like foo[10] or foo['bar'] where the index
6728 ;; expression can be trivially converted to a property name. They
6729 ;; effectively then become property gets.
6731 ;; All the different definition types are canonicalized into the form
6732 ;; foo.bar.baz = position-of-function-keyword
6734 ;; We need to build a trie-like structure for imenu. As an example,
6735 ;; consider the following JavaScript code:
6737 ;; a = function() {...} // function at position 5
6738 ;; b = function() {...} // function at position 25
6739 ;; foo = function() {...} // function at position 100
6740 ;; foo.bar = function() {...} // function at position 200
6741 ;; foo.bar.baz = function() {...} // function at position 300
6742 ;; foo.bar.zab = function() {...} // function at position 400
6744 ;; During parsing we accumulate an entry for each definition in
6745 ;; the variable `js2-imenu-recorder', like so:
6751 ;; (fn foo bar baz 300)
6752 ;; (fn foo bar zab 400))
6754 ;; Where 'fn' is the respective function node.
6755 ;; After parsing these entries are merged into this alist-trie:
6759 ;; (foo (<definition> . 3)
6760 ;; (bar (<definition> . 6)
6764 ;; Note the wacky need for a <definition> name. The token can be anything
6765 ;; that isn't a valid JavaScript identifier, because you might make foo
6766 ;; a function and then start setting properties on it that are also functions.
6768 (defsubst js2-prop-node-name (node)
6769 "Return the name of a node that may be a property-get/property-name.
6770 If NODE is not a valid name-node, string-node or integral number-node,
6771 returns nil. Otherwise returns the string name/value of the node."
6773 ((js2-name-node-p node)
6774 (js2-name-node-name node))
6775 ((js2-string-node-p node)
6776 (js2-string-node-value node))
6777 ((and (js2-number-node-p node)
6778 (string-match "^[0-9]+$" (js2-number-node-value node)))
6779 (js2-number-node-value node))
6780 ((js2-this-node-p node)
6783 (defsubst js2-node-qname-component (node)
6784 "Return the name of this node, if it contributes to a qname.
6785 Returns nil if the node doesn't contribute."
6787 (or (js2-prop-node-name node)
6788 (if (and (js2-function-node-p node)
6789 (js2-function-node-name node))
6790 (js2-name-node-name (js2-function-node-name node))))))
6792 (defsubst js2-record-imenu-entry (fn-node qname pos)
6793 "Add an entry to `js2-imenu-recorder'.
6794 FN-NODE should be the current item's function node.
6796 Associate FN-NODE with its QNAME for later lookup.
6797 This is used in postprocessing the chain list. For each chain, we find
6798 the parent function, look up its qname, then prepend a copy of it to the chain."
6799 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6800 (unless js2-imenu-function-map
6801 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6802 (puthash fn-node qname js2-imenu-function-map))
6804 (defun js2-record-imenu-functions (node &optional var)
6805 "Record function definitions for imenu.
6806 NODE is a function node or an object literal.
6807 VAR, if non-nil, is the expression that NODE is being assigned to."
6808 (when js2-parse-ide-mode
6809 (let ((fun-p (js2-function-node-p node))
6810 qname left fname-node pos)
6812 ;; non-anonymous function declaration?
6815 (setq fname-node (js2-function-node-name node)))
6816 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6817 ;; for remaining forms, compute left-side tree branch first
6818 ((and var (setq qname (js2-compute-nested-prop-get var)))
6820 ;; foo.bar.baz = function
6822 (js2-record-imenu-entry node qname (js2-node-pos node)))
6823 ;; foo.bar.baz = object-literal
6824 ;; look for nested functions: {a: {b: function() {...} }}
6825 ((js2-object-node-p node)
6826 ;; Node position here is still absolute, since the parser
6827 ;; passes the assignment target and value expressions
6828 ;; to us before they are added as children of the assignment node.
6829 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6831 (defun js2-compute-nested-prop-get (node)
6832 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6833 component nodes as a list. Otherwise return nil. Element-gets are treated
6834 as property-gets if the index expression is a string, or a positive integer."
6835 (let (left right head)
6837 ((or (js2-name-node-p node)
6838 (js2-this-node-p node))
6840 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6841 ((js2-prop-get-node-p node) ; foo.bar
6842 (setq left (js2-prop-get-node-left node)
6843 right (js2-prop-get-node-right node))
6844 (if (setq head (js2-compute-nested-prop-get left))
6845 (nconc head (list right))))
6846 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6847 (setq left (js2-elem-get-node-target node)
6848 right (js2-elem-get-node-element node))
6849 (if (or (js2-string-node-p right) ; ['bar']
6850 (and (js2-number-node-p right) ; [10]
6851 (string-match "^[0-9]+$"
6852 (js2-number-node-value right))))
6853 (if (setq head (js2-compute-nested-prop-get left))
6854 (nconc head (list right))))))))
6856 (defun js2-record-object-literal (node qname pos)
6857 "Recursively process an object literal looking for functions.
6858 NODE is an object literal that is the right-hand child of an assignment
6859 expression. QNAME is a list of nodes representing the assignment target,
6860 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6861 POS is the absolute position of the node.
6862 We do a depth-first traversal of NODE. For any functions we find,
6863 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6864 (let (left right prop-qname)
6865 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6866 (let ((left (js2-infix-node-left e))
6867 ;; Element positions are relative to the parent position.
6868 (pos (+ pos (js2-node-pos e))))
6870 ;; foo: function() {...}
6871 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6872 (when (js2-prop-node-name left)
6873 ;; As a policy decision, we record the position of the property,
6874 ;; not the position of the `function' keyword, since the property
6875 ;; is effectively the name of the function.
6876 (js2-record-imenu-entry right (append qname (list left)) pos)))
6877 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6878 ((js2-object-node-p right)
6879 (js2-record-object-literal right
6880 (append qname (list (js2-infix-node-left e)))
6881 (+ pos (js2-node-pos right)))))))))
6883 (defsubst js2-node-top-level-decl-p (node)
6884 "Return t if NODE's name is defined in the top-level scope.
6885 Also returns t if NODE's name is not defined in any scope, since it implies
6886 that it's an external variable, which must also be in the top-level scope."
6887 (let* ((name (js2-prop-node-name node))
6888 (this-scope (js2-node-get-enclosing-scope node))
6891 ((js2-this-node-p node)
6895 ((setq defining-scope (js2-get-defining-scope this-scope name))
6896 (js2-ast-root-p defining-scope))
6899 (defsubst js2-wrapper-function-p (node)
6900 "Returns t if NODE is a function expression that's immediately invoked.
6901 NODE must be `js2-function-node'."
6902 (let ((parent (js2-node-parent node)))
6904 ;; function(){...}();
6905 (js2-call-node-p parent)
6906 (and (js2-paren-node-p parent)
6907 ;; (function(){...})();
6908 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6909 ;; (function(){...}).call(this);
6910 (and (js2-prop-get-node-p parent)
6911 (member (js2-name-node-name (js2-prop-get-node-right parent))
6913 (js2-call-node-p (js2-node-parent parent))))))))
6915 (defun js2-browse-postprocess-chains (entries)
6916 "Modify function-declaration name chains after parsing finishes.
6917 Some of the information is only available after the parse tree is complete.
6918 For instance, processing a nested scope requires a parent function node."
6919 (let (result head fn current-fn parent-qname qname p elem)
6920 (dolist (entry entries)
6921 ;; function node goes first
6922 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6923 ;; examine its defining scope;
6924 ;; if top-level/external, keep as-is
6925 (if (js2-node-top-level-decl-p head)
6927 (when (js2-this-node-p head)
6928 (setq chain (cdr chain))) ; discard this-node
6929 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6930 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6931 (when (eq parent-qname 'not-found)
6932 ;; anonymous function expressions are not recorded
6933 ;; during the parse, so we need to handle this case here
6935 (if (js2-wrapper-function-p fn)
6936 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6937 (if (js2-ast-root-p grandparent)
6939 (gethash grandparent js2-imenu-function-map 'skip)))
6941 (puthash fn parent-qname js2-imenu-function-map))
6942 (unless (eq parent-qname 'skip)
6943 ;; prefix parent fn qname to this chain.
6944 (let ((qname (append parent-qname chain)))
6945 (puthash current-fn (butlast qname) js2-imenu-function-map)
6946 (push qname result)))))))
6947 ;; finally replace each node in each chain with its name.
6948 (dolist (chain result)
6951 (if (js2-node-p (setq elem (car p)))
6952 (setcar p (js2-node-qname-component elem)))
6956 ;; Merge name chains into a trie-like tree structure of nested lists.
6957 ;; To simplify construction of the trie, we first build it out using the rule
6958 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6959 ;; [key, num-or-list]. The second element can be a number; if so, this key
6960 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6961 ;; associated with the key at this level.) Otherwise the second element is
6962 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6963 ;; a simple recursive formulation.
6965 ;; js2-mode is building the data structure for imenu. The imenu documentation
6966 ;; claims that it's the structure above, but in practice it wants the children
6967 ;; at the same list level as the key for that level, which is how I've drawn
6968 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6969 ;; list wrapper around the children at each level.
6971 ;; A completed nested imenu-alist entry looks like this:
6973 ;; ("<definition>" . 7)
6978 ;; In particular, the documentation for `imenu--index-alist' says that
6979 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6980 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6982 (defun js2-treeify (lst)
6983 "Convert (a b c d) to (a ((b ((c d)))))"
6984 (if (null (cddr lst)) ; list length <= 2
6986 (list (car lst) (list (js2-treeify (cdr lst))))))
6988 (defun js2-build-alist-trie (chains trie)
6989 "Merge declaration name chains into a trie-like alist structure for imenu.
6990 CHAINS is the qname chain list produced during parsing. TRIE is a
6991 list of elements built up so far."
6992 (let (head tail pos branch kids)
6993 (dolist (chain chains)
6994 (setq head (car chain)
6996 pos (if (numberp (car tail)) (car tail))
6997 branch (js2-find-if (lambda (n)
6998 (string= (car n) head))
7000 kids (second branch))
7002 ;; case 1: this key isn't in the trie yet
7005 (setcdr (last trie) (list (js2-treeify chain)))
7006 (setq trie (list (js2-treeify chain)))))
7007 ;; case 2: key is present with a single number entry: replace w/ list
7008 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7009 ;; ("<definition>" 20)))
7011 (setcar (cdr branch)
7012 (list (list "<definition-1>" kids)
7014 (list "<definition-2>" pos)
7015 (js2-treeify tail)))))
7016 ;; case 3: key is there (with kids), and we're a number entry
7020 (list (format "<definition-%d>"
7021 (1+ (loop for kid in kids
7022 count (eq ?< (aref (car kid) 0)))))
7024 ;; case 4: key is there with kids, need to merge in our chain
7026 (js2-build-alist-trie (list tail) kids))))
7029 (defun js2-flatten-trie (trie)
7030 "Convert TRIE to imenu-format.
7031 Recurses through nodes, and for each one whose second element is a list,
7032 appends the list's flattened elements to the current element. Also
7033 changes the tails into conses. For instance, this pre-flattened trie
7045 Note that the root of the trie has no key, just a list of chains.
7046 This is also true for the value of any key with multiple children,
7047 e.g. key 'c' in the example above."
7050 (mapcar #'js2-flatten-trie trie))
7052 (if (numberp (second trie))
7053 (cons (car trie) (second trie))
7054 ;; else pop list and append its kids
7055 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7057 (defun js2-build-imenu-index ()
7058 "Turn `js2-imenu-recorder' into an imenu data structure."
7059 (unless (eq js2-imenu-recorder 'empty)
7060 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7061 (result (js2-build-alist-trie chains nil)))
7062 (js2-flatten-trie result))))
7064 (defun js2-test-print-chains (chains)
7065 "Print a list of qname chains.
7066 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7067 i.e. one or more nodes, and an integer position as the list tail."
7068 (mapconcat (lambda (chain)
7070 (mapconcat (lambda (elem)
7071 (if (js2-node-p elem)
7072 (or (js2-node-qname-component elem)
7074 (number-to-string elem)))
7083 (defconst js2-version "1.8.0"
7084 "Version of JavaScript supported, plus minor js2 version.")
7086 (defmacro js2-record-face (face)
7087 "Record a style run of FACE for the current token."
7088 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7090 (defsubst js2-node-end (n)
7091 "Computes the absolute end of node N.
7092 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7093 is only true until the node is added to its parent; i.e., while parsing."
7097 (defsubst js2-record-comment ()
7098 "Record a comment in `js2-scanned-comments'."
7099 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7100 :format js2-ts-comment-type)
7101 js2-scanned-comments)
7102 (when js2-parse-ide-mode
7103 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7105 'font-lock-comment-face))
7106 (when (memq js2-ts-comment-type '(html preprocessor))
7107 ;; Tell cc-engine the bounds of the comment.
7108 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7110 ;; This function is called depressingly often, so it should be fast.
7111 ;; Most of the time it's looking at the same token it peeked before.
7112 (defsubst js2-peek-token ()
7113 "Returns the next token without consuming it.
7114 If previous token was consumed, calls scanner to get new token.
7115 If previous token was -not- consumed, returns it (idempotent).
7117 This function will not return a newline (js2-EOL) - instead, it
7118 gobbles newlines until it finds a non-newline token, and flags
7119 that token as appearing just after a newline.
7121 This function will also not return a js2-COMMENT. Instead, it
7122 records comments found in `js2-scanned-comments'. If the token
7123 returned by this function immediately follows a jsdoc comment,
7124 the token is flagged as such.
7126 Note that this function always returned the un-flagged token!
7127 The flags, if any, are saved in `js2-current-flagged-token'."
7128 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7129 js2-current-token ; most common case - return already-peeked token
7130 (let ((tt (js2-get-token)) ; call scanner
7133 ;; process comments and whitespace
7134 (while (or (= tt js2-EOL)
7139 (if js2-record-comments
7140 (js2-record-comment)))
7141 (setq tt (js2-get-token))) ; call scanner
7142 (setq js2-current-token tt
7143 js2-current-flagged-token (if saw-eol
7144 (logior tt js2-ti-after-eol)
7146 ;; perform lexical fontification as soon as token is scanned
7147 (when js2-parse-ide-mode
7150 (js2-record-face 'js2-error-face))
7151 ((setq face (aref js2-kwd-tokens tt))
7152 (js2-record-face face))
7153 ((and (= tt js2-NAME)
7154 (equal js2-ts-string "undefined"))
7155 (js2-record-face 'font-lock-constant-face))))
7156 tt))) ; return unflagged token
7158 (defsubst js2-peek-flagged-token ()
7159 "Returns the current token along with any flags set for it."
7161 js2-current-flagged-token)
7163 (defsubst js2-consume-token ()
7164 (setq js2-current-flagged-token js2-EOF))
7166 (defsubst js2-next-token ()
7169 (js2-consume-token)))
7171 (defsubst js2-next-flagged-token ()
7173 (prog1 js2-current-flagged-token
7174 (js2-consume-token)))
7176 (defsubst js2-match-token (match)
7177 "Consume and return t if next token matches MATCH, a bytecode.
7178 Returns nil and consumes nothing if MATCH is not the next token."
7179 (if (/= (js2-peek-token) match)
7184 (defsubst js2-valid-prop-name-token (tt)
7186 (and js2-allow-keywords-as-property-names
7188 (aref js2-kwd-tokens tt))))
7190 (defsubst js2-match-prop-name ()
7191 "Consume token and return t if next token is a valid property name.
7192 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7193 is non-nil and it's a keyword token."
7194 (if (js2-valid-prop-name-token (js2-peek-token))
7200 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7201 (if (js2-match-prop-name)
7203 (js2-report-error msg-id nil pos len)
7206 (defsubst js2-peek-token-or-eol ()
7207 "Return js2-EOL if the current token immediately follows a newline.
7208 Else returns the current token. Used in situations where we don't
7209 consider certain token types valid if they are preceded by a newline.
7210 One example is the postfix ++ or -- operator, which has to be on the
7211 same line as its operand."
7212 (let ((tt (js2-peek-token)))
7213 ;; Check for last peeked token flags
7214 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7218 (defsubst js2-set-check-for-label ()
7219 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7220 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7222 (defsubst js2-must-match (token msg-id &optional pos len)
7223 "Match next token to token code TOKEN, or record a syntax error.
7224 MSG-ID is the error message to report if the match fails.
7225 Returns t on match, nil if no match."
7226 (if (js2-match-token token)
7228 (js2-report-error msg-id nil pos len)
7231 (defsubst js2-inside-function ()
7232 (plusp js2-nesting-of-function))
7234 (defsubst js2-set-requires-activation ()
7235 (if (js2-function-node-p js2-current-script-or-fn)
7236 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7238 (defsubst js2-check-activation-name (name token)
7239 (when (js2-inside-function)
7240 ;; skip language-version 1.2 check from Rhino
7241 (if (or (string= "arguments" name)
7242 (and js2-compiler-activation-names ; only used in codegen
7243 (gethash name js2-compiler-activation-names)))
7244 (js2-set-requires-activation))))
7246 (defsubst js2-set-is-generator ()
7247 (if (js2-function-node-p js2-current-script-or-fn)
7248 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7250 (defsubst js2-must-have-xml ()
7251 (unless js2-compiler-xml-available
7252 (js2-report-error "msg.XML.not.available")))
7254 (defsubst js2-push-scope (scope)
7255 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7256 (assert (js2-scope-p scope))
7257 (assert (null (js2-scope-parent-scope scope)))
7258 (assert (not (eq js2-current-scope scope)))
7259 (setf (js2-scope-parent-scope scope) js2-current-scope
7260 js2-current-scope scope))
7262 (defsubst js2-pop-scope ()
7263 (setq js2-current-scope
7264 (js2-scope-parent-scope js2-current-scope)))
7266 (defsubst js2-enter-loop (loop-node)
7267 (push loop-node js2-loop-set)
7268 (push loop-node js2-loop-and-switch-set)
7269 (js2-push-scope loop-node)
7270 ;; Tell the current labeled statement (if any) its statement,
7271 ;; and set the jump target of the first label to the loop.
7272 ;; These are used in `js2-parse-continue' to verify that the
7273 ;; continue target is an actual labeled loop. (And for codegen.)
7274 (when js2-labeled-stmt
7275 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7276 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7277 js2-labeled-stmt))) loop-node)))
7279 (defsubst js2-exit-loop ()
7281 (pop js2-loop-and-switch-set)
7284 (defsubst js2-enter-switch (switch-node)
7285 (push switch-node js2-loop-and-switch-set))
7287 (defsubst js2-exit-switch ()
7288 (pop js2-loop-and-switch-set))
7290 (defun js2-parse (&optional buf cb)
7291 "Tells the js2 parser to parse a region of JavaScript.
7293 BUF is a buffer or buffer name containing the code to parse.
7294 Call `narrow-to-region' first to parse only part of the buffer.
7296 The returned AST root node is given some additional properties:
7297 `node-count' - total number of nodes in the AST
7298 `buffer' - BUF. The buffer it refers to may change or be killed,
7299 so the value is not necessarily reliable.
7301 An optional callback CB can be specified to report parsing
7302 progress. If `(functionp CB)' returns t, it will be called with
7303 the current line number once before parsing begins, then again
7304 each time the lexer reaches a new line number.
7306 CB can also be a list of the form `(symbol cb ...)' to specify
7307 multiple callbacks with different criteria. Each symbol is a
7308 criterion keyword, and the following element is the callback to
7311 :line - called whenever the line number changes
7312 :token - called for each new token consumed
7314 The list of criteria could be extended to include entering or
7315 leaving a statement, an expression, or a function definition."
7316 (if (and cb (not (functionp cb)))
7317 (error "criteria callbacks not yet implemented"))
7318 (let ((inhibit-point-motion-hooks t)
7319 (js2-compiler-xml-available (>= js2-language-version 160))
7320 ;; This is a recursive-descent parser, so give it a big stack.
7321 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7322 (max-specpdl-size (max max-specpdl-size 3000))
7323 (case-fold-search nil)
7325 (message nil) ; clear any error message from previous parse
7327 (when buf (set-buffer buf))
7328 (setq js2-scanned-comments nil
7329 js2-parsed-errors nil
7330 js2-parsed-warnings nil
7331 js2-imenu-recorder nil
7332 js2-imenu-function-map nil
7335 (setq ast (js2-with-unmodifying-text-property-changes
7337 (unless js2-ts-hit-eof
7338 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7339 (setf (js2-ast-root-errors ast) js2-parsed-errors
7340 (js2-ast-root-warnings ast) js2-parsed-warnings)
7341 ;; if we didn't find any declarations, put a dummy in this list so we
7342 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7343 (unless js2-imenu-recorder
7344 (setq js2-imenu-recorder 'empty))
7345 (run-hooks 'js2-parse-finished-hook)
7348 ;; Corresponds to Rhino's Parser.parse() method.
7349 (defun js2-do-parse ()
7350 "Parse current buffer starting from current point.
7351 Scanner should be initialized."
7352 (let ((pos js2-ts-cursor)
7353 (end js2-ts-cursor) ; in case file is empty
7355 ;; initialize buffer-local parsing vars
7356 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7357 js2-current-script-or-fn root
7358 js2-current-scope root
7359 js2-current-flagged-token js2-EOF
7360 js2-nesting-of-function 0
7361 js2-labeled-stmt nil
7362 js2-recorded-identifiers nil) ; for js2-highlight
7363 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7364 (if (= tt js2-FUNCTION)
7367 (setq n (js2-parse-function (if js2-called-by-compile-function
7368 'FUNCTION_EXPRESSION
7369 'FUNCTION_STATEMENT))))
7370 ;; not a function - parse a statement
7371 (setq n (js2-parse-statement)))
7372 ;; add function or statement to script
7373 (setq end (js2-node-end n))
7374 (js2-block-node-push root n))
7375 ;; add comments to root in lexical order
7376 (when js2-scanned-comments
7377 ;; if we find a comment beyond end of normal kids, use its end
7378 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7379 (dolist (comment js2-scanned-comments)
7380 (push comment (js2-ast-root-comments root))
7381 (js2-node-add-children root comment)))
7382 (setf (js2-node-len root) (- end pos))
7383 ;; Give extensions a chance to muck with things before highlighting starts.
7384 (let ((js2-additional-externs js2-additional-externs))
7385 (dolist (callback js2-post-parse-callbacks)
7387 (js2-highlight-undeclared-vars))
7390 (defun js2-function-parser ()
7392 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7394 (defun js2-parse-function-closure-body (fn-node)
7395 "Parse a JavaScript 1.8 function closure body."
7396 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7398 (js2-report-error "msg.no.brace.body" nil
7399 (js2-node-pos fn-node)
7400 (- js2-ts-cursor (js2-node-pos fn-node)))
7401 (js2-node-add-children fn-node
7402 (setf (js2-function-node-body fn-node)
7403 (js2-parse-expr t))))))
7405 (defun js2-parse-function-body (fn-node)
7406 (js2-must-match js2-LC "msg.no.brace.body"
7407 (js2-node-pos fn-node)
7408 (- js2-ts-cursor (js2-node-pos fn-node)))
7409 (let ((pos js2-token-beg) ; LC position
7410 (pn (make-js2-block-node)) ; starts at LC position
7413 (incf js2-nesting-of-function)
7415 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7418 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7419 (js2-parse-statement)
7421 (js2-parse-function 'FUNCTION_STATEMENT))))
7422 (decf js2-nesting-of-function))
7423 (setq end js2-token-end) ; assume no curly and leave at current token
7424 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7425 (setq end js2-token-end))
7426 (setf (js2-node-pos pn) pos
7427 (js2-node-len pn) (- end pos))
7428 (setf (js2-function-node-body fn-node) pn)
7429 (js2-node-add-children fn-node pn)
7432 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7433 "Declare and fontify destructuring parameters inside NODE.
7434 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7436 ((js2-name-node-p node)
7438 (js2-define-symbol decl-type (js2-name-node-name node)
7439 node ignore-not-in-block)
7441 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7442 (+ leftpos (js2-node-len node))
7444 ((js2-object-node-p node)
7445 (dolist (elem (js2-object-node-elems node))
7446 (js2-define-destruct-symbols
7447 (if (js2-object-prop-node-p elem)
7448 (js2-object-prop-node-right elem)
7449 ;; abbreviated destructuring {a, b}
7451 decl-type face ignore-not-in-block)))
7452 ((js2-array-node-p node)
7453 (dolist (elem (js2-array-node-elems node))
7455 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7456 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7457 (js2-node-len node)))))
7459 (defun js2-parse-function-params (fn-node pos)
7460 (if (js2-match-token js2-RP)
7461 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7462 (let (params len param)
7463 (loop for tt = (js2-peek-token)
7466 ;; destructuring param
7467 ((or (= tt js2-LB) (= tt js2-LC))
7468 (setq param (js2-parse-primary-expr-lhs))
7469 (js2-define-destruct-symbols param
7471 'js2-function-param-face)
7472 (push param params))
7475 (js2-must-match js2-NAME "msg.no.parm")
7476 (js2-record-face 'js2-function-param-face)
7477 (setq param (js2-create-name-node))
7478 (js2-define-symbol js2-LP js2-ts-string param)
7479 (push param params)))
7481 (js2-match-token js2-COMMA))
7482 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7483 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7485 (js2-node-add-children fn-node p)
7486 (push p (js2-function-node-params fn-node))))))
7488 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7489 "Possibly show inconsistent-return warning.
7490 Last token scanned is the close-curly for the function body."
7491 (when (and js2-mode-show-strict-warnings
7492 js2-strict-inconsistent-return-warning
7493 (not (js2-has-consistent-return-usage
7494 (js2-function-node-body fn-node))))
7495 ;; Have it extend from close-curly to bol or beginning of block.
7496 (let ((pos (save-excursion
7497 (goto-char js2-token-end)
7498 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7500 (end js2-token-end))
7501 (if (plusp (js2-name-node-length name))
7502 (js2-add-strict-warning "msg.no.return.value"
7503 (js2-name-node-name name) pos end)
7504 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7506 (defun js2-parse-function (function-type)
7507 "Function parser. FUNCTION-TYPE is a symbol."
7508 (let ((pos js2-token-beg) ; start of 'function' keyword
7514 (synthetic-type function-type)
7516 ;; parse function name, expression, or non-name (anonymous)
7518 ;; function foo(...)
7519 ((js2-match-token js2-NAME)
7520 (setq name (js2-create-name-node t)
7521 name-beg js2-token-beg
7522 name-end js2-token-end)
7523 (unless (js2-match-token js2-LP)
7524 (when js2-allow-member-expr-as-function-name
7525 ;; function foo.bar(...)
7526 (setq member-expr-node name
7528 member-expr-node (js2-parse-member-expr-tail
7529 nil member-expr-node)))
7530 (js2-must-match js2-LP "msg.no.paren.parms")))
7531 ((js2-match-token js2-LP)
7532 nil) ; anonymous function: leave name as null
7534 ;; function random-member-expr(...)
7535 (when js2-allow-member-expr-as-function-name
7536 ;; Note that memberExpr can not start with '(' like
7537 ;; in function (1+2).toString(), because 'function (' already
7538 ;; processed as anonymous function
7539 (setq member-expr-node (js2-parse-member-expr)))
7540 (js2-must-match js2-LP "msg.no.paren.parms")))
7541 (if (= js2-current-token js2-LP) ; eventually matched LP?
7542 (setq lp js2-token-beg))
7543 (if member-expr-node
7545 (setq synthetic-type 'FUNCTION_EXPRESSION)
7546 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7548 (js2-set-face name-beg name-end
7549 'font-lock-function-name-face 'record)))
7550 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7551 (plusp (js2-name-node-length name)))
7552 ;; Function statements define a symbol in the enclosing scope
7553 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7554 (setf fn-node (make-js2-function-node :pos pos
7557 :lp (if lp (- lp pos))))
7558 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7559 ;; 1. Nested functions are not affected by the dynamic scope flag
7560 ;; as dynamic scope is already a parent of their scope.
7561 ;; 2. Functions defined under the with statement also immune to
7562 ;; this setup, in which case dynamic scope is ignored in favor
7563 ;; of the with object.
7564 (setf (js2-function-node-ignore-dynamic fn-node) t))
7565 ;; dynamically bind all the per-function variables
7566 (let ((js2-current-script-or-fn fn-node)
7567 (js2-current-scope fn-node)
7568 (js2-nesting-of-with 0)
7572 js2-loop-and-switch-set)
7573 (js2-parse-function-params fn-node pos)
7574 (if (and (>= js2-language-version 180)
7575 (/= (js2-peek-token) js2-LC))
7576 (js2-parse-function-closure-body fn-node)
7577 (js2-parse-function-body fn-node))
7579 (js2-node-add-children fn-node name))
7580 (js2-check-inconsistent-return-warning fn-node name)
7581 ;; Function expressions define a name only in the body of the
7582 ;; function, and only if not hidden by a parameter name
7584 (eq synthetic-type 'FUNCTION_EXPRESSION)
7585 (null (js2-scope-get-symbol js2-current-scope
7586 (js2-name-node-name name))))
7587 (js2-define-symbol js2-FUNCTION
7588 (js2-name-node-name name)
7591 (not (eq function-type 'FUNCTION_EXPRESSION)))
7592 (js2-record-imenu-functions fn-node)))
7593 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7594 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7595 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7596 ;; We wait until after parsing the function to set its parent scope,
7597 ;; since `js2-define-symbol' needs the defining-scope check to stop
7598 ;; at the function boundary when checking for redeclarations.
7599 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7602 (defun js2-parse-statements (&optional parent)
7603 "Parse a statement list. Last token consumed must be js2-LC.
7605 PARENT can be a `js2-block-node', in which case the statements are
7606 appended to PARENT. Otherwise a new `js2-block-node' is created
7609 This function does not match the closing js2-RC: the caller
7610 matches the RC so it can provide a suitable error message if not
7611 matched. This means it's up to the caller to set the length of
7612 the node to include the closing RC. The node start pos is set to
7613 the absolute buffer start position, and the caller should fix it
7614 up to be relative to the parent node. All children of this block
7615 node are given relative start positions and correct lengths."
7616 (let ((pn (or parent (make-js2-block-node)))
7618 (setf (js2-node-pos pn) js2-token-beg)
7619 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7621 (js2-block-node-push pn (js2-parse-statement)))
7624 (defun js2-parse-statement ()
7625 (let (tt pn beg end)
7626 ;; coarse-grained user-interrupt check - needs work
7627 (and js2-parse-interruptable-p
7628 (zerop (% (incf js2-parse-stmt-count)
7629 js2-statements-per-pause))
7631 (throw 'interrupted t))
7632 (setq pn (js2-statement-helper))
7633 ;; no-side-effects warning check
7634 (unless (js2-node-has-side-effects pn)
7635 (setq end (js2-node-end pn))
7638 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7639 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7642 ;; These correspond to the switch cases in Parser.statementHelper
7643 (defconst js2-parsers
7644 (let ((parsers (make-vector js2-num-tokens
7645 #'js2-parse-expr-stmt)))
7646 (aset parsers js2-BREAK #'js2-parse-break)
7647 (aset parsers js2-CONST #'js2-parse-const-var)
7648 (aset parsers js2-CONTINUE #'js2-parse-continue)
7649 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7650 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7651 (aset parsers js2-DO #'js2-parse-do)
7652 (aset parsers js2-FOR #'js2-parse-for)
7653 (aset parsers js2-FUNCTION #'js2-function-parser)
7654 (aset parsers js2-IF #'js2-parse-if)
7655 (aset parsers js2-LC #'js2-parse-block)
7656 (aset parsers js2-LET #'js2-parse-let-stmt)
7657 (aset parsers js2-NAME #'js2-parse-name-or-label)
7658 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7659 (aset parsers js2-SEMI #'js2-parse-semi)
7660 (aset parsers js2-SWITCH #'js2-parse-switch)
7661 (aset parsers js2-THROW #'js2-parse-throw)
7662 (aset parsers js2-TRY #'js2-parse-try)
7663 (aset parsers js2-VAR #'js2-parse-const-var)
7664 (aset parsers js2-WHILE #'js2-parse-while)
7665 (aset parsers js2-WITH #'js2-parse-with)
7666 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7668 "A vector mapping token types to parser functions.")
7670 (defsubst js2-parse-warn-missing-semi (beg end)
7671 (and js2-mode-show-strict-warnings
7672 js2-strict-missing-semi-warning
7673 (js2-add-strict-warning
7674 "msg.missing.semi" nil
7675 ;; back up to beginning of statement or line
7676 (max beg (save-excursion
7681 (defconst js2-no-semi-insertion
7693 "List of tokens that don't do automatic semicolon insertion.")
7695 (defconst js2-autoinsert-semi-and-warn
7696 (list js2-ERROR js2-EOF js2-RC))
7698 (defun js2-statement-helper ()
7699 (let* ((tt (js2-peek-token))
7702 (parser (if (= tt js2-ERROR)
7704 (aref js2-parsers tt)))
7707 ;; If the statement is set, then it's been told its label by now.
7708 (and js2-labeled-stmt
7709 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7710 (setq js2-labeled-stmt nil))
7711 (setq pn (funcall parser))
7712 ;; Don't do auto semi insertion for certain statement types.
7713 (unless (or (memq first-tt js2-no-semi-insertion)
7714 (js2-labeled-stmt-node-p pn))
7715 (js2-auto-insert-semicolon pn))
7718 (defun js2-auto-insert-semicolon (pn)
7719 (let* ((tt-flagged (js2-peek-flagged-token))
7720 (tt (logand tt-flagged js2-clear-ti-mask))
7721 (pos (js2-node-pos pn)))
7724 ;; Consume ';' as a part of expression
7726 ;; extend the node bounds to include the semicolon.
7727 (setf (js2-node-len pn) (- js2-token-end pos)))
7728 ((memq tt js2-autoinsert-semi-and-warn)
7730 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7732 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7733 ;; Report error if no EOL or autoinsert ';' otherwise
7734 (js2-report-error "msg.no.semi.stmt")
7735 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7737 (defun js2-parse-condition ()
7738 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7739 The parens are discarded and the expression node is returned.
7740 The `pos' field of the return value is set to an absolute position
7741 that must be fixed up by the caller.
7742 Return value is a list (EXPR LP RP), with absolute paren positions."
7744 (if (js2-must-match js2-LP "msg.no.paren.cond")
7745 (setq lp js2-token-beg))
7746 (setq pn (js2-parse-expr))
7747 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7748 (setq rp js2-token-beg))
7749 ;; Report strict warning on code like "if (a = 7) ..."
7750 (if (and js2-strict-cond-assign-warning
7751 (js2-assign-node-p pn))
7752 (js2-add-strict-warning "msg.equal.as.assign" nil
7754 (+ (js2-node-pos pn)
7755 (js2-node-len pn))))
7758 (defun js2-parse-if ()
7759 "Parser for if-statement. Last matched token must be js2-IF."
7760 (let ((pos js2-token-beg)
7768 (setq cond (js2-parse-condition)
7769 if-true (js2-parse-statement)
7770 if-false (if (js2-match-token js2-ELSE)
7772 (setq else-pos (- js2-token-beg pos))
7773 (js2-parse-statement)))
7774 end (js2-node-end (or if-false if-true))
7775 pn (make-js2-if-node :pos pos
7777 :condition (car cond)
7781 :lp (js2-relpos (second cond) pos)
7782 :rp (js2-relpos (third cond) pos)))
7783 (js2-node-add-children pn (car cond) if-true if-false)
7786 (defun js2-parse-switch ()
7787 "Parser for if-statement. Last matched token must be js2-SWITCH."
7788 (let ((pos js2-token-beg)
7801 (if (js2-must-match js2-LP "msg.no.paren.switch")
7802 (setq lp js2-token-beg))
7803 (setq discriminant (js2-parse-expr)
7804 pn (make-js2-switch-node :discriminant discriminant
7806 :lp (js2-relpos lp pos)))
7807 (js2-node-add-children pn discriminant)
7808 (js2-enter-switch pn)
7811 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7812 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7813 (js2-must-match js2-LC "msg.no.brace.switch")
7816 (setq tt (js2-next-token)
7817 case-pos js2-token-beg)
7820 (setf (js2-node-len pn) (- js2-token-end pos))
7821 (throw 'break nil)) ; done
7823 (setq case-expr (js2-parse-expr))
7824 (js2-must-match js2-COLON "msg.no.colon.case"))
7827 (js2-report-error "msg.double.switch.default"))
7830 (js2-must-match js2-COLON "msg.no.colon.case"))
7832 (js2-report-error "msg.bad.switch")
7833 (throw 'break nil)))
7834 (setq case-node (make-js2-case-node :pos case-pos
7835 :len (- js2-token-end case-pos)
7837 (js2-node-add-children case-node case-expr)
7838 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7842 (setf stmt (js2-parse-statement)
7843 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7844 (js2-block-node-push case-node stmt))
7845 (push case-node cases)))
7846 ;; add cases last, as pushing reverses the order to be correct
7848 (js2-node-add-children pn kid)
7849 (push kid (js2-switch-node-cases pn)))
7851 (js2-exit-switch))))
7853 (defun js2-parse-while ()
7854 "Parser for while-statement. Last matched token must be js2-WHILE."
7855 (let ((pos js2-token-beg)
7856 (pn (make-js2-while-node))
7863 (setf cond (js2-parse-condition)
7864 (js2-while-node-condition pn) (car cond)
7865 body (js2-parse-statement)
7866 (js2-while-node-body pn) body
7867 (js2-node-len pn) (- (js2-node-end body) pos)
7868 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7869 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7870 (js2-node-add-children pn body (car cond)))
7874 (defun js2-parse-do ()
7875 "Parser for do-statement. Last matched token must be js2-DO."
7876 (let ((pos js2-token-beg)
7877 (pn (make-js2-do-node))
7885 (setq body (js2-parse-statement))
7886 (js2-must-match js2-WHILE "msg.no.while.do")
7887 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7888 cond (js2-parse-condition)
7889 (js2-do-node-condition pn) (car cond)
7890 (js2-do-node-body pn) body
7892 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7893 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7894 (js2-node-add-children pn (car cond) body))
7896 ;; Always auto-insert semicolon to follow SpiderMonkey:
7897 ;; It is required by ECMAScript but is ignored by the rest of
7898 ;; world; see bug 238945
7899 (if (js2-match-token js2-SEMI)
7900 (setq end js2-ts-cursor))
7901 (setf (js2-node-len pn) (- end pos))
7904 (defun js2-parse-for ()
7905 "Parser for for-statement. Last matched token must be js2-FOR.
7906 Parses for, for-in, and for each-in statements."
7907 (let ((for-pos js2-token-beg)
7914 init ; Node init is also foo in 'foo in object'
7915 cond ; Node cond is also object in 'foo in object'
7916 incr ; 3rd section of for-loop initializer
7922 ;; See if this is a for each () instead of just a for ()
7923 (when (js2-match-token js2-NAME)
7924 (if (string= "each" js2-ts-string)
7927 each-pos (- js2-token-beg for-pos)) ; relative
7928 (js2-record-face 'font-lock-keyword-face))
7929 (js2-report-error "msg.no.paren.for")))
7930 (if (js2-must-match js2-LP "msg.no.paren.for")
7931 (setq lp (- js2-token-beg for-pos)))
7932 (setq tt (js2-peek-token))
7933 ;; 'for' makes local scope
7934 (js2-push-scope (make-js2-scope))
7936 ;; parse init clause
7937 (let ((js2-in-for-init t)) ; set as dynamic variable
7940 (setq init (make-js2-empty-expr-node)))
7941 ((or (= tt js2-VAR) (= tt js2-LET))
7943 (setq init (js2-parse-variables tt js2-token-beg)))
7945 (setq init (js2-parse-expr)))))
7946 (if (js2-match-token js2-IN)
7948 in-pos (- js2-token-beg for-pos)
7949 ;; scope of iteration target object is not the scope we've created above.
7950 ;; stash current scope temporary.
7951 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7952 (js2-parse-expr))) ; object over which we're iterating
7953 ;; else ordinary for loop - parse cond and incr
7954 (js2-must-match js2-SEMI "msg.no.semi.for")
7955 (setq cond (if (= (js2-peek-token) js2-SEMI)
7956 (make-js2-empty-expr-node) ; no loop condition
7958 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7959 (setq tmp-pos js2-token-end
7960 incr (if (= (js2-peek-token) js2-RP)
7961 (make-js2-empty-expr-node :pos tmp-pos)
7963 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7964 (setq rp (- js2-token-beg for-pos)))
7966 (setq pn (make-js2-for-node :init init
7971 ;; cond could be null if 'in obj' got eaten by the init node.
7972 (if (js2-infix-node-p init)
7973 ;; it was (foo in bar) instead of (var foo in bar)
7974 (setq cond (js2-infix-node-right init)
7975 init (js2-infix-node-left init))
7976 (if (and (js2-var-decl-node-p init)
7977 (> (length (js2-var-decl-node-kids init)) 1))
7978 (js2-report-error "msg.mult.index")))
7979 (setq pn (make-js2-for-in-node :iterator init
7982 :foreach-p is-for-each
7989 ;; We have to parse the body -after- creating the loop node,
7990 ;; so that the loop node appears in the js2-loop-set, allowing
7991 ;; break/continue statements to find the enclosing loop.
7992 (setf body (js2-parse-statement)
7993 (js2-loop-node-body pn) body
7994 (js2-node-pos pn) for-pos
7995 (js2-node-len pn) (- (js2-node-end body) for-pos))
7996 (js2-node-add-children pn init cond incr body))
8002 (defun js2-parse-try ()
8003 "Parser for try-statement. Last matched token must be js2-TRY."
8004 (let ((try-pos js2-token-beg)
8022 (if (/= (js2-peek-token) js2-LC)
8023 (js2-report-error "msg.no.brace.try"))
8024 (setq try-block (js2-parse-statement)
8025 try-end (js2-node-end try-block)
8026 peek (js2-peek-token))
8029 (while (js2-match-token js2-CATCH)
8030 (setq catch-pos js2-token-beg
8035 (if saw-default-catch
8036 (js2-report-error "msg.catch.unreachable"))
8037 (if (js2-must-match js2-LP "msg.no.paren.catch")
8038 (setq lp (- js2-token-beg catch-pos)))
8039 (js2-push-scope (make-js2-scope))
8040 (let ((tt (js2-peek-token)))
8042 ;; destructuring pattern
8043 ;; catch ({ message, file }) { ... }
8044 ((or (= tt js2-LB) (= tt js2-LC))
8046 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8050 (js2-must-match js2-NAME "msg.bad.catchcond")
8051 (setq param (js2-create-name-node))
8052 (js2-define-symbol js2-LET js2-ts-string param))))
8054 (if (js2-match-token js2-IF)
8055 (setq guard-kwd (- js2-token-beg catch-pos)
8056 catch-cond (js2-parse-expr))
8057 (setq saw-default-catch t))
8058 (if (js2-must-match js2-RP "msg.bad.catchcond")
8059 (setq rp (- js2-token-beg catch-pos)))
8060 (js2-must-match js2-LC "msg.no.brace.catchblock")
8061 (setq block (js2-parse-statements)
8062 try-end (js2-node-end block)
8063 catch-node (make-js2-catch-node :pos catch-pos
8065 :guard-expr catch-cond
8066 :guard-kwd guard-kwd
8071 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8072 (setq try-end js2-token-beg))
8073 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8074 (js2-node-len catch-node) (- try-end catch-pos))
8075 (js2-node-add-children catch-node param catch-cond block)
8076 (push catch-node catch-blocks)))
8077 ((/= peek js2-FINALLY)
8078 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8079 (js2-node-pos try-block)
8080 (- (setq try-end (js2-node-end try-block))
8081 (js2-node-pos try-block)))))
8082 (when (js2-match-token js2-FINALLY)
8083 (setq finally-pos js2-token-beg
8084 block (js2-parse-statement)
8085 try-end (js2-node-end block)
8086 finally-block (make-js2-finally-node :pos finally-pos
8087 :len (- try-end finally-pos)
8089 (js2-node-add-children finally-block block))
8090 (setq pn (make-js2-try-node :pos try-pos
8091 :len (- try-end try-pos)
8092 :try-block try-block
8093 :finally-block finally-block))
8094 (js2-node-add-children pn try-block finally-block)
8095 ;; push them onto the try-node, which reverses and corrects their order
8096 (dolist (cb catch-blocks)
8097 (js2-node-add-children pn cb)
8098 (push cb (js2-try-node-catch-clauses pn)))
8101 (defun js2-parse-throw ()
8102 "Parser for throw-statement. Last matched token must be js2-THROW."
8103 (let ((pos js2-token-beg)
8107 (if (= (js2-peek-token-or-eol) js2-EOL)
8108 ;; ECMAScript does not allow new lines before throw expression,
8110 (js2-report-error "msg.bad.throw.eol"))
8111 (setq expr (js2-parse-expr)
8112 pn (make-js2-throw-node :pos pos
8113 :len (- (js2-node-end expr) pos)
8115 (js2-node-add-children pn expr)
8118 (defsubst js2-match-jump-label-name (label-name)
8119 "If break/continue specified a label, return that label's labeled stmt.
8120 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8121 does not match an existing label, reports an error and returns nil."
8122 (let ((bundle (cdr (assoc label-name js2-label-set))))
8124 (js2-report-error "msg.undef.label"))
8127 (defun js2-parse-break ()
8128 "Parser for break-statement. Last matched token must be js2-BREAK."
8129 (let ((pos js2-token-beg)
8131 break-target ; statement to break from
8132 break-label ; in "break foo", name-node representing the foo
8133 labels ; matching labeled statement to break to
8135 (js2-consume-token) ; `break'
8136 (when (eq (js2-peek-token-or-eol) js2-NAME)
8138 (setq break-label (js2-create-name-node)
8139 end (js2-node-end break-label)
8140 ;; matchJumpLabelName only matches if there is one
8141 labels (js2-match-jump-label-name js2-ts-string)
8142 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8143 (unless (or break-target break-label)
8144 ;; no break target specified - try for innermost enclosing loop/switch
8145 (if (null js2-loop-and-switch-set)
8147 (js2-report-error "msg.bad.break" nil pos (length "break")))
8148 (setq break-target (car js2-loop-and-switch-set))))
8149 (setq pn (make-js2-break-node :pos pos
8152 :target break-target))
8153 (js2-node-add-children pn break-label) ; but not break-target
8156 (defun js2-parse-continue ()
8157 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8158 (let ((pos js2-token-beg)
8160 label ; optional user-specified label, a `js2-name-node'
8161 labels ; current matching labeled stmt, if any
8162 target ; the `js2-loop-node' target of this continue stmt
8164 (js2-consume-token) ; `continue'
8165 (when (= (js2-peek-token-or-eol) js2-NAME)
8167 (setq label (js2-create-name-node)
8168 end (js2-node-end label)
8169 ;; matchJumpLabelName only matches if there is one
8170 labels (js2-match-jump-label-name js2-ts-string)))
8172 ((null labels) ; no current label to go to
8173 (if (null js2-loop-set) ; no loop to continue to
8174 (js2-report-error "msg.continue.outside" nil pos
8175 (length "continue"))
8176 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8178 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8179 (setq target (js2-labeled-stmt-node-stmt labels))
8180 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8181 (setq pn (make-js2-continue-node :pos pos
8185 (js2-node-add-children pn label) ; but not target - it's not our child
8188 (defun js2-parse-with ()
8189 "Parser for with-statement. Last matched token must be js2-WITH."
8191 (let ((pos js2-token-beg)
8193 (if (js2-must-match js2-LP "msg.no.paren.with")
8194 (setq lp js2-token-beg))
8195 (setq obj (js2-parse-expr))
8196 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8197 (setq rp js2-token-beg))
8198 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8199 (setq body (js2-parse-statement)))
8200 (setq pn (make-js2-with-node :pos pos
8201 :len (- (js2-node-end body) pos)
8204 :lp (js2-relpos lp pos)
8205 :rp (js2-relpos rp pos)))
8206 (js2-node-add-children pn obj body)
8209 (defun js2-parse-const-var ()
8210 "Parser for var- or const-statement.
8211 Last matched token must be js2-CONST or js2-VAR."
8212 (let ((tt (js2-peek-token))
8217 (setq expr (js2-parse-variables tt js2-token-beg)
8218 pn (make-js2-expr-stmt-node :pos pos
8219 :len (- (js2-node-end expr) pos)
8221 (js2-node-add-children pn expr)
8224 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8225 (let ((pn (make-js2-expr-stmt-node :pos pos
8226 :len (js2-node-len expr)
8227 :type (if (js2-inside-function)
8232 (js2-node-add-children pn expr))
8235 (defun js2-parse-let-stmt ()
8236 "Parser for let-statement. Last matched token must be js2-LET."
8238 (let ((pos js2-token-beg)
8241 (if (= (js2-peek-token) js2-LP)
8242 ;; let expression in statement context
8243 (setq expr (js2-parse-let pos 'statement)
8244 pn (js2-wrap-with-expr-stmt pos expr t))
8245 ;; else we're looking at a statement like let x=6, y=7;
8246 (setf expr (js2-parse-variables js2-LET pos)
8247 pn (js2-wrap-with-expr-stmt pos expr t)
8248 (js2-node-type pn) js2-EXPR_RESULT))
8251 (defun js2-parse-ret-yield ()
8252 (js2-parse-return-or-yield (js2-peek-token) nil))
8254 (defconst js2-parse-return-stmt-enders
8255 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8257 (defsubst js2-now-all-set (before after mask)
8258 "Return whether or not the bits in the mask have changed to all set.
8259 BEFORE is bits before change, AFTER is bits after change, and MASK is
8260 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8262 (and (/= (logand before mask) mask)
8263 (= (logand after mask) mask)))
8265 (defun js2-parse-return-or-yield (tt expr-context)
8266 (let ((pos js2-token-beg)
8268 (before js2-end-flags)
8269 (inside-function (js2-inside-function))
8273 (unless inside-function
8274 (js2-report-error (if (eq tt js2-RETURN)
8278 ;; This is ugly, but we don't want to require a semicolon.
8279 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8280 (setq e (js2-parse-expr)
8281 end (js2-node-end e)))
8284 (js2-set-flag js2-end-flags (if (null e)
8286 js2-end-returns-value))
8287 (setq ret (make-js2-return-node :pos pos
8290 (js2-node-add-children ret e)
8291 ;; See if we need a strict mode warning.
8292 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8293 ;; more thorough and accurate than this before/after flag check.
8294 ;; E.g. if there's a finally-block that always returns, we shouldn't
8295 ;; show a warning generated by inconsistent returns in the catch blocks.
8296 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8297 ;; so we know which returns/yields to highlight, and we should get rid of
8298 ;; all the checking in `js2-parse-return-or-yield'.
8299 (if (and js2-strict-inconsistent-return-warning
8300 (js2-now-all-set before js2-end-flags
8301 (logior js2-end-returns js2-end-returns-value)))
8302 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8304 (unless (js2-inside-function)
8305 (js2-report-error "msg.bad.yield"))
8306 (js2-set-flag js2-end-flags js2-end-yields)
8307 (setq ret (make-js2-yield-node :pos pos
8310 (js2-node-add-children ret e)
8311 (unless expr-context
8313 ret (js2-wrap-with-expr-stmt pos e t))
8314 (js2-set-requires-activation)
8315 (js2-set-is-generator))))
8316 ;; see if we are mixing yields and value returns.
8317 (when (and inside-function
8318 (js2-now-all-set before js2-end-flags
8319 (logior js2-end-yields js2-end-returns-value)))
8320 (setq name (js2-function-name js2-current-script-or-fn))
8321 (if (zerop (length name))
8322 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8323 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8326 (defun js2-parse-debugger ()
8328 (make-js2-keyword-node :type js2-DEBUGGER))
8330 (defun js2-parse-block ()
8331 "Parser for a curly-delimited statement block.
8332 Last token matched must be js2-LC."
8333 (let ((pos js2-token-beg)
8334 (pn (make-js2-scope)))
8339 (js2-parse-statements pn)
8340 (js2-must-match js2-RC "msg.no.brace.block")
8341 (setf (js2-node-len pn) (- js2-token-end pos)))
8345 ;; for js2-ERROR too, to have a node for error recovery to work on
8346 (defun js2-parse-semi ()
8347 "Parse a statement or handle an error.
8348 Last matched token is js-SEMI or js-ERROR."
8349 (let ((tt (js2-peek-token)) pos len)
8351 (if (eq tt js2-SEMI)
8352 (make-js2-empty-expr-node :len 1)
8353 (setq pos js2-token-beg
8354 len (- js2-token-beg pos))
8355 (js2-report-error "msg.syntax" nil pos len)
8356 (make-js2-error-node :pos pos :len len))))
8358 (defun js2-parse-default-xml-namespace ()
8359 "Parse a `default xml namespace = <expr>' e4x statement."
8360 (let ((pos js2-token-beg)
8361 end len expr unary es)
8364 (js2-set-requires-activation)
8365 (setq len (- js2-ts-cursor pos))
8366 (unless (and (js2-match-token js2-NAME)
8367 (string= js2-ts-string "xml"))
8368 (js2-report-error "msg.bad.namespace" nil pos len))
8369 (unless (and (js2-match-token js2-NAME)
8370 (string= js2-ts-string "namespace"))
8371 (js2-report-error "msg.bad.namespace" nil pos len))
8372 (unless (js2-match-token js2-ASSIGN)
8373 (js2-report-error "msg.bad.namespace" nil pos len))
8374 (setq expr (js2-parse-expr)
8375 end (js2-node-end expr)
8376 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8380 (js2-node-add-children unary expr)
8381 (make-js2-expr-stmt-node :pos pos
8385 (defun js2-record-label (label bundle)
8386 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8388 (let ((name (js2-label-node-name label))
8391 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8392 ;; flag both labels if possible when used in editing mode
8393 (if (and js2-parse-ide-mode
8394 (setq dup (js2-get-label-by-name labeled-stmt name)))
8395 (js2-report-error "msg.dup.label" nil
8396 (js2-node-abs-pos dup) (js2-node-len dup)))
8397 (js2-report-error "msg.dup.label" nil
8398 (js2-node-pos label) (js2-node-len label)))
8399 (js2-labeled-stmt-node-add-label bundle label)
8400 (js2-node-add-children bundle label)
8401 ;; Add one reference to the bundle per label in `js2-label-set'
8402 (push (cons name bundle) js2-label-set)))
8404 (defun js2-parse-name-or-label ()
8405 "Parser for identifier or label. Last token matched must be js2-NAME.
8406 Called when we found a name in a statement context. If it's a label, we gather
8407 up any following labels and the next non-label statement into a
8408 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8409 expression and return it wrapped in a `js2-expr-stmt-node'."
8410 (let ((pos js2-token-beg)
8417 ;; set check for label and call down to `js2-parse-primary-expr'
8418 (js2-set-check-for-label)
8419 (setq expr (js2-parse-expr))
8420 (if (/= (js2-node-type expr) js2-LABEL)
8421 ;; Parsed non-label expression - wrap with expression stmt.
8422 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8423 ;; else parsed a label
8424 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8425 (js2-record-label expr bundle)
8426 ;; look for more labels
8427 (while (and continue (= (js2-peek-token) js2-NAME))
8428 (js2-set-check-for-label)
8429 (setq expr (js2-parse-expr))
8430 (if (/= (js2-node-type expr) js2-LABEL)
8432 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8434 (js2-auto-insert-semicolon stmt))
8435 (js2-record-label expr bundle)))
8436 ;; no more labels; now parse the labeled statement
8439 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8440 (setq stmt (js2-statement-helper))))
8441 ;; remove the labels for this statement from the global set
8442 (dolist (label (js2-labeled-stmt-node-labels bundle))
8443 (setq js2-label-set (remove label js2-label-set))))
8444 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8445 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8446 (js2-node-add-children bundle stmt)
8449 (defun js2-parse-expr-stmt ()
8450 "Default parser in statement context, if no recognized statement found."
8451 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8453 (defun js2-parse-variables (decl-type pos)
8454 "Parse a comma-separated list of variable declarations.
8455 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8457 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8458 For 'var' or 'const', the keyword should be the token last scanned.
8460 POS is the position where the node should start. It's sometimes the
8461 var/const/let keyword, and other times the beginning of the first token
8462 in the first variable declaration.
8464 Returns the parsed `js2-var-decl-node' expression node."
8465 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8477 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8478 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8479 ;; var {a, b} = baz;
8481 (setq destructuring nil
8484 kid-pos js2-token-beg
8487 (if (or (= tt js2-LB) (= tt js2-LC))
8488 ;; Destructuring assignment, e.g., var [a, b] = ...
8489 (setq destructuring (js2-parse-primary-expr-lhs)
8490 end (js2-node-end destructuring))
8491 ;; Simple variable name
8492 (when (js2-must-match js2-NAME "msg.bad.var")
8493 (setq name (js2-create-name-node)
8497 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8498 (when (js2-match-token js2-ASSIGN)
8499 (setq init (js2-parse-assign-expr)
8500 end (js2-node-end init))
8501 (if (and js2-parse-ide-mode
8502 (or (js2-object-node-p init)
8503 (js2-function-node-p init)))
8504 (js2-record-imenu-functions init name)))
8506 (js2-set-face nbeg nend (if (js2-function-node-p init)
8507 'font-lock-function-name-face
8508 'font-lock-variable-name-face)
8510 (setq vi (make-js2-var-init-node :pos kid-pos
8511 :len (- end kid-pos)
8515 (if (and (null init) (not js2-in-for-init))
8516 (js2-report-error "msg.destruct.assign.no.init"))
8517 (js2-define-destruct-symbols destructuring
8519 'font-lock-variable-name-face)
8520 (setf (js2-var-init-node-target vi) destructuring))
8521 (setf (js2-var-init-node-target vi) name))
8522 (setf (js2-var-init-node-initializer vi) init)
8523 (js2-node-add-children vi name destructuring init)
8524 (js2-block-node-push result vi)
8525 (unless (js2-match-token js2-COMMA)
8526 (setq continue nil)))
8527 (setf (js2-node-len result) (- end pos))
8530 (defun js2-parse-let (pos &optional stmt-p)
8531 "Parse a let expression or statement.
8532 A let-expression is of the form `let (vars) expr'.
8533 A let-statment is of the form `let (vars) {statements}'.
8534 The third form of let is a variable declaration list, handled
8535 by `js2-parse-variables'."
8536 (let ((pn (make-js2-let-node :pos pos))
8538 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8539 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8543 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8544 (if (js2-must-match js2-RP "msg.no.paren.let")
8545 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8546 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8550 (setf beg js2-token-beg ; position stmt at LC
8551 body (js2-parse-statements))
8552 (js2-must-match js2-RC "msg.no.curly.let")
8553 (setf (js2-node-len body) (- js2-token-end beg)
8554 (js2-node-len pn) (- js2-token-end pos)
8555 (js2-let-node-body pn) body
8556 (js2-node-type pn) js2-LET))
8558 (setf body (js2-parse-expr)
8559 (js2-node-len pn) (- (js2-node-end body) pos)
8560 (js2-let-node-body pn) body))
8561 (js2-node-add-children pn vars body))
8565 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8566 (js2-scope-put-symbol (or scope js2-current-scope)
8568 (make-js2-symbol decl-type name node)))
8570 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8571 "Define a symbol in the current scope.
8572 If NODE is non-nil, it is the AST node associated with the symbol."
8573 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8574 (symbol (if defining-scope
8575 (js2-scope-get-symbol defining-scope name)))
8576 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8578 ((and symbol ; already defined
8579 (or (= sdt js2-CONST) ; old version is const
8580 (= decl-type js2-CONST) ; new version is const
8581 ;; two let-bound vars in this block have same name
8582 (and (= sdt js2-LET)
8583 (eq defining-scope js2-current-scope))))
8586 ((= sdt js2-CONST) "msg.const.redecl")
8587 ((= sdt js2-LET) "msg.let.redecl")
8588 ((= sdt js2-VAR) "msg.var.redecl")
8589 ((= sdt js2-FUNCTION) "msg.function.redecl")
8590 (t "msg.parm.redecl"))
8592 ((= decl-type js2-LET)
8593 (if (and (not ignore-not-in-block)
8594 (or (= (js2-node-type js2-current-scope) js2-IF)
8595 (js2-loop-node-p js2-current-scope)))
8596 (js2-report-error "msg.let.decl.not.in.block")
8597 (js2-define-new-symbol decl-type name node)))
8598 ((or (= decl-type js2-VAR)
8599 (= decl-type js2-CONST)
8600 (= decl-type js2-FUNCTION))
8602 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8603 (js2-add-strict-warning "msg.var.redecl" name)
8604 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8605 (js2-add-strict-warning "msg.var.hides.arg" name)))
8606 (js2-define-new-symbol decl-type name node
8607 js2-current-script-or-fn)))
8608 ((= decl-type js2-LP)
8610 ;; must be duplicate parameter. Second parameter hides the
8611 ;; first, so go ahead and add the second pararameter
8612 (js2-report-warning "msg.dup.parms" name))
8613 (js2-define-new-symbol decl-type name node))
8614 (t (js2-code-bug)))))
8616 (defun js2-parse-expr (&optional oneshot)
8617 (let* ((pn (js2-parse-assign-expr))
8618 (pos (js2-node-pos pn))
8622 (while (and (not oneshot)
8623 (js2-match-token js2-COMMA))
8624 (setq op-pos (- js2-token-beg pos)) ; relative
8625 (if (= (js2-peek-token) js2-YIELD)
8626 (js2-report-error "msg.yield.parenthesized"))
8627 (setq right (js2-parse-assign-expr)
8629 pn (make-js2-infix-node :type js2-COMMA
8631 :len (- js2-ts-cursor pos)
8635 (js2-node-add-children pn left right))
8638 (defun js2-parse-assign-expr ()
8639 (let ((tt (js2-peek-token))
8645 (if (= tt js2-YIELD)
8646 (js2-parse-return-or-yield tt t)
8647 ;; not yield - parse assignment expression
8648 (setq pn (js2-parse-cond-expr)
8649 tt (js2-peek-token))
8650 (when (and (<= js2-first-assign tt)
8651 (<= tt js2-last-assign))
8652 ;; tt express assignment (=, |=, ^=, ..., %=)
8654 (setq op-pos (- js2-token-beg pos) ; relative
8656 right (js2-parse-assign-expr)
8657 pn (make-js2-assign-node :type tt
8659 :len (- (js2-node-end right) pos)
8663 (when js2-parse-ide-mode
8664 (js2-highlight-assign-targets pn left right)
8665 (if (or (js2-function-node-p right)
8666 (js2-object-node-p right))
8667 (js2-record-imenu-functions right left)))
8668 ;; do this last so ide checks above can use absolute positions
8669 (js2-node-add-children pn left right))
8672 (defun js2-parse-cond-expr ()
8673 (let ((pos js2-token-beg)
8674 (pn (js2-parse-or-expr))
8680 (when (js2-match-token js2-HOOK)
8681 (setq q-pos (- js2-token-beg pos)
8682 if-true (js2-parse-assign-expr))
8683 (js2-must-match js2-COLON "msg.no.colon.cond")
8684 (setq c-pos (- js2-token-beg pos)
8685 if-false (js2-parse-assign-expr)
8687 pn (make-js2-cond-node :pos pos
8688 :len (- (js2-node-end if-false) pos)
8689 :test-expr test-expr
8691 :false-expr if-false
8694 (js2-node-add-children pn test-expr if-true if-false))
8697 (defun js2-make-binary (type left parser)
8698 "Helper for constructing a binary-operator AST node.
8699 LEFT is the left-side-expression, already parsed, and the
8700 binary operator should have just been matched.
8701 PARSER is a function to call to parse the right operand,
8702 or a `js2-node' struct if it has already been parsed."
8703 (let* ((pos (js2-node-pos left))
8704 (op-pos (- js2-token-beg pos))
8705 (right (if (js2-node-p parser)
8708 (pn (make-js2-infix-node :type type
8710 :len (- (js2-node-end right) pos)
8714 (js2-node-add-children pn left right)
8717 (defun js2-parse-or-expr ()
8718 (let ((pn (js2-parse-and-expr)))
8719 (when (js2-match-token js2-OR)
8720 (setq pn (js2-make-binary js2-OR
8722 'js2-parse-or-expr)))
8725 (defun js2-parse-and-expr ()
8726 (let ((pn (js2-parse-bit-or-expr)))
8727 (when (js2-match-token js2-AND)
8728 (setq pn (js2-make-binary js2-AND
8730 'js2-parse-and-expr)))
8733 (defun js2-parse-bit-or-expr ()
8734 (let ((pn (js2-parse-bit-xor-expr)))
8735 (while (js2-match-token js2-BITOR)
8736 (setq pn (js2-make-binary js2-BITOR
8738 'js2-parse-bit-xor-expr)))
8741 (defun js2-parse-bit-xor-expr ()
8742 (let ((pn (js2-parse-bit-and-expr)))
8743 (while (js2-match-token js2-BITXOR)
8744 (setq pn (js2-make-binary js2-BITXOR
8746 'js2-parse-bit-and-expr)))
8749 (defun js2-parse-bit-and-expr ()
8750 (let ((pn (js2-parse-eq-expr)))
8751 (while (js2-match-token js2-BITAND)
8752 (setq pn (js2-make-binary js2-BITAND
8754 'js2-parse-eq-expr)))
8757 (defconst js2-parse-eq-ops
8758 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8760 (defun js2-parse-eq-expr ()
8761 (let ((pn (js2-parse-rel-expr))
8763 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8765 (setq pn (js2-make-binary tt
8767 'js2-parse-rel-expr)))
8770 (defconst js2-parse-rel-ops
8771 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8773 (defun js2-parse-rel-expr ()
8774 (let ((pn (js2-parse-shift-expr))
8778 (setq tt (js2-peek-token))
8780 ((and js2-in-for-init (= tt js2-IN))
8781 (setq continue nil))
8782 ((memq tt js2-parse-rel-ops)
8784 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8786 (setq continue nil))))
8789 (defconst js2-parse-shift-ops
8790 (list js2-LSH js2-URSH js2-RSH))
8792 (defun js2-parse-shift-expr ()
8793 (let ((pn (js2-parse-add-expr))
8797 (setq tt (js2-peek-token))
8798 (if (memq tt js2-parse-shift-ops)
8801 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8802 (setq continue nil)))
8805 (defun js2-parse-add-expr ()
8806 (let ((pn (js2-parse-mul-expr))
8810 (setq tt (js2-peek-token))
8811 (if (or (= tt js2-ADD) (= tt js2-SUB))
8814 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8815 (setq continue nil)))
8818 (defconst js2-parse-mul-ops
8819 (list js2-MUL js2-DIV js2-MOD))
8821 (defun js2-parse-mul-expr ()
8822 (let ((pn (js2-parse-unary-expr))
8826 (setq tt (js2-peek-token))
8827 (if (memq tt js2-parse-mul-ops)
8830 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8831 (setq continue nil)))
8834 (defsubst js2-make-unary (type parser &rest args)
8835 "Make a unary node of type TYPE.
8836 PARSER is either a node (for postfix operators) or a function to call
8837 to parse the operand (for prefix operators)."
8838 (let* ((pos js2-token-beg)
8839 (postfix (js2-node-p parser))
8842 (apply parser args)))
8845 (if postfix ; e.g. i++
8846 (setq pos (js2-node-pos expr)
8848 (setq end (js2-node-end expr)))
8849 (setq pn (make-js2-unary-node :type type
8853 (js2-node-add-children pn expr)
8856 (defconst js2-incrementable-node-types
8857 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8858 "Node types that can be the operand of a ++ or -- operator.")
8860 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8861 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8862 js2-incrementable-node-types)
8863 (js2-report-error (if (= tt js2-INC)
8866 nil beg (- end beg))))
8868 (defun js2-parse-unary-expr ()
8869 (let ((tt (js2-peek-token))
8872 ((or (= tt js2-VOID)
8877 (js2-make-unary tt 'js2-parse-unary-expr))
8880 ;; Convert to special POS token in decompiler and parse tree
8881 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8884 ;; Convert to special NEG token in decompiler and parse tree
8885 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8890 (setq beg js2-token-beg
8892 expr (js2-make-unary tt 'js2-parse-member-expr t))
8893 (js2-check-bad-inc-dec tt beg end expr)))
8896 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8899 (make-js2-error-node)) ; try to continue
8901 js2-compiler-xml-available)
8902 ;; XML stream encountered in expression.
8904 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8906 (setq pn (js2-parse-member-expr t)
8907 ;; Don't look across a newline boundary for a postfix incop.
8908 tt (js2-peek-token-or-eol))
8909 (when (or (= tt js2-INC) (= tt js2-DEC))
8912 pn (js2-make-unary tt expr))
8913 (js2-node-set-prop pn 'postfix t)
8914 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8917 (defun js2-parse-xml-initializer ()
8918 "Parse an E4X XML initializer.
8919 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8920 Then I'll postprocess the result, depending on whether we're in IDE
8921 mode or codegen mode, and generate the appropriate rewritten AST.
8922 IDE mode uses a rich AST that models the XML structure. Codegen mode
8923 just concatenates everything and makes a new XML or XMLList out of it."
8924 (let ((tt (js2-get-first-xml-token))
8932 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8933 (js2-report-error "msg.syntax"))
8934 (setq pn-xml (make-js2-xml-node))
8937 (setq first-token nil)
8938 (setq tt (js2-get-next-xml-token)))
8940 ;; js2-XML means we found a {expr} in the XML stream.
8941 ;; The js2-ts-string is the XML up to the left-curly.
8943 (push (make-js2-string-node :pos js2-token-beg
8944 :len (- js2-ts-cursor js2-token-beg))
8946 (js2-must-match js2-LC "msg.syntax")
8947 (setq expr-pos js2-ts-cursor
8948 expr (if (eq (js2-peek-token) js2-RC)
8949 (make-js2-empty-expr-node :pos expr-pos)
8951 (js2-must-match js2-RC "msg.syntax")
8952 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8953 :len (js2-node-len expr)
8955 (js2-node-add-children pn expr)
8957 ;; a js2-XMLEND token means we hit the final close-tag.
8959 (push (make-js2-string-node :pos js2-token-beg
8960 :len (- js2-ts-cursor js2-token-beg))
8962 (dolist (kid (nreverse kids))
8963 (js2-block-node-push pn-xml kid))
8964 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8965 (js2-node-pos pn-xml))
8968 (js2-report-error "msg.syntax")
8969 (setq continue nil))))
8973 (defun js2-parse-argument-list ()
8974 "Parse an argument list and return it as a lisp list of nodes.
8975 Returns the list in reverse order. Consumes the right-paren token."
8977 (unless (js2-match-token js2-RP)
8979 (if (= (js2-peek-token) js2-YIELD)
8980 (js2-report-error "msg.yield.parenthesized"))
8981 (push (js2-parse-assign-expr) result)
8983 (js2-match-token js2-COMMA))
8984 (js2-must-match js2-RP "msg.no.paren.arg")
8987 (defun js2-parse-member-expr (&optional allow-call-syntax)
8988 (let ((tt (js2-peek-token))
8998 (setq pn (js2-parse-primary-expr))
8999 ;; parse a 'new' expression
9001 (setq pos js2-token-beg
9003 target (js2-parse-member-expr)
9004 end (js2-node-end target)
9005 pn (make-js2-new-node :pos pos
9008 (js2-node-add-children pn target)
9009 (when (js2-match-token js2-LP)
9010 ;; Add the arguments to pn, if any are supplied.
9011 (setf beg pos ; start of "new" keyword
9013 args (nreverse (js2-parse-argument-list))
9014 (js2-new-node-args pn) args
9016 (js2-new-node-lp pn) (- pos beg)
9017 (js2-new-node-rp pn) (- end 1 beg))
9018 (apply #'js2-node-add-children pn args))
9019 (when (and js2-allow-rhino-new-expr-initializer
9020 (js2-match-token js2-LC))
9021 (setf init (js2-parse-object-literal)
9022 end (js2-node-end init)
9023 (js2-new-node-initializer pn) init)
9024 (js2-node-add-children pn init))
9025 (setf (js2-node-len pn) (- end beg))) ; end outer if
9026 (js2-parse-member-expr-tail allow-call-syntax pn)))
9028 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9029 "Parse a chain of property/array accesses or function calls.
9030 Includes parsing for E4X operators like `..' and `.@'.
9031 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9032 Returns an expression tree that includes PN, the parent node."
9033 (let ((beg (js2-node-pos pn))
9037 (setq tt (js2-peek-token))
9039 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9040 (setq pn (js2-parse-property-access tt pn)))
9041 ((= tt js2-DOTQUERY)
9042 (setq pn (js2-parse-dot-query pn)))
9044 (setq pn (js2-parse-element-get pn)))
9046 (if allow-call-syntax
9047 (setq pn (js2-parse-function-call pn))
9048 (setq continue nil)))
9050 (setq continue nil))))
9051 (if (>= js2-highlight-level 2)
9052 (js2-parse-highlight-member-expr-node pn))
9055 (defun js2-parse-dot-query (pn)
9056 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9057 Last token parsed must be `js2-DOTQUERY'."
9058 (let ((pos (js2-node-pos pn))
9064 (js2-set-requires-activation)
9065 (setq op-pos js2-token-beg
9066 expr (js2-parse-expr)
9067 end (js2-node-end expr)
9068 pn (make-js2-xml-dot-query-node :left pn
9072 (js2-node-add-children pn
9073 (js2-xml-dot-query-node-left pn)
9074 (js2-xml-dot-query-node-right pn))
9075 (if (js2-must-match js2-RP "msg.no.paren")
9076 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9078 (setf (js2-node-len pn) (- end pos))
9081 (defun js2-parse-element-get (pn)
9082 "Parse an element-get expression, e.g. foo[bar].
9083 Last token parsed must be `js2-RB'."
9084 (let ((lb js2-token-beg)
9085 (pos (js2-node-pos pn))
9089 (setq expr (js2-parse-expr))
9090 (if (js2-must-match js2-RB "msg.no.bracket.index")
9091 (setq rb js2-token-beg))
9092 (setq pn (make-js2-elem-get-node :target pn
9095 :lb (js2-relpos lb pos)
9096 :rb (js2-relpos rb pos)
9097 :len (- js2-token-end pos)))
9098 (js2-node-add-children pn
9099 (js2-elem-get-node-target pn)
9100 (js2-elem-get-node-element pn))
9103 (defun js2-parse-function-call (pn)
9105 (pos (js2-node-pos pn)))
9107 (setq pn (make-js2-call-node :pos pos
9109 :lp (- js2-token-beg pos)))
9110 (js2-node-add-children pn (js2-call-node-target pn))
9111 ;; Add the arguments to pn, if any are supplied.
9112 (setf args (nreverse (js2-parse-argument-list))
9113 (js2-call-node-rp pn) (- js2-token-beg pos)
9114 (js2-call-node-args pn) args)
9115 (apply #'js2-node-add-children pn args)
9116 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9119 (defun js2-parse-property-access (tt pn)
9120 "Parse a property access, XML descendants access, or XML attr access."
9121 (let ((member-type-flags 0)
9122 (dot-pos js2-token-beg)
9123 (dot-len (if (= tt js2-DOTDOT) 2 1))
9125 ref ; right side of . or .. operator
9128 (when (= tt js2-DOTDOT)
9130 (setq member-type-flags js2-descendants-flag))
9131 (if (not js2-compiler-xml-available)
9133 (js2-must-match-prop-name "msg.no.name.after.dot")
9134 (setq name (js2-create-name-node t js2-GETPROP)
9135 result (make-js2-prop-get-node :left pn
9138 :len (- js2-token-end
9140 (js2-node-add-children result pn name)
9142 ;; otherwise look for XML operators
9143 (setf result (if (= tt js2-DOT)
9144 (make-js2-prop-get-node)
9145 (make-js2-infix-node :type js2-DOTDOT))
9146 (js2-node-pos result) (js2-node-pos pn)
9147 (js2-infix-node-op-pos result) dot-pos
9148 (js2-infix-node-left result) pn ; do this after setting position
9149 tt (js2-next-token))
9151 ;; needed for generator.throw()
9153 (js2-save-name-token-data js2-token-beg "throw")
9154 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9155 ;; handles: name, ns::name, ns::*, ns::[expr]
9156 ((js2-valid-prop-name-token tt)
9157 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9158 ;; handles: *, *::name, *::*, *::[expr]
9160 (js2-save-name-token-data js2-token-beg "*")
9161 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9162 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9164 (setq result (js2-parse-attribute-access)))
9166 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9168 (setf (js2-node-len result) (- (js2-node-end ref)
9169 (js2-node-pos result))
9170 (js2-infix-node-right result) ref))
9171 (if (js2-infix-node-p result)
9172 (js2-node-add-children result
9173 (js2-infix-node-left result)
9174 (js2-infix-node-right result)))
9177 (defun js2-parse-attribute-access ()
9178 "Parse an E4X XML attribute expression.
9179 This includes expressions of the forms:
9181 @attr @ns::attr @ns::*
9183 @[expr] @*::[expr] @ns::[expr]
9185 Called if we peeked an '@' token."
9186 (let ((tt (js2-next-token))
9187 (at-pos js2-token-beg))
9189 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9190 ((js2-valid-prop-name-token tt)
9191 (js2-parse-property-name at-pos js2-ts-string 0))
9192 ;; handles: @*, @*::name, @*::*, @*::[expr]
9194 (js2-save-name-token-data js2-token-beg "*")
9195 (js2-parse-property-name js2-token-beg "*" 0))
9198 (js2-parse-xml-elem-ref at-pos))
9200 (js2-report-error "msg.no.name.after.xmlAttr")
9201 ;; Avoid cascaded errors that happen if we make an error node here.
9202 (js2-save-name-token-data js2-token-beg "")
9203 (js2-parse-property-name js2-token-beg "" 0)))))
9205 (defun js2-parse-property-name (at-pos s member-type-flags)
9206 "Check if :: follows name in which case it becomes qualified name.
9208 AT-POS is a natural number if we just read an '@' token, else nil.
9209 S is the name or string that was matched: an identifier, 'throw' or '*'.
9210 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9212 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9213 operator, or the name is followed by ::. For a plain name, returns a
9214 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9215 (let ((pos (or at-pos js2-token-beg))
9217 (name (js2-create-name-node t js2-current-token))
9223 (when (js2-match-token js2-COLONCOLON)
9225 colon-pos js2-token-beg
9226 tt (js2-next-token))
9228 ;; handles name::name
9229 ((js2-valid-prop-name-token tt)
9230 (setq name (js2-create-name-node)))
9233 (js2-save-name-token-data js2-token-beg "*")
9234 (setq name (js2-create-name-node)))
9235 ;; handles name::[expr]
9237 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9239 (js2-report-error "msg.no.name.after.coloncolon"))))
9240 (if (and (null ns) (zerop member-type-flags))
9244 (make-js2-xml-prop-ref-node :pos pos
9245 :len (- (js2-node-end name) pos)
9247 :colon-pos colon-pos
9249 (js2-node-add-children pn name))))))
9251 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9252 "Parse the [expr] portion of an xml element reference.
9253 For instance, @[expr], @*::[expr], or ns::[expr]."
9254 (let* ((lb js2-token-beg)
9255 (pos (or at-pos lb))
9257 (expr (js2-parse-expr))
9258 (end (js2-node-end expr))
9260 (if (js2-must-match js2-RB "msg.no.bracket.index")
9261 (setq rb js2-token-beg
9265 (make-js2-xml-elem-ref-node :pos pos
9267 :namespace namespace
9268 :colon-pos colon-pos
9271 :lb (js2-relpos lb pos)
9272 :rb (js2-relpos rb pos)))
9273 (js2-node-add-children pn namespace expr))))
9275 (defsubst js2-parse-primary-expr-lhs ()
9276 (let ((js2-is-in-lhs t))
9277 (js2-parse-primary-expr)))
9279 (defun js2-parse-primary-expr ()
9280 "Parses a literal (leaf) expression of some sort.
9281 Includes complex literals such as functions, object-literals,
9282 array-literals, array comprehensions and regular expressions."
9283 (let ((tt-flagged (js2-next-flagged-token))
9284 pn ; parent node (usually return value)
9286 px-pos ; paren-expr pos
9288 flags ; regexp flags
9290 (setq tt js2-current-token)
9292 ((= tt js2-FUNCTION)
9293 (js2-parse-function 'FUNCTION_EXPRESSION))
9295 (js2-parse-array-literal))
9297 (js2-parse-object-literal))
9299 (js2-parse-let js2-token-beg))
9301 (setq px-pos js2-token-beg
9302 expr (js2-parse-expr))
9303 (js2-must-match js2-RP "msg.no.paren")
9304 (setq pn (make-js2-paren-node :pos px-pos
9306 :len (- js2-token-end px-pos)))
9307 (js2-node-add-children pn (js2-paren-node-expr pn))
9311 (js2-parse-attribute-access))
9313 (js2-parse-name tt-flagged tt))
9315 (make-js2-number-node))
9318 (make-js2-string-node)
9319 (js2-record-face 'font-lock-string-face)))
9320 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9321 ;; Got / or /= which in this context means a regexp literal
9322 (setq px-pos js2-token-beg)
9323 (js2-read-regexp tt)
9324 (setq flags js2-ts-regexp-flags
9325 js2-ts-regexp-flags nil)
9327 (make-js2-regexp-node :pos px-pos
9328 :len (- js2-ts-cursor px-pos)
9329 :value js2-ts-string
9331 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9332 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9333 ((or (= tt js2-NULL)
9337 (make-js2-keyword-node :type tt))
9338 ((= tt js2-RESERVED)
9339 (js2-report-error "msg.reserved.id")
9340 (make-js2-name-node))
9342 ;; the scanner or one of its subroutines reported the error.
9343 (make-js2-error-node))
9345 (setq px-pos (point-at-bol)
9346 len (- js2-ts-cursor px-pos))
9347 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9348 (make-js2-error-node :pos px-pos :len len))
9350 (js2-report-error "msg.syntax")
9351 (make-js2-error-node)))))
9353 (defun js2-parse-name (tt-flagged tt)
9354 (let ((name js2-ts-string)
9355 (name-pos js2-token-beg)
9357 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9358 (= (js2-peek-token) js2-COLON))
9360 ;; Do not consume colon, it is used as unwind indicator
9361 ;; to return to statementHelper.
9362 (make-js2-label-node :pos name-pos
9363 :len (- js2-token-end name-pos)
9365 (js2-set-face name-pos
9367 'font-lock-variable-name-face 'record))
9368 ;; Otherwise not a label, just a name. Unfortunately peeking
9369 ;; the next token to check for a colon has biffed js2-token-beg
9370 ;; and js2-token-end. We store the name's bounds in buffer vars
9371 ;; and `js2-create-name-node' uses them.
9372 (js2-save-name-token-data name-pos name)
9373 (setq node (if js2-compiler-xml-available
9374 (js2-parse-property-name nil name 0)
9375 (js2-create-name-node 'check-activation)))
9376 (if js2-highlight-external-variables
9377 (js2-record-name-node node))
9380 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9381 (js2-add-strict-warning
9383 ;; back up from comma to beginning of line or array/objlit
9385 (js2-node-pos (car elems))
9388 (goto-char comma-pos)
9389 (back-to-indentation)
9393 (defun js2-parse-array-literal ()
9394 (let ((pos js2-token-beg)
9396 (after-lb-or-comma t)
9402 (unless js2-is-in-lhs
9403 (js2-push-scope (make-js2-scope))) ; for array comp
9405 (setq tt (js2-peek-token))
9410 (setq after-comma js2-token-end)
9411 (if (not after-lb-or-comma)
9412 (setq after-lb-or-comma t)
9416 (= tt js2-EOF)) ; prevent infinite loop
9418 (js2-report-error "msg.no.bracket.arg" nil pos)
9419 (js2-consume-token))
9422 pn (make-js2-array-node :pos pos
9423 :len (- js2-ts-cursor pos)
9424 :elems (nreverse elems)))
9425 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9426 (when (and after-comma (not js2-is-in-lhs))
9427 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9428 pos elems after-comma)))
9429 ;; destructuring binding
9431 (push (if (or (= tt js2-LC)
9434 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9435 (js2-parse-primary-expr-lhs)
9438 (js2-report-error "msg.bad.var")
9439 (make-js2-error-node))
9441 (setq after-lb-or-comma nil
9444 ((and (>= js2-language-version 170)
9445 (= tt js2-FOR) ; check for array comprehension
9446 (not after-lb-or-comma) ; "for" can't follow a comma
9447 elems ; must have at least 1 element
9448 (not (cdr elems))) ; but no 2nd element
9450 pn (js2-parse-array-comprehension (car elems) pos)))
9454 (unless after-lb-or-comma
9455 (js2-report-error "msg.no.bracket.arg"))
9456 (push (js2-parse-assign-expr) elems)
9457 (setq after-lb-or-comma nil
9459 (unless js2-is-in-lhs
9463 (defun js2-parse-array-comprehension (expr pos)
9464 "Parse a JavaScript 1.7 Array Comprehension.
9465 EXPR is the first expression after the opening left-bracket.
9466 POS is the beginning of the LB token preceding EXPR.
9467 We should have just parsed the 'for' keyword before calling this function."
9475 (while (= (js2-peek-token) js2-FOR)
9476 (let ((prev (car loops))) ; rearrange scope chain
9477 (push (setq loop (js2-parse-array-comp-loop)) loops)
9478 (if prev ; each loop is parent scope to the next one
9479 (setf (js2-scope-parent-scope loop) prev)
9480 ; first loop takes expr scope's parent
9481 (setf (js2-scope-parent-scope (setq first loop))
9482 (js2-scope-parent-scope js2-current-scope)))))
9483 ;; set expr scope's parent to the last loop
9484 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9485 (when (= (js2-peek-token) js2-IF)
9487 (setq if-pos (- js2-token-beg pos) ; relative
9488 filter (js2-parse-condition)))
9489 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9490 (setq result (make-js2-array-comp-node :pos pos
9491 :len (- js2-ts-cursor pos)
9493 :loops (nreverse loops)
9494 :filter (car filter)
9495 :lp (js2-relpos (second filter) pos)
9496 :rp (js2-relpos (third filter) pos)
9498 (apply #'js2-node-add-children result expr (car filter)
9499 (js2-array-comp-node-loops result))
9500 (setq js2-current-scope first) ; pop to the first loop
9503 (defun js2-parse-array-comp-loop ()
9504 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9505 Last token peeked should be the initial FOR."
9506 (let ((pos js2-token-beg)
9507 (pn (make-js2-array-comp-loop-node))
9516 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9520 (when (js2-match-token js2-NAME)
9521 (if (string= js2-ts-string "each")
9524 each-pos (- js2-token-beg pos)) ; relative
9525 (js2-record-face 'font-lock-keyword-face))
9526 (js2-report-error "msg.no.paren.for")))
9527 (if (js2-must-match js2-LP "msg.no.paren.for")
9528 (setq lp (- js2-token-beg pos)))
9529 (setq tt (js2-peek-token))
9533 ;; handle destructuring assignment
9534 (setq iter (js2-parse-primary-expr-lhs))
9535 (js2-define-destruct-symbols iter js2-LET
9536 'font-lock-variable-name-face t))
9537 ((js2-valid-prop-name-token tt)
9539 (setq iter (js2-create-name-node)))
9541 (js2-report-error "msg.bad.var")))
9542 ;; Define as a let since we want the scope of the variable to
9543 ;; be restricted to the array comprehension
9544 (if (js2-name-node-p iter)
9545 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9546 (if (js2-must-match js2-IN "msg.in.after.for.name")
9547 (setq in-pos (- js2-token-beg pos)))
9548 (setq obj (js2-parse-expr))
9549 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9550 (setq rp (- js2-token-beg pos)))
9551 (setf (js2-node-pos pn) pos
9552 (js2-node-len pn) (- js2-ts-cursor pos)
9553 (js2-array-comp-loop-node-iterator pn) iter
9554 (js2-array-comp-loop-node-object pn) obj
9555 (js2-array-comp-loop-node-in-pos pn) in-pos
9556 (js2-array-comp-loop-node-each-pos pn) each-pos
9557 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9558 (js2-array-comp-loop-node-lp pn) lp
9559 (js2-array-comp-loop-node-rp pn) rp)
9560 (js2-node-add-children pn iter obj))
9564 (defun js2-parse-object-literal ()
9565 (let ((pos js2-token-beg)
9572 (setq tt (js2-peek-token))
9574 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9575 ((or (js2-valid-prop-name-token tt)
9577 (setq after-comma nil
9578 result (js2-parse-named-prop tt))
9579 (if (and (null result)
9580 (not js2-recover-from-parse-errors))
9582 (push result elems)))
9583 ;; {12: x} or {10.7: x}
9586 (setq after-comma nil)
9587 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9592 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9593 pos elems after-comma)))
9595 (js2-report-error "msg.bad.prop")
9596 (unless js2-recover-from-parse-errors
9597 (setq continue nil)))) ; end switch
9598 (if (js2-match-token js2-COMMA)
9599 (setq after-comma js2-token-end)
9600 (setq continue nil))) ; end loop
9601 (js2-must-match js2-RC "msg.no.brace.prop")
9602 (setq result (make-js2-object-node :pos pos
9603 :len (- js2-ts-cursor pos)
9604 :elems (nreverse elems)))
9605 (apply #'js2-node-add-children result (js2-object-node-elems result))
9608 (defun js2-parse-named-prop (tt)
9609 "Parse a name, string, or getter/setter object property.
9610 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9612 (let ((string-prop (and (= tt js2-STRING)
9613 (make-js2-string-node)))
9615 (ppos js2-token-beg)
9616 (pend js2-token-end)
9617 (name (js2-create-name-node))
9618 (prop js2-ts-string))
9620 ;; getter/setter prop
9621 ((and (= tt js2-NAME)
9622 (= (js2-peek-token) js2-NAME)
9623 (or (string= prop "get")
9624 (string= prop "set")))
9626 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9627 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9628 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9629 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9630 ;; abbreviated destructuring bind e.g., {a, b} = c;
9631 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9632 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9633 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9634 ;; assignment but it's difficult because it requires looking ahead of expression.
9637 (let ((ctk (js2-peek-token)))
9638 (or (= ctk js2-COMMA)
9640 (js2-valid-prop-name-token ctk))))
9645 (setq expr (js2-parse-plain-property (or string-prop name)))
9646 (js2-set-face ppos pend
9647 (if (js2-function-node-p
9648 (js2-object-prop-node-right expr))
9649 'font-lock-function-name-face
9650 'font-lock-variable-name-face)
9653 (defun js2-parse-plain-property (prop)
9654 "Parse a non-getter/setter property in an object literal.
9655 PROP is the node representing the property: a number, name or string."
9656 (js2-must-match js2-COLON "msg.no.colon.prop")
9657 (let* ((pos (js2-node-pos prop))
9658 (colon (- js2-token-beg pos))
9659 (expr (js2-parse-assign-expr))
9660 (result (make-js2-object-prop-node
9662 ;; don't include last consumed token in length
9663 :len (- (+ (js2-node-pos expr)
9664 (js2-node-len expr))
9669 (js2-node-add-children result prop expr)
9672 (defun js2-parse-getter-setter-prop (pos prop get-p)
9673 "Parse getter or setter property in an object literal.
9674 JavaScript syntax is:
9676 { get foo() {...}, set foo(x) {...} }
9678 and expression closure style is also supported
9680 { get foo() x, set foo(x) _x = x }
9682 POS is the start position of the `get' or `set' keyword.
9683 PROP is the `js2-name-node' representing the property name.
9684 GET-P is non-nil if the keyword was `get'."
9685 (let ((type (if get-p js2-GET js2-SET))
9688 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9689 ;; it has to be an anonymous function, as we already parsed the name
9690 (if (/= (js2-node-type fn) js2-FUNCTION)
9691 (js2-report-error "msg.bad.prop")
9692 (if (plusp (length (js2-function-name fn)))
9693 (js2-report-error "msg.bad.prop")))
9694 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9695 (setq end (js2-node-end fn)
9696 result (make-js2-getter-setter-node :type type
9701 (js2-node-add-children result prop fn)
9704 (defun js2-create-name-node (&optional check-activation-p token)
9705 "Create a name node using the token info from last scanned name.
9706 In some cases we need to either synthesize a name node, or we lost
9707 the name token information by peeking. If the TOKEN parameter is
9708 not `js2-NAME', then we use the token info saved in instance vars."
9709 (let ((beg js2-token-beg)
9712 (when (/= js2-current-token js2-NAME)
9713 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9714 s js2-prev-name-token-string
9715 js2-prev-name-token-start nil
9716 js2-prev-name-token-string nil))
9717 (setq name (make-js2-name-node :pos beg
9720 (if check-activation-p
9721 (js2-check-activation-name s (or token js2-NAME)))
9724 ;;; Indentation support
9726 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9727 ;; Karl cleverly deduces that the desired indentation level is often a
9728 ;; function of paren/bracket/brace nesting depth, which can be determined
9729 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9730 ;; then does some equally clever checks to see if we're in the context of a
9731 ;; substatement of a possibly braceless statement keyword such as if, while,
9732 ;; or finally. This approach yields pretty good results.
9734 ;; The indenter is often "wrong", however, and needs to be overridden.
9735 ;; The right long-term solution is probably to emulate (or integrate
9736 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9737 ;; parse tree from `js2-parse' is present, which is not true at the
9738 ;; moment the user is typing, computing indentation is still thousands
9739 ;; of lines of code to handle every possible syntactic edge case.
9741 ;; In the meantime, the compromise solution is that we offer a "bounce
9742 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9743 ;; current line indent among various likely guess points. This approach
9744 ;; is far from perfect, but should at least make it slightly easier to
9745 ;; move the line towards its desired indentation when manually
9746 ;; overriding Karl's heuristic nesting guesser.
9748 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9749 ;; extensions such as `let' and Array comprehensions. Major kudos to
9750 ;; Karl for coming up with the initial approach, which packs a lot of
9751 ;; punch for so little code.
9753 (defconst js-possibly-braceless-keywords-re
9754 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9755 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9756 "try" "while" "with" "let")))
9757 "Regular expression matching keywords that are optionally
9758 followed by an opening brace.")
9760 (defconst js-indent-operator-re
9761 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9762 (regexp-opt '("in" "instanceof") 'words))
9763 "Regular expression matching operators that affect indentation
9764 of continued expressions.")
9766 (defconst js-declaration-keyword-re
9767 (regexp-opt '("var" "let" "const") 'words)
9768 "Regular expression matching variable declaration keywords.")
9770 ;; This function has horrible results if you're typing an array
9771 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9772 ;; in conjunction with electric-indent, so just disabling it.
9773 (defsubst js2-code-at-bol-p ()
9774 "Return t if the first character on line is non-whitespace."
9777 (defun js2-insert-and-indent (key)
9778 "Run command bound to key and indent current line. Runs the command
9779 bound to KEY in the global keymap and indents the current line."
9780 (interactive (list (this-command-keys)))
9781 (let ((cmd (lookup-key (current-global-map) key)))
9783 (call-interactively cmd)))
9784 ;; don't do the electric keys inside comments or strings,
9785 ;; and don't do bounce-indent with them.
9786 (let ((parse-state (syntax-ppss (point)))
9787 (js2-bounce-indent-p (js2-code-at-bol-p)))
9788 (unless (or (nth 3 parse-state)
9789 (nth 4 parse-state))
9790 (indent-according-to-mode))))
9792 (defun js-re-search-forward-inner (regexp &optional bound count)
9793 "Auxiliary function for `js-re-search-forward'."
9794 (let (parse saved-point)
9796 (re-search-forward regexp bound)
9797 (setq parse (if saved-point
9798 (parse-partial-sexp saved-point (point))
9799 (syntax-ppss (point))))
9800 (cond ((nth 3 parse)
9802 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9803 (save-excursion (end-of-line) (point)) t))
9807 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9808 (re-search-forward "\\*/"))
9810 (setq count (1- count))))
9811 (setq saved-point (point))))
9814 (defun js-re-search-forward (regexp &optional bound noerror count)
9815 "Search forward but ignore strings and comments. Invokes
9816 `re-search-forward' but treats the buffer as if strings and
9817 comments have been removed."
9818 (let ((saved-point (point))
9821 '(js-re-search-forward-inner regexp bound 1))
9823 '(js-re-search-backward-inner regexp bound (- count)))
9825 '(js-re-search-forward-inner regexp bound count)))))
9829 (goto-char saved-point)
9831 (error (error-message-string err)))))))
9833 (defun js-re-search-backward-inner (regexp &optional bound count)
9834 "Auxiliary function for `js-re-search-backward'."
9835 (let (parse saved-point)
9837 (re-search-backward regexp bound)
9838 (setq parse (if saved-point
9839 (parse-partial-sexp saved-point (point))
9840 (syntax-ppss (point))))
9841 (cond ((nth 3 parse)
9843 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9844 (save-excursion (beginning-of-line) (point)) t))
9846 (goto-char (nth 8 parse)))
9848 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9849 (re-search-backward "/\\*"))
9851 (setq count (1- count))))))
9854 (defun js-re-search-backward (regexp &optional bound noerror count)
9855 "Search backward but ignore strings and comments. Invokes
9856 `re-search-backward' but treats the buffer as if strings and
9857 comments have been removed."
9858 (let ((saved-point (point))
9861 '(js-re-search-backward-inner regexp bound 1))
9863 '(js-re-search-forward-inner regexp bound (- count)))
9865 '(js-re-search-backward-inner regexp bound count)))))
9869 (goto-char saved-point)
9871 (error (error-message-string err)))))))
9873 (defun js-looking-at-operator-p ()
9874 "Return non-nil if text after point is an operator (that is not
9877 (and (looking-at js-indent-operator-re)
9878 (or (not (looking-at ":"))
9880 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9881 (looking-at "?")))))))
9883 (defun js-continued-expression-p ()
9884 "Returns non-nil if the current line continues an expression."
9886 (back-to-indentation)
9887 (or (js-looking-at-operator-p)
9889 (and (js-re-search-backward "\n" nil t)
9891 (skip-chars-backward " \t")
9894 (and (js-looking-at-operator-p)
9897 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9899 (defun js-end-of-do-while-loop-p ()
9900 "Returns non-nil if word after point is `while' of a do-while
9901 statement, else returns nil. A braceless do-while statement
9902 spanning several lines requires that the start of the loop is
9903 indented to the same column as the current line."
9907 (when (looking-at "\\s-*\\<while\\>")
9909 (skip-chars-backward "[ \t\n]*}")
9910 (looking-at "[ \t\n]*}"))
9912 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9913 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9914 (or (looking-at "\\<do\\>")
9915 (let ((saved-indent (current-indentation)))
9916 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9917 (/= (current-indentation) saved-indent)))
9918 (and (looking-at "[ \t]*\\<do\\>")
9919 (not (js-re-search-forward
9920 "\\<while\\>" (point-at-eol) t))
9921 (= (current-indentation) saved-indent)))))))))
9923 (defun js-multiline-decl-indentation ()
9924 "Returns the declaration indentation column if the current line belongs
9925 to a multiline declaration statement. All declarations are lined up vertically:
9931 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9932 assigned expression is a function or array/object literal, it will be indented
9935 var o = { var bar = 2,
9940 (let (forward-sexp-function ; use lisp version
9943 (back-to-indentation)
9944 (when (not (looking-at js-declaration-keyword-re))
9945 (when (looking-at js-indent-operator-re)
9946 (goto-char (match-end 0))) ; continued expressions are ok
9947 (while (and (not at-opening-bracket)
9949 (let ((pos (point)))
9952 (or (eq (char-before) ?,)
9953 (and (not (eq (char-before) ?\;))
9955 (prog2 (skip-chars-backward "[[:punct:]]")
9956 (looking-at js-indent-operator-re)
9958 (not (eq (char-before) ?\;))))
9959 (js2-same-line pos)))))
9962 (scan-error (setq at-opening-bracket t))))
9963 (when (looking-at js-declaration-keyword-re)
9964 (- (1+ (match-end 0)) (point-at-bol)))))))
9966 (defun js-ctrl-statement-indentation ()
9967 "Returns the proper indentation of the current line if it
9968 starts the body of a control statement without braces, else
9970 (let (forward-sexp-function) ; temporarily unbind it
9972 (back-to-indentation)
9973 (when (and (not (js2-same-line (point-min)))
9974 (not (looking-at "{"))
9975 (js-re-search-backward "[[:graph:]]" nil t)
9976 (not (looking-at "[{([]"))
9979 (when (= (char-before) ?\))
9980 ;; scan-sexps sometimes throws an error
9981 (ignore-errors (backward-sexp))
9982 (skip-chars-backward " \t" (point-at-bol)))
9984 (back-to-indentation)
9985 (and (looking-at js-possibly-braceless-keywords-re)
9986 (= (match-end 0) pt)
9987 (not (js-end-of-do-while-loop-p))))))
9988 (+ (current-indentation) js2-basic-offset)))))
9990 (defun js2-indent-in-array-comp (parse-status)
9991 "Return non-nil if we think we're in an array comprehension.
9992 In particular, return the buffer position of the first `for' kwd."
9993 (let ((bracket (nth 1 parse-status))
9998 (when (looking-at "\\[")
10001 (if (looking-at "[[{]")
10002 (let (forward-sexp-function) ; use lisp version
10003 (forward-sexp) ; skip destructuring form
10005 (if (and (/= (char-after) ?,) ; regular array
10006 (looking-at "for"))
10007 (match-beginning 0)))
10008 ;; to skip arbitrary expressions we need the parser,
10009 ;; so we'll just guess at it.
10010 (if (and (> end (point)) ; not empty literal
10011 (re-search-forward "[^,]]* \\(for\\) " end t)
10012 ;; not inside comment or string literal
10013 (let ((state (parse-partial-sexp bracket (point))))
10014 (not (or (nth 3 state) (nth 4 state)))))
10015 (match-beginning 1))))))))
10017 (defun js2-array-comp-indentation (parse-status for-kwd)
10018 (if (js2-same-line for-kwd)
10019 ;; first continuation line
10021 (goto-char (nth 1 parse-status))
10023 (skip-chars-forward " \t")
10026 (goto-char for-kwd)
10027 (current-column))))
10029 (defun js-proper-indentation (parse-status)
10030 "Return the proper indentation for the current line."
10032 (back-to-indentation)
10033 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10034 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10035 (continued-expr-p (js-continued-expression-p))
10036 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10037 (js-multiline-decl-indentation)))
10038 (bracket (nth 1 parse-status))
10041 ;; indent array comprehension continuation lines specially
10043 (>= js2-language-version 170)
10044 (not (js2-same-line bracket))
10045 (setq beg (js2-indent-in-array-comp parse-status))
10046 (>= (point) (save-excursion
10048 (point-at-bol)))) ; at or after first loop?
10049 (js2-array-comp-indentation parse-status beg))
10053 ((and declaration-indent continued-expr-p)
10054 (+ declaration-indent js2-basic-offset))
10056 (declaration-indent)
10059 (goto-char bracket)
10061 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10062 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10063 (when (save-excursion (skip-chars-backward " \t)")
10067 (not js2-consistent-level-indent-inner-bracket-p))
10068 (progn (goto-char (1+ (nth 1 p)))
10069 (skip-chars-forward " \t"))
10070 (back-to-indentation)
10071 (when (and js2-pretty-multiline-decl-indentation-p
10072 js2-always-indent-assigned-expr-in-decls-p
10073 (looking-at js-declaration-keyword-re))
10074 (goto-char (1+ (match-end 0)))))
10075 (cond (same-indent-p
10078 (+ (current-column) (* 2 js2-basic-offset)))
10080 (+ (current-column) js2-basic-offset)))))
10082 (unless same-indent-p
10084 (skip-chars-forward " \t"))
10085 (current-column))))
10087 (continued-expr-p js2-basic-offset)
10091 (defun js2-lineup-comment (parse-status)
10092 "Indent a multi-line block comment continuation line."
10093 (let* ((beg (nth 8 parse-status))
10094 (first-line (js2-same-line beg))
10095 (offset (save-excursion
10097 (if (looking-at "/\\*")
10098 (+ 1 (current-column))
10101 (indent-line-to offset))))
10103 (defun js2-backward-sws ()
10104 "Move backward through whitespace and comments."
10106 (while (forward-comment -1)))
10108 (defun js2-forward-sws ()
10109 "Move forward through whitespace and comments."
10111 (while (forward-comment 1)))
10113 (defsubst js2-current-indent (&optional pos)
10114 "Return column of indentation on current line.
10115 If POS is non-nil, go to that point and return indentation for that line."
10119 (back-to-indentation)
10122 (defsubst js2-arglist-close ()
10123 "Return non-nil if we're on a line beginning with a close-paren/brace."
10126 (goto-char (point-at-bol))
10128 (looking-at "[])}]"))))
10130 (defsubst js2-indent-looks-like-label-p ()
10131 (goto-char (point-at-bol))
10133 (looking-at (concat js2-mode-identifier-re ":")))
10135 (defun js2-indent-in-objlit-p (parse-status)
10136 "Return non-nil if this looks like an object-literal entry."
10137 (let ((start (nth 1 parse-status)))
10141 (and (zerop (forward-line -1))
10142 (not (< (point) start)) ; crossed a {} boundary
10143 (js2-indent-looks-like-label-p)))
10145 (js2-indent-looks-like-label-p)))))
10147 ;; if prev line looks like foobar({ then we're passing an object
10148 ;; literal to a function call, and people pretty much always want to
10149 ;; de-dent back to the previous line, so move the 'basic-offset'
10150 ;; position to the front.
10151 (defsubst js2-indent-objlit-arg-p (parse-status)
10153 (back-to-indentation)
10155 (and (eq (1- (point)) (nth 1 parse-status))
10156 (eq (char-before) ?{)
10159 (skip-chars-backward " \t")
10160 (eq (char-before) ?\()))))
10162 (defsubst js2-indent-case-block-p ()
10164 (back-to-indentation)
10166 (goto-char (point-at-bol))
10167 (skip-chars-forward " \t")
10169 (looking-at "case\\s-.+:"))))
10171 (defsubst js2-syntax-bol ()
10172 "Return the point at the first non-whitespace char on the line.
10173 Returns `point-at-bol' if the line is empty."
10175 (beginning-of-line)
10176 (skip-chars-forward " \t")
10179 (defun js2-bounce-indent (normal-col parse-status backwards)
10180 "Cycle among alternate computed indentation positions.
10181 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10182 of the buffer to the current point. NORMAL-COL is the indentation
10183 column computed by the heuristic guesser based on current paren,
10184 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10186 (let ((cur-indent (js2-current-indent))
10187 (old-buffer-undo-list buffer-undo-list)
10188 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10189 (current-line (save-excursion
10190 (forward-line 0) ; move to bol
10191 (1+ (count-lines (point-min) (point)))))
10201 ;; temporarily don't record undo info, if user requested this
10202 (if js2-mode-indent-inhibit-undo
10203 (setq buffer-undo-list t))
10206 ;; first likely point: indent from beginning of previous code line
10207 (push (setq basic-offset
10209 (back-to-indentation)
10211 (back-to-indentation)
10212 (setq prev-line-col (current-column)))
10216 ;; (first + epsilon) likely point: indent 2x from beginning of
10217 ;; previous code line. Some companies like this approach. Ahem.
10218 ;; Seriously, though -- 4-space indent for expression continuation
10219 ;; lines isn't a bad idea. We should eventually implement it
10221 (push (setq basic-offset
10223 (back-to-indentation)
10225 (back-to-indentation)
10226 (setq prev-line-col (current-column)))
10227 (* 2 js2-basic-offset)))
10230 ;; second likely point: indent from assign-expr RHS. This
10231 ;; is just a crude guess based on finding " = " on the previous
10232 ;; line containing actual code.
10233 (setq pos (save-excursion
10236 (goto-char (point-at-bol))
10237 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10239 (goto-char (match-end 1))
10240 (skip-chars-forward " \t\r\n")
10241 (current-column)))))
10243 (incf pos js2-basic-offset)
10244 (push pos positions))
10246 ;; third likely point: same indent as previous line of code.
10247 ;; Make it the first likely point if we're not on an
10248 ;; arglist-close line and previous line ends in a comma, or
10249 ;; both this line and prev line look like object-literal
10251 (setq pos (save-excursion
10252 (goto-char (point-at-bol))
10254 (back-to-indentation)
10257 ;; while we're here, look for trailing comma
10258 (if (save-excursion
10259 (goto-char (point-at-eol))
10261 (eq (char-before) ?,))
10262 (setq arglist-cont (1- (point)))))))
10264 (if (and (or arglist-cont
10265 (js2-indent-in-objlit-p parse-status))
10266 (not (js2-arglist-close)))
10267 (setq same-indent pos))
10268 (push pos positions))
10270 ;; fourth likely point: first preceding code with less indentation
10271 ;; than the immediately preceding code line.
10272 (setq pos (save-excursion
10273 (back-to-indentation)
10275 (back-to-indentation)
10276 (setq anchor (current-column))
10277 (while (and (zerop (forward-line -1))
10279 (back-to-indentation)
10282 (setq pos (current-column))))
10283 (push pos positions)
10285 ;; nesting-heuristic position, main by default
10286 (push (setq main-pos normal-col) positions)
10288 ;; delete duplicates and sort positions list
10289 (setq positions (sort (delete-dups positions) '<))
10291 ;; comma-list continuation lines: prev line indent takes precedence
10293 (setq main-pos same-indent))
10295 ;; common special cases where we want to indent in from previous line
10296 (if (or (js2-indent-case-block-p)
10297 (js2-indent-objlit-arg-p parse-status))
10298 (setq main-pos basic-offset))
10300 ;; if bouncing backwards, reverse positions list
10302 (setq positions (reverse positions)))
10304 ;; record whether we're already sitting on one of the alternatives
10305 (setq pos (member cur-indent positions))
10308 ;; case 0: we're one one of the alternatives and this is the
10309 ;; first time they've pressed TAB on this line (best-guess).
10310 ((and js2-mode-indent-ignore-first-tab
10312 ;; first time pressing TAB on this line?
10313 (not (eq js2-mode-last-indented-line current-line)))
10315 (setq computed-pos nil))
10316 ;; case 1: only one computed position => use it
10317 ((null (cdr positions))
10318 (setq computed-pos 0))
10319 ;; case 2: not on any of the computed spots => use main spot
10321 (setq computed-pos (js2-position main-pos positions)))
10322 ;; case 3: on last position: cycle to first position
10324 (setq computed-pos 0))
10325 ;; case 4: on intermediate position: cycle to next position
10327 (setq computed-pos (js2-position (second pos) positions))))
10329 ;; see if any hooks want to indent; otherwise we do it
10330 (loop with result = nil
10331 for hook in js2-indent-hook
10332 while (null result)
10334 (setq result (funcall hook positions computed-pos))
10336 (unless (or result (null computed-pos))
10337 (indent-line-to (nth computed-pos positions)))))
10340 (if js2-mode-indent-inhibit-undo
10341 (setq buffer-undo-list old-buffer-undo-list))
10342 ;; see commentary for `js2-mode-last-indented-line'
10343 (setq js2-mode-last-indented-line current-line))))
10345 (defun js2-indent-bounce-backwards ()
10346 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10347 cycles between the computed indentation positions in reverse order."
10349 (js2-indent-line t))
10351 (defsubst js2-1-line-comment-continuation-p ()
10352 "Return t if we're in a 1-line comment continuation.
10353 If so, we don't ever want to use bounce-indent."
10358 (looking-at "\\s-*//"))
10362 (when (looking-at "\\s-*$")
10365 (looking-at "\\s-*//"))))))
10367 (defun js2-indent-line (&optional bounce-backwards)
10368 "Indent the current line as JavaScript source text."
10374 ;; don't whine about errors/warnings when we're indenting.
10375 ;; This has to be set before calling parse-partial-sexp below.
10376 (inhibit-point-motion-hooks t))
10377 (setq parse-status (save-excursion
10378 (syntax-ppss (point-at-bol)))
10379 offset (- (point) (save-excursion
10380 (back-to-indentation)
10382 (js2-with-underscore-as-word-syntax
10383 (if (nth 4 parse-status)
10384 (js2-lineup-comment parse-status)
10385 (setq indent-col (js-proper-indentation parse-status))
10386 ;; see comments below about js2-mode-last-indented-line
10388 ;; bounce-indenting is disabled during electric-key indent.
10389 ;; It doesn't work well on first line of buffer.
10390 ((and js2-bounce-indent-p
10391 (not (js2-same-line (point-min)))
10392 (not (js2-1-line-comment-continuation-p)))
10393 (js2-bounce-indent indent-col parse-status bounce-backwards))
10394 ;; just indent to the guesser's likely spot
10395 (t (indent-line-to indent-col)))
10396 (when (plusp offset)
10397 (forward-char offset))))))
10399 (defun js2-indent-region (start end)
10400 "Indent the region, but don't use bounce indenting."
10401 (let ((js2-bounce-indent-p nil)
10402 (indent-region-function nil)
10403 (after-change-functions (remq 'js2-mode-edit
10404 after-change-functions)))
10405 (indent-region start end nil) ; nil for byte-compiler
10406 (js2-mode-edit start end (- end start))))
10408 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10412 "Major mode for editing JavaScript code."
10414 (kill-all-local-variables)
10415 (set-syntax-table js2-mode-syntax-table)
10416 (use-local-map js2-mode-map)
10417 (make-local-variable 'comment-start)
10418 (make-local-variable 'comment-end)
10419 (make-local-variable 'comment-start-skip)
10420 (setq major-mode 'js2-mode
10421 mode-name "JavaScript-IDE"
10422 comment-start "//" ; used by comment-region; don't change it
10424 (setq local-abbrev-table js2-mode-abbrev-table)
10425 (set (make-local-variable 'max-lisp-eval-depth)
10426 (max max-lisp-eval-depth 3000))
10427 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10428 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10430 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10431 ;; on most platforms other than the one I originally wrote it on.
10432 ;; So it's back to `c-fill-paragraph'.
10433 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10435 (add-hook 'before-save-hook #'js2-before-save nil t)
10436 (set (make-local-variable 'next-error-function) #'js2-next-error)
10437 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10438 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10439 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10440 ;; for characters inside regexp literals.
10441 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10442 ;; this is necessary to make `show-paren-function' work properly
10443 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10444 ;; needed for M-x rgrep, among other things
10445 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10447 ;; some variables needed by cc-engine for paragraph-fill, etc.
10448 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10449 c-comment-start-regexp "/[*/]\\|\\s|"
10450 c-line-comment-starter "//"
10451 c-paragraph-start js2-paragraph-start
10452 c-paragraph-separate "$"
10453 comment-start-skip js2-comment-start-skip
10454 c-syntactic-ws-start js2-syntactic-ws-start
10455 c-syntactic-ws-end js2-syntactic-ws-end
10456 c-syntactic-eol js2-syntactic-eol)
10458 (let ((c-buffer-is-cc-mode t))
10459 ;; Copied from `js-mode'. Also see Bug#6071.
10460 (make-local-variable 'paragraph-start)
10461 (make-local-variable 'paragraph-separate)
10462 (make-local-variable 'paragraph-ignore-fill-prefix)
10463 (make-local-variable 'adaptive-fill-mode)
10464 (make-local-variable 'adaptive-fill-regexp)
10465 (c-setup-paragraph-variables))
10467 (setq js2-default-externs
10468 (append js2-ecma-262-externs
10469 (if js2-include-browser-externs
10470 js2-browser-externs)
10471 (if js2-include-gears-externs
10473 (if js2-include-rhino-externs
10474 js2-rhino-externs)))
10476 ;; We do our own syntax highlighting based on the parse tree.
10477 ;; However, we want minor modes that add keywords to highlight properly
10478 ;; (examples: doxymacs, column-marker).
10479 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10480 (setq font-lock-defaults '(nil t))
10482 ;; Experiment: make reparse-delay longer for longer files.
10483 (if (plusp js2-dynamic-idle-timer-adjust)
10484 (setq js2-idle-timer-delay
10485 (* js2-idle-timer-delay
10486 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10488 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10489 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10490 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10491 (imenu-add-to-menubar (concat "IM-" mode-name))
10492 (when js2-mirror-mode
10493 (js2-enter-mirror-mode))
10494 (add-to-invisibility-spec '(js2-outline . t))
10495 (set (make-local-variable 'line-move-ignore-invisible) t)
10496 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10498 (if (fboundp 'run-mode-hooks)
10499 (run-mode-hooks 'js2-mode-hook)
10500 (run-hooks 'js2-mode-hook))
10502 (setq js2-mode-functions-hidden nil
10503 js2-mode-comments-hidden nil
10504 js2-mode-buffer-dirty-p t
10505 js2-mode-parsing nil)
10508 (defun js2-mode-exit ()
10509 "Exit `js2-mode' and clean up."
10511 (when js2-mode-node-overlay
10512 (delete-overlay js2-mode-node-overlay)
10513 (setq js2-mode-node-overlay nil))
10514 (js2-remove-overlays)
10515 (setq js2-mode-ast nil)
10516 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10517 (remove-from-invisibility-spec '(js2-outline . t))
10518 (js2-mode-show-all)
10519 (js2-with-unmodifying-text-property-changes
10520 (js2-clear-face (point-min) (point-max))))
10522 (defun js2-before-save ()
10523 "Clean up whitespace before saving file.
10524 You can disable this by customizing `js2-cleanup-whitespace'."
10525 (when js2-cleanup-whitespace
10526 (let ((col (current-column)))
10527 (delete-trailing-whitespace)
10528 ;; don't change trailing whitespace on current line
10529 (unless (eq (current-column) col)
10530 (indent-to col)))))
10532 (defsubst js2-mode-reset-timer ()
10533 "Cancel any existing parse timer and schedule a new one."
10534 (if js2-mode-parse-timer
10535 (cancel-timer js2-mode-parse-timer))
10536 (setq js2-mode-parsing nil)
10537 (setq js2-mode-parse-timer
10538 (run-with-idle-timer js2-idle-timer-delay nil
10539 #'js2-mode-idle-reparse (current-buffer))))
10541 (defun js2-mode-idle-reparse (buffer)
10542 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10543 it to be reparsed when the buffer is selected."
10544 (if (eq buffer (current-buffer))
10546 ;; reparse when the buffer is selected again
10547 (with-current-buffer buffer
10548 (add-hook 'window-configuration-change-hook
10549 #'js2-mode-idle-reparse-inner
10552 (defun js2-mode-idle-reparse-inner ()
10553 (remove-hook 'window-configuration-change-hook
10554 #'js2-mode-idle-reparse-inner
10558 (defun js2-mode-edit (beg end len)
10559 "Schedule a new parse after buffer is edited.
10560 Buffer edit spans from BEG to END and is of length LEN.
10561 Also clears the `js2-magic' bit on autoinserted parens/brackets
10562 if the edit occurred on a line different from the magic paren."
10563 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10564 (line (if magic-pos (line-number-at-pos magic-pos))))
10566 (or (/= (line-number-at-pos beg) line)
10568 (/= (line-number-at-pos end) line)))
10569 (js2-mode-mundanify-parens)))
10570 (setq js2-mode-buffer-dirty-p t)
10571 (js2-mode-hide-overlay)
10572 (js2-mode-reset-timer))
10574 (defun js2-reparse (&optional force)
10575 "Re-parse current buffer after user finishes some data entry.
10576 If we get any user input while parsing, including cursor motion,
10577 we discard the parse and reschedule it. If FORCE is nil, then the
10578 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10581 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10582 (unless js2-mode-parsing
10583 (setq js2-mode-parsing t)
10585 (when (or js2-mode-buffer-dirty-p force)
10586 (js2-remove-overlays)
10587 (js2-with-unmodifying-text-property-changes
10588 (setq js2-mode-buffer-dirty-p nil
10589 js2-mode-fontifications nil
10590 js2-mode-deferred-properties nil)
10591 (if js2-mode-verbose-parse-p
10592 (message "parsing..."))
10595 (setq interrupted-p
10596 (catch 'interrupted
10597 (setq js2-mode-ast (js2-parse))
10598 ;; if parsing is interrupted, comments and regex
10599 ;; literals stay ignored by `parse-partial-sexp'
10600 (remove-text-properties (point-min) (point-max)
10602 (js2-mode-apply-deferred-properties)
10603 (js2-mode-remove-suppressed-warnings)
10604 (js2-mode-show-warnings)
10605 (js2-mode-show-errors)
10606 (js2-mode-highlight-magic-parens)
10607 (if (>= js2-highlight-level 1)
10608 (js2-highlight-jsdoc js2-mode-ast))
10612 ;; unfinished parse => try again
10613 (setq js2-mode-buffer-dirty-p t)
10614 (js2-mode-reset-timer))
10615 (if js2-mode-verbose-parse-p
10616 (message "Parse time: %s" time)))))
10617 (setq js2-mode-parsing nil)
10618 (unless interrupted-p
10619 (setq js2-mode-parse-timer nil))))))
10621 (defun js2-mode-show-node ()
10622 "Debugging aid: highlight selected AST node on mouse click."
10624 (let ((node (js2-node-at-point))
10627 (when js2-mode-show-overlay
10629 (message "No node found at location %s" (point))
10630 (setq beg (js2-node-abs-pos node)
10631 end (+ beg (js2-node-len node)))
10632 (if js2-mode-node-overlay
10633 (move-overlay js2-mode-node-overlay beg end)
10634 (setq js2-mode-node-overlay (make-overlay beg end))
10635 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10636 (js2-with-unmodifying-text-property-changes
10637 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10638 (message "%s, parent: %s"
10639 (js2-node-short-name node)
10640 (if (js2-node-parent node)
10641 (js2-node-short-name (js2-node-parent node))
10644 (defun js2-mode-hide-overlay (&optional p1 p2)
10645 "Remove the debugging overlay when the point moves.
10646 P1 and P2 are the old and new values of point, respectively."
10647 (when js2-mode-node-overlay
10648 (let ((beg (overlay-start js2-mode-node-overlay))
10649 (end (overlay-end js2-mode-node-overlay)))
10650 ;; Sometimes we're called spuriously.
10654 (js2-with-unmodifying-text-property-changes
10655 (remove-text-properties beg end '(point-left nil)))
10656 (delete-overlay js2-mode-node-overlay)
10657 (setq js2-mode-node-overlay nil)))))
10659 (defun js2-mode-reset ()
10660 "Debugging helper: reset everything."
10665 (defsubst js2-mode-show-warn-or-err (e face)
10666 "Highlight a warning or error E with FACE.
10667 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10668 (let* ((key (first e))
10670 (end (+ beg (third e)))
10671 ;; Don't inadvertently go out of bounds.
10672 (beg (max (point-min) (min beg (point-max))))
10673 (end (max (point-min) (min end (point-max))))
10674 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10675 (ovl (make-overlay beg end)))
10676 (overlay-put ovl 'font-lock-face face)
10677 (overlay-put ovl 'js2-error t)
10678 (put-text-property beg end 'help-echo (js2-get-msg key))
10679 (put-text-property beg end 'point-entered #'js2-echo-error)))
10681 (defun js2-remove-overlays ()
10682 "Remove overlays from buffer that have a `js2-error' property."
10683 (let ((beg (point-min))
10686 (dolist (o (overlays-in beg end))
10687 (when (overlay-get o 'js2-error)
10688 (delete-overlay o))))))
10690 (defun js2-error-at-point (&optional pos)
10691 "Return non-nil if there's an error overlay at POS.
10692 Defaults to point."
10693 (loop with pos = (or pos (point))
10694 for o in (overlays-at pos)
10695 thereis (overlay-get o 'js2-error)))
10697 (defun js2-mode-apply-deferred-properties ()
10698 "Apply fontifications and other text properties recorded during parsing."
10699 (when (plusp js2-highlight-level)
10700 ;; We defer clearing faces as long as possible to eliminate flashing.
10701 (js2-clear-face (point-min) (point-max))
10702 ;; Have to reverse the recorded fontifications list so that errors
10703 ;; and warnings overwrite the normal fontifications.
10704 (dolist (f (nreverse js2-mode-fontifications))
10705 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10706 (setq js2-mode-fontifications nil))
10707 (dolist (p js2-mode-deferred-properties)
10708 (apply #'put-text-property p))
10709 (setq js2-mode-deferred-properties nil))
10711 (defun js2-mode-show-errors ()
10712 "Highlight syntax errors."
10713 (when js2-mode-show-parse-errors
10714 (dolist (e (js2-ast-root-errors js2-mode-ast))
10715 (js2-mode-show-warn-or-err e 'js2-error-face))))
10717 (defun js2-mode-remove-suppressed-warnings ()
10718 "Take suppressed warnings out of the AST warnings list.
10719 This ensures that the counts and `next-error' are correct."
10720 (setf (js2-ast-root-warnings js2-mode-ast)
10723 (let ((key (caar e)))
10725 (and (not js2-strict-trailing-comma-warning)
10726 (string-match "trailing\\.comma" key))
10727 (and (not js2-strict-cond-assign-warning)
10728 (string= key "msg.equal.as.assign"))
10729 (and js2-missing-semi-one-line-override
10730 (string= key "msg.missing.semi")
10731 (let* ((beg (second e))
10732 (node (js2-node-at-point beg))
10733 (fn (js2-mode-find-parent-fn node))
10734 (body (and fn (js2-function-node-body fn)))
10735 (lc (and body (js2-node-abs-pos body)))
10736 (rc (and lc (+ lc (js2-node-len body)))))
10741 (and (js2-same-line lc)
10742 (js2-same-line rc))))))))))
10743 (js2-ast-root-warnings js2-mode-ast))))
10745 (defun js2-mode-show-warnings ()
10746 "Highlight strict-mode warnings."
10747 (when js2-mode-show-strict-warnings
10748 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10749 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10751 (defun js2-echo-error (old-point new-point)
10752 "Called by point-motion hooks."
10753 (let ((msg (get-text-property new-point 'help-echo)))
10754 (if (and msg (or (not (current-message))
10755 (string= (current-message) "Quit")))
10758 (defalias #'js2-echo-help #'js2-echo-error)
10760 (defun js2-enter-key ()
10761 "Handle user pressing the Enter key."
10763 (let ((parse-status (save-excursion
10764 (syntax-ppss (point))))
10765 (js2-bounce-indent-p nil))
10767 ;; check if we're inside a string
10768 ((nth 3 parse-status)
10769 (if js2-concat-multiline-strings
10770 (js2-mode-split-string parse-status)
10772 ;; check if inside a block comment
10773 ((nth 4 parse-status)
10774 (js2-mode-extend-comment))
10776 ;; should probably figure out what the mode-map says we should do
10777 (if js2-indent-on-enter-key
10780 (if js2-enter-indents-newline
10781 (js2-indent-line))))))
10783 (defun js2-mode-split-string (parse-status)
10784 "Turn a newline in mid-string into a string concatenation.
10785 PARSE-STATUS is as documented in `parse-partial-sexp'."
10786 (let* ((col (current-column))
10787 (quote-char (nth 3 parse-status))
10788 (quote-string (string quote-char))
10789 (string-beg (nth 8 parse-status))
10790 (indent (save-match-data
10793 (back-to-indentation)
10794 (if (looking-at "\\+")
10797 (goto-char string-beg)
10798 (if (looking-back "\\+\\s-+")
10799 (goto-char (match-beginning 0)))
10800 (current-column))))))
10801 (insert quote-char "\n")
10803 (insert "+ " quote-string)
10805 (insert quote-string)
10806 (backward-char 1))))
10808 (defun js2-mode-extend-comment ()
10809 "Indent the line and, when inside a comment block, add comment prefix."
10810 (let (star single col first-line needs-close)
10812 (back-to-indentation)
10814 ((looking-at "\\*[^/]")
10816 col (current-column)))
10817 ((looking-at "/\\*")
10820 col (1+ (current-column))))
10823 col (current-column)))))
10824 ;; Heuristic for whether we need to close the comment:
10825 ;; if we've got a parse error here, assume it's an unterminated
10829 (eq (get-text-property (1- (point)) 'point-entered)
10831 ;; The heuristic above doesn't work well when we're
10832 ;; creating a comment and there's another one downstream,
10833 ;; as our parser thinks this one ends at the end of the
10834 ;; next one. (You can have a /* inside a js block comment.)
10835 ;; So just close it if the next non-ws char isn't a *.
10839 (skip-chars-forward " \t\r\n")
10840 (not (eq (char-after) ?*))))))
10846 (if (and first-line needs-close)
10853 (and (zerop (forward-line 1))
10854 (looking-at "\\s-*//"))))
10857 ;; don't need to extend the comment after all
10858 (js2-enter-indents-newline
10859 (js2-indent-line)))))
10861 (defun js2-beginning-of-line ()
10862 "Toggles point between bol and first non-whitespace char in line.
10863 Also moves past comment delimiters when inside comments."
10868 (back-to-indentation))
10870 (skip-chars-forward "/ \t"))
10871 ((and (eq (char-after) ?*)
10872 (setq node (js2-comment-at-point))
10873 (memq (js2-comment-node-format node) '(jsdoc block))
10875 (skip-chars-backward " \t")
10877 (skip-chars-forward "\* \t"))
10879 (goto-char (point-at-bol))))))
10881 (defun js2-end-of-line ()
10882 "Toggles point between eol and last non-whitespace char in line."
10885 (skip-chars-backward " \t")
10886 (goto-char (point-at-eol))))
10888 (defun js2-enter-mirror-mode()
10889 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10892 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10893 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10894 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10895 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10896 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10897 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10898 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10899 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10901 (defun js2-leave-mirror-mode()
10902 "Turns off mirror mode."
10904 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10905 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10907 (defsubst js2-mode-inside-string ()
10908 "Return non-nil if inside a string.
10909 Actually returns the quote character that begins the string."
10910 (let ((parse-state (save-excursion
10911 (syntax-ppss (point)))))
10912 (nth 3 parse-state)))
10914 (defsubst js2-mode-inside-comment-or-string ()
10915 "Return non-nil if inside a comment or string."
10917 (let ((comment-start
10919 (goto-char (point-at-bol))
10920 (if (re-search-forward "//" (point-at-eol) t)
10921 (match-beginning 0)))))
10923 (<= comment-start (point))))
10924 (let ((parse-state (save-excursion
10925 (syntax-ppss (point)))))
10926 (or (nth 3 parse-state)
10927 (nth 4 parse-state)))))
10929 (defsubst js2-make-magic-delimiter (delim &optional pos)
10930 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10931 Sets value of `js2-magic' text property to line number at POS."
10933 'js2-magic (line-number-at-pos pos)
10934 'font-lock-face 'js2-magic-paren-face))
10936 (defun js2-mode-match-delimiter (open close)
10937 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10938 The rule we use, which as far as we can tell is how Eclipse works,
10939 is that we insert the match if we're not in a comment or string,
10940 and the next non-whitespace character is either punctuation or
10941 occurs on another line."
10943 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10944 (not (js2-mode-inside-comment-or-string)))
10946 (insert (js2-make-magic-delimiter close)))
10947 (when js2-auto-indent-p
10948 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10949 (js2-indent-line)))))
10951 (defun js2-mode-match-bracket ()
10952 "Insert matching bracket."
10954 (js2-mode-match-delimiter "[" "]"))
10956 (defun js2-mode-match-paren ()
10957 "Insert matching paren unless already inserted."
10959 (js2-mode-match-delimiter "(" ")"))
10961 (defun js2-mode-match-curly (arg)
10962 "Insert matching curly-brace.
10963 With prefix arg, no formatting or indentation will occur -- the close-brace
10964 is simply inserted directly at the point."
10968 (current-prefix-arg
10969 (js2-mode-match-delimiter "{" "}"))
10970 ((and js2-auto-insert-catch-block
10971 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10973 (match-beginning 1))))
10974 (js2-insert-catch-skel try-pos))
10976 ;; Otherwise try to do something smarter.
10978 (unless (or (not (looking-at "\\s-*$"))
10980 (skip-chars-forward " \t\r\n")
10981 (and (looking-at "}")
10982 (js2-error-at-point)))
10983 (js2-mode-inside-comment-or-string))
10985 ;; absolutely mystifying bug: when inserting the next "\n",
10986 ;; the buffer-undo-list is given two new entries: the inserted range,
10987 ;; and the incorrect position of the point. It's recorded incorrectly
10988 ;; as being before the opening "{", not after it. But it's recorded
10989 ;; as the correct value if you're debugging `js2-mode-match-curly'
10990 ;; in edebug. I have no idea why it's doing this, but incrementing
10991 ;; the inserted position fixes the problem, so that the undo takes us
10992 ;; back to just after the user-inserted "{".
10995 (incf (cadr buffer-undo-list)))
10999 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11000 (js2-indent-line))))))))
11002 (defun js2-insert-catch-skel (try-pos)
11003 "Complete a try/catch block after inserting a { following a try keyword.
11004 Rationale is that a try always needs a catch or a finally, and the catch is
11005 the more likely of the two.
11007 TRY-POS is the buffer position of the try keyword. The open-curly should
11008 already have been inserted."
11010 (let ((try-col (save-excursion
11011 (goto-char try-pos)
11012 (current-column))))
11015 (js2-indent-line) ;; indent the blank line where cursor will end up
11018 (indent-to try-col)
11019 (insert "} catch (x) {\n\n")
11020 (indent-to try-col)
11023 (defun js2-mode-highlight-magic-parens ()
11024 "Re-highlight magic parens after parsing nukes the 'face prop."
11025 (let ((beg (point-min))
11027 (while (setq beg (next-single-property-change beg 'js2-magic))
11028 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11029 (if (get-text-property beg 'js2-magic)
11030 (js2-with-unmodifying-text-property-changes
11031 (put-text-property beg (or end (1+ beg))
11032 'font-lock-face 'js2-magic-paren-face))))))
11034 (defun js2-mode-mundanify-parens ()
11035 "Clear all magic parens and brackets."
11036 (let ((beg (point-min))
11038 (while (setq beg (next-single-property-change beg 'js2-magic))
11039 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11040 (remove-text-properties beg (or end (1+ beg))
11041 '(js2-magic face)))))
11043 (defsubst js2-match-quote (quote-string)
11044 (let ((start-quote (js2-mode-inside-string)))
11046 ;; inside a comment - don't do quote-matching, since we can't
11047 ;; reliably figure out if we're in a string inside the comment
11048 ((js2-comment-at-point)
11049 (insert quote-string))
11051 ;; not in string => insert matched quotes
11052 (insert quote-string)
11053 ;; exception: if we're just before a word, don't double it.
11054 (unless (looking-at "[^ \t\r\n]")
11056 (insert quote-string))))
11057 ((looking-at quote-string)
11058 (if (looking-back "[^\\]\\\\")
11059 (insert quote-string)
11061 ((and js2-mode-escape-quotes
11064 (re-search-forward quote-string (point-at-eol) t))))
11065 ;; inside terminated string, escape quote (unless already escaped)
11066 (insert (if (looking-back "[^\\]\\\\")
11068 (concat "\\" quote-string))))
11070 (insert quote-string))))) ; else terminate the string
11072 (defun js2-mode-match-single-quote ()
11073 "Insert matching single-quote."
11075 (let ((parse-status (syntax-ppss (point))))
11076 ;; don't match inside comments, since apostrophe is more common
11077 (if (nth 4 parse-status)
11079 (js2-match-quote "'"))))
11081 (defun js2-mode-match-double-quote ()
11082 "Insert matching double-quote."
11084 (js2-match-quote "\""))
11086 ;; Eclipse works as follows:
11087 ;; * type an open-paren and it auto-inserts close-paren
11088 ;; - auto-inserted paren gets a green bracket
11089 ;; - green bracket means typing close-paren there will skip it
11090 ;; * if you insert any text on a different line, it turns off
11091 (defun js2-mode-magic-close-paren ()
11092 "Skip over close-paren rather than inserting, where appropriate."
11094 (let* ((here (point))
11095 (parse-status (syntax-ppss here))
11096 (open-pos (nth 1 parse-status))
11097 (close last-input-event)
11106 (if (and (eq (char-after) close)
11107 (eq open (char-after open-pos))
11108 (js2-same-line open-pos)
11109 (get-text-property here 'js2-magic))
11111 (remove-text-properties here (1+ here) '(js2-magic face))
11113 (insert-char close 1))
11114 (blink-matching-open)))
11116 (defun js2-mode-wait-for-parse (callback)
11117 "Invoke CALLBACK when parsing is finished.
11118 If parsing is already finished, calls CALLBACK immediately."
11119 (if (not js2-mode-buffer-dirty-p)
11121 (push callback js2-mode-pending-parse-callbacks)
11122 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11124 (defun js2-mode-parse-finished ()
11125 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11126 ;; We can't let errors propagate up, since it prevents the
11127 ;; `js2-parse' method from completing normally and returning
11128 ;; the ast, which makes things mysteriously not work right.
11130 (dolist (cb js2-mode-pending-parse-callbacks)
11131 (condition-case err
11133 (error (message "%s" err))))
11134 (setq js2-mode-pending-parse-callbacks nil)))
11136 (defun js2-mode-flag-region (from to flag)
11137 "Hide or show text from FROM to TO, according to FLAG.
11138 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11139 Returns the created overlay if FLAG is non-nil."
11140 (remove-overlays from to 'invisible 'js2-outline)
11142 (let ((o (make-overlay from to)))
11143 (overlay-put o 'invisible 'js2-outline)
11144 (overlay-put o 'isearch-open-invisible
11145 'js2-isearch-open-invisible)
11148 ;; Function to be set as an outline-isearch-open-invisible' property
11149 ;; to the overlay that makes the outline invisible (see
11150 ;; `js2-mode-flag-region').
11151 (defun js2-isearch-open-invisible (overlay)
11152 ;; We rely on the fact that isearch places point on the matched text.
11153 (js2-mode-show-element))
11155 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11156 "Return cons cell of bounds of folding overlay at POS.
11157 Returns nil if not found."
11158 (let ((overlays (overlays-at (or pos (point))))
11160 (while (and overlays
11162 (if (overlay-get (car overlays) 'invisible)
11163 (setq o (car overlays))
11164 (setq overlays (cdr overlays))))
11166 (cons (overlay-start o) (overlay-end o)))))
11168 (defun js2-mode-function-at-point (&optional pos)
11169 "Return the innermost function node enclosing current point.
11170 Returns nil if point is not in a function."
11171 (let ((node (js2-node-at-point pos)))
11172 (while (and node (not (js2-function-node-p node)))
11173 (setq node (js2-node-parent node)))
11174 (if (js2-function-node-p node)
11177 (defun js2-mode-toggle-element ()
11178 "Hide or show the foldable element at the point."
11180 (let (comment fn pos)
11184 ;; /* ... */ comment?
11185 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11186 (if (js2-mode-invisible-overlay-bounds
11187 (setq pos (+ 3 (js2-node-abs-pos comment))))
11190 (js2-mode-show-element))
11191 (js2-mode-hide-element)))
11194 (back-to-indentation)
11195 (looking-at js2-mode-//-comment-re))
11196 (js2-mode-toggle-//-comment))
11198 ((setq fn (js2-mode-function-at-point))
11199 (setq pos (and (js2-function-node-body fn)
11200 (js2-node-abs-pos (js2-function-node-body fn))))
11201 (goto-char (1+ pos))
11202 (if (js2-mode-invisible-overlay-bounds)
11203 (js2-mode-show-element)
11204 (js2-mode-hide-element)))
11206 (message "Nothing at point to hide or show")))))))
11208 (defun js2-mode-hide-element ()
11209 "Fold/hide contents of a block, showing ellipses.
11210 Show the hidden text with \\[js2-mode-show-element]."
11212 (if js2-mode-buffer-dirty-p
11213 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11214 (let (node body beg end)
11216 ((js2-mode-invisible-overlay-bounds)
11217 (message "already hidden"))
11219 (setq node (js2-node-at-point))
11221 ((js2-block-comment-p node)
11222 (js2-mode-hide-comment node))
11224 (while (and node (not (js2-function-node-p node)))
11225 (setq node (js2-node-parent node)))
11227 (setq body (js2-function-node-body node)))
11229 (setq beg (js2-node-abs-pos body)
11230 end (+ beg (js2-node-len body)))
11231 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11232 (message "No collapsable element found at point"))))))))
11234 (defun js2-mode-show-element ()
11235 "Show the hidden element at current point."
11237 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11239 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11240 (message "Nothing to un-hide"))))
11242 (defun js2-mode-show-all ()
11243 "Show all of the text in the buffer."
11245 (js2-mode-flag-region (point-min) (point-max) nil))
11247 (defun js2-mode-toggle-hide-functions ()
11249 (if js2-mode-functions-hidden
11250 (js2-mode-show-functions)
11251 (js2-mode-hide-functions)))
11253 (defun js2-mode-hide-functions ()
11254 "Hides all non-nested function bodies in the buffer.
11255 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11256 to open an individual entry."
11258 (if js2-mode-buffer-dirty-p
11259 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11260 (if (null js2-mode-ast)
11261 (message "Oops - parsing failed")
11262 (setq js2-mode-functions-hidden t)
11263 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11265 (defun js2-mode-function-hider (n endp)
11267 (let ((tt (js2-node-type n))
11270 ((and (= tt js2-FUNCTION)
11271 (setq body (js2-function-node-body n)))
11272 (setq beg (js2-node-abs-pos body)
11273 end (+ beg (js2-node-len body)))
11274 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11275 nil) ; don't process children of function
11277 t))))) ; keep processing other AST nodes
11279 (defun js2-mode-show-functions ()
11280 "Un-hide any folded function bodies in the buffer."
11282 (setq js2-mode-functions-hidden nil)
11284 (goto-char (point-min))
11285 (while (/= (goto-char (next-overlay-change (point)))
11287 (dolist (o (overlays-at (point)))
11288 (when (and (overlay-get o 'invisible)
11289 (not (overlay-get o 'comment)))
11290 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11292 (defun js2-mode-hide-comment (n)
11293 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11296 (beg (+ (js2-node-abs-pos n) head))
11297 (end (- (+ beg (js2-node-len n)) head 2))
11298 (o (js2-mode-flag-region beg end 'hide)))
11299 (overlay-put o 'comment t)))
11301 (defun js2-mode-toggle-hide-comments ()
11302 "Folds all block comments in the buffer.
11303 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11304 to open an individual entry."
11306 (if js2-mode-comments-hidden
11307 (js2-mode-show-comments)
11308 (js2-mode-hide-comments)))
11310 (defun js2-mode-hide-comments ()
11312 (if js2-mode-buffer-dirty-p
11313 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11314 (if (null js2-mode-ast)
11315 (message "Oops - parsing failed")
11316 (setq js2-mode-comments-hidden t)
11317 (dolist (n (js2-ast-root-comments js2-mode-ast))
11318 (let ((format (js2-comment-node-format n)))
11319 (when (js2-block-comment-p n)
11320 (js2-mode-hide-comment n))))
11321 (js2-mode-hide-//-comments)))
11323 (defsubst js2-mode-extend-//-comment (direction)
11324 "Find start or end of a block of similar //-comment lines.
11325 DIRECTION is -1 to look back, 1 to look forward.
11326 INDENT is the indentation level to match.
11327 Returns the end-of-line position of the furthest adjacent
11328 //-comment line with the same indentation as the current line.
11329 If there is no such matching line, returns current end of line."
11330 (let ((pos (point-at-eol))
11331 (indent (current-indentation)))
11334 (while (and (zerop (forward-line direction))
11335 (looking-at js2-mode-//-comment-re)
11336 (eq indent (length (match-string 1))))
11337 (setq pos (point-at-eol)))
11340 (defun js2-mode-hide-//-comments ()
11341 "Fold adjacent 1-line comments, showing only snippet of first one."
11345 (goto-char (point-min))
11346 (while (re-search-forward js2-mode-//-comment-re nil t)
11348 end (js2-mode-extend-//-comment 1))
11349 (unless (eq beg end)
11350 (overlay-put (js2-mode-flag-region beg end 'hide)
11353 (forward-char 1))))))
11355 (defun js2-mode-toggle-//-comment ()
11356 "Fold or un-fold any multi-line //-comment at point.
11357 Caller should have determined that this line starts with a //-comment."
11358 (let* ((beg (point-at-eol))
11362 (if (js2-mode-invisible-overlay-bounds)
11363 (js2-mode-show-element)
11364 ;; else hide the comment
11365 (setq beg (js2-mode-extend-//-comment -1)
11366 end (js2-mode-extend-//-comment 1))
11367 (unless (eq beg end)
11368 (overlay-put (js2-mode-flag-region beg end 'hide)
11371 (defun js2-mode-show-comments ()
11372 "Un-hide any hidden comments, leaving other hidden elements alone."
11374 (setq js2-mode-comments-hidden nil)
11376 (goto-char (point-min))
11377 (while (/= (goto-char (next-overlay-change (point)))
11379 (dolist (o (overlays-at (point)))
11380 (when (overlay-get o 'comment)
11381 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11383 (defun js2-mode-display-warnings-and-errors ()
11384 "Turn on display of warnings and errors."
11386 (setq js2-mode-show-parse-errors t
11387 js2-mode-show-strict-warnings t)
11388 (js2-reparse 'force))
11390 (defun js2-mode-hide-warnings-and-errors ()
11391 "Turn off display of warnings and errors."
11393 (setq js2-mode-show-parse-errors nil
11394 js2-mode-show-strict-warnings nil)
11395 (js2-reparse 'force))
11397 (defun js2-mode-toggle-warnings-and-errors ()
11398 "Toggle the display of warnings and errors.
11399 Some users don't like having warnings/errors reported while they type."
11401 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11402 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11403 (if (interactive-p)
11404 (message "warnings and errors %s"
11405 (if js2-mode-show-parse-errors
11408 (js2-reparse 'force))
11410 (defun js2-mode-customize ()
11412 (customize-group 'js2-mode))
11414 (defun js2-mode-forward-sexp (&optional arg)
11415 "Move forward across one statement or balanced expression.
11416 With ARG, do it that many times. Negative arg -N means
11417 move backward across N balanced expressions."
11419 (setq arg (or arg 1))
11420 (if js2-mode-buffer-dirty-p
11421 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11422 (let (node end (start (point)))
11425 ;; could probably make this better for some cases:
11426 ;; - if in statement block (e.g. function body), go to parent
11427 ;; - infix exprs like (foo in bar) - maybe go to beginning
11428 ;; of infix expr if in the right-side expression?
11429 ((and arg (minusp arg))
11430 (dotimes (i (- arg))
11432 (forward-char -1) ; enter the node we backed up to
11433 (setq node (js2-node-at-point (point) t))
11434 (goto-char (if node
11435 (js2-node-abs-pos node)
11442 (setq node (js2-node-at-point (point) t)
11443 end (if node (+ (js2-node-abs-pos node)
11444 (js2-node-len node))))
11445 (goto-char (or end (point-max))))))))
11447 (defun js2-next-error (&optional arg reset)
11448 "Move to next parse error.
11449 Typically invoked via \\[next-error].
11450 ARG is the number of errors, forward or backward, to move.
11451 RESET means start over from the beginning."
11453 (if (or (null js2-mode-ast)
11454 (and (null (js2-ast-root-errors js2-mode-ast))
11455 (null (js2-ast-root-warnings js2-mode-ast))))
11456 (message "No errors")
11458 (goto-char (point-min)))
11459 (let* ((errs (copy-sequence
11460 (append (js2-ast-root-errors js2-mode-ast)
11461 (js2-ast-root-warnings js2-mode-ast))))
11465 (backward (minusp count))
11466 (sorter (if backward '> '<))
11467 (stopper (if backward '< '>))
11468 (count (abs count))
11471 ;; sort by start position
11472 (setq errs (sort errs (lambda (e1 e2)
11473 (funcall sorter (second e1) (second e2))))
11475 ;; find nth error with pos > start
11476 (while (and errs continue)
11477 (when (funcall stopper (cadar errs) start)
11478 (setq err (car errs))
11479 (if (zerop (decf count))
11480 (setq continue nil)))
11481 (setq errs (cdr errs)))
11483 (goto-char (second err))
11484 ;; wrap around to first error
11485 (goto-char (second (car all-errs)))
11486 ;; if we were already on it, echo msg again
11487 (if (= (point) start)
11488 (js2-echo-error (point) (point)))))))
11490 (defun js2-down-mouse-3 ()
11491 "Make right-click move the point to the click location.
11492 This makes right-click context menu operations a bit more intuitive.
11493 The point will not move if the region is active, however, to avoid
11494 destroying the region selection."
11496 (when (and js2-move-point-on-right-click
11498 (let ((e last-input-event))
11500 (goto-char (cadadr e))))))
11502 (defun js2-mode-create-imenu-index ()
11503 "Return an alist for `imenu--index-alist'."
11504 ;; This is built up in `js2-parse-record-imenu' during parsing.
11506 ;; if we have an ast but no recorder, they're requesting a rescan
11507 (unless js2-imenu-recorder
11508 (js2-reparse 'force))
11510 (js2-build-imenu-index)
11511 (setq js2-imenu-recorder nil
11512 js2-imenu-function-map nil))))
11514 (defun js2-mode-find-tag ()
11515 "Replacement for `find-tag-default'.
11516 `find-tag-default' returns a ridiculous answer inside comments."
11518 (js2-with-underscore-as-word-syntax
11520 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11521 (looking-back "[A-Za-z0-9_$]"))
11522 (setq beg (progn (forward-word -1) (point))
11523 end (progn (forward-word 1) (point)))
11524 (setq beg (progn (forward-word 1) (point))
11525 end (progn (forward-word -1) (point))))
11526 (replace-regexp-in-string
11528 (buffer-substring-no-properties beg end))))))
11530 (defun js2-mode-forward-sibling ()
11531 "Move to the end of the sibling following point in parent.
11532 Returns non-nil if successful, or nil if there was no following sibling."
11533 (let* ((node (js2-node-at-point))
11534 (parent (js2-mode-find-enclosing-fn node))
11536 (when (setq sib (js2-node-find-child-after (point) parent))
11537 (goto-char (+ (js2-node-abs-pos sib)
11538 (js2-node-len sib))))))
11540 (defun js2-mode-backward-sibling ()
11541 "Move to the beginning of the sibling node preceding point in parent.
11542 Parent is defined as the enclosing script or function."
11543 (let* ((node (js2-node-at-point))
11544 (parent (js2-mode-find-enclosing-fn node))
11546 (when (setq sib (js2-node-find-child-before (point) parent))
11547 (goto-char (js2-node-abs-pos sib)))))
11549 (defun js2-beginning-of-defun (&optional arg)
11550 "Go to line on which current function starts, and return t on success.
11551 If we're not in a function or already at the beginning of one, go
11552 to beginning of previous script-level element.
11553 With ARG N, do that N times. If N is negative, move forward."
11554 (setq arg (or arg 1))
11556 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11558 ((js2-function-node-p parent)
11559 (goto-char (js2-node-abs-pos parent)))
11561 (js2-mode-backward-sibling)))
11563 (js2-beginning-of-defun (1- arg))
11565 (when (js2-end-of-defun)
11567 (js2-beginning-of-defun 1)
11568 (js2-beginning-of-defun (1+ arg))))))
11570 (defun js2-end-of-defun ()
11571 "Go to the char after the last position of the current function
11572 or script-level element."
11573 (let* ((node (js2-node-at-point))
11574 (parent (or (and (js2-function-node-p node) node)
11575 (js2-node-parent-script-or-fn node)))
11577 (unless (js2-function-node-p parent)
11578 ;; use current script-level node, or, if none, the next one
11579 (setq script (or parent node))
11580 (setq parent (js2-node-find-child-before (point) script))
11581 (when (or (null parent)
11582 (>= (point) (+ (js2-node-abs-pos parent)
11583 (js2-node-len parent))))
11584 (setq parent (js2-node-find-child-after (point) script))))
11586 (goto-char (+ (js2-node-abs-pos parent)
11587 (js2-node-len parent))))))
11589 (defun js2-mark-defun (&optional allow-extend)
11590 "Put mark at end of this function, point at beginning.
11591 The function marked is the one that contains point.
11593 Interactively, if this command is repeated,
11594 or (in Transient Mark mode) if the mark is active,
11595 it marks the next defun after the ones already marked."
11598 (when (and allow-extend
11599 (or (and (eq last-command this-command) (mark t))
11600 (and transient-mark-mode mark-active)))
11601 (let ((sib (save-excursion
11603 (if (js2-mode-forward-sibling)
11610 ;; no more siblings - try extending to enclosing node
11611 (goto-char (mark t)))))
11612 (when (not extended)
11613 (let ((node (js2-node-at-point (point) t)) ; skip comments
11614 ast fn stmt parent beg end)
11615 (when (js2-ast-root-p node)
11617 node (or (js2-node-find-child-after (point) node)
11618 (js2-node-find-child-before (point) node))))
11619 ;; only mark whole buffer if we can't find any children
11622 (if (js2-function-node-p node)
11624 (setq fn (js2-mode-find-enclosing-fn node)
11625 stmt (if (or (null fn)
11626 (js2-ast-root-p fn))
11627 (js2-mode-find-first-stmt node))
11628 parent (or stmt fn)))
11629 (setq beg (js2-node-abs-pos parent)
11630 end (+ beg (js2-node-len parent)))
11633 (exchange-point-and-mark)))))
11635 (defun js2-narrow-to-defun ()
11636 "Narrow to the function enclosing point."
11638 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11639 (fn (if (js2-script-node-p node)
11641 (js2-mode-find-enclosing-fn node)))
11642 (beg (js2-node-abs-pos fn)))
11643 (unless (js2-ast-root-p fn)
11644 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11646 (provide 'js2-mode)
11648 ;;; js2-mode.el ends here