1 ;;; js2-mode.el --- an improved JavaScript editing mode
3 ;; Copyright (C) 2009, 2012 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
48 ;; To install it as your major mode for JavaScript editing:
50 ;; (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
52 ;; Alternately, to install it as a minor mode just for JavaScript linting,
53 ;; you must add it to the appropriate major-mode hook. Normally this would be:
55 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
57 ;; To customize how it works:
58 ;; M-x customize-group RET js2-mode RET
62 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
63 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
64 ;; `js2-mode' current as the EcmaScript language standard evolves.
66 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
67 ;; customizable. It is a surprising amount of work to support customizable
68 ;; indentation. The current compromise is that the tab key lets you cycle among
69 ;; various likely indentation points, similar to the behavior of python-mode.
71 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
72 ;; and `mumamo', although it could be made to do so with some effort.
73 ;; This means that `js2-mode' is currently only useful for editing JavaScript
74 ;; files, and not for editing JavaScript within <script> tags or templates.
82 (require 'cc-cmds) ; for `c-fill-paragraph'
85 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
86 (require 'cc-langs) ; it's here in Emacs 21...
87 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
89 (defvar electric-layout-rules)
91 ;;; Externs (variables presumed to be defined by the host system)
93 (defvar js2-ecma-262-externs
95 '(Array Boolean Date Error EvalError Function Infinity
96 Math NaN Number Object RangeError ReferenceError RegExp
97 String SyntaxError TypeError URIError arguments
98 decodeURI decodeURIComponent encodeURI
99 encodeURIComponent escape eval isFinite isNaN
100 parseFloat parseInt undefined unescape))
101 "Ecma-262 externs. Included in `js2-externs' by default.")
103 (defvar js2-browser-externs
106 Attr CDATASection CharacterData Comment DOMException
107 DOMImplementation Document DocumentFragment
108 DocumentType Element Entity EntityReference
109 ExceptionCode NamedNodeMap Node NodeList Notation
110 ProcessingInstruction Text
113 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
114 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
115 HTMLBodyElement HTMLButtonElement HTMLCollection
116 HTMLDListElement HTMLDirectoryElement HTMLDivElement
117 HTMLDocument HTMLElement HTMLFieldSetElement
118 HTMLFontElement HTMLFormElement HTMLFrameElement
119 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
120 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
121 HTMLImageElement HTMLInputElement HTMLIsIndexElement
122 HTMLLIElement HTMLLabelElement HTMLLegendElement
123 HTMLLinkElement HTMLMapElement HTMLMenuElement
124 HTMLMetaElement HTMLModElement HTMLOListElement
125 HTMLObjectElement HTMLOptGroupElement
126 HTMLOptionElement HTMLOptionsCollection
127 HTMLParagraphElement HTMLParamElement HTMLPreElement
128 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
129 HTMLStyleElement HTMLTableCaptionElement
130 HTMLTableCellElement HTMLTableColElement
131 HTMLTableElement HTMLTableRowElement
132 HTMLTableSectionElement HTMLTextAreaElement
133 HTMLTitleElement HTMLUListElement
136 DOMConfiguration DOMError DOMException
137 DOMImplementationList DOMImplementationSource
138 DOMLocator DOMStringList NameList TypeInfo
142 window alert confirm document java navigator prompt screen
146 CSSCharsetRule CSSFontFace CSSFontFaceRule
147 CSSImportRule CSSMediaRule CSSPageRule
148 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
149 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
150 CSSValue CSSValueList Counter DOMImplementationCSS
151 DocumentCSS DocumentStyle ElementCSSInlineStyle
152 LinkStyle MediaList RGBColor Rect StyleSheet
153 StyleSheetList ViewCSS
156 EventListener EventTarget Event DocumentEvent UIEvent
157 MouseEvent MutationEvent KeyboardEvent
160 DocumentRange Range RangeException
163 XPathResult XMLHttpRequest))
165 You can cause these to be included or excluded with the custom
166 variable `js2-include-browser-externs'.")
168 (defvar js2-rhino-externs
170 '(Packages importClass importPackage com org java
171 ;; Global object (shell) externs.
172 defineClass deserialize doctest gc help load
173 loadClass print quit readFile readUrl runCommand seal
174 serialize spawn sync toint32 version))
175 "Mozilla Rhino externs.
176 Set `js2-include-rhino-externs' to t to include them.")
178 (defvar js2-gears-externs
181 ;; TODO(stevey): add these
183 "Google Gears externs.
184 Set `js2-include-gears-externs' to t to include them.")
188 (defun js2-mark-safe-local (name pred)
189 "Make the variable NAME buffer-local and mark it as safe file-local
190 variable with predicate PRED."
191 (make-variable-buffer-local name)
192 (put name 'safe-local-variable pred))
194 (defcustom js2-highlight-level 2
195 "Amount of syntax highlighting to perform.
196 0 or a negative value means do no highlighting.
197 1 adds basic syntax highlighting.
198 2 adds highlighting of some Ecma built-in properties.
199 3 adds highlighting of many Ecma built-in functions."
201 :type '(choice (const :tag "None" 0)
202 (const :tag "Basic" 1)
203 (const :tag "Include Properties" 2)
204 (const :tag "Include Functions" 3)))
206 (defvar js2-mode-dev-mode-p nil
207 "Non-nil if running in development mode. Normally nil.")
209 (defgroup js2-mode nil
210 "An improved JavaScript mode."
213 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
214 (numberp c-basic-offset))
217 "Number of spaces to indent nested statements.
218 Similar to `c-basic-offset'."
221 (js2-mark-safe-local 'js2-basic-offset 'integerp)
224 (defcustom js2-bounce-indent-p nil
225 "Non-nil to have indent-line function choose among alternatives.
226 If nil, the indent-line function will indent to a predetermined column
227 based on heuristic guessing. If non-nil, then if the current line is
228 already indented to that predetermined column, indenting will choose
229 another likely column and indent to that spot. Repeated invocation of
230 the indent-line function will cycle among the computed alternatives.
231 See the function `js2-bounce-indent' for details. When it is non-nil,
232 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
236 (defcustom js2-consistent-level-indent-inner-bracket-p t
237 "Non-nil to make indentation level inner bracket consistent,
238 regardless of the beginning bracket position."
241 (js2-mark-safe-local 'js2-consistent-level-indent-inner-bracket-p 'booleanp)
243 (defcustom js2-pretty-multiline-decl-indentation-p t
244 "Non-nil to line up multiline declarations vertically. See the
245 function `js2-multiline-decl-indentation' for details."
248 (js2-mark-safe-local 'js2-pretty-multiline-decl-indentation-p 'booleanp)
250 (defcustom js2-always-indent-assigned-expr-in-decls-p nil
251 "If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
252 always additionally indent function expression or array/object literal
253 assigned in a declaration, even when only one var is declared."
256 (js2-mark-safe-local 'js2-always-indent-assigned-expr-in-decls-p 'booleanp)
258 (defcustom js2-indent-on-enter-key nil
259 "Non-nil to have Enter/Return key indent the line.
260 This is unusual for Emacs modes but common in IDEs like Eclipse."
264 (defcustom js2-enter-indents-newline nil
265 "Non-nil to have Enter/Return key indent the newly-inserted line.
266 This is unusual for Emacs modes but common in IDEs like Eclipse."
270 (defcustom js2-idle-timer-delay 0.2
271 "Delay in secs before re-parsing after user makes changes.
272 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
275 (make-variable-buffer-local 'js2-idle-timer-delay)
277 (defcustom js2-dynamic-idle-timer-adjust 0
278 "Positive to adjust `js2-idle-timer-delay' based on file size.
279 The idea is that for short files, parsing is faster so we can be
280 more responsive to user edits without interfering with editing.
281 The buffer length in characters (typically bytes) is divided by
282 this value and used to multiply `js2-idle-timer-delay' for the
283 buffer. For example, a 21k file and 10k adjust yields 21k/10k
284 == 2, so js2-idle-timer-delay is multiplied by 2.
285 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
286 `js2-idle-timer-delay' is not dependent on the file size."
290 (defcustom js2-mode-escape-quotes t
291 "Non-nil to disable automatic quote-escaping inside strings."
295 (defcustom js2-mode-squeeze-spaces t
296 "Non-nil to normalize whitespace when filling in comments.
297 Multiple runs of spaces are converted to a single space."
301 (defcustom js2-mode-show-parse-errors t
302 "True to highlight parse errors."
306 (defcustom js2-mode-show-strict-warnings t
307 "Non-nil to emit Ecma strict-mode warnings.
308 Some of the warnings can be individually disabled by other flags,
309 even if this flag is non-nil."
313 (defcustom js2-strict-trailing-comma-warning t
314 "Non-nil to warn about trailing commas in array literals.
315 Ecma-262 forbids them, but many browsers permit them. IE is the
316 big exception, and can produce bugs if you have trailing commas."
320 (defcustom js2-strict-missing-semi-warning t
321 "Non-nil to warn about semicolon auto-insertion after statement.
322 Technically this is legal per Ecma-262, but some style guides disallow
327 (defcustom js2-missing-semi-one-line-override nil
328 "Non-nil to permit missing semicolons in one-line functions.
329 In one-liner functions such as `function identity(x) {return x}'
330 people often omit the semicolon for a cleaner look. If you are
331 such a person, you can suppress the missing-semicolon warning
332 by setting this variable to t."
336 (defcustom js2-strict-inconsistent-return-warning t
337 "Non-nil to warn about mixing returns with value-returns.
338 It's perfectly legal to have a `return' and a `return foo' in the
339 same function, but it's often an indicator of a bug, and it also
340 interferes with type inference (in systems that support it.)"
344 (defcustom js2-strict-cond-assign-warning t
345 "Non-nil to warn about expressions like if (a = b).
346 This often should have been '==' instead of '='. If the warning
347 is enabled, you can suppress it on a per-expression basis by
348 parenthesizing the expression, e.g. if ((a = b)) ..."
352 (defcustom js2-strict-cond-assign-warning t
353 "Non-nil to warn about expressions like if (a = b).
354 This often should have been '==' instead of '='. If the warning
355 is enabled, you can suppress it on a per-expression basis by
356 parenthesizing the expression, e.g. if ((a = b)) ..."
360 (defcustom js2-strict-var-redeclaration-warning t
361 "Non-nil to warn about redeclaring variables in a script or function."
365 (defcustom js2-strict-var-hides-function-arg-warning t
366 "Non-nil to warn about a var decl hiding a function argument."
370 (defcustom js2-skip-preprocessor-directives nil
371 "Non-nil to treat lines beginning with # as comments.
372 Useful for viewing Mozilla JavaScript source code."
376 (defcustom js2-language-version 180
377 "Configures what JavaScript language version to recognize.
378 Currently versions 150, 160, 170 and 180 are supported, corresponding
379 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
380 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
381 and 1.8 adds function closures."
385 (defcustom js2-allow-keywords-as-property-names t
386 "If non-nil, you can use JavaScript keywords as object property names.
389 var foo = {int: 5, while: 6, continue: 7};
392 Ecma-262 forbids this syntax, but many browsers support it."
396 (defcustom js2-instanceof-has-side-effects nil
397 "If non-nil, treats the instanceof operator as having side effects.
398 This is useful for xulrunner apps."
402 (defcustom js2-move-point-on-right-click t
403 "Non-nil to move insertion point when you right-click.
404 This makes right-click context menu behavior a bit more intuitive,
405 since menu operations generally apply to the point. The exception
406 is if there is a region selection, in which case the point does -not-
407 move, so cut/copy/paste can work properly.
409 Note that IntelliJ moves the point, and Eclipse leaves it alone,
410 so this behavior is customizable."
414 (defcustom js2-allow-rhino-new-expr-initializer t
415 "Non-nil to support a Rhino's experimental syntactic construct.
417 Rhino supports the ability to follow a `new' expression with an object
418 literal, which is used to set additional properties on the new object
419 after calling its constructor. Syntax:
421 new <expr> [ ( arglist ) ] [initializer]
423 Hence, this expression:
425 new Object {a: 1, b: 2}
427 results in an Object with properties a=1 and b=2. This syntax is
428 apparently not configurable in Rhino - it's currently always enabled,
429 as of Rhino version 1.7R2."
433 (defcustom js2-allow-member-expr-as-function-name nil
434 "Non-nil to support experimental Rhino syntax for function names.
436 Rhino supports an experimental syntax configured via the Rhino Context
437 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
439 function <member-expr> ( [ arg-list ] ) { <body> }
441 Where member-expr is a non-parenthesized 'member expression', which
442 is anything at the grammar level of a new-expression or lower, meaning
443 any expression that does not involve infix or unary operators.
445 When <member-expr> is not a simple identifier, then it is syntactic
446 sugar for assigning the anonymous function to the <member-expr>. Hence,
449 function a.b().c[2] (x, y) { ... }
453 a.b().c[2] = function(x, y) {...}
455 which doesn't seem particularly useful, but Rhino permits it."
459 (defvar js2-mode-version 20120416
460 "Release number for `js2-mode'.")
464 (defmacro js2-deflocal (name value &optional comment)
465 "Define a buffer-local variable NAME with VALUE and COMMENT."
467 (defvar ,name ,value ,comment)
468 (make-variable-buffer-local ',name)))
470 ;; We record the start and end position of each token.
471 (js2-deflocal js2-token-beg 1)
472 (js2-deflocal js2-token-end -1)
474 (defvar js2-EOF_CHAR -1
475 "Represents end of stream. Distinct from js2-EOF token type.")
477 ;; I originally used symbols to represent tokens, but Rhino uses
478 ;; ints and then sets various flag bits in them, so ints it is.
479 ;; The upshot is that we need a `js2-' prefix in front of each name.
480 (defvar js2-ERROR -1)
483 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
484 (defvar js2-LEAVEWITH 3)
485 (defvar js2-RETURN 4)
489 (defvar js2-SETNAME 8)
491 (defvar js2-BITXOR 10)
492 (defvar js2-BITAND 11)
502 (defvar js2-ADD 21) ; infix plus
503 (defvar js2-SUB 22) ; infix minus
508 (defvar js2-BITNOT 27)
509 (defvar js2-POS 28) ; unary plus
510 (defvar js2-NEG 29) ; unary minus
512 (defvar js2-DELPROP 31)
513 (defvar js2-TYPEOF 32)
514 (defvar js2-GETPROP 33)
515 (defvar js2-GETPROPNOWARN 34)
516 (defvar js2-SETPROP 35)
517 (defvar js2-GETELEM 36)
518 (defvar js2-SETELEM 37)
520 (defvar js2-NAME 39) ; an identifier
521 (defvar js2-NUMBER 40)
522 (defvar js2-STRING 41)
525 (defvar js2-FALSE 44)
527 (defvar js2-SHEQ 46) ; shallow equality (===)
528 (defvar js2-SHNE 47) ; shallow inequality (!==)
529 (defvar js2-REGEXP 48)
530 (defvar js2-BINDNAME 49)
531 (defvar js2-THROW 50)
532 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
534 (defvar js2-INSTANCEOF 53)
535 (defvar js2-LOCAL_LOAD 54)
536 (defvar js2-GETVAR 55)
537 (defvar js2-SETVAR 56)
538 (defvar js2-CATCH_SCOPE 57)
539 (defvar js2-ENUM_INIT_KEYS 58)
540 (defvar js2-ENUM_INIT_VALUES 59)
541 (defvar js2-ENUM_INIT_ARRAY 60)
542 (defvar js2-ENUM_NEXT 61)
543 (defvar js2-ENUM_ID 62)
544 (defvar js2-THISFN 63)
545 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
546 (defvar js2-ARRAYLIT 65) ; array literal
547 (defvar js2-OBJECTLIT 66) ; object literal
548 (defvar js2-GET_REF 67) ; *reference
549 (defvar js2-SET_REF 68) ; *reference = something
550 (defvar js2-DEL_REF 69) ; delete reference
551 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
552 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
553 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
556 (defvar js2-DEFAULTNAMESPACE 73)
557 (defvar js2-ESCXMLATTR 74)
558 (defvar js2-ESCXMLTEXT 75)
559 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
560 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
561 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
562 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
564 (defvar js2-first-bytecode js2-ENTERWITH)
565 (defvar js2-last-bytecode js2-REF_NS_NAME)
568 (defvar js2-SEMI 81) ; semicolon
569 (defvar js2-LB 82) ; left and right brackets
571 (defvar js2-LC 84) ; left and right curly-braces
573 (defvar js2-LP 86) ; left and right parens
575 (defvar js2-COMMA 88) ; comma operator
577 (defvar js2-ASSIGN 89) ; simple assignment (=)
578 (defvar js2-ASSIGN_BITOR 90) ; |=
579 (defvar js2-ASSIGN_BITXOR 91) ; ^=
580 (defvar js2-ASSIGN_BITAND 92) ; &=
581 (defvar js2-ASSIGN_LSH 93) ; <<=
582 (defvar js2-ASSIGN_RSH 94) ; >>=
583 (defvar js2-ASSIGN_URSH 95) ; >>>=
584 (defvar js2-ASSIGN_ADD 96) ; +=
585 (defvar js2-ASSIGN_SUB 97) ; -=
586 (defvar js2-ASSIGN_MUL 98) ; *=
587 (defvar js2-ASSIGN_DIV 99) ; /=
588 (defvar js2-ASSIGN_MOD 100) ; %=
590 (defvar js2-first-assign js2-ASSIGN)
591 (defvar js2-last-assign js2-ASSIGN_MOD)
593 (defvar js2-HOOK 101) ; conditional (?:)
594 (defvar js2-COLON 102)
595 (defvar js2-OR 103) ; logical or (||)
596 (defvar js2-AND 104) ; logical and (&&)
597 (defvar js2-INC 105) ; increment/decrement (++ --)
599 (defvar js2-DOT 107) ; member operator (.)
600 (defvar js2-FUNCTION 108) ; function keyword
601 (defvar js2-EXPORT 109) ; export keyword
602 (defvar js2-IMPORT 110) ; import keyword
603 (defvar js2-IF 111) ; if keyword
604 (defvar js2-ELSE 112) ; else keyword
605 (defvar js2-SWITCH 113) ; switch keyword
606 (defvar js2-CASE 114) ; case keyword
607 (defvar js2-DEFAULT 115) ; default keyword
608 (defvar js2-WHILE 116) ; while keyword
609 (defvar js2-DO 117) ; do keyword
610 (defvar js2-FOR 118) ; for keyword
611 (defvar js2-BREAK 119) ; break keyword
612 (defvar js2-CONTINUE 120) ; continue keyword
613 (defvar js2-VAR 121) ; var keyword
614 (defvar js2-WITH 122) ; with keyword
615 (defvar js2-CATCH 123) ; catch keyword
616 (defvar js2-FINALLY 124) ; finally keyword
617 (defvar js2-VOID 125) ; void keyword
618 (defvar js2-RESERVED 126) ; reserved keywords
620 (defvar js2-EMPTY 127)
622 ;; Types used for the parse tree - never returned by scanner.
624 (defvar js2-BLOCK 128) ; statement block
625 (defvar js2-LABEL 129) ; label
626 (defvar js2-TARGET 130)
627 (defvar js2-LOOP 131)
628 (defvar js2-EXPR_VOID 132) ; expression statement in functions
629 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
631 (defvar js2-SCRIPT 135) ; top-level node for entire script
632 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
633 (defvar js2-USE_STACK 137)
634 (defvar js2-SETPROP_OP 138) ; x.y op= something
635 (defvar js2-SETELEM_OP 139) ; x[y] op= something
636 (defvar js2-LOCAL_BLOCK 140)
637 (defvar js2-SET_REF_OP 141) ; *reference op= something
640 (defvar js2-DOTDOT 142) ; member operator (..)
641 (defvar js2-COLONCOLON 143) ; namespace::name
642 (defvar js2-XML 144) ; XML type
643 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
644 (defvar js2-XMLATTR 146) ; @
645 (defvar js2-XMLEND 147)
647 ;; Optimizer-only tokens
648 (defvar js2-TO_OBJECT 148)
649 (defvar js2-TO_DOUBLE 149)
651 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
652 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
653 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
654 (defvar js2-CONST 153)
655 (defvar js2-SETCONST 154)
656 (defvar js2-SETCONSTVAR 155)
657 (defvar js2-ARRAYCOMP 156)
658 (defvar js2-LETEXPR 157)
659 (defvar js2-WITHEXPR 158)
660 (defvar js2-DEBUGGER 159)
662 (defvar js2-COMMENT 160)
663 (defvar js2-ENUM 161) ; for "enum" reserved word
665 (defconst js2-num-tokens (1+ js2-ENUM))
667 (defconst js2-debug-print-trees nil)
669 ;; Rhino accepts any string or stream as input. Emacs character
670 ;; processing works best in buffers, so we'll assume the input is a
671 ;; buffer. JavaScript strings can be copied into temp buffers before
674 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
675 ;; They're the Emacs equivalent of instance variables, more or less.
677 (js2-deflocal js2-ts-dirty-line nil
678 "Token stream buffer-local variable.
679 Indicates stuff other than whitespace since start of line.")
681 (js2-deflocal js2-ts-regexp-flags nil
682 "Token stream buffer-local variable.")
684 (js2-deflocal js2-ts-string ""
685 "Token stream buffer-local variable.
686 Last string scanned.")
688 (js2-deflocal js2-ts-number nil
689 "Token stream buffer-local variable.
690 Last literal number scanned.")
692 (js2-deflocal js2-ts-hit-eof nil
693 "Token stream buffer-local variable.")
695 (js2-deflocal js2-ts-line-start 0
696 "Token stream buffer-local variable.")
698 (js2-deflocal js2-ts-lineno 1
699 "Token stream buffer-local variable.")
701 (js2-deflocal js2-ts-line-end-char -1
702 "Token stream buffer-local variable.")
704 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
705 "Token stream buffer-local variable.
706 Current scan position.")
708 (js2-deflocal js2-ts-is-xml-attribute nil
709 "Token stream buffer-local variable.")
711 (js2-deflocal js2-ts-xml-is-tag-content nil
712 "Token stream buffer-local variable.")
714 (js2-deflocal js2-ts-xml-open-tags-count 0
715 "Token stream buffer-local variable.")
717 (js2-deflocal js2-ts-string-buffer nil
718 "Token stream buffer-local variable.
719 List of chars built up while scanning various tokens.")
721 (js2-deflocal js2-ts-comment-type nil
722 "Token stream buffer-local variable.")
726 (js2-deflocal js2-parsed-errors nil
727 "List of errors produced during scanning/parsing.")
729 (js2-deflocal js2-parsed-warnings nil
730 "List of warnings produced during scanning/parsing.")
732 (js2-deflocal js2-recover-from-parse-errors t
733 "Non-nil to continue parsing after a syntax error.
735 In recovery mode, the AST will be built in full, and any error
736 nodes will be flagged with appropriate error information. If
737 this flag is nil, a syntax error will result in an error being
740 The variable is automatically buffer-local, because different
741 modes that use the parser will need different settings.")
743 (js2-deflocal js2-parse-hook nil
744 "List of callbacks for receiving parsing progress.")
746 (defvar js2-parse-finished-hook nil
747 "List of callbacks to notify when parsing finishes.
748 Not called if parsing was interrupted.")
750 (js2-deflocal js2-is-eval-code nil
751 "True if we're evaluating code in a string.
752 If non-nil, the tokenizer will record the token text, and the AST nodes
753 will record their source text. Off by default for IDE modes, since the
754 text is available in the buffer.")
756 (defvar js2-parse-ide-mode t
757 "Non-nil if the parser is being used for `js2-mode'.
758 If non-nil, the parser will set text properties for fontification
759 and the syntax table. The value should be nil when using the
760 parser as a frontend to an interpreter or byte compiler.")
762 ;;; Parser instance variables (buffer-local vars for js2-parse)
764 (defconst js2-clear-ti-mask #xFFFF
765 "Mask to clear token information bits.")
767 (defconst js2-ti-after-eol (lsh 1 16)
768 "Flag: first token of the source line.")
770 (defconst js2-ti-check-label (lsh 1 17)
771 "Flag: indicates to check for label.")
773 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
775 (js2-deflocal js2-compiler-generate-debug-info t)
776 (js2-deflocal js2-compiler-use-dynamic-scope nil)
777 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
778 (js2-deflocal js2-compiler-xml-available t)
779 (js2-deflocal js2-compiler-optimization-level 0)
780 (js2-deflocal js2-compiler-generating-source t)
781 (js2-deflocal js2-compiler-strict-mode nil)
782 (js2-deflocal js2-compiler-report-warning-as-error nil)
783 (js2-deflocal js2-compiler-generate-observer-count nil)
784 (js2-deflocal js2-compiler-activation-names nil)
788 ;; There's a compileFunction method in Context.java - may need it.
789 (js2-deflocal js2-called-by-compile-function nil
790 "True if `js2-parse' was called by `js2-compile-function'.
791 Will only be used when we finish implementing the interpreter.")
793 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
795 (js2-deflocal js2-current-flagged-token js2-EOF)
796 (js2-deflocal js2-current-token js2-EOF)
798 ;; SKIP: node factory - we're going to just call functions directly,
799 ;; and eventually go to a unified AST format.
801 (js2-deflocal js2-nesting-of-function 0)
803 (js2-deflocal js2-recorded-identifiers nil
804 "Tracks identifiers found during parsing.")
806 (defmacro js2-in-lhs (body)
807 `(let ((js2-is-in-lhs t))
810 (defmacro js2-in-rhs (body)
811 `(let ((js2-is-in-lhs nil))
814 (js2-deflocal js2-is-in-lhs nil
815 "True while parsing lhs statement")
817 (defcustom js2-global-externs nil
818 "A list of any extern names you'd like to consider always declared.
819 This list is global and is used by all `js2-mode' files.
820 You can create buffer-local externs list using `js2-additional-externs'.
822 There is also a buffer-local variable `js2-default-externs',
823 which is initialized by default to include the Ecma-262 externs
824 and the standard browser externs. The three lists are all
825 checked during highlighting."
829 (js2-deflocal js2-default-externs nil
830 "Default external declarations.
832 These are currently only used for highlighting undeclared variables,
833 which only worries about top-level (unqualified) references.
834 As js2-mode's processing improves, we will flesh out this list.
836 The initial value is set to `js2-ecma-262-externs', unless you
837 have set `js2-include-browser-externs', in which case the browser
838 externs are also included.
840 See `js2-additional-externs' for more information.")
842 (defcustom js2-include-browser-externs t
843 "Non-nil to include browser externs in the master externs list.
844 If you work on JavaScript files that are not intended for browsers,
845 such as Mozilla Rhino server-side JavaScript, set this to nil.
846 You can always include them on a per-file basis by calling
847 `js2-add-browser-externs' from a function on `js2-mode-hook'.
849 See `js2-additional-externs' for more information about externs."
853 (defcustom js2-include-rhino-externs t
854 "Non-nil to include Mozilla Rhino externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
859 (defcustom js2-include-gears-externs t
860 "Non-nil to include Google Gears externs in the master externs list.
861 See `js2-additional-externs' for more information about externs."
865 (js2-deflocal js2-additional-externs nil
866 "A buffer-local list of additional external declarations.
867 It is used to decide whether variables are considered undeclared
868 for purposes of highlighting.
870 Each entry is a Lisp string. The string should be the fully qualified
871 name of an external entity. All externs should be added to this list,
872 so that as js2-mode's processing improves it can take advantage of them.
874 You may want to declare your externs in three ways.
875 First, you can add externs that are valid for all your JavaScript files.
876 You should probably do this by adding them to `js2-global-externs', which
877 is a global list used for all js2-mode files.
879 Next, you can add a function to `js2-mode-hook' that adds additional
880 externs appropriate for the specific file, perhaps based on its path.
881 These should go in `js2-additional-externs', which is buffer-local.
883 Finally, you can add a function to `js2-post-parse-callbacks',
884 which is called after parsing completes, and `root' is bound to
885 the root of the parse tree. At this stage you can set up an AST
886 node visitor using `js2-visit-ast' and examine the parse tree
887 for specific import patterns that may imply the existence of
888 other externs, possibly tied to your build system. These should also
889 be added to `js2-additional-externs'.
891 Your post-parse callback may of course also use the simpler and
892 faster (but perhaps less robust) approach of simply scanning the
893 buffer text for your imports, using regular expressions.")
896 ;; SKIP: encoded-source
898 ;;; The following variables are per-function and should be saved/restored
899 ;;; during function parsing...
901 (js2-deflocal js2-current-script-or-fn nil)
902 (js2-deflocal js2-current-scope nil)
903 (js2-deflocal js2-nesting-of-with 0)
904 (js2-deflocal js2-label-set nil
905 "An alist mapping label names to nodes.")
907 (js2-deflocal js2-loop-set nil)
908 (js2-deflocal js2-loop-and-switch-set nil)
909 (js2-deflocal js2-has-return-value nil)
910 (js2-deflocal js2-end-flags 0)
912 ;;; ...end of per function variables
914 ;; Without 2-token lookahead, labels are a problem.
915 ;; These vars store the token info of the last matched name,
916 ;; iff it wasn't the last matched token. Only valid in some contexts.
917 (defvar js2-prev-name-token-start nil)
918 (defvar js2-prev-name-token-string nil)
920 (defsubst js2-save-name-token-data (pos name)
921 (setq js2-prev-name-token-start pos
922 js2-prev-name-token-string name))
924 ;; These flags enumerate the possible ways a statement/function can
925 ;; terminate. These flags are used by endCheck() and by the Parser to
926 ;; detect inconsistent return usage.
928 ;; END_UNREACHED is reserved for code paths that are assumed to always be
929 ;; able to execute (example: throw, continue)
931 ;; END_DROPS_OFF indicates if the statement can transfer control to the
932 ;; next one. Statement such as return dont. A compound statement may have
933 ;; some branch that drops off control to the next statement.
935 ;; END_RETURNS indicates that the statement can return (without arguments)
936 ;; END_RETURNS_VALUE indicates that the statement can return a value.
938 ;; A compound statement such as
942 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
944 (defconst js2-end-unreached #x0)
945 (defconst js2-end-drops-off #x1)
946 (defconst js2-end-returns #x2)
947 (defconst js2-end-returns-value #x4)
948 (defconst js2-end-yields #x8)
950 ;; Rhino awkwardly passes a statementLabel parameter to the
951 ;; statementHelper() function, the main statement parser, which
952 ;; is then used by quite a few of the sub-parsers. We just make
953 ;; it a buffer-local variable and make sure it's cleaned up properly.
954 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
956 ;; Similarly, Rhino passes an inForInit boolean through about half
957 ;; the expression parsers. We use a dynamically-scoped variable,
958 ;; which makes it easier to funcall the parsers individually without
959 ;; worrying about whether they take the parameter or not.
960 (js2-deflocal js2-in-for-init nil)
961 (js2-deflocal js2-temp-name-counter 0)
962 (js2-deflocal js2-parse-stmt-count 0)
964 (defsubst js2-get-next-temp-name ()
965 (format "$%d" (incf js2-temp-name-counter)))
967 (defvar js2-parse-interruptable-p t
968 "Set this to nil to force parse to continue until finished.
969 This will mostly be useful for interpreters.")
971 (defvar js2-statements-per-pause 50
972 "Pause after this many statements to check for user input.
973 If user input is pending, stop the parse and discard the tree.
974 This makes for a smoother user experience for large files.
975 You may have to wait a second or two before the highlighting
976 and error-reporting appear, but you can always type ahead if
977 you wish. This appears to be more or less how Eclipse, IntelliJ
978 and other editors work.")
980 (js2-deflocal js2-record-comments t
981 "Instructs the scanner to record comments in `js2-scanned-comments'.")
983 (js2-deflocal js2-scanned-comments nil
984 "List of all comments from the current parse.")
986 (defcustom js2-mode-indent-inhibit-undo nil
987 "Non-nil to disable collection of Undo information when indenting lines.
988 Some users have requested this behavior. It's nil by default because
989 other Emacs modes don't work this way."
993 (defcustom js2-mode-indent-ignore-first-tab nil
994 "If non-nil, ignore first TAB keypress if we look indented properly.
995 It's fairly common for users to navigate to an already-indented line
996 and press TAB for reassurance that it's been indented. For this class
997 of users, we want the first TAB press on a line to be ignored if the
998 line is already indented to one of the precomputed alternatives.
1000 This behavior is only partly implemented. If you TAB-indent a line,
1001 navigate to another line, and then navigate back, it fails to clear
1002 the last-indented variable, so it thinks you've already hit TAB once,
1003 and performs the indent. A full solution would involve getting on the
1004 point-motion hooks for the entire buffer. If we come across another
1005 use cases that requires watching point motion, I'll consider doing it.
1007 If you set this variable to nil, then the TAB key will always change
1008 the indentation of the current line, if more than one alternative
1009 indentation spot exists."
1013 (defvar js2-indent-hook nil
1014 "A hook for user-defined indentation rules.
1016 Functions on this hook should expect two arguments: (LIST INDEX)
1017 The LIST argument is the list of computed indentation points for
1018 the current line. INDEX is the list index of the indentation point
1019 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1020 indent function is not going to change the current line indentation.
1022 If a hook function on this list returns a non-nil value, then
1023 `js2-bounce-indent' assumes the hook function has performed its own
1024 indentation, and will do nothing. If all hook functions on the list
1025 return nil, then `js2-bounce-indent' will use its computed indentation
1026 and reindent the line.
1028 When hook functions on this hook list are called, the variable
1029 `js2-mode-ast' may or may not be set, depending on whether the
1030 parse tree is available. If the variable is nil, you can pass a
1031 callback to `js2-mode-wait-for-parse', and your callback will be
1032 called after the new parse tree is built. This can take some time
1035 (defface js2-warning-face
1036 `((((class color) (background light))
1037 (:underline "orange"))
1038 (((class color) (background dark))
1039 (:underline "orange"))
1041 "Face for JavaScript warnings."
1044 (defface js2-error-face
1045 `((((class color) (background light))
1046 (:foreground "red"))
1047 (((class color) (background dark))
1048 (:foreground "red"))
1049 (t (:foreground "red")))
1050 "Face for JavaScript errors."
1053 (defface js2-jsdoc-tag-face
1054 '((t :foreground "SlateGray"))
1055 "Face used to highlight @whatever tags in jsdoc comments."
1058 (defface js2-jsdoc-type-face
1059 '((t :foreground "SteelBlue"))
1060 "Face used to highlight {FooBar} types in jsdoc comments."
1063 (defface js2-jsdoc-value-face
1064 '((t :foreground "PeachPuff3"))
1065 "Face used to highlight tag values in jsdoc comments."
1068 (defface js2-function-param-face
1069 '((t :foreground "SeaGreen"))
1070 "Face used to highlight function parameters in javascript."
1073 (defface js2-instance-member-face
1074 '((t :foreground "DarkOrchid"))
1075 "Face used to highlight instance variables in javascript.
1076 Not currently used."
1079 (defface js2-private-member-face
1080 '((t :foreground "PeachPuff3"))
1081 "Face used to highlight calls to private methods in javascript.
1082 Not currently used."
1085 (defface js2-private-function-call-face
1086 '((t :foreground "goldenrod"))
1087 "Face used to highlight calls to private functions in javascript.
1088 Not currently used."
1091 (defface js2-jsdoc-html-tag-name-face
1092 '((((class color) (min-colors 88) (background light))
1093 (:foreground "rosybrown"))
1094 (((class color) (min-colors 8) (background dark))
1095 (:foreground "yellow"))
1096 (((class color) (min-colors 8) (background light))
1097 (:foreground "magenta")))
1098 "Face used to highlight jsdoc html tag names"
1101 (defface js2-jsdoc-html-tag-delimiter-face
1102 '((((class color) (min-colors 88) (background light))
1103 (:foreground "dark khaki"))
1104 (((class color) (min-colors 8) (background dark))
1105 (:foreground "green"))
1106 (((class color) (min-colors 8) (background light))
1107 (:foreground "green")))
1108 "Face used to highlight brackets in jsdoc html tags."
1112 (defcustom js2-post-parse-callbacks nil
1113 "A list of callback functions invoked after parsing finishes.
1114 Currently, the main use for this function is to add synthetic
1115 declarations to `js2-recorded-identifiers', which see."
1119 (defface js2-external-variable-face
1120 '((t :foreground "orange"))
1121 "Face used to highlight undeclared variable identifiers.
1122 An undeclared variable is any variable not declared with var or let
1123 in the current scope or any lexically enclosing scope. If you use
1124 such a variable, then you are either expecting it to originate from
1125 another file, or you've got a potential bug."
1128 (defcustom js2-highlight-external-variables t
1129 "Non-nil to highlight undeclared variable identifiers."
1133 (defcustom js2-auto-insert-catch-block t
1134 "Non-nil to insert matching catch block on open-curly after `try'."
1138 (defvar js2-mode-map
1139 (let ((map (make-sparse-keymap))
1141 (define-key map [mouse-1] #'js2-mode-show-node)
1142 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1143 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1144 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1145 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1146 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1147 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1148 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1149 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1150 (when js2-bounce-indent-p
1151 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1153 (define-key map [menu-bar javascript]
1154 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1156 (define-key map [menu-bar javascript customize-js2-mode]
1157 '(menu-item "Customize js2-mode" js2-mode-customize
1158 :help "Customize the behavior of this mode"))
1160 (define-key map [menu-bar javascript js2-force-refresh]
1161 '(menu-item "Force buffer refresh" js2-mode-reset
1162 :help "Re-parse the buffer from scratch"))
1164 (define-key map [menu-bar javascript separator-2]
1167 (define-key map [menu-bar javascript next-error]
1168 '(menu-item "Next warning or error" next-error
1169 :enabled (and js2-mode-ast
1170 (or (js2-ast-root-errors js2-mode-ast)
1171 (js2-ast-root-warnings js2-mode-ast)))
1172 :help "Move to next warning or error"))
1174 (define-key map [menu-bar javascript display-errors]
1175 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1176 :visible (not js2-mode-show-parse-errors)
1177 :help "Turn on display of warnings and errors"))
1179 (define-key map [menu-bar javascript hide-errors]
1180 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1181 :visible js2-mode-show-parse-errors
1182 :help "Turn off display of warnings and errors"))
1184 (define-key map [menu-bar javascript separator-1]
1187 (define-key map [menu-bar javascript js2-toggle-function]
1188 '(menu-item "Show/collapse element" js2-mode-toggle-element
1189 :help "Hide or show function body or comment"))
1191 (define-key map [menu-bar javascript show-comments]
1192 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1193 :visible js2-mode-comments-hidden
1194 :help "Expand all hidden block comments"))
1196 (define-key map [menu-bar javascript hide-comments]
1197 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1198 :visible (not js2-mode-comments-hidden)
1199 :help "Show block comments as /*...*/"))
1201 (define-key map [menu-bar javascript show-all-functions]
1202 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1203 :visible js2-mode-functions-hidden
1204 :help "Expand all hidden function bodies"))
1206 (define-key map [menu-bar javascript hide-all-functions]
1207 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1208 :visible (not js2-mode-functions-hidden)
1209 :help "Show {...} for all top-level function bodies"))
1212 "Keymap used in `js2-mode' buffers.")
1214 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1216 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1217 "Matches a //-comment line. Must be first non-whitespace on line.
1218 First match-group is the leading whitespace.")
1220 (defvar js2-mode-hook nil)
1222 (js2-deflocal js2-mode-ast nil "Private variable.")
1223 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1224 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1225 (js2-deflocal js2-mode-parsing nil "Private variable.")
1226 (js2-deflocal js2-mode-node-overlay nil)
1228 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1229 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1231 (js2-deflocal js2-mode-fontifications nil "Private variable")
1232 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1233 (js2-deflocal js2-imenu-recorder nil "Private variable")
1234 (js2-deflocal js2-imenu-function-map nil "Private variable")
1236 (defvar js2-paragraph-start
1237 "\\(@[a-zA-Z]+\\>\\|$\\)")
1239 ;; Note that we also set a 'c-in-sws text property in html comments,
1240 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1241 (defvar js2-syntactic-ws-start
1242 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1244 (defvar js2-syntactic-ws-end
1245 "\\s \\|[\n\r/]\\|\\s!")
1247 (defvar js2-syntactic-eol
1248 (concat "\\s *\\(/\\*[^*\n\r]*"
1249 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1251 "\\(//\\|/\\*[^*\n\r]*"
1252 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1254 "Copied from `java-mode'. Needed for some cc-engine functions.")
1256 (defvar js2-comment-prefix-regexp
1259 (defvar js2-comment-start-skip
1260 "\\(//+\\|/\\*+\\)\\s *")
1262 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1263 "Non-nil to emit status messages during parsing.")
1265 (defvar js2-mode-functions-hidden nil "Private variable.")
1266 (defvar js2-mode-comments-hidden nil "Private variable.")
1268 (defvar js2-mode-syntax-table
1269 (let ((table (make-syntax-table)))
1270 (c-populate-syntax-table table)
1272 "Syntax table used in `js2-mode' buffers.")
1274 (defvar js2-mode-abbrev-table nil
1275 "Abbrev table in use in `js2-mode' buffers.")
1276 (define-abbrev-table 'js2-mode-abbrev-table ())
1278 (defvar js2-mode-pending-parse-callbacks nil
1279 "List of functions waiting to be notified that parse is finished.")
1281 (defvar js2-mode-last-indented-line -1)
1283 ;;; Localizable error and warning messages
1285 ;; Messages are copied from Rhino's Messages.properties.
1286 ;; Many of the Java-specific messages have been elided.
1287 ;; Add any js2-specific ones at the end, so we can keep
1288 ;; this file synced with changes to Rhino's.
1290 (defvar js2-message-table
1291 (make-hash-table :test 'equal :size 250)
1292 "Contains localized messages for `js2-mode'.")
1294 ;; TODO(stevey): construct this table at compile-time.
1295 (defmacro js2-msg (key &rest strings)
1296 `(puthash ,key (funcall #'concat ,@strings)
1299 (defun js2-get-msg (msg-key)
1300 "Look up a localized message.
1301 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1302 the correct number of ARGS must be provided."
1303 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1304 (args (if (listp msg-key) (cdr msg-key)))
1305 (msg (gethash key js2-message-table)))
1307 (apply #'format msg args)
1308 key))) ; default to showing the key
1310 (js2-msg "msg.dup.parms"
1311 "Duplicate parameter name '%s'.")
1313 (js2-msg "msg.too.big.jump"
1314 "Program too complex: jump offset too big.")
1316 (js2-msg "msg.too.big.index"
1317 "Program too complex: internal index exceeds 64K limit.")
1319 (js2-msg "msg.while.compiling.fn"
1320 "Encountered code generation error while compiling function '%s': %s")
1322 (js2-msg "msg.while.compiling.script"
1323 "Encountered code generation error while compiling script: %s")
1326 (js2-msg "msg.ctor.not.found"
1327 "Constructor for '%s' not found.")
1329 (js2-msg "msg.not.ctor"
1330 "'%s' is not a constructor.")
1333 (js2-msg "msg.varargs.ctor"
1334 "Method or constructor '%s' must be static "
1335 "with the signature (Context cx, Object[] args, "
1336 "Function ctorObj, boolean inNewExpr) "
1337 "to define a variable arguments constructor.")
1339 (js2-msg "msg.varargs.fun"
1340 "Method '%s' must be static with the signature "
1341 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1342 "to define a variable arguments function.")
1344 (js2-msg "msg.incompat.call"
1345 "Method '%s' called on incompatible object.")
1347 (js2-msg "msg.bad.parms"
1348 "Unsupported parameter type '%s' in method '%s'.")
1350 (js2-msg "msg.bad.method.return"
1351 "Unsupported return type '%s' in method '%s'.")
1353 (js2-msg "msg.bad.ctor.return"
1354 "Construction of objects of type '%s' is not supported.")
1356 (js2-msg "msg.no.overload"
1357 "Method '%s' occurs multiple times in class '%s'.")
1359 (js2-msg "msg.method.not.found"
1360 "Method '%s' not found in '%s'.")
1364 (js2-msg "msg.bad.for.in.lhs"
1365 "Invalid left-hand side of for..in loop.")
1367 (js2-msg "msg.mult.index"
1368 "Only one variable allowed in for..in loop.")
1370 (js2-msg "msg.bad.for.in.destruct"
1371 "Left hand side of for..in loop must be an array of "
1372 "length 2 to accept key/value pair.")
1374 (js2-msg "msg.cant.convert"
1375 "Can't convert to type '%s'.")
1377 (js2-msg "msg.bad.assign.left"
1378 "Invalid assignment left-hand side.")
1380 (js2-msg "msg.bad.decr"
1381 "Invalid decerement operand.")
1383 (js2-msg "msg.bad.incr"
1384 "Invalid increment operand.")
1386 (js2-msg "msg.bad.yield"
1387 "yield must be in a function.")
1389 (js2-msg "msg.yield.parenthesized"
1390 "yield expression must be parenthesized.")
1393 (js2-msg "msg.cant.call.indirect"
1394 "Function '%s' must be called directly, and not by way of a "
1395 "function of another name.")
1397 (js2-msg "msg.eval.nonstring"
1398 "Calling eval() with anything other than a primitive "
1399 "string value will simply return the value. "
1400 "Is this what you intended?")
1402 (js2-msg "msg.eval.nonstring.strict"
1403 "Calling eval() with anything other than a primitive "
1404 "string value is not allowed in strict mode.")
1406 (js2-msg "msg.bad.destruct.op"
1407 "Invalid destructuring assignment operator")
1410 (js2-msg "msg.only.from.new"
1411 "'%s' may only be invoked from a `new' expression.")
1413 (js2-msg "msg.deprec.ctor"
1414 "The '%s' constructor is deprecated.")
1417 (js2-msg "msg.no.function.ref.found"
1418 "no source found to decompile function reference %s")
1420 (js2-msg "msg.arg.isnt.array"
1421 "second argument to Function.prototype.apply must be an array")
1424 (js2-msg "msg.bad.esc.mask"
1425 "invalid string escape mask")
1428 (js2-msg "msg.bad.quant"
1429 "Invalid quantifier %s")
1431 (js2-msg "msg.overlarge.backref"
1432 "Overly large back reference %s")
1434 (js2-msg "msg.overlarge.min"
1435 "Overly large minimum %s")
1437 (js2-msg "msg.overlarge.max"
1438 "Overly large maximum %s")
1440 (js2-msg "msg.zero.quant"
1441 "Zero quantifier %s")
1443 (js2-msg "msg.max.lt.min"
1444 "Maximum %s less than minimum")
1446 (js2-msg "msg.unterm.quant"
1447 "Unterminated quantifier %s")
1449 (js2-msg "msg.unterm.paren"
1450 "Unterminated parenthetical %s")
1452 (js2-msg "msg.unterm.class"
1453 "Unterminated character class %s")
1455 (js2-msg "msg.bad.range"
1456 "Invalid range in character class.")
1458 (js2-msg "msg.trail.backslash"
1459 "Trailing \\ in regular expression.")
1461 (js2-msg "msg.re.unmatched.right.paren"
1462 "unmatched ) in regular expression.")
1464 (js2-msg "msg.no.regexp"
1465 "Regular expressions are not available.")
1467 (js2-msg "msg.bad.backref"
1468 "back-reference exceeds number of capturing parentheses.")
1470 (js2-msg "msg.bad.regexp.compile"
1471 "Only one argument may be specified if the first "
1472 "argument to RegExp.prototype.compile is a RegExp object.")
1475 (js2-msg "msg.got.syntax.errors"
1476 "Compilation produced %s syntax errors.")
1478 (js2-msg "msg.var.redecl"
1479 "TypeError: redeclaration of var %s.")
1481 (js2-msg "msg.const.redecl"
1482 "TypeError: redeclaration of const %s.")
1484 (js2-msg "msg.let.redecl"
1485 "TypeError: redeclaration of variable %s.")
1487 (js2-msg "msg.parm.redecl"
1488 "TypeError: redeclaration of formal parameter %s.")
1490 (js2-msg "msg.fn.redecl"
1491 "TypeError: redeclaration of function %s.")
1493 (js2-msg "msg.let.decl.not.in.block"
1494 "SyntaxError: let declaration not directly within block")
1497 (js2-msg "msg.dup.label"
1500 (js2-msg "msg.undef.label"
1503 (js2-msg "msg.bad.break"
1504 "unlabelled break must be inside loop or switch")
1506 (js2-msg "msg.continue.outside"
1507 "continue must be inside loop")
1509 (js2-msg "msg.continue.nonloop"
1510 "continue can only use labels of iteration statements")
1512 (js2-msg "msg.bad.throw.eol"
1513 "Line terminator is not allowed between the throw "
1514 "keyword and throw expression.")
1516 (js2-msg "msg.no.paren.parms"
1517 "missing ( before function parameters.")
1519 (js2-msg "msg.no.parm"
1520 "missing formal parameter")
1522 (js2-msg "msg.no.paren.after.parms"
1523 "missing ) after formal parameters")
1525 (js2-msg "msg.no.brace.body"
1526 "missing '{' before function body")
1528 (js2-msg "msg.no.brace.after.body"
1529 "missing } after function body")
1531 (js2-msg "msg.no.paren.cond"
1532 "missing ( before condition")
1534 (js2-msg "msg.no.paren.after.cond"
1535 "missing ) after condition")
1537 (js2-msg "msg.no.semi.stmt"
1538 "missing ; before statement")
1540 (js2-msg "msg.missing.semi"
1541 "missing ; after statement")
1543 (js2-msg "msg.no.name.after.dot"
1544 "missing name after . operator")
1546 (js2-msg "msg.no.name.after.coloncolon"
1547 "missing name after :: operator")
1549 (js2-msg "msg.no.name.after.dotdot"
1550 "missing name after .. operator")
1552 (js2-msg "msg.no.name.after.xmlAttr"
1553 "missing name after .@")
1555 (js2-msg "msg.no.bracket.index"
1556 "missing ] in index expression")
1558 (js2-msg "msg.no.paren.switch"
1559 "missing ( before switch expression")
1561 (js2-msg "msg.no.paren.after.switch"
1562 "missing ) after switch expression")
1564 (js2-msg "msg.no.brace.switch"
1565 "missing '{' before switch body")
1567 (js2-msg "msg.bad.switch"
1568 "invalid switch statement")
1570 (js2-msg "msg.no.colon.case"
1571 "missing : after case expression")
1573 (js2-msg "msg.double.switch.default"
1574 "double default label in the switch statement")
1576 (js2-msg "msg.no.while.do"
1577 "missing while after do-loop body")
1579 (js2-msg "msg.no.paren.for"
1580 "missing ( after for")
1582 (js2-msg "msg.no.semi.for"
1583 "missing ; after for-loop initializer")
1585 (js2-msg "msg.no.semi.for.cond"
1586 "missing ; after for-loop condition")
1588 (js2-msg "msg.in.after.for.name"
1589 "missing in after for")
1591 (js2-msg "msg.no.paren.for.ctrl"
1592 "missing ) after for-loop control")
1594 (js2-msg "msg.no.paren.with"
1595 "missing ( before with-statement object")
1597 (js2-msg "msg.no.paren.after.with"
1598 "missing ) after with-statement object")
1600 (js2-msg "msg.no.paren.after.let"
1601 "missing ( after let")
1603 (js2-msg "msg.no.paren.let"
1604 "missing ) after variable list")
1606 (js2-msg "msg.no.curly.let"
1607 "missing } after let statement")
1609 (js2-msg "msg.bad.return"
1612 (js2-msg "msg.no.brace.block"
1613 "missing } in compound statement")
1615 (js2-msg "msg.bad.label"
1618 (js2-msg "msg.bad.var"
1619 "missing variable name")
1621 (js2-msg "msg.bad.var.init"
1622 "invalid variable initialization")
1624 (js2-msg "msg.no.colon.cond"
1625 "missing : in conditional expression")
1627 (js2-msg "msg.no.paren.arg"
1628 "missing ) after argument list")
1630 (js2-msg "msg.no.bracket.arg"
1631 "missing ] after element list")
1633 (js2-msg "msg.bad.prop"
1634 "invalid property id")
1636 (js2-msg "msg.no.colon.prop"
1637 "missing : after property id")
1639 (js2-msg "msg.no.brace.prop"
1640 "missing } after property list")
1642 (js2-msg "msg.no.paren"
1643 "missing ) in parenthetical")
1645 (js2-msg "msg.reserved.id"
1646 "identifier is a reserved word")
1648 (js2-msg "msg.no.paren.catch"
1649 "missing ( before catch-block condition")
1651 (js2-msg "msg.bad.catchcond"
1652 "invalid catch block condition")
1654 (js2-msg "msg.catch.unreachable"
1655 "any catch clauses following an unqualified catch are unreachable")
1657 (js2-msg "msg.no.brace.try"
1658 "missing '{' before try block")
1660 (js2-msg "msg.no.brace.catchblock"
1661 "missing '{' before catch-block body")
1663 (js2-msg "msg.try.no.catchfinally"
1664 "'try' without 'catch' or 'finally'")
1666 (js2-msg "msg.no.return.value"
1667 "function %s does not always return a value")
1669 (js2-msg "msg.anon.no.return.value"
1670 "anonymous function does not always return a value")
1672 (js2-msg "msg.return.inconsistent"
1673 "return statement is inconsistent with previous usage")
1675 (js2-msg "msg.generator.returns"
1676 "TypeError: generator function '%s' returns a value")
1678 (js2-msg "msg.anon.generator.returns"
1679 "TypeError: anonymous generator function returns a value")
1681 (js2-msg "msg.syntax"
1684 (js2-msg "msg.unexpected.eof"
1685 "Unexpected end of file")
1687 (js2-msg "msg.XML.bad.form"
1688 "illegally formed XML syntax")
1690 (js2-msg "msg.XML.not.available"
1691 "XML runtime not available")
1693 (js2-msg "msg.too.deep.parser.recursion"
1694 "Too deep recursion while parsing")
1696 (js2-msg "msg.no.side.effects"
1697 "Code has no side effects")
1699 (js2-msg "msg.extra.trailing.comma"
1700 "Trailing comma is not legal in an ECMA-262 object initializer")
1702 (js2-msg "msg.array.trailing.comma"
1703 "Trailing comma yields different behavior across browsers")
1705 (js2-msg "msg.equal.as.assign"
1706 (concat "Test for equality (==) mistyped as assignment (=)?"
1707 " (parenthesize to suppress warning)"))
1709 (js2-msg "msg.var.hides.arg"
1710 "Variable %s hides argument")
1712 (js2-msg "msg.destruct.assign.no.init"
1713 "Missing = in destructuring declaration")
1716 (js2-msg "msg.no.properties"
1717 "%s has no properties.")
1719 (js2-msg "msg.invalid.iterator"
1720 "Invalid iterator value")
1722 (js2-msg "msg.iterator.primitive"
1723 "__iterator__ returned a primitive value")
1725 (js2-msg "msg.assn.create.strict"
1726 "Assignment to undeclared variable %s")
1728 (js2-msg "msg.ref.undefined.prop"
1729 "Reference to undefined property '%s'")
1731 (js2-msg "msg.prop.not.found"
1732 "Property %s not found.")
1734 (js2-msg "msg.invalid.type"
1735 "Invalid JavaScript value of type %s")
1737 (js2-msg "msg.primitive.expected"
1738 "Primitive type expected (had %s instead)")
1740 (js2-msg "msg.namespace.expected"
1741 "Namespace object expected to left of :: (found %s instead)")
1743 (js2-msg "msg.null.to.object"
1744 "Cannot convert null to an object.")
1746 (js2-msg "msg.undef.to.object"
1747 "Cannot convert undefined to an object.")
1749 (js2-msg "msg.cyclic.value"
1750 "Cyclic %s value not allowed.")
1752 (js2-msg "msg.is.not.defined"
1753 "'%s' is not defined.")
1755 (js2-msg "msg.undef.prop.read"
1756 "Cannot read property '%s' from %s")
1758 (js2-msg "msg.undef.prop.write"
1759 "Cannot set property '%s' of %s to '%s'")
1761 (js2-msg "msg.undef.prop.delete"
1762 "Cannot delete property '%s' of %s")
1764 (js2-msg "msg.undef.method.call"
1765 "Cannot call method '%s' of %s")
1767 (js2-msg "msg.undef.with"
1768 "Cannot apply 'with' to %s")
1770 (js2-msg "msg.isnt.function"
1771 "%s is not a function, it is %s.")
1773 (js2-msg "msg.isnt.function.in"
1774 "Cannot call property %s in object %s. "
1775 "It is not a function, it is '%s'.")
1777 (js2-msg "msg.function.not.found"
1778 "Cannot find function %s.")
1780 (js2-msg "msg.function.not.found.in"
1781 "Cannot find function %s in object %s.")
1783 (js2-msg "msg.isnt.xml.object"
1784 "%s is not an xml object.")
1786 (js2-msg "msg.no.ref.to.get"
1787 "%s is not a reference to read reference value.")
1789 (js2-msg "msg.no.ref.to.set"
1790 "%s is not a reference to set reference value to %s.")
1792 (js2-msg "msg.no.ref.from.function"
1793 "Function %s can not be used as the left-hand "
1794 "side of assignment or as an operand of ++ or -- operator.")
1796 (js2-msg "msg.bad.default.value"
1797 "Object's getDefaultValue() method returned an object.")
1799 (js2-msg "msg.instanceof.not.object"
1800 "Can't use instanceof on a non-object.")
1802 (js2-msg "msg.instanceof.bad.prototype"
1803 "'prototype' property of %s is not an object.")
1805 (js2-msg "msg.bad.radix"
1806 "illegal radix %s.")
1809 (js2-msg "msg.default.value"
1810 "Cannot find default value for object.")
1812 (js2-msg "msg.zero.arg.ctor"
1813 "Cannot load class '%s' which has no zero-parameter constructor.")
1815 (js2-msg "msg.ctor.multiple.parms"
1816 "Can't define constructor or class %s since more than "
1817 "one constructor has multiple parameters.")
1819 (js2-msg "msg.extend.scriptable"
1820 "%s must extend ScriptableObject in order to define property %s.")
1822 (js2-msg "msg.bad.getter.parms"
1823 "In order to define a property, getter %s must have zero "
1824 "parameters or a single ScriptableObject parameter.")
1826 (js2-msg "msg.obj.getter.parms"
1827 "Expected static or delegated getter %s to take "
1828 "a ScriptableObject parameter.")
1830 (js2-msg "msg.getter.static"
1831 "Getter and setter must both be static or neither be static.")
1833 (js2-msg "msg.setter.return"
1834 "Setter must have void return type: %s")
1836 (js2-msg "msg.setter2.parms"
1837 "Two-parameter setter must take a ScriptableObject as "
1838 "its first parameter.")
1840 (js2-msg "msg.setter1.parms"
1841 "Expected single parameter setter for %s")
1843 (js2-msg "msg.setter2.expected"
1844 "Expected static or delegated setter %s to take two parameters.")
1846 (js2-msg "msg.setter.parms"
1847 "Expected either one or two parameters for setter.")
1849 (js2-msg "msg.setter.bad.type"
1850 "Unsupported parameter type '%s' in setter '%s'.")
1852 (js2-msg "msg.add.sealed"
1853 "Cannot add a property to a sealed object: %s.")
1855 (js2-msg "msg.remove.sealed"
1856 "Cannot remove a property from a sealed object: %s.")
1858 (js2-msg "msg.modify.sealed"
1859 "Cannot modify a property of a sealed object: %s.")
1861 (js2-msg "msg.modify.readonly"
1862 "Cannot modify readonly property: %s.")
1865 (js2-msg "msg.missing.exponent"
1868 (js2-msg "msg.caught.nfe"
1869 "number format error")
1871 (js2-msg "msg.unterminated.string.lit"
1872 "unterminated string literal")
1874 (js2-msg "msg.unterminated.comment"
1875 "unterminated comment")
1877 (js2-msg "msg.unterminated.re.lit"
1878 "unterminated regular expression literal")
1880 (js2-msg "msg.invalid.re.flag"
1881 "invalid flag after regular expression")
1883 (js2-msg "msg.no.re.input.for"
1886 (js2-msg "msg.illegal.character"
1887 "illegal character")
1889 (js2-msg "msg.invalid.escape"
1890 "invalid Unicode escape sequence")
1892 (js2-msg "msg.bad.namespace"
1893 "not a valid default namespace statement. "
1894 "Syntax is: default xml namespace = EXPRESSION;")
1896 ;; TokensStream warnings
1897 (js2-msg "msg.bad.octal.literal"
1898 "illegal octal literal digit %s; "
1899 "interpreting it as a decimal digit")
1901 (js2-msg "msg.reserved.keyword"
1902 "illegal usage of future reserved keyword %s; "
1903 "interpreting it as ordinary identifier")
1905 (js2-msg "msg.script.is.not.constructor"
1906 "Script objects are not constructors.")
1909 (js2-msg "msg.arraylength.bad"
1910 "Inappropriate array length.")
1913 (js2-msg "msg.arraylength.too.big"
1914 "Array length %s exceeds supported capacity limit.")
1917 (js2-msg "msg.bad.uri"
1918 "Malformed URI sequence.")
1921 (js2-msg "msg.bad.precision"
1922 "Precision %s out of range.")
1925 (js2-msg "msg.send.newborn"
1926 "Attempt to send value to newborn generator")
1928 (js2-msg "msg.already.exec.gen"
1929 "Already executing generator")
1931 (js2-msg "msg.StopIteration.invalid"
1932 "StopIteration may not be changed to an arbitrary object.")
1935 (js2-msg "msg.yield.closing"
1936 "Yield from closing generator")
1940 (defun js2-delete-if (predicate list)
1941 "Remove all items satisfying PREDICATE in LIST."
1942 (loop for item in list
1943 if (not (funcall predicate item))
1946 (defun js2-position (element list)
1947 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1948 Returns nil if element is not found in the list."
1951 (while (and list (not found))
1952 (if (eq element (car list))
1954 (setq count (1+ count)
1958 (defun js2-find-if (predicate list)
1959 "Find first item satisfying PREDICATE in LIST."
1961 (while (and list (not result))
1962 (if (funcall predicate (car list))
1963 (setq result (car list)))
1964 (setq list (cdr list)))
1967 (defmacro js2-time (form)
1968 "Evaluate FORM, discard result, and return elapsed time in sec."
1970 (let ((beg (make-symbol "--js2-time-beg--"))
1971 (delta (make-symbol "--js2-time-end--")))
1972 `(let ((,beg (current-time))
1975 (/ (truncate (* (- (float-time (current-time))
1980 (defsubst js2-same-line (pos)
1981 "Return t if POS is on the same line as current point."
1982 (and (>= pos (point-at-bol))
1983 (<= pos (point-at-eol))))
1985 (defun js2-same-line-2 (p1 p2)
1986 "Return t if P1 is on the same line as P2."
1989 (js2-same-line p2)))
1991 (defun js2-code-bug ()
1992 "Signal an error when we encounter an unexpected code path."
1993 (error "failed assertion"))
1995 (defsubst js2-record-text-property (beg end prop value)
1996 "Record a text property to set when parsing finishes."
1997 (push (list beg end prop value) js2-mode-deferred-properties))
1999 ;; I'd like to associate errors with nodes, but for now the
2000 ;; easiest thing to do is get the context info from the last token.
2001 (defun js2-record-parse-error (msg &optional arg pos len)
2002 (push (list (list msg arg)
2003 (or pos js2-token-beg)
2004 (or len (- js2-token-end js2-token-beg)))
2007 (defun js2-report-error (msg &optional msg-arg pos len)
2008 "Signal a syntax error or record a parse error."
2009 (if js2-recover-from-parse-errors
2010 (js2-record-parse-error msg msg-arg pos len)
2011 (signal 'js2-syntax-error
2015 (goto-char js2-ts-cursor)
2019 (defun js2-report-warning (msg &optional msg-arg pos len)
2020 (if js2-compiler-report-warning-as-error
2021 (js2-report-error msg msg-arg pos len)
2022 (push (list (list msg msg-arg)
2023 (or pos js2-token-beg)
2024 (or len (- js2-token-end js2-token-beg)))
2025 js2-parsed-warnings)))
2027 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2028 (if js2-compiler-strict-mode
2029 (js2-report-warning msg-id msg-arg beg
2030 (and beg end (- end beg)))))
2032 (put 'js2-syntax-error 'error-conditions
2033 '(error syntax-error js2-syntax-error))
2034 (put 'js2-syntax-error 'error-message "Syntax error")
2036 (put 'js2-parse-error 'error-conditions
2037 '(error parse-error js2-parse-error))
2038 (put 'js2-parse-error 'error-message "Parse error")
2040 (defmacro js2-clear-flag (flags flag)
2041 `(setq ,flags (logand ,flags (lognot ,flag))))
2043 (defmacro js2-set-flag (flags flag)
2044 "Logical-or FLAG into FLAGS."
2045 `(setq ,flags (logior ,flags ,flag)))
2047 (defsubst js2-flag-set-p (flags flag)
2048 (/= 0 (logand flags flag)))
2050 (defsubst js2-flag-not-set-p (flags flag)
2051 (zerop (logand flags flag)))
2053 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2054 "Evaluate BODY with the _ character set to be word-syntax."
2055 (declare (indent 0) (debug t))
2056 (let ((old-syntax (make-symbol "old-syntax")))
2057 `(let ((,old-syntax (string (char-syntax ?_))))
2060 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2062 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2064 (defsubst js2-char-uppercase-p (c)
2065 "Return t if C is an uppercase character.
2066 Handles unicode and latin chars properly."
2067 (/= c (downcase c)))
2069 (defsubst js2-char-lowercase-p (c)
2070 "Return t if C is an uppercase character.
2071 Handles unicode and latin chars properly."
2074 ;;; AST struct and function definitions
2076 ;; flags for ast node property 'member-type (used for e4x operators)
2077 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2078 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2079 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2081 (defsubst js2-relpos (pos anchor)
2082 "Convert POS to be relative to ANCHOR.
2083 If POS is nil, returns nil."
2084 (and pos (- pos anchor)))
2086 (defun js2-make-pad (indent)
2089 (make-string (* indent js2-basic-offset) ? )))
2091 (defun js2-visit-ast (node callback)
2092 "Visit every node in ast NODE with visitor CALLBACK.
2094 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2095 called twice: once to visit the node, and again after all the node's
2096 children have been processed. The END-P argument is nil on the first
2097 call and non-nil on the second call. The return value of the callback
2098 affects the traversal: if non-nil, the children of NODE are processed.
2099 If the callback returns nil, or if the node has no children, then the
2100 callback is called immediately with a non-nil END-P argument.
2102 The node traversal is approximately lexical-order, although there
2103 are currently no guarantees around this."
2105 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2107 (when (funcall callback node nil)
2110 ((eq vfunc 'js2-visit-none)
2111 nil) ; don't even bother calling it
2112 ;; Each AST node type has to define a `js2-visitor' function
2113 ;; that takes a node and a callback, and calls `js2-visit-ast'
2114 ;; on each child of the node.
2116 (funcall vfunc node callback))
2118 (error "%s does not define a visitor-traversal function"
2120 ;; call the end-visit
2121 (funcall callback node t))))
2123 (defstruct (js2-node
2124 (:constructor nil)) ; abstract
2125 "Base AST node type."
2126 (type -1) ; token type
2127 (pos -1) ; start position of this AST node in parsed input
2128 (len 1) ; num characters spanned by the node
2129 props ; optional node property list (an alist)
2130 parent) ; link to parent node; null for root
2132 (defsubst js2-node-get-prop (node prop &optional default)
2133 (or (cadr (assoc prop (js2-node-props node))) default))
2135 (defsubst js2-node-set-prop (node prop value)
2136 (setf (js2-node-props node)
2137 (cons (list prop value) (js2-node-props node))))
2139 (defun js2-fixup-starts (n nodes)
2140 "Adjust the start positions of NODES to be relative to N.
2141 Any node in the list may be nil, for convenience."
2142 (dolist (node nodes)
2144 (setf (js2-node-pos node) (- (js2-node-pos node)
2145 (js2-node-pos n))))))
2147 (defun js2-node-add-children (parent &rest nodes)
2148 "Set parent node of NODES to PARENT, and return PARENT.
2149 Does nothing if we're not recording parent links.
2150 If any given node in NODES is nil, doesn't record that link."
2151 (js2-fixup-starts parent nodes)
2152 (dolist (node nodes)
2154 (setf (js2-node-parent node) parent))))
2156 ;; Non-recursive since it's called a frightening number of times.
2157 (defun js2-node-abs-pos (n)
2158 (let ((pos (js2-node-pos n)))
2159 (while (setq n (js2-node-parent n))
2160 (setq pos (+ pos (js2-node-pos n))))
2163 (defsubst js2-node-abs-end (n)
2164 "Return absolute buffer position of end of N."
2165 (+ (js2-node-abs-pos n) (js2-node-len n)))
2167 ;; It's important to make sure block nodes have a Lisp list for the
2168 ;; child nodes, to limit printing recursion depth in an AST that
2169 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2170 ;; a sufficiently large vector tree.
2172 (defstruct (js2-block-node
2175 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2180 "A block of statements."
2181 kids) ; a Lisp list of the child statement nodes
2183 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2184 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2186 (defun js2-visit-block (ast callback)
2187 "Visit the `js2-block-node' children of AST."
2188 (dolist (kid (js2-block-node-kids ast))
2189 (js2-visit-ast kid callback)))
2191 (defun js2-print-block (n i)
2192 (let ((pad (js2-make-pad i)))
2194 (dolist (kid (js2-block-node-kids n))
2195 (js2-print-ast kid (1+ i)))
2198 (defstruct (js2-scope
2199 (:include js2-block-node)
2201 (:constructor make-js2-scope (&key (type js2-BLOCK)
2205 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2206 ;; I don't have one of those handy, so I'll use an alist for now.
2207 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2208 ;; and is much lighter-weight to construct (both CPU and mem).
2209 ;; The keys are interned strings (symbols) for faster lookup.
2210 ;; Should switch to hybrid alist/hashtable eventually.
2211 symbol-table ; an alist of (symbol . js2-symbol)
2212 parent-scope ; a `js2-scope'
2213 top) ; top-level `js2-scope' (script/function)
2215 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2216 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2218 (defun js2-scope-set-parent-scope (scope parent)
2219 (setf (js2-scope-parent-scope scope) parent
2220 (js2-scope-top scope) (if (null parent)
2222 (js2-scope-top parent))))
2224 (defun js2-node-get-enclosing-scope (node)
2225 "Return the innermost `js2-scope' node surrounding NODE.
2226 Returns nil if there is no enclosing scope node."
2227 (let ((parent (js2-node-parent node)))
2228 (while (not (js2-scope-p parent))
2229 (setq parent (js2-node-parent parent)))
2232 (defun js2-get-defining-scope (scope name)
2233 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2234 Returns `js2-scope' in which NAME is defined, or nil if not found."
2235 (let ((sym (if (symbolp name)
2241 (while (and scope continue)
2242 (if (and (setq table (js2-scope-symbol-table scope))
2246 (setq scope (js2-scope-parent-scope scope))))
2249 (defun js2-scope-get-symbol (scope name)
2250 "Return symbol table entry for NAME in SCOPE.
2251 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2252 (and (js2-scope-symbol-table scope)
2253 (cdr (assq (if (symbolp name)
2256 (js2-scope-symbol-table scope)))))
2258 (defun js2-scope-put-symbol (scope name symbol)
2259 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2260 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2261 (let* ((table (js2-scope-symbol-table scope))
2262 (sym (if (symbolp name) name (intern name)))
2263 (entry (assq sym table)))
2265 (setcdr entry symbol)
2266 (push (cons sym symbol)
2267 (js2-scope-symbol-table scope)))))
2269 (defstruct (js2-symbol
2271 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2272 "A symbol table entry."
2273 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2274 ;; js2-LET, or js2-CONST
2277 ast-node) ; a `js2-node'
2279 (defstruct (js2-error-node
2281 (:constructor nil) ; silence emacs21 byte-compiler
2282 (:constructor make-js2-error-node (&key (type js2-ERROR)
2285 "AST node representing a parse error.")
2287 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2288 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2290 (defstruct (js2-script-node
2291 (:include js2-scope)
2293 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2298 functions ; Lisp list of nested functions
2299 regexps ; Lisp list of (string . flags)
2300 symbols ; alist (every symbol gets unique index)
2302 var-names ; vector of string names
2303 consts ; bool-vector matching var-decls
2304 (temp-number 0)) ; for generating temp variables
2306 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2307 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2309 (defun js2-print-script (node indent)
2310 (dolist (kid (js2-block-node-kids node))
2311 (js2-print-ast kid indent)))
2313 (defstruct (js2-ast-root
2314 (:include js2-script-node)
2316 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2320 "The root node of a js2 AST."
2321 buffer ; the source buffer from which the code was parsed
2322 comments ; a Lisp list of comments, ordered by start position
2323 errors ; a Lisp list of errors found during parsing
2324 warnings ; a Lisp list of warnings found during parsing
2325 node-count) ; number of nodes in the tree, including the root
2327 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2328 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2330 (defun js2-visit-ast-root (ast callback)
2331 (dolist (kid (js2-ast-root-kids ast))
2332 (js2-visit-ast kid callback))
2333 (dolist (comment (js2-ast-root-comments ast))
2334 (js2-visit-ast comment callback)))
2336 (defstruct (js2-comment-node
2339 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2342 (format js2-ts-comment-type))))
2343 format) ; 'line, 'block, 'jsdoc or 'html
2345 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2346 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2348 (defun js2-print-comment (n i)
2349 ;; We really ought to link end-of-line comments to their nodes.
2350 ;; Or maybe we could add a new comment type, 'endline.
2351 (insert (js2-make-pad i)
2352 (js2-node-string n)))
2354 (defstruct (js2-expr-stmt-node
2357 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2361 "An expression statement."
2364 (defsubst js2-expr-stmt-node-set-has-result (node)
2365 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2366 (setf (js2-node-type node) js2-EXPR_RESULT))
2368 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2369 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2371 (defun js2-visit-expr-stmt-node (n v)
2372 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2374 (defun js2-print-expr-stmt-node (n indent)
2375 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2378 (defstruct (js2-loop-node
2379 (:include js2-scope)
2381 "Abstract supertype of loop nodes."
2382 body ; a `js2-block-node'
2383 lp ; position of left-paren, nil if omitted
2384 rp) ; position of right-paren, nil if omitted
2386 (defstruct (js2-do-node
2387 (:include js2-loop-node)
2389 (:constructor make-js2-do-node (&key (type js2-DO)
2397 "AST node for do-loop."
2398 condition ; while (expression)
2399 while-pos) ; buffer position of 'while' keyword
2401 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2402 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2404 (defun js2-visit-do-node (n v)
2405 (js2-visit-ast (js2-do-node-body n) v)
2406 (js2-visit-ast (js2-do-node-condition n) v))
2408 (defun js2-print-do-node (n i)
2409 (let ((pad (js2-make-pad i)))
2410 (insert pad "do {\n")
2411 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2412 (js2-print-ast kid (1+ i)))
2413 (insert pad "} while (")
2414 (js2-print-ast (js2-do-node-condition n) 0)
2417 (defstruct (js2-while-node
2418 (:include js2-loop-node)
2420 (:constructor make-js2-while-node (&key (type js2-WHILE)
2425 "AST node for while-loop."
2426 condition) ; while-condition
2428 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2429 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2431 (defun js2-visit-while-node (n v)
2432 (js2-visit-ast (js2-while-node-condition n) v)
2433 (js2-visit-ast (js2-while-node-body n) v))
2435 (defun js2-print-while-node (n i)
2436 (let ((pad (js2-make-pad i)))
2437 (insert pad "while (")
2438 (js2-print-ast (js2-while-node-condition n) 0)
2440 (js2-print-body (js2-while-node-body n) (1+ i))
2441 (insert pad "}\n")))
2443 (defstruct (js2-for-node
2444 (:include js2-loop-node)
2446 (:constructor make-js2-for-node (&key (type js2-FOR)
2451 "AST node for a C-style for-loop."
2452 init ; initialization expression
2453 condition ; loop condition
2454 update) ; update clause
2456 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2457 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2459 (defun js2-visit-for-node (n v)
2460 (js2-visit-ast (js2-for-node-init n) v)
2461 (js2-visit-ast (js2-for-node-condition n) v)
2462 (js2-visit-ast (js2-for-node-update n) v)
2463 (js2-visit-ast (js2-for-node-body n) v))
2465 (defun js2-print-for-node (n i)
2466 (let ((pad (js2-make-pad i)))
2467 (insert pad "for (")
2468 (js2-print-ast (js2-for-node-init n) 0)
2470 (js2-print-ast (js2-for-node-condition n) 0)
2472 (js2-print-ast (js2-for-node-update n) 0)
2474 (js2-print-body (js2-for-node-body n) (1+ i))
2475 (insert pad "}\n")))
2477 (defstruct (js2-for-in-node
2478 (:include js2-loop-node)
2480 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2489 "AST node for a for..in loop."
2490 iterator ; [var] foo in ...
2491 object ; object over which we're iterating
2492 in-pos ; buffer position of 'in' keyword
2493 each-pos ; buffer position of 'each' keyword, if foreach-p
2494 foreach-p) ; t if it's a for-each loop
2496 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2497 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2499 (defun js2-visit-for-in-node (n v)
2500 (js2-visit-ast (js2-for-in-node-iterator n) v)
2501 (js2-visit-ast (js2-for-in-node-object n) v)
2502 (js2-visit-ast (js2-for-in-node-body n) v))
2504 (defun js2-print-for-in-node (n i)
2505 (let ((pad (js2-make-pad i))
2506 (foreach (js2-for-in-node-foreach-p n)))
2511 (js2-print-ast (js2-for-in-node-iterator n) 0)
2513 (js2-print-ast (js2-for-in-node-object n) 0)
2515 (js2-print-body (js2-for-in-node-body n) (1+ i))
2516 (insert pad "}\n")))
2518 (defstruct (js2-return-node
2521 (:constructor make-js2-return-node (&key (type js2-RETURN)
2525 "AST node for a return statement."
2526 retval) ; expression to return, or 'undefined
2528 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2529 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2531 (defun js2-visit-return-node (n v)
2532 (js2-visit-ast (js2-return-node-retval n) v))
2534 (defun js2-print-return-node (n i)
2535 (insert (js2-make-pad i) "return")
2536 (when (js2-return-node-retval n)
2538 (js2-print-ast (js2-return-node-retval n) 0))
2541 (defstruct (js2-if-node
2544 (:constructor make-js2-if-node (&key (type js2-IF)
2551 "AST node for an if-statement."
2552 condition ; expression
2553 then-part ; statement or block
2554 else-pos ; optional buffer position of 'else' keyword
2555 else-part ; optional statement or block
2556 lp ; position of left-paren, nil if omitted
2557 rp) ; position of right-paren, nil if omitted
2559 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2560 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2562 (defun js2-visit-if-node (n v)
2563 (js2-visit-ast (js2-if-node-condition n) v)
2564 (js2-visit-ast (js2-if-node-then-part n) v)
2565 (js2-visit-ast (js2-if-node-else-part n) v))
2567 (defun js2-print-if-node (n i)
2568 (let ((pad (js2-make-pad i))
2569 (then-part (js2-if-node-then-part n))
2570 (else-part (js2-if-node-else-part n)))
2572 (js2-print-ast (js2-if-node-condition n) 0)
2574 (js2-print-body then-part (1+ i))
2579 ((js2-if-node-p else-part)
2581 (js2-print-body else-part i))
2583 (insert " else {\n")
2584 (js2-print-body else-part (1+ i))
2585 (insert pad "}\n")))))
2587 (defstruct (js2-try-node
2590 (:constructor make-js2-try-node (&key (type js2-TRY)
2596 "AST node for a try-statement."
2598 catch-clauses ; a Lisp list of `js2-catch-node'
2599 finally-block) ; a `js2-finally-node'
2601 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2602 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2604 (defun js2-visit-try-node (n v)
2605 (js2-visit-ast (js2-try-node-try-block n) v)
2606 (dolist (clause (js2-try-node-catch-clauses n))
2607 (js2-visit-ast clause v))
2608 (js2-visit-ast (js2-try-node-finally-block n) v))
2610 (defun js2-print-try-node (n i)
2611 (let ((pad (js2-make-pad i))
2612 (catches (js2-try-node-catch-clauses n))
2613 (finally (js2-try-node-finally-block n)))
2614 (insert pad "try {\n")
2615 (js2-print-body (js2-try-node-try-block n) (1+ i))
2618 (dolist (catch catches)
2619 (js2-print-ast catch i)))
2621 (js2-print-ast finally i)
2624 (defstruct (js2-catch-node
2627 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2635 "AST node for a catch clause."
2636 param ; destructuring form or simple name node
2637 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2638 guard-expr ; catch condition, a `js2-node'
2639 block ; statements, a `js2-block-node'
2640 lp ; buffer position of left-paren, nil if omitted
2641 rp) ; buffer position of right-paren, nil if omitted
2643 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2644 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2646 (defun js2-visit-catch-node (n v)
2647 (js2-visit-ast (js2-catch-node-param n) v)
2648 (when (js2-catch-node-guard-kwd n)
2649 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2650 (js2-visit-ast (js2-catch-node-block n) v))
2652 (defun js2-print-catch-node (n i)
2653 (let ((pad (js2-make-pad i))
2654 (guard-kwd (js2-catch-node-guard-kwd n))
2655 (guard-expr (js2-catch-node-guard-expr n)))
2657 (js2-print-ast (js2-catch-node-param n) 0)
2660 (js2-print-ast guard-expr 0))
2662 (js2-print-body (js2-catch-node-block n) (1+ i))
2665 (defstruct (js2-finally-node
2668 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2671 "AST node for a finally clause."
2672 body) ; a `js2-node', often but not always a block node
2674 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2675 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2677 (defun js2-visit-finally-node (n v)
2678 (js2-visit-ast (js2-finally-node-body n) v))
2680 (defun js2-print-finally-node (n i)
2681 (let ((pad (js2-make-pad i)))
2682 (insert " finally {\n")
2683 (js2-print-body (js2-finally-node-body n) (1+ i))
2684 (insert pad "}\n")))
2686 (defstruct (js2-switch-node
2689 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2695 "AST node for a switch statement."
2696 discriminant ; a `js2-node' (switch expression)
2697 cases ; a Lisp list of `js2-case-node'
2698 lp ; position of open-paren for discriminant, nil if omitted
2699 rp) ; position of close-paren for discriminant, nil if omitted
2701 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2702 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2704 (defun js2-visit-switch-node (n v)
2705 (js2-visit-ast (js2-switch-node-discriminant n) v)
2706 (dolist (c (js2-switch-node-cases n))
2707 (js2-visit-ast c v)))
2709 (defun js2-print-switch-node (n i)
2710 (let ((pad (js2-make-pad i))
2711 (cases (js2-switch-node-cases n)))
2712 (insert pad "switch (")
2713 (js2-print-ast (js2-switch-node-discriminant n) 0)
2715 (dolist (case cases)
2716 (js2-print-ast case i))
2717 (insert pad "}\n")))
2719 (defstruct (js2-case-node
2720 (:include js2-block-node)
2722 (:constructor make-js2-case-node (&key (type js2-CASE)
2725 "AST node for a case clause of a switch statement."
2726 expr) ; the case expression (nil for default)
2728 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2729 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2731 (defun js2-visit-case-node (n v)
2732 (js2-visit-ast (js2-case-node-expr n) v)
2733 (js2-visit-block n v))
2735 (defun js2-print-case-node (n i)
2736 (let ((pad (js2-make-pad i))
2737 (expr (js2-case-node-expr n)))
2740 (insert "default:\n")
2742 (js2-print-ast expr 0)
2744 (dolist (kid (js2-case-node-kids n))
2745 (js2-print-ast kid (1+ i)))))
2747 (defstruct (js2-throw-node
2750 (:constructor make-js2-throw-node (&key (type js2-THROW)
2753 "AST node for a throw statement."
2754 expr) ; the expression to throw
2756 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2757 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2759 (defun js2-visit-throw-node (n v)
2760 (js2-visit-ast (js2-throw-node-expr n) v))
2762 (defun js2-print-throw-node (n i)
2763 (insert (js2-make-pad i) "throw ")
2764 (js2-print-ast (js2-throw-node-expr n) 0)
2767 (defstruct (js2-with-node
2770 (:constructor make-js2-with-node (&key (type js2-WITH)
2774 "AST node for a with-statement."
2777 lp ; buffer position of left-paren around object, nil if omitted
2778 rp) ; buffer position of right-paren around object, nil if omitted
2780 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2781 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2783 (defun js2-visit-with-node (n v)
2784 (js2-visit-ast (js2-with-node-object n) v)
2785 (js2-visit-ast (js2-with-node-body n) v))
2787 (defun js2-print-with-node (n i)
2788 (let ((pad (js2-make-pad i)))
2789 (insert pad "with (")
2790 (js2-print-ast (js2-with-node-object n) 0)
2792 (js2-print-body (js2-with-node-body n) (1+ i))
2793 (insert pad "}\n")))
2795 (defstruct (js2-label-node
2798 (:constructor make-js2-label-node (&key (type js2-LABEL)
2801 "AST node for a statement label or case label."
2803 loop) ; for validating and code-generating continue-to-label
2805 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2806 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2808 (defun js2-print-label (n i)
2809 (insert (js2-make-pad i)
2810 (js2-label-node-name n)
2813 (defstruct (js2-labeled-stmt-node
2816 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2817 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2818 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2821 "AST node for a statement with one or more labels.
2822 Multiple labels for a statement are collapsed into the labels field."
2823 labels ; Lisp list of `js2-label-node'
2824 stmt) ; the statement these labels are for
2826 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2827 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2829 (defun js2-get-label-by-name (lbl-stmt name)
2830 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2831 Returns nil if no such label is in the list."
2832 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2834 (while (and label-list (not result))
2835 (if (string= (js2-label-node-name (car label-list)) name)
2836 (setq result (car label-list))
2837 (setq label-list (cdr label-list))))
2840 (defun js2-visit-labeled-stmt (n v)
2841 (dolist (label (js2-labeled-stmt-node-labels n))
2842 (js2-visit-ast label v))
2843 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2845 (defun js2-print-labeled-stmt (n i)
2846 (dolist (label (js2-labeled-stmt-node-labels n))
2847 (js2-print-ast label i))
2848 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2850 (defun js2-labeled-stmt-node-contains (node label)
2851 "Return t if NODE contains LABEL in its label set.
2852 NODE is a `js2-labels-node'. LABEL is an identifier."
2853 (loop for nl in (js2-labeled-stmt-node-labels node)
2854 if (string= label (js2-label-node-name nl))
2856 finally return nil))
2858 (defsubst js2-labeled-stmt-node-add-label (node label)
2859 "Add a `js2-label-node' to the label set for this statement."
2860 (setf (js2-labeled-stmt-node-labels node)
2861 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2863 (defstruct (js2-jump-node
2866 "Abstract supertype of break and continue nodes."
2867 label ; `js2-name-node' for location of label identifier, if present
2868 target) ; target js2-labels-node or loop/switch statement
2870 (defun js2-visit-jump-node (n v)
2871 ;; We don't visit the target, since it's a back-link.
2872 (js2-visit-ast (js2-jump-node-label n) v))
2874 (defstruct (js2-break-node
2875 (:include js2-jump-node)
2877 (:constructor make-js2-break-node (&key (type js2-BREAK)
2880 "AST node for a break statement.
2881 The label field is a `js2-name-node', possibly nil, for the named label
2882 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2883 is the target of the break - a label node or enclosing loop/switch statement.")
2885 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2886 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2888 (defun js2-print-break-node (n i)
2889 (insert (js2-make-pad i) "break")
2890 (when (js2-break-node-label n)
2892 (js2-print-ast (js2-break-node-label n) 0))
2895 (defstruct (js2-continue-node
2896 (:include js2-jump-node)
2898 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2901 "AST node for a continue statement.
2902 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2903 It is nil if continue specifies no label. The target field is the jump target:
2904 a `js2-label-node' or the innermost enclosing loop.")
2906 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2907 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2909 (defun js2-print-continue-node (n i)
2910 (insert (js2-make-pad i) "continue")
2911 (when (js2-continue-node-label n)
2913 (js2-print-ast (js2-continue-node-label n) 0))
2916 (defstruct (js2-function-node
2917 (:include js2-script-node)
2919 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2923 (form 'FUNCTION_STATEMENT)
2927 "AST node for a function declaration.
2928 The `params' field is a Lisp list of nodes. Each node is either a simple
2929 `js2-name-node', or if it's a destructuring-assignment parameter, a
2930 `js2-array-node' or `js2-object-node'."
2931 ftype ; FUNCTION, GETTER or SETTER
2932 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2933 name ; function name (a `js2-name-node', or nil if anonymous)
2934 params ; a Lisp list of destructuring forms or simple name nodes
2935 body ; a `js2-block-node' or expression node (1.8 only)
2936 lp ; position of arg-list open-paren, or nil if omitted
2937 rp ; position of arg-list close-paren, or nil if omitted
2938 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2939 needs-activation ; t if we need an activation object for this frame
2940 is-generator ; t if this function contains a yield
2941 member-expr) ; nonstandard Ecma extension from Rhino
2943 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2944 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2946 (defun js2-visit-function-node (n v)
2947 (js2-visit-ast (js2-function-node-name n) v)
2948 (dolist (p (js2-function-node-params n))
2949 (js2-visit-ast p v))
2950 (js2-visit-ast (js2-function-node-body n) v))
2952 (defun js2-print-function-node (n i)
2953 (let ((pad (js2-make-pad i))
2954 (getter (js2-node-get-prop n 'GETTER_SETTER))
2955 (name (js2-function-node-name n))
2956 (params (js2-function-node-params n))
2957 (body (js2-function-node-body n))
2958 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2960 (insert pad "function"))
2963 (js2-print-ast name 0))
2965 (loop with len = (length params)
2969 (js2-print-ast param 0)
2975 ;; TODO: fix this to be smarter about indenting, etc.
2976 (js2-print-body body (1+ i))
2981 (defun js2-function-name (node)
2982 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2983 (and (js2-function-node-name node)
2984 (js2-name-node-name (js2-function-node-name node))))
2986 ;; Having this be an expression node makes it more flexible.
2987 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2988 ;; that work better if you assume it's an expression. Whenever we have
2989 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2990 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2991 (defstruct (js2-var-decl-node
2994 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2998 "AST node for a variable declaration list (VAR, CONST or LET).
2999 The node bounds differ depending on the declaration type. For VAR or
3000 CONST declarations, the bounds include the var/const keyword. For LET
3001 declarations, the node begins at the position of the first child."
3002 kids ; a Lisp list of `js2-var-init-node' structs.
3003 decl-type) ; js2-VAR, js2-CONST or js2-LET
3005 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3006 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3008 (defun js2-visit-var-decl (n v)
3009 (dolist (kid (js2-var-decl-node-kids n))
3010 (js2-visit-ast kid v)))
3012 (defun js2-print-var-decl (n i)
3013 (let ((pad (js2-make-pad i))
3014 (tt (js2-var-decl-node-decl-type n)))
3017 ((= tt js2-VAR) "var ")
3018 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3019 ((= tt js2-CONST) "const ")
3021 (error "malformed var-decl node"))))
3022 (loop with kids = (js2-var-decl-node-kids n)
3023 with len = (length kids)
3027 (js2-print-ast kid 0)
3031 (defstruct (js2-var-init-node
3034 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3038 "AST node for a variable declaration.
3039 The type field will be js2-CONST for a const decl."
3040 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3041 initializer) ; initializer expression, a `js2-node'
3043 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3044 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3046 (defun js2-visit-var-init-node (n v)
3047 (js2-visit-ast (js2-var-init-node-target n) v)
3048 (js2-visit-ast (js2-var-init-node-initializer n) v))
3050 (defun js2-print-var-init-node (n i)
3051 (let ((pad (js2-make-pad i))
3052 (name (js2-var-init-node-target n))
3053 (init (js2-var-init-node-initializer n)))
3055 (js2-print-ast name 0)
3058 (js2-print-ast init 0))))
3060 (defstruct (js2-cond-node
3063 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3070 "AST node for the ternary operator"
3074 q-pos ; buffer position of ?
3075 c-pos) ; buffer position of :
3077 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3078 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3080 (defun js2-visit-cond-node (n v)
3081 (js2-visit-ast (js2-cond-node-test-expr n) v)
3082 (js2-visit-ast (js2-cond-node-true-expr n) v)
3083 (js2-visit-ast (js2-cond-node-false-expr n) v))
3085 (defun js2-print-cond-node (n i)
3086 (let ((pad (js2-make-pad i)))
3088 (js2-print-ast (js2-cond-node-test-expr n) 0)
3090 (js2-print-ast (js2-cond-node-true-expr n) 0)
3092 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3094 (defstruct (js2-infix-node
3097 (:constructor make-js2-infix-node (&key type
3101 "Represents infix expressions.
3102 Includes assignment ops like `|=', and the comma operator.
3103 The type field inherited from `js2-node' holds the operator."
3104 op-pos ; buffer position where operator begins
3105 left ; any `js2-node'
3106 right) ; any `js2-node'
3108 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3109 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3111 (defun js2-visit-infix-node (n v)
3112 (js2-visit-ast (js2-infix-node-left n) v)
3113 (js2-visit-ast (js2-infix-node-right n) v))
3115 (defconst js2-operator-tokens
3116 (let ((table (make-hash-table :test 'eq))
3118 (list (cons js2-IN "in")
3119 (cons js2-TYPEOF "typeof")
3120 (cons js2-INSTANCEOF "instanceof")
3121 (cons js2-DELPROP "delete")
3122 (cons js2-COMMA ",")
3123 (cons js2-COLON ":")
3128 (cons js2-BITOR "|")
3129 (cons js2-BITXOR "^")
3130 (cons js2-BITAND "&")
3139 (cons js2-URSH ">>>")
3140 (cons js2-ADD "+") ; infix plus
3141 (cons js2-SUB "-") ; infix minus
3146 (cons js2-BITNOT "~")
3147 (cons js2-POS "+") ; unary plus
3148 (cons js2-NEG "-") ; unary minus
3149 (cons js2-SHEQ "===") ; shallow equality
3150 (cons js2-SHNE "!==") ; shallow inequality
3151 (cons js2-ASSIGN "=")
3152 (cons js2-ASSIGN_BITOR "|=")
3153 (cons js2-ASSIGN_BITXOR "^=")
3154 (cons js2-ASSIGN_BITAND "&=")
3155 (cons js2-ASSIGN_LSH "<<=")
3156 (cons js2-ASSIGN_RSH ">>=")
3157 (cons js2-ASSIGN_URSH ">>>=")
3158 (cons js2-ASSIGN_ADD "+=")
3159 (cons js2-ASSIGN_SUB "-=")
3160 (cons js2-ASSIGN_MUL "*=")
3161 (cons js2-ASSIGN_DIV "/=")
3162 (cons js2-ASSIGN_MOD "%="))))
3163 (loop for (k . v) in tokens do
3164 (puthash k v table))
3167 (defun js2-print-infix-node (n i)
3168 (let* ((tt (js2-node-type n))
3169 (op (gethash tt js2-operator-tokens)))
3171 (error "unrecognized infix operator %s" (js2-node-type n)))
3172 (insert (js2-make-pad i))
3173 (js2-print-ast (js2-infix-node-left n) 0)
3174 (unless (= tt js2-COMMA)
3178 (js2-print-ast (js2-infix-node-right n) 0)))
3180 (defstruct (js2-assign-node
3181 (:include js2-infix-node)
3183 (:constructor make-js2-assign-node (&key type
3187 "Represents any assignment.
3188 The type field holds the actual assignment operator.")
3190 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3191 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3193 (defstruct (js2-unary-node
3196 (:constructor make-js2-unary-node (&key type ; required
3199 "AST node type for unary operator nodes.
3200 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3201 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3202 property is added if the operator follows the operand."
3203 operand) ; a `js2-node' expression
3205 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3206 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3208 (defun js2-visit-unary-node (n v)
3209 (js2-visit-ast (js2-unary-node-operand n) v))
3211 (defun js2-print-unary-node (n i)
3212 (let* ((tt (js2-node-type n))
3213 (op (gethash tt js2-operator-tokens))
3214 (postfix (js2-node-get-prop n 'postfix)))
3216 (error "unrecognized unary operator %s" tt))
3217 (insert (js2-make-pad i))
3220 (if (or (= tt js2-TYPEOF)
3223 (js2-print-ast (js2-unary-node-operand n) 0)
3227 (defstruct (js2-let-node
3228 (:include js2-scope)
3230 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3234 "AST node for a let expression or a let statement.
3235 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3236 vars ; a `js2-var-decl-node'
3237 body ; a `js2-node' representing the expression or body block
3241 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3242 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3244 (defun js2-visit-let-node (n v)
3245 (js2-visit-ast (js2-let-node-vars n) v)
3246 (js2-visit-ast (js2-let-node-body n) v))
3248 (defun js2-print-let-node (n i)
3249 (insert (js2-make-pad i) "let (")
3250 (js2-print-ast (js2-let-node-vars n) 0)
3252 (js2-print-ast (js2-let-node-body n) i))
3254 (defstruct (js2-keyword-node
3257 (:constructor make-js2-keyword-node (&key type
3259 (len (- js2-ts-cursor pos)))))
3260 "AST node representing a literal keyword such as `null'.
3261 Used for `null', `this', `true', `false' and `debugger'.
3262 The node type is set to js2-NULL, js2-THIS, etc.")
3264 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3265 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3267 (defun js2-print-keyword-node (n i)
3268 (insert (js2-make-pad i)
3269 (let ((tt (js2-node-type n)))
3271 ((= tt js2-THIS) "this")
3272 ((= tt js2-NULL) "null")
3273 ((= tt js2-TRUE) "true")
3274 ((= tt js2-FALSE) "false")
3275 ((= tt js2-DEBUGGER) "debugger")
3276 (t (error "Invalid keyword literal type: %d" tt))))))
3278 (defsubst js2-this-node-p (node)
3279 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3280 (eq (js2-node-type node) js2-THIS))
3282 (defstruct (js2-new-node
3285 (:constructor make-js2-new-node (&key (type js2-NEW)
3290 "AST node for new-expression such as new Foo()."
3291 target ; an identifier or reference
3292 args ; a Lisp list of argument nodes
3293 lp ; position of left-paren, nil if omitted
3294 rp ; position of right-paren, nil if omitted
3295 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3297 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3298 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3300 (defun js2-visit-new-node (n v)
3301 (js2-visit-ast (js2-new-node-target n) v)
3302 (dolist (arg (js2-new-node-args n))
3303 (js2-visit-ast arg v))
3304 (js2-visit-ast (js2-new-node-initializer n) v))
3306 (defun js2-print-new-node (n i)
3307 (insert (js2-make-pad i) "new ")
3308 (js2-print-ast (js2-new-node-target n))
3310 (js2-print-list (js2-new-node-args n))
3312 (when (js2-new-node-initializer n)
3314 (js2-print-ast (js2-new-node-initializer n))))
3316 (defstruct (js2-name-node
3319 (:constructor make-js2-name-node (&key (type js2-NAME)
3321 (len (- js2-ts-cursor
3323 (name js2-ts-string))))
3324 "AST node for a JavaScript identifier"
3326 scope) ; a `js2-scope' (optional, used for codegen)
3328 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3329 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3331 (defun js2-print-name-node (n i)
3332 (insert (js2-make-pad i)
3333 (js2-name-node-name n)))
3335 (defsubst js2-name-node-length (node)
3336 "Return identifier length of NODE, a `js2-name-node'.
3337 Returns 0 if NODE is nil or its identifier field is nil."
3339 (length (js2-name-node-name node))
3342 (defstruct (js2-number-node
3345 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3347 (len (- js2-ts-cursor
3349 (value js2-ts-string)
3350 (num-value js2-ts-number))))
3351 "AST node for a number literal."
3352 value ; the original string, e.g. "6.02e23"
3353 num-value) ; the parsed number value
3355 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3356 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3358 (defun js2-print-number-node (n i)
3359 (insert (js2-make-pad i)
3360 (number-to-string (js2-number-node-num-value n))))
3362 (defstruct (js2-regexp-node
3365 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3367 (len (- js2-ts-cursor
3370 "AST node for a regular expression literal."
3371 value ; the regexp string, without // delimiters
3372 flags) ; a string of flags, e.g. `mi'.
3374 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3375 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3377 (defun js2-print-regexp (n i)
3378 (insert (js2-make-pad i)
3380 (js2-regexp-node-value n)
3382 (if (js2-regexp-node-flags n)
3383 (insert (js2-regexp-node-flags n))))
3385 (defstruct (js2-string-node
3388 (:constructor make-js2-string-node (&key (type js2-STRING)
3390 (len (- js2-ts-cursor
3392 (value js2-ts-string))))
3394 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3395 You can tell the quote type by looking at the first character."
3396 value) ; the characters of the string, including the quotes
3398 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3399 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3401 (defun js2-print-string-node (n i)
3402 (insert (js2-make-pad i)
3403 (js2-node-string n)))
3405 (defstruct (js2-array-node
3408 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3411 "AST node for an array literal."
3412 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3414 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3415 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3417 (defun js2-visit-array-node (n v)
3418 (dolist (e (js2-array-node-elems n))
3419 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3421 (defun js2-print-array-node (n i)
3422 (insert (js2-make-pad i) "[")
3423 (js2-print-list (js2-array-node-elems n))
3426 (defstruct (js2-object-node
3429 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3433 "AST node for an object literal expression.
3434 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3435 The latter represents abbreviation in destructuring expressions."
3438 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3439 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3441 (defun js2-visit-object-node (n v)
3442 (dolist (e (js2-object-node-elems n))
3443 (js2-visit-ast e v)))
3445 (defun js2-print-object-node (n i)
3446 (insert (js2-make-pad i) "{")
3447 (js2-print-list (js2-object-node-elems n))
3450 (defstruct (js2-object-prop-node
3451 (:include js2-infix-node)
3453 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3457 "AST node for an object literal prop:value entry.
3458 The `left' field is the property: a name node, string node or number node.
3459 The `right' field is a `js2-node' representing the initializer value.")
3461 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3462 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3464 (defun js2-print-object-prop-node (n i)
3465 (insert (js2-make-pad i))
3466 (js2-print-ast (js2-object-prop-node-left n) 0)
3468 (js2-print-ast (js2-object-prop-node-right n) 0))
3470 (defstruct (js2-getter-setter-node
3471 (:include js2-infix-node)
3473 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3476 "AST node for a getter/setter property in an object literal.
3477 The `left' field is the `js2-name-node' naming the getter/setter prop.
3478 The `right' field is always an anonymous `js2-function-node' with a node
3479 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3481 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3482 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3484 (defun js2-print-getter-setter (n i)
3485 (let ((pad (js2-make-pad i))
3486 (left (js2-getter-setter-node-left n))
3487 (right (js2-getter-setter-node-right n)))
3489 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3490 (js2-print-ast left 0)
3491 (js2-print-ast right 0)))
3493 (defstruct (js2-prop-get-node
3494 (:include js2-infix-node)
3496 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3499 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3501 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3502 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3504 (defun js2-visit-prop-get-node (n v)
3505 (js2-visit-ast (js2-prop-get-node-left n) v)
3506 (js2-visit-ast (js2-prop-get-node-right n) v))
3508 (defun js2-print-prop-get-node (n i)
3509 (insert (js2-make-pad i))
3510 (js2-print-ast (js2-prop-get-node-left n) 0)
3512 (js2-print-ast (js2-prop-get-node-right n) 0))
3514 (defstruct (js2-elem-get-node
3517 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3521 "AST node for an array index expression such as foo[bar]."
3522 target ; a `js2-node' - the expression preceding the "."
3523 element ; a `js2-node' - the expression in brackets
3524 lb ; position of left-bracket, nil if omitted
3525 rb) ; position of right-bracket, nil if omitted
3527 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3528 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3530 (defun js2-visit-elem-get-node (n v)
3531 (js2-visit-ast (js2-elem-get-node-target n) v)
3532 (js2-visit-ast (js2-elem-get-node-element n) v))
3534 (defun js2-print-elem-get-node (n i)
3535 (insert (js2-make-pad i))
3536 (js2-print-ast (js2-elem-get-node-target n) 0)
3538 (js2-print-ast (js2-elem-get-node-element n) 0)
3541 (defstruct (js2-call-node
3544 (:constructor make-js2-call-node (&key (type js2-CALL)
3548 "AST node for a JavaScript function call."
3549 target ; a `js2-node' evaluating to the function to call
3550 args ; a Lisp list of `js2-node' arguments
3551 lp ; position of open-paren, or nil if missing
3552 rp) ; position of close-paren, or nil if missing
3554 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3555 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3557 (defun js2-visit-call-node (n v)
3558 (js2-visit-ast (js2-call-node-target n) v)
3559 (dolist (arg (js2-call-node-args n))
3560 (js2-visit-ast arg v)))
3562 (defun js2-print-call-node (n i)
3563 (insert (js2-make-pad i))
3564 (js2-print-ast (js2-call-node-target n) 0)
3566 (js2-print-list (js2-call-node-args n))
3569 (defstruct (js2-yield-node
3572 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3575 "AST node for yield statement or expression."
3576 value) ; optional: value to be yielded
3578 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3579 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3581 (defun js2-visit-yield-node (n v)
3582 (js2-visit-ast (js2-yield-node-value n) v))
3584 (defun js2-print-yield-node (n i)
3585 (insert (js2-make-pad i))
3587 (when (js2-yield-node-value n)
3589 (js2-print-ast (js2-yield-node-value n) 0)))
3591 (defstruct (js2-paren-node
3594 (:constructor make-js2-paren-node (&key (type js2-LP)
3597 "AST node for a parenthesized expression.
3598 In particular, used when the parens are syntactically optional,
3599 as opposed to required parens such as those enclosing an if-conditional."
3602 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3603 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3605 (defun js2-visit-paren-node (n v)
3606 (js2-visit-ast (js2-paren-node-expr n) v))
3608 (defun js2-print-paren-node (n i)
3609 (insert (js2-make-pad i))
3611 (js2-print-ast (js2-paren-node-expr n) 0)
3614 (defstruct (js2-array-comp-node
3615 (:include js2-scope)
3617 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3622 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3623 result ; result expression (just after left-bracket)
3624 loops ; a Lisp list of `js2-array-comp-loop-node'
3625 filter ; guard/filter expression
3626 if-pos ; buffer pos of 'if' keyword, if present, else nil
3627 lp ; buffer position of if-guard left-paren, or nil if not present
3628 rp) ; buffer position of if-guard right-paren, or nil if not present
3630 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3631 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3633 (defun js2-visit-array-comp-node (n v)
3634 (js2-visit-ast (js2-array-comp-node-result n) v)
3635 (dolist (l (js2-array-comp-node-loops n))
3636 (js2-visit-ast l v))
3637 (js2-visit-ast (js2-array-comp-node-filter n) v))
3639 (defun js2-print-array-comp-node (n i)
3640 (let ((pad (js2-make-pad i))
3641 (result (js2-array-comp-node-result n))
3642 (loops (js2-array-comp-node-loops n))
3643 (filter (js2-array-comp-node-filter n)))
3645 (js2-print-ast result 0)
3648 (js2-print-ast l 0))
3651 (js2-print-ast filter 0))
3654 (defstruct (js2-array-comp-loop-node
3655 (:include js2-for-in-node)
3657 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3664 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3666 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3667 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3669 (defun js2-visit-array-comp-loop (n v)
3670 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3671 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3673 (defun js2-print-array-comp-loop (n i)
3675 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3677 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3680 (defstruct (js2-empty-expr-node
3683 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3686 "AST node for an empty expression.")
3688 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3689 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3691 (defstruct (js2-xml-node
3692 (:include js2-block-node)
3694 (:constructor make-js2-xml-node (&key (type js2-XML)
3697 "AST node for initial parse of E4X literals.
3698 The kids field is a list of XML fragments, each a `js2-string-node' or
3699 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3701 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3702 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3704 (defun js2-print-xml-node (n i)
3705 (dolist (kid (js2-xml-node-kids n))
3706 (js2-print-ast kid i)))
3708 (defstruct (js2-xml-js-expr-node
3709 (:include js2-xml-node)
3711 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3714 "AST node for an embedded JavaScript {expression} in an E4X literal.
3715 The start and end fields correspond to the curly-braces."
3716 expr) ; a `js2-expr-node' of some sort
3718 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3719 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3721 (defun js2-visit-xml-js-expr (n v)
3722 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3724 (defun js2-print-xml-js-expr (n i)
3725 (insert (js2-make-pad i))
3727 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3730 (defstruct (js2-xml-dot-query-node
3731 (:include js2-infix-node)
3733 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3737 "AST node for an E4X foo.(bar) filter expression.
3738 Note that the left-paren is automatically the character immediately
3739 following the dot (.) in the operator. No whitespace is permitted
3740 between the dot and the lp by the scanner."
3743 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3744 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3746 (defun js2-print-xml-dot-query (n i)
3747 (insert (js2-make-pad i))
3748 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3750 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3753 (defstruct (js2-xml-ref-node
3755 (:constructor nil)) ; abstract
3756 "Base type for E4X XML attribute-access or property-get expressions.
3757 Such expressions can take a variety of forms. The general syntax has
3760 - (optional) an @ (specifying an attribute access)
3761 - (optional) a namespace (a `js2-name-node') and double-colon
3762 - (required) either a `js2-name-node' or a bracketed [expression]
3764 The property-name expressions (examples: ns::name, @name) are
3765 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3766 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3768 This node type (or more specifically, its subclasses) will sometimes
3769 be the right-hand child of a `js2-prop-get-node' or a
3770 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3771 The `js2-xml-ref-node' may also be a standalone primary expression with
3772 no explicit target, which is valid in certain expression contexts such as
3774 company..employee.(@id < 100)
3776 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3777 expression whose parent is a `js2-xml-dot-query-node'."
3782 (defsubst js2-xml-ref-node-attr-access-p (node)
3783 "Return non-nil if this expression began with an @-token."
3784 (and (numberp (js2-xml-ref-node-at-pos node))
3785 (plusp (js2-xml-ref-node-at-pos node))))
3787 (defstruct (js2-xml-prop-ref-node
3788 (:include js2-xml-ref-node)
3790 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3795 "AST node for an E4X XML [expr] property-ref expression.
3796 The JavaScript syntax is an optional @, an optional ns::, and a name.
3798 [ '@' ] [ name '::' ] name
3800 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3801 @ns::*, @*::attr, @*::*, and @*.
3803 The node starts at the @ token, if present. Otherwise it starts at the
3804 namespace name. The node bounds extend through the closing right-bracket,
3805 or if it is missing due to a syntax error, through the end of the index
3809 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3810 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3812 (defun js2-visit-xml-prop-ref-node (n v)
3813 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3814 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3816 (defun js2-print-xml-prop-ref-node (n i)
3817 (insert (js2-make-pad i))
3818 (if (js2-xml-ref-node-attr-access-p n)
3820 (when (js2-xml-prop-ref-node-namespace n)
3821 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3823 (if (js2-xml-prop-ref-node-propname n)
3824 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3826 (defstruct (js2-xml-elem-ref-node
3827 (:include js2-xml-ref-node)
3829 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3834 "AST node for an E4X XML [expr] member-ref expression.
3837 [ '@' ] [ name '::' ] '[' expr ']'
3839 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3841 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3842 is not a legal E4X XML element-ref expression, since it's already used
3843 for standard JavaScript element-get array indexing. Hence, a
3844 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3845 non-nil namespace node, or both.
3847 The node starts at the @ token, if present. Otherwise it starts
3848 at the namespace name. The node bounds extend through the closing
3849 right-bracket, or if it is missing due to a syntax error, through the
3850 end of the index expression."
3851 expr ; the bracketed index expression
3855 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3856 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3858 (defun js2-visit-xml-elem-ref-node (n v)
3859 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3860 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3862 (defun js2-print-xml-elem-ref-node (n i)
3863 (insert (js2-make-pad i))
3864 (if (js2-xml-ref-node-attr-access-p n)
3866 (when (js2-xml-elem-ref-node-namespace n)
3867 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3870 (if (js2-xml-elem-ref-node-expr n)
3871 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3874 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3876 (defstruct (js2-xml-start-tag-node
3877 (:include js2-xml-node)
3879 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3883 "AST node for an XML start-tag. Not currently used.
3884 The `kids' field is a Lisp list of child content nodes."
3885 name ; a `js2-xml-name-node'
3886 attrs ; a Lisp list of `js2-xml-attr-node'
3887 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3889 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3890 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3892 (defun js2-visit-xml-start-tag (n v)
3893 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3894 (dolist (attr (js2-xml-start-tag-node-attrs n))
3895 (js2-visit-ast attr v))
3896 (js2-visit-block n v))
3898 (defun js2-print-xml-start-tag (n i)
3899 (insert (js2-make-pad i) "<")
3900 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3901 (when (js2-xml-start-tag-node-attrs n)
3903 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3906 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3907 ;; and add the end-tag to the kids list of the parent as well.
3908 (defstruct (js2-xml-end-tag-node
3909 (:include js2-xml-node)
3911 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3914 "AST node for an XML end-tag. Not currently used."
3915 name) ; a `js2-xml-name-node'
3917 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3918 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3920 (defun js2-visit-xml-end-tag (n v)
3921 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3923 (defun js2-print-xml-end-tag (n i)
3924 (insert (js2-make-pad i))
3926 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3929 (defstruct (js2-xml-name-node
3930 (:include js2-xml-node)
3932 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3934 len namespace kids)))
3935 "AST node for an E4X XML name. Not currently used.
3936 Any XML name can be qualified with a namespace, hence the namespace field.
3937 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3938 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3939 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3940 namespace) ; a `js2-string-node'
3942 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3943 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3945 (defun js2-visit-xml-name-node (n v)
3946 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3948 (defun js2-print-xml-name-node (n i)
3949 (insert (js2-make-pad i))
3950 (when (js2-xml-name-node-namespace n)
3951 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3953 (dolist (kid (js2-xml-name-node-kids n))
3954 (js2-print-ast kid 0)))
3956 (defstruct (js2-xml-pi-node
3957 (:include js2-xml-node)
3959 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3962 "AST node for an E4X XML processing instruction. Not currently used."
3963 name ; a `js2-xml-name-node'
3964 attrs) ; a list of `js2-xml-attr-node'
3966 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3967 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3969 (defun js2-visit-xml-pi-node (n v)
3970 (js2-visit-ast (js2-xml-pi-node-name n) v)
3971 (dolist (attr (js2-xml-pi-node-attrs n))
3972 (js2-visit-ast attr v)))
3974 (defun js2-print-xml-pi-node (n i)
3975 (insert (js2-make-pad i) "<?")
3976 (js2-print-ast (js2-xml-pi-node-name n))
3977 (when (js2-xml-pi-node-attrs n)
3979 (js2-print-list (js2-xml-pi-node-attrs n)))
3982 (defstruct (js2-xml-cdata-node
3983 (:include js2-xml-node)
3985 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3988 "AST node for a CDATA escape section. Not currently used."
3989 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3991 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3992 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3994 (defun js2-visit-xml-cdata-node (n v)
3995 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3997 (defun js2-print-xml-cdata-node (n i)
3998 (insert (js2-make-pad i))
3999 (js2-print-ast (js2-xml-cdata-node-content n)))
4001 (defstruct (js2-xml-attr-node
4002 (:include js2-xml-node)
4004 (:constructor make-js2-attr-node (&key (type js2-XML)
4007 eq-pos quote-type)))
4008 "AST node representing a foo='bar' XML attribute value. Not yet used."
4009 name ; a `js2-xml-name-node'
4010 value ; a `js2-xml-name-node'
4011 eq-pos ; buffer position of "=" sign
4012 quote-type) ; 'single or 'double
4014 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4015 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4017 (defun js2-visit-xml-attr-node (n v)
4018 (js2-visit-ast (js2-xml-attr-node-name n) v)
4019 (js2-visit-ast (js2-xml-attr-node-value n) v))
4021 (defun js2-print-xml-attr-node (n i)
4022 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4025 (insert (js2-make-pad i))
4026 (js2-print-ast (js2-xml-attr-node-name n) 0)
4028 (js2-print-ast (js2-xml-attr-node-value n) 0)
4031 (defstruct (js2-xml-text-node
4032 (:include js2-xml-node)
4034 (:constructor make-js2-text-node (&key (type js2-XML)
4037 "AST node for an E4X XML text node. Not currently used."
4038 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4040 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4041 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4043 (defun js2-visit-xml-text-node (n v)
4044 (js2-visit-ast (js2-xml-text-node-content n) v))
4046 (defun js2-print-xml-text-node (n i)
4047 (insert (js2-make-pad i))
4048 (dolist (kid (js2-xml-text-node-content n))
4049 (js2-print-ast kid)))
4051 (defstruct (js2-xml-comment-node
4052 (:include js2-xml-node)
4054 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4057 "AST node for E4X XML comment. Not currently used.")
4059 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4060 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4062 (defun js2-print-xml-comment (n i)
4063 (insert (js2-make-pad i)
4064 (js2-node-string n)))
4068 (defsubst js2-node-line (n)
4069 "Fetch the source line number at the start of node N.
4070 This is O(n) in the length of the source buffer; use prudently."
4071 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4073 (defsubst js2-block-node-kid (n i)
4074 "Return child I of node N, or nil if there aren't that many."
4075 (nth i (js2-block-node-kids n)))
4077 (defsubst js2-block-node-first (n)
4078 "Return first child of block node N, or nil if there is none."
4079 (first (js2-block-node-kids n)))
4081 (defun js2-node-root (n)
4082 "Return the root of the AST containing N.
4083 If N has no parent pointer, returns N."
4084 (let ((parent (js2-node-parent n)))
4086 (js2-node-root parent)
4089 (defun js2-node-position-in-parent (node &optional parent)
4090 "Return the position of NODE in parent's block-kids list.
4091 PARENT can be supplied if known. Positioned returned is zero-indexed.
4092 Returns 0 if NODE is not a child of a block statement, or if NODE
4093 is not a statement node."
4094 (let ((p (or parent (js2-node-parent node)))
4096 (if (not (js2-block-node-p p))
4098 (or (js2-position node (js2-block-node-kids p))
4101 (defsubst js2-node-short-name (n)
4102 "Return the short name of node N as a string, e.g. `js2-if-node'."
4103 (substring (symbol-name (aref n 0))
4104 (length "cl-struct-")))
4106 (defun js2-node-child-list (node)
4107 "Return the child list for NODE, a Lisp list of nodes.
4108 Works for block nodes, array nodes, obj literals, funarg lists,
4109 var decls and try nodes (for catch clauses). Note that you should call
4110 `js2-block-node-kids' on the function body for the body statements.
4111 Returns nil for zero-length child lists or unsupported nodes."
4113 ((js2-function-node-p node)
4114 (js2-function-node-params node))
4115 ((js2-block-node-p node)
4116 (js2-block-node-kids node))
4117 ((js2-try-node-p node)
4118 (js2-try-node-catch-clauses node))
4119 ((js2-array-node-p node)
4120 (js2-array-node-elems node))
4121 ((js2-object-node-p node)
4122 (js2-object-node-elems node))
4123 ((js2-call-node-p node)
4124 (js2-call-node-args node))
4125 ((js2-new-node-p node)
4126 (js2-new-node-args node))
4127 ((js2-var-decl-node-p node)
4128 (js2-var-decl-node-kids node))
4132 (defun js2-node-set-child-list (node kids)
4133 "Set the child list for NODE to KIDS."
4135 ((js2-function-node-p node)
4136 (setf (js2-function-node-params node) kids))
4137 ((js2-block-node-p node)
4138 (setf (js2-block-node-kids node) kids))
4139 ((js2-try-node-p node)
4140 (setf (js2-try-node-catch-clauses node) kids))
4141 ((js2-array-node-p node)
4142 (setf (js2-array-node-elems node) kids))
4143 ((js2-object-node-p node)
4144 (setf (js2-object-node-elems node) kids))
4145 ((js2-call-node-p node)
4146 (setf (js2-call-node-args node) kids))
4147 ((js2-new-node-p node)
4148 (setf (js2-new-node-args node) kids))
4149 ((js2-var-decl-node-p node)
4150 (setf (js2-var-decl-node-kids node) kids))
4152 (error "Unsupported node type: %s" (js2-node-short-name node))))
4155 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4156 (defconst js2-paren-expr-nodes
4157 '(cl-struct-js2-array-comp-loop-node
4158 cl-struct-js2-array-comp-node
4159 cl-struct-js2-call-node
4160 cl-struct-js2-catch-node
4161 cl-struct-js2-do-node
4162 cl-struct-js2-elem-get-node
4163 cl-struct-js2-for-in-node
4164 cl-struct-js2-for-node
4165 cl-struct-js2-function-node
4166 cl-struct-js2-if-node
4167 cl-struct-js2-let-node
4168 cl-struct-js2-new-node
4169 cl-struct-js2-paren-node
4170 cl-struct-js2-switch-node
4171 cl-struct-js2-while-node
4172 cl-struct-js2-with-node
4173 cl-struct-js2-xml-dot-query-node)
4174 "Node types that can have a parenthesized child expression.
4175 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4177 (defsubst js2-paren-expr-node-p (node)
4178 "Return t for nodes that typically have a parenthesized child expression.
4179 Useful for computing the indentation anchors for arg-lists and conditions.
4180 Note that it may return a false positive, for instance when NODE is
4181 a `js2-new-node' and there are no arguments or parentheses."
4182 (memq (aref node 0) js2-paren-expr-nodes))
4184 ;; Fake polymorphism... yech.
4185 (defun js2-node-lp (node)
4186 "Return relative left-paren position for NODE, if applicable.
4187 For `js2-elem-get-node' structs, returns left-bracket position.
4188 Note that the position may be nil in the case of a parse error."
4190 ((js2-elem-get-node-p node)
4191 (js2-elem-get-node-lb node))
4192 ((js2-loop-node-p node)
4193 (js2-loop-node-lp node))
4194 ((js2-function-node-p node)
4195 (js2-function-node-lp node))
4196 ((js2-if-node-p node)
4197 (js2-if-node-lp node))
4198 ((js2-new-node-p node)
4199 (js2-new-node-lp node))
4200 ((js2-call-node-p node)
4201 (js2-call-node-lp node))
4202 ((js2-paren-node-p node)
4203 (js2-node-pos node))
4204 ((js2-switch-node-p node)
4205 (js2-switch-node-lp node))
4206 ((js2-catch-node-p node)
4207 (js2-catch-node-lp node))
4208 ((js2-let-node-p node)
4209 (js2-let-node-lp node))
4210 ((js2-array-comp-node-p node)
4211 (js2-array-comp-node-lp node))
4212 ((js2-with-node-p node)
4213 (js2-with-node-lp node))
4214 ((js2-xml-dot-query-node-p node)
4215 (1+ (js2-infix-node-op-pos node)))
4217 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4219 ;; Fake polymorphism... blech.
4220 (defun js2-node-rp (node)
4221 "Return relative right-paren position for NODE, if applicable.
4222 For `js2-elem-get-node' structs, returns right-bracket position.
4223 Note that the position may be nil in the case of a parse error."
4225 ((js2-elem-get-node-p node)
4226 (js2-elem-get-node-lb node))
4227 ((js2-loop-node-p node)
4228 (js2-loop-node-rp node))
4229 ((js2-function-node-p node)
4230 (js2-function-node-rp node))
4231 ((js2-if-node-p node)
4232 (js2-if-node-rp node))
4233 ((js2-new-node-p node)
4234 (js2-new-node-rp node))
4235 ((js2-call-node-p node)
4236 (js2-call-node-rp node))
4237 ((js2-paren-node-p node)
4238 (+ (js2-node-pos node) (js2-node-len node)))
4239 ((js2-switch-node-p node)
4240 (js2-switch-node-rp node))
4241 ((js2-catch-node-p node)
4242 (js2-catch-node-rp node))
4243 ((js2-let-node-p node)
4244 (js2-let-node-rp node))
4245 ((js2-array-comp-node-p node)
4246 (js2-array-comp-node-rp node))
4247 ((js2-with-node-p node)
4248 (js2-with-node-rp node))
4249 ((js2-xml-dot-query-node-p node)
4250 (1+ (js2-xml-dot-query-node-rp node)))
4252 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4254 (defsubst js2-node-first-child (node)
4255 "Return the first element of `js2-node-child-list' for NODE."
4256 (car (js2-node-child-list node)))
4258 (defsubst js2-node-last-child (node)
4259 "Return the last element of `js2-node-last-child' for NODE."
4260 (car (last (js2-node-child-list node))))
4262 (defun js2-node-prev-sibling (node)
4263 "Return the previous statement in parent.
4264 Works for parents supported by `js2-node-child-list'.
4265 Returns nil if NODE is not in the parent, or PARENT is
4266 not a supported node, or if NODE is the first child."
4267 (let* ((p (js2-node-parent node))
4268 (kids (js2-node-child-list p))
4271 (not (eq node (cadr kids))))
4272 (setq kids (cdr kids)
4276 (defun js2-node-next-sibling (node)
4277 "Return the next statement in parent block.
4278 Returns nil if NODE is not in the block, or PARENT is not
4279 a block node, or if NODE is the last statement."
4280 (let* ((p (js2-node-parent node))
4281 (kids (js2-node-child-list p)))
4283 (not (eq node (car kids))))
4284 (setq kids (cdr kids)))
4287 (defun js2-node-find-child-before (pos parent &optional after)
4288 "Find the last child that starts before POS in parent.
4289 If AFTER is non-nil, returns first child starting after POS.
4290 POS is an absolute buffer position. PARENT is any node
4291 supported by `js2-node-child-list'.
4292 Returns nil if no applicable child is found."
4293 (let ((kids (if (js2-function-node-p parent)
4294 (js2-block-node-kids (js2-function-node-body parent))
4295 (js2-node-child-list parent)))
4296 (beg (if (js2-function-node-p parent)
4297 (js2-node-abs-pos (js2-function-node-body parent))
4298 (js2-node-abs-pos parent)))
4301 (setq fn (if after '>= '<))
4302 (while (and kids continue)
4303 (setq kid (car kids))
4304 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4306 continue (if after nil t))
4307 (setq continue (if after t nil)))
4308 (setq kids (cdr kids)))
4311 (defun js2-node-find-child-after (pos parent)
4312 "Find first child that starts after POS in parent.
4313 POS is an absolute buffer position. PARENT is any node
4314 supported by `js2-node-child-list'.
4315 Returns nil if no applicable child is found."
4316 (js2-node-find-child-before pos parent 'after))
4318 (defun js2-node-replace-child (pos parent new-node)
4319 "Replace node at index POS in PARENT with NEW-NODE.
4320 Only works for parents supported by `js2-node-child-list'."
4321 (let ((kids (js2-node-child-list parent))
4324 (setq kids (cdr kids)
4326 (setcar kids new-node)
4327 (js2-node-add-children parent new-node)))
4329 (defun js2-node-buffer (n)
4330 "Return the buffer associated with AST N.
4331 Returns nil if the buffer is not set as a property on the root
4332 node, or if parent links were not recorded during parsing."
4333 (let ((root (js2-node-root n)))
4335 (js2-ast-root-p root)
4336 (js2-ast-root-buffer root))))
4338 (defun js2-block-node-push (n kid)
4339 "Push js2-node KID onto the end of js2-block-node N's child list.
4340 KID is always added to the -end- of the kids list.
4341 Function also calls `js2-node-add-children' to add the parent link."
4342 (let ((kids (js2-node-child-list n)))
4344 (setcdr kids (nconc (cdr kids) (list kid)))
4345 (js2-node-set-child-list n (list kid)))
4346 (js2-node-add-children n kid)))
4348 (defun js2-node-string (node)
4349 (with-current-buffer (or (js2-node-buffer node)
4350 (error "No buffer available for node %s" node))
4351 (let ((pos (js2-node-abs-pos node)))
4352 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4354 ;; Container for storing the node we're looking for in a traversal.
4355 (js2-deflocal js2-discovered-node nil)
4357 ;; Keep track of absolute node position during traversals.
4358 (js2-deflocal js2-visitor-offset nil)
4360 (js2-deflocal js2-node-search-point nil)
4362 (when js2-mode-dev-mode-p
4363 (defun js2-find-node-at-point ()
4365 (let ((node (js2-node-at-point)))
4366 (message "%s" (or node "No node found at point"))))
4367 (defun js2-node-name-at-point ()
4369 (let ((node (js2-node-at-point)))
4370 (message "%s" (if node
4371 (js2-node-short-name node)
4372 "No node found at point.")))))
4374 (defun js2-node-at-point (&optional pos skip-comments)
4375 "Return AST node at POS, a buffer position, defaulting to current point.
4376 The `js2-mode-ast' variable must be set to the current parse tree.
4377 Signals an error if the AST (`js2-mode-ast') is nil.
4378 Always returns a node - if it can't find one, it returns the root.
4379 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4380 (let ((ast js2-mode-ast)
4383 (error "No JavaScript AST available"))
4384 ;; Look through comments first, since they may be inside nodes that
4385 ;; would otherwise report a match.
4386 (setq pos (or pos (point))
4387 result (if (> pos (js2-node-abs-end ast))
4389 (if (not skip-comments)
4390 (js2-comment-at-point pos))))
4392 (setq js2-discovered-node nil
4393 js2-visitor-offset 0
4394 js2-node-search-point pos)
4396 (catch 'js2-visit-done
4397 (js2-visit-ast ast #'js2-node-at-point-visitor))
4398 (setq js2-visitor-offset nil
4399 js2-node-search-point nil))
4400 (setq result js2-discovered-node))
4401 ;; may have found a comment beyond end of last child node,
4402 ;; since visiting the ast-root looks at the comment-list last.
4403 (if (and skip-comments
4404 (js2-comment-node-p result))
4406 (or result js2-mode-ast)))
4408 (defun js2-node-at-point-visitor (node end-p)
4409 (let ((rel-pos (js2-node-pos node))
4412 (point js2-node-search-point))
4415 ;; this evaluates to a non-nil return value, even if it's zero
4416 (decf js2-visitor-offset rel-pos))
4417 ;; we already looked for comments before visiting, and don't want them now
4418 ((js2-comment-node-p node)
4421 (setq abs-pos (incf js2-visitor-offset rel-pos)
4422 ;; we only want to use the node if the point is before
4423 ;; the last character position in the node, so we decrement
4424 ;; the absolute end by 1.
4425 abs-end (+ abs-pos (js2-node-len node) -1))
4427 ;; If this node starts after search-point, stop the search.
4429 (throw 'js2-visit-done nil))
4430 ;; If this node ends before the search-point, don't check kids.
4434 ;; Otherwise point is within this node, possibly in a child.
4435 (setq js2-discovered-node node)
4436 t)))))) ; keep processing kids to look for more specific match
4438 (defsubst js2-block-comment-p (node)
4439 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4440 (and (js2-comment-node-p node)
4441 (memq (js2-comment-node-format node) '(jsdoc block))))
4443 ;; TODO: put the comments in a vector and binary-search them instead
4444 (defun js2-comment-at-point (&optional pos)
4445 "Look through scanned comment nodes for one containing POS.
4446 POS is a buffer position that defaults to current point.
4447 Function returns nil if POS was not in any comment node."
4448 (let ((ast js2-mode-ast)
4449 (x (or pos (point)))
4452 (error "No JavaScript AST available"))
4454 ;; Comments are stored in lexical order.
4455 (dolist (comment (js2-ast-root-comments ast) nil)
4456 (setq beg (js2-node-abs-pos comment)
4457 end (+ beg (js2-node-len comment)))
4460 (throw 'done comment))))))
4462 (defun js2-mode-find-parent-fn (node)
4463 "Find function enclosing NODE.
4464 Returns nil if NODE is not inside a function."
4465 (setq node (js2-node-parent node))
4466 (while (and node (not (js2-function-node-p node)))
4467 (setq node (js2-node-parent node)))
4468 (and (js2-function-node-p node) node))
4470 (defun js2-mode-find-enclosing-fn (node)
4471 "Find function or root enclosing NODE."
4472 (if (js2-ast-root-p node)
4474 (setq node (js2-node-parent node))
4475 (while (not (or (js2-ast-root-p node)
4476 (js2-function-node-p node)))
4477 (setq node (js2-node-parent node)))
4480 (defun js2-mode-find-enclosing-node (beg end)
4481 "Find script or function fully enclosing BEG and END."
4482 (let ((node (js2-node-at-point beg))
4486 (if (or (js2-ast-root-p node)
4487 (and (js2-function-node-p node)
4488 (<= (setq pos (js2-node-abs-pos node)) beg)
4489 (>= (+ pos (js2-node-len node)) end)))
4491 (setq node (js2-node-parent node))))
4494 (defun js2-node-parent-script-or-fn (node)
4495 "Find script or function immediately enclosing NODE.
4496 If NODE is the ast-root, returns nil."
4497 (if (js2-ast-root-p node)
4499 (setq node (js2-node-parent node))
4500 (while (and node (not (or (js2-function-node-p node)
4501 (js2-script-node-p node))))
4502 (setq node (js2-node-parent node)))
4505 (defun js2-nested-function-p (node)
4506 "Return t if NODE is a nested function, or is inside a nested function."
4507 (unless (js2-ast-root-p node)
4508 (js2-function-node-p (if (js2-function-node-p node)
4509 (js2-node-parent-script-or-fn node)
4510 (js2-node-parent-script-or-fn
4511 (js2-node-parent-script-or-fn node))))))
4513 (defun js2-function-param-node-p (node)
4514 "Return non-nil if NODE is a param node of a `js2-function-node'."
4515 (let ((parent (js2-node-parent node)))
4517 (js2-function-node-p parent)
4518 (memq node (js2-function-node-params parent)))))
4520 (defun js2-mode-shift-kids (kids start offset)
4522 (if (> (js2-node-pos kid) start)
4523 (incf (js2-node-pos kid) offset))))
4525 (defun js2-mode-shift-children (parent start offset)
4526 "Update start-positions of all children of PARENT beyond START."
4527 (let ((root (js2-node-root parent)))
4528 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4529 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4531 (defun js2-node-is-descendant (node ancestor)
4532 "Return t if NODE is a descendant of ANCESTOR."
4534 (not (eq node ancestor)))
4535 (setq node (js2-node-parent node)))
4538 ;;; visitor infrastructure
4540 (defun js2-visit-none (node callback)
4541 "Visitor for AST node that have no node children."
4544 (defun js2-print-none (node indent)
4545 "Visitor for AST node with no printed representation.")
4547 (defun js2-print-body (node indent)
4548 "Print a statement, or a block without braces."
4549 (if (js2-block-node-p node)
4550 (dolist (kid (js2-block-node-kids node))
4551 (js2-print-ast kid indent))
4552 (js2-print-ast node indent)))
4554 (defun js2-print-list (args &optional delimiter)
4555 (loop with len = (length args)
4559 (js2-print-ast arg 0)
4561 (insert (or delimiter ", ")))))
4563 (defun js2-print-tree (ast)
4564 "Prints an AST to the current buffer.
4565 Makes `js2-ast-parent-nodes' available to the printer functions."
4566 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4567 (js2-print-ast ast)))
4569 (defun js2-print-ast (node &optional indent)
4570 "Helper function for printing AST nodes.
4571 Requires `js2-ast-parent-nodes' to be non-nil.
4572 You should use `js2-print-tree' instead of this function."
4573 (let ((printer (get (aref node 0) 'js2-printer))
4575 (pos (js2-node-abs-pos node)))
4576 ;; TODO: wedge comments in here somewhere
4578 (funcall printer node i))))
4580 (defconst js2-side-effecting-tokens
4581 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4582 (dolist (tt (list js2-ASSIGN
4651 (if js2-instanceof-has-side-effects
4652 (aset tokens js2-INSTANCEOF t))
4655 (defun js2-node-has-side-effects (node)
4656 "Return t if NODE has side effects."
4657 (when node ; makes it easier to handle malformed expressions
4658 (let ((tt (js2-node-type node)))
4660 ;; This doubtless needs some work, since EXPR_VOID is used
4661 ;; in several ways in Rhino and I may not have caught them all.
4662 ;; I'll wait for people to notice incorrect warnings.
4663 ((and (= tt js2-EXPR_VOID)
4664 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4665 (let ((expr (js2-expr-stmt-node-expr node)))
4666 (or (js2-node-has-side-effects expr)
4667 (when (js2-string-node-p expr)
4668 (string= "use strict" (js2-string-node-value expr))))))
4670 (js2-node-has-side-effects (js2-infix-node-right node)))
4673 (or (js2-node-has-side-effects (js2-infix-node-right node))
4674 (js2-node-has-side-effects (js2-infix-node-left node))))
4676 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4677 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4678 ((js2-paren-node-p node)
4679 (js2-node-has-side-effects (js2-paren-node-expr node)))
4680 ((= tt js2-ERROR) ; avoid cascaded error messages
4683 (aref js2-side-effecting-tokens tt))))))
4685 (defun js2-member-expr-leftmost-name (node)
4686 "For an expr such as foo.bar.baz, return leftmost node foo.
4687 NODE is any `js2-node' object. If it represents a member expression,
4688 which is any sequence of property gets, element-gets, function calls,
4689 or xml descendants/filter operators, then we look at the lexically
4690 leftmost (first) node in the chain. If it is a name-node we return it.
4691 Note that NODE can be a raw name-node and it will be returned as well.
4692 If NODE is not a name-node or member expression, or if it is a member
4693 expression whose leftmost target is not a name node, returns nil."
4696 (while (and continue (not result))
4698 ((js2-name-node-p node)
4700 ((js2-prop-get-node-p node)
4701 (setq node (js2-prop-get-node-left node)))
4702 ;; TODO: handle call-nodes, xml-nodes, others?
4704 (setq continue nil))))
4707 (defconst js2-stmt-node-types
4711 js2-DEFAULT ; e4x "default xml namespace" statement
4723 "Node types that only appear in statement contexts.
4724 The list does not include nodes that always appear as the child
4725 of another specific statement type, such as switch-cases,
4726 catch and finally blocks, and else-clauses. The list also excludes
4727 nodes like yield, let and var, which may appear in either expression
4728 or statement context, and in the latter context always have a
4729 `js2-expr-stmt-node' parent. Finally, the list does not include
4730 functions or scripts, which are treated separately from statements
4731 by the JavaScript parser and runtime.")
4733 (defun js2-stmt-node-p (node)
4734 "Heuristic for figuring out if NODE is a statement.
4735 Some node types can appear in either an expression context or a
4736 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4737 For these node types in a statement context, the parent will be a
4738 `js2-expr-stmt-node'.
4739 Functions aren't included in the check."
4740 (memq (js2-node-type node) js2-stmt-node-types))
4742 (defun js2-mode-find-first-stmt (node)
4743 "Search upward starting from NODE looking for a statement.
4744 For purposes of this function, a `js2-function-node' counts."
4745 (while (not (or (js2-stmt-node-p node)
4746 (js2-function-node-p node)))
4747 (setq node (js2-node-parent node)))
4750 (defun js2-node-parent-stmt (node)
4751 "Return the node's first ancestor that is a statement.
4752 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4753 appearing in a statement context will have a parent that is a
4754 `js2-expr-stmt-node' that will be returned by this function."
4755 (let ((parent (js2-node-parent node)))
4756 (if (or (null parent)
4757 (js2-stmt-node-p parent)
4758 (and (js2-function-node-p parent)
4759 (not (eq (js2-function-node-form parent)
4760 'FUNCTION_EXPRESSION))))
4762 (js2-node-parent-stmt parent))))
4764 ;; In the Mozilla Rhino sources, Roshan James writes:
4765 ;; Does consistent-return analysis on the function body when strict mode is
4768 ;; function (x) { return (x+1) }
4772 ;; function (x) { if (x < 0) return (x+1); }
4774 ;; is not because the function can potentially return a value when the
4775 ;; condition is satisfied and if not, the function does not explicitly
4778 ;; This extends to checking mismatches such as "return" and "return <value>"
4779 ;; used in the same function. Warnings are not emitted if inconsistent
4780 ;; returns exist in code that can be statically shown to be unreachable.
4782 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4784 ;; emits no warning. However if the loop had a break statement, then a
4785 ;; warning would be emitted.
4787 ;; The consistency analysis looks at control structures such as loops, ifs,
4788 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4789 ;; warns the user about an inconsistent set of termination possibilities.
4791 ;; These flags enumerate the possible ways a statement/function can
4792 ;; terminate. These flags are used by endCheck() and by the Parser to
4793 ;; detect inconsistent return usage.
4795 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4796 ;; able to execute (example: throw, continue)
4798 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4799 ;; next one. Statement such as return dont. A compound statement may have
4800 ;; some branch that drops off control to the next statement.
4802 ;; END_RETURNS indicates that the statement can return with no value.
4803 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4805 ;; A compound statement such as
4809 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4811 (defconst js2-END_UNREACHED 0)
4812 (defconst js2-END_DROPS_OFF 1)
4813 (defconst js2-END_RETURNS 2)
4814 (defconst js2-END_RETURNS_VALUE 4)
4815 (defconst js2-END_YIELDS 8)
4817 (defun js2-has-consistent-return-usage (node)
4818 "Check that every return usage in a function body is consistent.
4819 Returns t if the function satisfies strict mode requirement."
4820 (let ((n (js2-end-check node)))
4821 ;; either it doesn't return a value in any branch...
4822 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4823 ;; or it returns a value (or is unreached) at every branch
4824 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4828 (defun js2-end-check-if (node)
4829 "Ensure that return usage in then/else blocks is consistent.
4830 If there is no else block, then the return statement can fall through.
4831 Returns logical OR of END_* flags"
4832 (let ((th (js2-if-node-then-part node))
4833 (el (js2-if-node-else-part node)))
4836 (logior (js2-end-check th) (if el
4838 js2-END_DROPS_OFF)))))
4840 (defun js2-end-check-switch (node)
4841 "Consistency of return statements is checked between the case statements.
4842 If there is no default, then the switch can fall through. If there is a
4843 default, we check to see if all code paths in the default return or if
4844 there is a code path that can fall through.
4845 Returns logical OR of END_* flags."
4846 (let ((rv js2-END_UNREACHED)
4848 ;; examine the cases
4850 (dolist (c (js2-switch-node-cases node))
4851 (if (js2-case-node-expr c)
4852 (js2-set-flag rv (js2-end-check-block c))
4853 (setq default-case c)
4854 (throw 'break nil))))
4855 ;; we don't care how the cases drop into each other
4856 (js2-clear-flag rv js2-END_DROPS_OFF)
4857 ;; examine the default
4858 (js2-set-flag rv (if default-case
4859 (js2-end-check default-case)
4863 (defun js2-end-check-try (node)
4864 "If the block has a finally, return consistency is checked in the
4865 finally block. If all code paths in the finally return, then the
4866 returns in the try-catch blocks don't matter. If there is a code path
4867 that does not return or if there is no finally block, the returns
4868 of the try and catch blocks are checked for mismatch.
4869 Returns logical OR of END_* flags."
4870 (let ((finally (js2-try-node-finally-block node))
4872 ;; check the finally if it exists
4873 (setq rv (if finally
4874 (js2-end-check (js2-finally-node-body finally))
4876 ;; If the finally block always returns, then none of the returns
4877 ;; in the try or catch blocks matter.
4878 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4879 (js2-clear-flag rv js2-END_DROPS_OFF)
4880 ;; examine the try block
4881 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4882 ;; check each catch block
4883 (dolist (cb (js2-try-node-catch-clauses node))
4884 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4887 (defun js2-end-check-loop (node)
4888 "Return statement in the loop body must be consistent.
4889 The default assumption for any kind of a loop is that it will eventually
4890 terminate. The only exception is a loop with a constant true condition.
4891 Code that follows such a loop is examined only if one can determine
4892 statically that there is a break out of the loop.
4894 for(... ; ... ; ...) {}
4899 Returns logical OR of END_* flags."
4900 (let ((rv (js2-end-check (js2-loop-node-body node)))
4902 ((js2-while-node-p node)
4903 (js2-while-node-condition node))
4904 ((js2-do-node-p node)
4905 (js2-do-node-condition node))
4906 ((js2-for-node-p node)
4907 (js2-for-node-condition node)))))
4909 ;; check to see if the loop condition is always true
4911 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4912 (js2-clear-flag rv js2-END_DROPS_OFF))
4914 ;; look for effect of breaks
4915 (js2-set-flag rv (js2-node-get-prop node
4920 (defun js2-end-check-block (node)
4921 "A general block of code is examined statement by statement.
4922 If any statement (even a compound one) returns in all branches, then
4923 subsequent statements are not examined.
4924 Returns logical OR of END_* flags."
4925 (let* ((rv js2-END_DROPS_OFF)
4926 (kids (js2-block-node-kids node))
4928 ;; Check each statment. If the statement can continue onto the next
4929 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4930 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4931 (js2-clear-flag rv js2-END_DROPS_OFF)
4932 (js2-set-flag rv (js2-end-check n))
4933 (setq kids (cdr kids)
4937 (defun js2-end-check-label (node)
4938 "A labeled statement implies that there may be a break to the label.
4939 The function processes the labeled statement and then checks the
4940 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4942 Returns logical OR of END_* flags."
4943 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4944 (logior rv (js2-node-get-prop node
4946 js2-END_UNREACHED))))
4948 (defun js2-end-check-break (node)
4949 "When a break is encountered annotate the statement being broken
4950 out of by setting its CONTROL_BLOCK_PROP property.
4951 Returns logical OR of END_* flags."
4952 (and (js2-break-node-target node)
4953 (js2-node-set-prop (js2-break-node-target node)
4958 (defun js2-end-check (node)
4959 "Examine the body of a function, doing a basic reachability analysis.
4960 Returns a combination of flags END_* flags that indicate
4961 how the function execution can terminate. These constitute only the
4962 pessimistic set of termination conditions. It is possible that at
4963 runtime certain code paths will never be actually taken. Hence this
4964 analysis will flag errors in cases where there may not be errors.
4965 Returns logical OR of END_* flags"
4968 ((js2-break-node-p node)
4969 (js2-end-check-break node))
4970 ((js2-expr-stmt-node-p node)
4971 (if (setq kid (js2-expr-stmt-node-expr node))
4974 ((or (js2-continue-node-p node)
4975 (js2-throw-node-p node))
4977 ((js2-return-node-p node)
4978 (if (setq kid (js2-return-node-retval node))
4979 js2-END_RETURNS_VALUE
4981 ((js2-loop-node-p node)
4982 (js2-end-check-loop node))
4983 ((js2-switch-node-p node)
4984 (js2-end-check-switch node))
4985 ((js2-labeled-stmt-node-p node)
4986 (js2-end-check-label node))
4987 ((js2-if-node-p node)
4988 (js2-end-check-if node))
4989 ((js2-try-node-p node)
4990 (js2-end-check-try node))
4991 ((js2-block-node-p node)
4992 (if (null (js2-block-node-kids node))
4994 (js2-end-check-block node)))
4995 ((js2-yield-node-p node)
4998 js2-END_DROPS_OFF))))
5000 (defun js2-always-defined-boolean-p (node)
5001 "Check if NODE always evaluates to true or false in boolean context.
5002 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5004 (let ((tt (js2-node-type node))
5007 ((or (= tt js2-FALSE) (= tt js2-NULL))
5012 (setq num (js2-number-node-num-value node))
5013 (if (and (not (eq num 0.0e+NaN))
5020 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5021 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5023 (defvar js2-tokens nil
5024 "List of all defined token names.") ; initialized in `js2-token-names'
5026 (defconst js2-token-names
5027 (let* ((names (make-vector js2-num-tokens -1))
5028 (case-fold-search nil) ; only match js2-UPPER_CASE
5029 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5030 (loop for sym in syms
5033 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5035 (aset names (symbol-value sym) ; code, e.g. 152
5036 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5037 (push sym js2-tokens)))
5039 "Vector mapping int values to token string names, sans `js2-' prefix.")
5041 (defun js2-token-name (tok)
5042 "Return a string name for TOK, a token symbol or code.
5043 Signals an error if it's not a recognized token."
5046 (setq code (symbol-value tok)))
5049 (if (and (numberp code)
5051 (< code js2-num-tokens))
5052 (aref js2-token-names code)
5053 (error "Invalid token: %s" code)))))
5055 (defsubst js2-token-sym (tok)
5056 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5057 (intern (js2-token-name tok)))
5059 (defconst js2-token-codes
5060 (let ((table (make-hash-table :test 'eq :size 256)))
5061 (loop for name across js2-token-names
5062 for sym = (intern (concat "js2-" name))
5064 (puthash sym (symbol-value sym) table))
5065 ;; clean up a few that are "wrong" in Rhino's token codes
5066 (puthash 'js2-DELETE js2-DELPROP table)
5068 "Hashtable mapping token symbols to their bytecodes.")
5070 (defsubst js2-token-code (sym)
5071 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5072 (or (gethash sym js2-token-codes)
5073 (error "Invalid token symbol: %s " sym))) ; signal code bug
5075 (defun js2-report-scan-error (msg &optional no-throw beg len)
5076 (setq js2-token-end js2-ts-cursor)
5077 (js2-report-error msg nil
5078 (or beg js2-token-beg)
5079 (or len (- js2-token-end js2-token-beg)))
5081 (throw 'return js2-ERROR)))
5083 (defun js2-get-string-from-buffer ()
5084 "Reverse the char accumulator and return it as a string."
5085 (setq js2-token-end js2-ts-cursor)
5086 (if js2-ts-string-buffer
5087 (apply #'string (nreverse js2-ts-string-buffer))
5090 ;; TODO: could potentially avoid a lot of consing by allocating a
5091 ;; char buffer the way Rhino does.
5092 (defsubst js2-add-to-string (c)
5093 (push c js2-ts-string-buffer))
5095 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5096 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5097 ;; any other character: when it's not part of the current token, we
5098 ;; unget it, allowing it to be read again by the following call.
5099 (defsubst js2-unget-char ()
5100 (decf js2-ts-cursor))
5102 ;; Rhino distinguishes \r and \n line endings. We don't need to
5103 ;; because we only scan from Emacs buffers, which always use \n.
5104 (defun js2-get-char ()
5105 "Read and return the next character from the input buffer.
5106 Increments `js2-ts-lineno' if the return value is a newline char.
5107 Updates `js2-ts-cursor' to the point after the returned char.
5108 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5109 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5111 ;; check for end of buffer
5112 (if (>= js2-ts-cursor (point-max))
5113 (setq js2-ts-hit-eof t
5114 js2-ts-cursor (1+ js2-ts-cursor)
5115 c js2-EOF_CHAR) ; return value
5116 ;; otherwise read next char
5117 (setq c (char-before (incf js2-ts-cursor)))
5118 ;; if we read a newline, update counters
5120 (setq js2-ts-line-start js2-ts-cursor
5121 js2-ts-lineno (1+ js2-ts-lineno)))
5122 ;; TODO: skip over format characters
5125 (defun js2-read-unicode-escape ()
5126 "Read a \\uNNNN sequence from the input.
5127 Assumes the ?\ and ?u have already been read.
5128 Returns the unicode character, or nil if it wasn't a valid character.
5129 Doesn't change the values of any scanner variables."
5130 ;; I really wish I knew a better way to do this, but I can't
5131 ;; find the Emacs function that takes a 16-bit int and converts
5132 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5133 ;; Have to first check that it's 4 hex characters or it may stop
5136 (let ((s (buffer-substring-no-properties js2-ts-cursor
5137 (+ 4 js2-ts-cursor))))
5138 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5139 (read (concat "?\\u" s))))))
5141 (defun js2-match-char (test)
5142 "Consume and return next character if it matches TEST, a character.
5143 Returns nil and consumes nothing if TEST is not the next character."
5144 (let ((c (js2-get-char)))
5150 (defun js2-peek-char ()
5155 (defun js2-java-identifier-start-p (c)
5158 (js2-char-uppercase-p c)
5159 (js2-char-lowercase-p c)))
5161 (defun js2-java-identifier-part-p (c)
5162 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5163 ;; TODO: make me Unicode-friendly. See comments above.
5166 (js2-char-uppercase-p c)
5167 (js2-char-lowercase-p c)
5168 (and (>= c ?0) (<= c ?9))))
5170 (defun js2-alpha-p (c)
5171 (cond ((and (<= ?A c) (<= c ?Z)) t)
5172 ((and (<= ?a c) (<= c ?z)) t)
5175 (defsubst js2-digit-p (c)
5176 (and (<= ?0 c) (<= c ?9)))
5178 (defun js2-js-space-p (c)
5180 (memq c '(#x20 #x9 #xB #xC #xD))
5183 ;; TODO: change this nil to check for Unicode space character
5186 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5188 (defun js2-skip-line ()
5189 "Skip to end of line."
5191 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5193 (setq js2-token-end js2-ts-cursor)))
5195 (defun js2-init-scanner (&optional buf line)
5196 "Create token stream for BUF starting on LINE.
5197 BUF defaults to `current-buffer' and LINE defaults to 1.
5199 A buffer can only have one scanner active at a time, which yields
5200 dramatically simpler code than using a defstruct. If you need to
5201 have simultaneous scanners in a buffer, copy the regions to scan
5203 (with-current-buffer (or buf (current-buffer))
5204 (setq js2-ts-dirty-line nil
5205 js2-ts-regexp-flags nil
5210 js2-ts-lineno (or line 1)
5211 js2-ts-line-end-char -1
5212 js2-ts-cursor (point-min)
5213 js2-ts-is-xml-attribute nil
5214 js2-ts-xml-is-tag-content nil
5215 js2-ts-xml-open-tags-count 0
5216 js2-ts-string-buffer nil)))
5218 ;; This function uses the cached op, string and number fields in
5219 ;; TokenStream; if getToken has been called since the passed token
5220 ;; was scanned, the op or string printed may be incorrect.
5221 (defun js2-token-to-string (token)
5222 ;; Not sure where this function is used in Rhino. Not tested.
5223 (if (not js2-debug-print-trees)
5225 (let ((name (js2-token-name token)))
5227 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5228 (concat name " `" js2-ts-string "'"))
5229 ((eq token js2-NUMBER)
5230 (format "NUMBER %g" js2-ts-number))
5234 (defconst js2-keywords
5236 case catch const continue
5237 debugger default delete do
5239 false finally for function
5240 if in instanceof import
5245 this throw true try typeof
5250 ;; Token names aren't exactly the same as the keywords, unfortunately.
5251 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5252 (defconst js2-kwd-tokens
5253 (let ((table (make-vector js2-num-tokens nil))
5256 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5257 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5259 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5260 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5265 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5270 (aset table i 'font-lock-keyword-face))
5271 (aset table js2-STRING 'font-lock-string-face)
5272 (aset table js2-REGEXP 'font-lock-string-face)
5273 (aset table js2-COMMENT 'font-lock-comment-face)
5274 (aset table js2-THIS 'font-lock-builtin-face)
5275 (aset table js2-VOID 'font-lock-constant-face)
5276 (aset table js2-NULL 'font-lock-constant-face)
5277 (aset table js2-TRUE 'font-lock-constant-face)
5278 (aset table js2-FALSE 'font-lock-constant-face)
5280 "Vector whose values are non-nil for tokens that are keywords.
5281 The values are default faces to use for highlighting the keywords.")
5283 (defconst js2-reserved-words
5291 implements import int interface
5294 package private protected public
5295 short static super synchronized
5299 (defconst js2-keyword-names
5300 (let ((table (make-hash-table :test 'equal)))
5301 (loop for k in js2-keywords
5303 (symbol-name k) ; instanceof
5304 (intern (concat "js2-"
5305 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5308 "JavaScript keywords by name, mapped to their symbols.")
5310 (defconst js2-reserved-word-names
5311 (let ((table (make-hash-table :test 'equal)))
5312 (loop for k in js2-reserved-words
5314 (puthash (symbol-name k) 'js2-RESERVED table))
5316 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5318 (defun js2-collect-string (buf)
5319 "Convert BUF, a list of chars, to a string.
5320 Reverses BUF before converting."
5324 ((null buf) ; for emacs21 compat
5328 (apply #'string (nreverse buf))
5331 (defun js2-string-to-keyword (s)
5332 "Return token for S, a string, if S is a keyword or reserved word.
5333 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5334 (or (gethash s js2-keyword-names)
5335 (gethash s js2-reserved-word-names)))
5337 (defsubst js2-ts-set-char-token-bounds ()
5338 "Used when next token is one character."
5339 (setq js2-token-beg (1- js2-ts-cursor)
5340 js2-token-end js2-ts-cursor))
5342 (defsubst js2-ts-return (token)
5343 "Return an N-character TOKEN from `js2-get-token'.
5344 Updates `js2-token-end' accordingly."
5345 (setq js2-token-end js2-ts-cursor)
5346 (throw 'return token))
5348 (defun js2-x-digit-to-int (c accumulator)
5349 "Build up a hex number.
5350 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5351 corresponding number. Otherwise return -1."
5354 ;; Use 0..9 < A..Z < a..z
5359 (throw 'check nil)))
5363 (throw 'check nil)))
5367 (throw 'check nil))))
5369 (logior c (lsh accumulator 4))))
5371 (defun js2-get-token ()
5372 "Return next JavaScript token, an int such as js2-RETURN."
5373 (let (c c1 identifier-start is-unicode-escape-start
5374 contains-escape escape-val escape-start str result base
5375 is-integer quote-char val look-for-slash continue)
5378 ;; Eat whitespace, possibly sensitive to newlines.
5381 (setq c (js2-get-char))
5383 ((eq c js2-EOF_CHAR)
5384 (js2-ts-set-char-token-bounds)
5385 (throw 'return js2-EOF))
5387 (js2-ts-set-char-token-bounds)
5388 (setq js2-ts-dirty-line nil)
5389 (throw 'return js2-EOL))
5390 ((not (js2-js-space-p c))
5391 (if (/= c ?-) ; in case end of HTML comment
5392 (setq js2-ts-dirty-line t))
5393 (setq continue nil))))
5394 ;; Assume the token will be 1 char - fixed up below.
5395 (js2-ts-set-char-token-bounds)
5397 (throw 'return js2-XMLATTR))
5398 ;; identifier/keyword/instanceof?
5399 ;; watch out for starting with a <backslash>
5402 (setq c (js2-get-char))
5404 (setq identifier-start t
5405 is-unicode-escape-start t
5406 js2-ts-string-buffer nil)
5407 (setq identifier-start nil)
5411 (when (setq identifier-start (js2-java-identifier-start-p c))
5412 (setq js2-ts-string-buffer nil)
5413 (js2-add-to-string c))))
5414 (when identifier-start
5415 (setq contains-escape is-unicode-escape-start)
5418 (if is-unicode-escape-start
5419 ;; strictly speaking we should probably push-back
5420 ;; all the bad characters if the <backslash>uXXXX
5421 ;; sequence is malformed. But since there isn't a
5422 ;; correct context(is there?) for a bad Unicode
5423 ;; escape sequence in an identifier, we can report
5428 (setq c (js2-get-char)
5429 escape-val (js2-x-digit-to-int c escape-val))
5430 ;; Next check takes care of c < 0 and bad escape
5431 (if (minusp escape-val)
5432 (throw 'break nil)))
5433 (if (minusp escape-val)
5434 (js2-report-scan-error "msg.invalid.escape" t))
5435 (js2-add-to-string escape-val)
5436 (setq is-unicode-escape-start nil))
5437 (setq c (js2-get-char))
5440 (setq c (js2-get-char))
5442 (setq is-unicode-escape-start t
5444 (js2-report-scan-error "msg.illegal.character" t)))
5446 (if (or (eq c js2-EOF_CHAR)
5447 (not (js2-java-identifier-part-p c)))
5449 (js2-add-to-string c))))))
5451 (setq str (js2-get-string-from-buffer))
5452 (unless contains-escape
5453 ;; OPT we shouldn't have to make a string (object!) to
5454 ;; check if it's a keyword.
5455 ;; Return the corresponding token if it's a keyword
5456 (when (setq result (js2-string-to-keyword str))
5457 (if (and (< js2-language-version 170)
5458 (memq result '(js2-LET js2-YIELD)))
5459 ;; LET and YIELD are tokens only in 1.7 and later
5460 (setq result 'js2-NAME))
5461 (if (not (eq result 'js2-RESERVED))
5462 (throw 'return (js2-token-code result)))
5463 (js2-report-warning "msg.reserved.keyword" str)))
5464 ;; If we want to intern these as Rhino does, just use (intern str)
5465 (setq js2-ts-string str)
5466 (throw 'return js2-NAME)) ; end identifier/kwd check
5468 (when (or (js2-digit-p c)
5469 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5470 (setq js2-ts-string-buffer nil
5473 (setq c (js2-get-char))
5475 ((or (eq c ?x) (eq c ?X))
5477 (setq c (js2-get-char)))
5481 (js2-add-to-string ?0))))
5483 (while (<= 0 (js2-x-digit-to-int c 0))
5484 (js2-add-to-string c)
5485 (setq c (js2-get-char)))
5486 (while (and (<= ?0 c) (<= c ?9))
5487 ;; We permit 08 and 09 as decimal numbers, which
5488 ;; makes our behavior a superset of the ECMA
5489 ;; numeric grammar. We might not always be so
5490 ;; permissive, so we warn about it.
5491 (when (and (eq base 8) (>= c ?8))
5492 (js2-report-warning "msg.bad.octal.literal"
5493 (if (eq c ?8) "8" "9"))
5495 (js2-add-to-string c)
5496 (setq c (js2-get-char))))
5498 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5499 (setq is-integer nil)
5502 (js2-add-to-string c)
5503 (setq c (js2-get-char))
5504 while (js2-digit-p c)))
5505 (when (memq c '(?e ?E))
5506 (js2-add-to-string c)
5507 (setq c (js2-get-char))
5508 (when (memq c '(?+ ?-))
5509 (js2-add-to-string c)
5510 (setq c (js2-get-char)))
5511 (unless (js2-digit-p c)
5512 (js2-report-scan-error "msg.missing.exponent" t))
5514 (js2-add-to-string c)
5515 (setq c (js2-get-char))
5516 while (js2-digit-p c))))
5518 (setq js2-ts-string (js2-get-string-from-buffer)
5520 (if (and (eq base 10) (not is-integer))
5521 (string-to-number js2-ts-string)
5522 ;; TODO: call runtime number-parser. Some of it is in
5523 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5524 (string-to-number js2-ts-string)))
5525 (throw 'return js2-NUMBER))
5527 (when (memq c '(?\" ?\'))
5528 ;; We attempt to accumulate a string the fast way, by
5529 ;; building it directly out of the reader. But if there
5530 ;; are any escaped characters in the string, we revert to
5531 ;; building it out of a string buffer.
5533 js2-ts-string-buffer nil
5536 (while (/= c quote-char)
5538 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5540 (setq js2-token-end js2-ts-cursor)
5541 (js2-report-error "msg.unterminated.string.lit")
5542 (throw 'return js2-STRING))
5544 ;; We've hit an escaped character
5545 (setq c (js2-get-char))
5554 (setq c1 (js2-read-unicode-escape))
5555 (if js2-parse-ide-mode
5558 ;; just copy the string in IDE-mode
5559 (js2-add-to-string ?\\)
5560 (js2-add-to-string ?u)
5562 (js2-add-to-string (js2-get-char)))
5563 (setq c (js2-get-char))) ; added at end of loop
5564 ;; flag it as an invalid escape
5565 (js2-report-warning "msg.invalid.escape"
5566 nil (- js2-ts-cursor 2) 6))
5567 ;; Get 4 hex digits; if the u escape is not
5568 ;; followed by 4 hex digits, use 'u' + the
5569 ;; literal character sequence that follows.
5570 (js2-add-to-string ?u)
5573 (setq c (js2-get-char)
5574 escape-val (js2-x-digit-to-int c escape-val))
5575 (if (minusp escape-val)
5576 (throw 'continue nil))
5577 (js2-add-to-string c))
5578 ;; prepare for replace of stored 'u' sequence by escape value
5579 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5582 ;; Get 2 hex digits, defaulting to 'x'+literal
5583 ;; sequence, as above.
5584 (setq c (js2-get-char)
5585 escape-val (js2-x-digit-to-int c 0))
5586 (if (minusp escape-val)
5588 (js2-add-to-string ?x)
5589 (throw 'continue nil))
5592 escape-val (js2-x-digit-to-int c escape-val))
5593 (if (minusp escape-val)
5595 (js2-add-to-string ?x)
5596 (js2-add-to-string c1)
5597 (throw 'continue nil))
5599 (setq c escape-val))))
5601 ;; Remove line terminator after escape to follow
5602 ;; SpiderMonkey and C/C++
5603 (setq c (js2-get-char))
5604 (throw 'continue nil))
5606 (when (and (<= ?0 c) (< c ?8))
5609 (when (and (<= ?0 c) (< c ?8))
5610 (setq val (- (+ (* 8 val) c) ?0)
5612 (when (and (<= ?0 c)
5615 ;; c is 3rd char of octal sequence only
5616 ;; if the resulting val <= 0377
5617 (setq val (- (+ (* 8 val) c) ?0)
5621 (js2-add-to-string c)
5622 (setq c (js2-get-char)))))
5623 (setq js2-ts-string (js2-get-string-from-buffer))
5624 (throw 'return js2-STRING))
5627 (throw 'return js2-SEMI))
5629 (throw 'return js2-LB))
5631 (throw 'return js2-RB))
5633 (throw 'return js2-LC))
5635 (throw 'return js2-RC))
5637 (throw 'return js2-LP))
5639 (throw 'return js2-RP))
5641 (throw 'return js2-COMMA))
5643 (throw 'return js2-HOOK))
5645 (if (js2-match-char ?:)
5646 (js2-ts-return js2-COLONCOLON)
5647 (throw 'return js2-COLON)))
5649 (if (js2-match-char ?.)
5650 (js2-ts-return js2-DOTDOT)
5651 (if (js2-match-char ?\()
5652 (js2-ts-return js2-DOTQUERY)
5653 (throw 'return js2-DOT))))
5655 (if (js2-match-char ?|)
5656 (throw 'return js2-OR)
5657 (if (js2-match-char ?=)
5658 (js2-ts-return js2-ASSIGN_BITOR)
5659 (throw 'return js2-BITOR))))
5661 (if (js2-match-char ?=)
5662 (js2-ts-return js2-ASSIGN_BITOR)
5663 (throw 'return js2-BITXOR)))
5665 (if (js2-match-char ?&)
5666 (throw 'return js2-AND)
5667 (if (js2-match-char ?=)
5668 (js2-ts-return js2-ASSIGN_BITAND)
5669 (throw 'return js2-BITAND))))
5671 (if (js2-match-char ?=)
5672 (if (js2-match-char ?=)
5673 (js2-ts-return js2-SHEQ)
5674 (throw 'return js2-EQ))
5675 (throw 'return js2-ASSIGN)))
5677 (if (js2-match-char ?=)
5678 (if (js2-match-char ?=)
5679 (js2-ts-return js2-SHNE)
5680 (js2-ts-return js2-NE))
5681 (throw 'return js2-NOT)))
5683 ;; NB:treat HTML begin-comment as comment-till-eol
5684 (when (js2-match-char ?!)
5685 (when (js2-match-char ?-)
5686 (when (js2-match-char ?-)
5688 (setq js2-ts-comment-type 'html)
5689 (throw 'return js2-COMMENT)))
5691 (if (js2-match-char ?<)
5692 (if (js2-match-char ?=)
5693 (js2-ts-return js2-ASSIGN_LSH)
5694 (js2-ts-return js2-LSH))
5695 (if (js2-match-char ?=)
5696 (js2-ts-return js2-LE)
5697 (throw 'return js2-LT))))
5699 (if (js2-match-char ?>)
5700 (if (js2-match-char ?>)
5701 (if (js2-match-char ?=)
5702 (js2-ts-return js2-ASSIGN_URSH)
5703 (js2-ts-return js2-URSH))
5704 (if (js2-match-char ?=)
5705 (js2-ts-return js2-ASSIGN_RSH)
5706 (js2-ts-return js2-RSH)))
5707 (if (js2-match-char ?=)
5708 (js2-ts-return js2-GE)
5709 (throw 'return js2-GT))))
5711 (if (js2-match-char ?=)
5712 (js2-ts-return js2-ASSIGN_MUL)
5713 (throw 'return js2-MUL)))
5715 ;; is it a // comment?
5716 (when (js2-match-char ?/)
5717 (setq js2-token-beg (- js2-ts-cursor 2))
5719 (setq js2-ts-comment-type 'line)
5720 ;; include newline so highlighting goes to end of window
5721 (incf js2-token-end)
5722 (throw 'return js2-COMMENT))
5723 ;; is it a /* comment?
5724 (when (js2-match-char ?*)
5725 (setq look-for-slash nil
5726 js2-token-beg (- js2-ts-cursor 2)
5728 (if (js2-match-char ?*)
5730 (setq look-for-slash t)
5734 (setq c (js2-get-char))
5736 ((eq c js2-EOF_CHAR)
5737 (setq js2-token-end (1- js2-ts-cursor))
5738 (js2-report-error "msg.unterminated.comment")
5739 (throw 'return js2-COMMENT))
5741 (setq look-for-slash t))
5744 (js2-ts-return js2-COMMENT)))
5746 (setq look-for-slash nil
5747 js2-token-end js2-ts-cursor)))))
5748 (if (js2-match-char ?=)
5749 (js2-ts-return js2-ASSIGN_DIV)
5750 (throw 'return js2-DIV)))
5752 (when js2-skip-preprocessor-directives
5754 (setq js2-ts-comment-type 'preprocessor
5755 js2-token-end js2-ts-cursor)
5756 (throw 'return js2-COMMENT))
5757 (throw 'return js2-ERROR))
5759 (if (js2-match-char ?=)
5760 (js2-ts-return js2-ASSIGN_MOD)
5761 (throw 'return js2-MOD)))
5763 (throw 'return js2-BITNOT))
5765 (if (js2-match-char ?=)
5766 (js2-ts-return js2-ASSIGN_ADD)
5767 (if (js2-match-char ?+)
5768 (js2-ts-return js2-INC)
5769 (throw 'return js2-ADD))))
5772 ((js2-match-char ?=)
5773 (setq c js2-ASSIGN_SUB))
5774 ((js2-match-char ?-)
5775 (unless js2-ts-dirty-line
5776 ;; treat HTML end-comment after possible whitespace
5777 ;; after line start as comment-until-eol
5778 (when (js2-match-char ?>)
5780 (setq js2-ts-comment-type 'html)
5781 (throw 'return js2-COMMENT)))
5785 (setq js2-ts-dirty-line t)
5788 (js2-report-scan-error "msg.illegal.character")))))))
5790 (defun js2-read-regexp (start-token)
5791 "Called by parser when it gets / or /= in literal context."
5793 in-class ; inside a '[' .. ']' character-class
5796 (setq js2-token-beg js2-ts-cursor
5797 js2-ts-string-buffer nil
5798 js2-ts-regexp-flags nil)
5799 (if (eq start-token js2-ASSIGN_DIV)
5801 (js2-add-to-string ?=)
5802 (if (not (eq start-token js2-DIV))
5803 (error "failed assertion")))
5804 (while (and (not err)
5805 (or (/= (setq c (js2-get-char)) ?/)
5810 (setq js2-token-end (1- js2-ts-cursor)
5812 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5813 (js2-report-error "msg.unterminated.re.lit"))
5816 (js2-add-to-string c)
5817 (setq c (js2-get-char)))
5821 (setq in-class nil)))
5822 (js2-add-to-string c))))
5826 ((js2-match-char ?g)
5828 ((js2-match-char ?i)
5830 ((js2-match-char ?m)
5833 (setq continue nil))))
5834 (if (js2-alpha-p (js2-peek-char))
5835 (js2-report-scan-error "msg.invalid.re.flag" t
5837 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5838 js2-ts-regexp-flags (js2-collect-string flags)
5839 js2-token-end js2-ts-cursor)
5840 ;; tell `parse-partial-sexp' to ignore this range of chars
5841 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5843 (defun js2-get-first-xml-token ()
5844 (setq js2-ts-xml-open-tags-count 0
5845 js2-ts-is-xml-attribute nil
5846 js2-ts-xml-is-tag-content nil)
5848 (js2-get-next-xml-token))
5850 (defun js2-xml-discard-string ()
5851 "Throw away the string in progress and flag an XML parse error."
5852 (setq js2-ts-string-buffer nil
5854 (js2-report-scan-error "msg.XML.bad.form" t))
5856 (defun js2-get-next-xml-token ()
5857 (setq js2-ts-string-buffer nil ; for recording the XML
5858 js2-token-beg js2-ts-cursor)
5863 (setq c (js2-get-char))
5866 (throw 'return js2-ERROR))
5867 (js2-ts-xml-is-tag-content
5870 (js2-add-to-string c)
5871 (setq js2-ts-xml-is-tag-content nil
5872 js2-ts-is-xml-attribute nil))
5874 (js2-add-to-string c)
5875 (when (eq ?> (js2-peek-char))
5876 (setq c (js2-get-char))
5877 (js2-add-to-string c)
5878 (setq js2-ts-xml-is-tag-content nil)
5879 (decf js2-ts-xml-open-tags-count)))
5882 (setq js2-ts-string (js2-get-string-from-buffer))
5883 (throw 'return js2-XML))
5885 (js2-add-to-string c)
5886 (unless (js2-read-quoted-string c)
5887 (throw 'return js2-ERROR)))
5889 (js2-add-to-string c)
5890 (setq js2-ts-is-xml-attribute t))
5892 (js2-add-to-string c))
5894 (js2-add-to-string c)
5895 (setq js2-ts-is-xml-attribute nil)))
5896 (when (and (not js2-ts-xml-is-tag-content)
5897 (zerop js2-ts-xml-open-tags-count))
5898 (setq js2-ts-string (js2-get-string-from-buffer))
5899 (throw 'return js2-XMLEND)))
5901 ;; else not tag content
5904 (js2-add-to-string c)
5905 (setq c (js2-peek-char))
5908 (setq c (js2-get-char)) ;; skip !
5909 (js2-add-to-string c)
5910 (setq c (js2-peek-char))
5913 (setq c (js2-get-char)) ;; skip -
5914 (js2-add-to-string c)
5917 (js2-add-to-string c)
5918 (unless (js2-read-xml-comment)
5919 (throw 'return js2-ERROR)))
5920 (js2-xml-discard-string)
5921 (throw 'return js2-ERROR)))
5923 (setq c (js2-get-char)) ;; skip [
5924 (js2-add-to-string c)
5925 (if (and (= (js2-get-char) ?C)
5926 (= (js2-get-char) ?D)
5927 (= (js2-get-char) ?A)
5928 (= (js2-get-char) ?T)
5929 (= (js2-get-char) ?A)
5930 (= (js2-get-char) ?\[))
5932 (js2-add-to-string ?C)
5933 (js2-add-to-string ?D)
5934 (js2-add-to-string ?A)
5935 (js2-add-to-string ?T)
5936 (js2-add-to-string ?A)
5937 (js2-add-to-string ?\[)
5938 (unless (js2-read-cdata)
5939 (throw 'return js2-ERROR)))
5940 (js2-xml-discard-string)
5941 (throw 'return js2-ERROR)))
5943 (unless (js2-read-entity)
5944 (throw 'return js2-ERROR))))
5945 ;; Allow bare CDATA section, e.g.:
5946 ;; let xml = <![CDATA[ foo bar baz ]]>;
5947 (when (zerop js2-ts-xml-open-tags-count)
5948 (throw 'return js2-XMLEND)))
5950 (setq c (js2-get-char)) ;; skip ?
5951 (js2-add-to-string c)
5952 (unless (js2-read-PI)
5953 (throw 'return js2-ERROR)))
5956 (setq c (js2-get-char)) ;; skip /
5957 (js2-add-to-string c)
5958 (when (zerop js2-ts-xml-open-tags-count)
5959 (js2-xml-discard-string)
5960 (throw 'return js2-ERROR))
5961 (setq js2-ts-xml-is-tag-content t)
5962 (decf js2-ts-xml-open-tags-count))
5965 (setq js2-ts-xml-is-tag-content t)
5966 (incf js2-ts-xml-open-tags-count))))
5969 (setq js2-ts-string (js2-get-string-from-buffer))
5970 (throw 'return js2-XML))
5972 (js2-add-to-string c))))))))
5973 (setq js2-token-end js2-ts-cursor)
5976 (defun js2-read-quoted-string (quote)
5979 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5980 (js2-add-to-string c)
5983 (js2-xml-discard-string) ;; throw away string in progress
5986 (defun js2-read-xml-comment ()
5987 (let ((c (js2-get-char)))
5989 (while (/= c js2-EOF_CHAR)
5991 (js2-add-to-string c)
5992 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5993 (setq c (js2-get-char))
5994 (js2-add-to-string c)
5995 (if (eq (js2-peek-char) ?>)
5997 (setq c (js2-get-char)) ;; skip >
5998 (js2-add-to-string c)
6000 (throw 'continue nil)))
6001 (setq c (js2-get-char))))
6002 (js2-xml-discard-string)
6005 (defun js2-read-cdata ()
6006 (let ((c (js2-get-char)))
6008 (while (/= c js2-EOF_CHAR)
6010 (js2-add-to-string c)
6011 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6012 (setq c (js2-get-char))
6013 (js2-add-to-string c)
6014 (if (eq (js2-peek-char) ?>)
6016 (setq c (js2-get-char)) ;; Skip >
6017 (js2-add-to-string c)
6019 (throw 'continue nil)))
6020 (setq c (js2-get-char))))
6021 (js2-xml-discard-string)
6024 (defun js2-read-entity ()
6028 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6029 (js2-add-to-string c)
6035 (if (zerop decl-tags)
6036 (throw 'return t)))))
6037 (js2-xml-discard-string)
6040 (defun js2-read-PI ()
6041 "Scan an XML processing instruction."
6044 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6045 (js2-add-to-string c)
6046 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6047 (setq c (js2-get-char)) ;; Skip >
6048 (js2-add-to-string c)
6050 (js2-xml-discard-string)
6053 (defun js2-scanner-get-line ()
6054 "Return the text of the current scan line."
6055 (buffer-substring (point-at-bol) (point-at-eol)))
6059 (defun js2-set-face (beg end face &optional record)
6060 "Fontify a region. If RECORD is non-nil, record for later."
6061 (when (plusp js2-highlight-level)
6062 (setq beg (min (point-max) beg)
6063 beg (max (point-min) beg)
6064 end (min (point-max) end)
6065 end (max (point-min) end))
6067 (push (list beg end face) js2-mode-fontifications)
6068 (put-text-property beg end 'font-lock-face face))))
6070 (defun js2-set-kid-face (pos kid len face)
6071 "Set-face on a child node.
6072 POS is absolute buffer position of parent.
6073 KID is the child node.
6074 LEN is the length to fontify.
6075 FACE is the face to fontify with."
6076 (js2-set-face (+ pos (js2-node-pos kid))
6077 (+ pos (js2-node-pos kid) (js2-node-len kid))
6080 (defsubst js2-fontify-kwd (start length)
6081 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6083 (defsubst js2-clear-face (beg end)
6084 (remove-text-properties beg end '(font-lock-face nil
6089 (defconst js2-ecma-global-props
6092 '("Infinity" "NaN" "undefined" "arguments") t)
6094 "Value properties of the Ecma-262 Global Object.
6095 Shown at or above `js2-highlight-level' 2.")
6097 ;; might want to add the name "arguments" to this list?
6098 (defconst js2-ecma-object-props
6101 '("prototype" "__proto__" "__parent__") t)
6103 "Value properties of the Ecma-262 Object constructor.
6104 Shown at or above `js2-highlight-level' 2.")
6106 (defconst js2-ecma-global-funcs
6110 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6111 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6113 "Function properties of the Ecma-262 Global object.
6114 Shown at or above `js2-highlight-level' 2.")
6116 (defconst js2-ecma-number-props
6118 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6120 "POSITIVE_INFINITY") t)
6122 "Properties of the Ecma-262 Number constructor.
6123 Shown at or above `js2-highlight-level' 2.")
6125 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6126 "Properties of the Ecma-262 Date constructor.
6127 Shown at or above `js2-highlight-level' 2.")
6129 (defconst js2-ecma-math-props
6132 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6135 "Properties of the Ecma-262 Math object.
6136 Shown at or above `js2-highlight-level' 2.")
6138 (defconst js2-ecma-math-funcs
6141 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6142 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6144 "Function properties of the Ecma-262 Math object.
6145 Shown at or above `js2-highlight-level' 2.")
6147 (defconst js2-ecma-function-props
6151 '(;; properties of the Object prototype object
6152 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6153 "toLocaleString" "toString" "valueOf"
6154 ;; properties of the Function prototype object
6156 ;; properties of the Array prototype object
6157 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6159 ;; properties of the String prototype object
6160 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6161 "localeCompare" "match" "replace" "search" "split" "substring"
6162 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6164 ;; properties of the Number prototype object
6165 "toExponential" "toFixed" "toPrecision"
6166 ;; properties of the Date prototype object
6167 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6168 "getMinutes" "getMonth" "getSeconds" "getTime"
6169 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6170 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6171 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6172 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6173 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6174 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6175 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6176 "toTimeString" "toUTCString"
6177 ;; properties of the RegExp prototype object
6179 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6180 "toSource" "__defineGetter__" "__defineSetter__"
6181 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6182 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6185 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6186 Shown at or above `js2-highlight-level' 3.")
6188 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6189 (let ((target-name (and target
6190 (js2-name-node-p target)
6191 (js2-name-node-name target)))
6192 (prop-name (if prop (js2-name-node-name prop)))
6193 (level1 (>= js2-highlight-level 1))
6194 (level2 (>= js2-highlight-level 2))
6195 (level3 (>= js2-highlight-level 3))
6202 ((and level3 (string-match js2-ecma-function-props prop-name))
6203 (setq face 'font-lock-builtin-face))
6204 ((and target-name prop)
6206 ((string= target-name "Date")
6207 (if (string-match js2-ecma-date-props prop-name)
6208 (setq face 'font-lock-builtin-face)))
6209 ((string= target-name "Math")
6210 (if (string-match js2-ecma-math-funcs prop-name)
6211 (setq face 'font-lock-builtin-face)))))))
6213 (if (string-match js2-ecma-global-funcs prop-name)
6214 (setq face 'font-lock-builtin-face))))
6218 ((string= target-name "Number")
6219 (if (string-match js2-ecma-number-props prop-name)
6220 (setq face 'font-lock-constant-face)))
6221 ((string= target-name "Math")
6222 (if (string-match js2-ecma-math-props prop-name)
6223 (setq face 'font-lock-constant-face)))))
6225 (if (string-match js2-ecma-object-props prop-name)
6226 (setq face 'font-lock-constant-face)))))
6228 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6229 (js2-node-pos prop))) ; relative
6230 (+ pos (js2-node-len prop))
6233 (defun js2-parse-highlight-member-expr-node (node)
6234 "Perform syntax highlighting of EcmaScript built-in properties.
6235 The variable `js2-highlight-level' governs this highighting."
6236 (let (face target prop name pos end parent call-p callee)
6238 ;; case 1: simple name, e.g. foo
6239 ((js2-name-node-p node)
6240 (setq name (js2-name-node-name node))
6241 ;; possible for name to be nil in rare cases - saw it when
6242 ;; running js2-mode on an elisp buffer. Might as well try to
6243 ;; make it so js2-mode never barfs.
6245 (setq face (if (string-match js2-ecma-global-props name)
6246 'font-lock-constant-face))
6248 (setq pos (js2-node-pos node)
6249 end (+ pos (js2-node-len node)))
6250 (js2-set-face pos end face))))
6251 ;; case 2: property access or function call
6252 ((or (js2-prop-get-node-p node)
6253 ;; highlight function call if expr is a prop-get node
6254 ;; or a plain name (i.e. unqualified function call)
6255 (and (setq call-p (js2-call-node-p node))
6256 (setq callee (js2-call-node-target node)) ; separate setq!
6257 (or (js2-prop-get-node-p callee)
6258 (js2-name-node-p callee))))
6260 node (if call-p callee node))
6261 (if (and call-p (js2-name-node-p callee))
6263 (setq target (js2-prop-get-node-left node)
6264 prop (js2-prop-get-node-right node)))
6266 ((js2-name-node-p target)
6267 (if (js2-name-node-p prop)
6268 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6269 (js2-parse-highlight-prop-get parent target prop call-p)
6270 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6271 (js2-parse-highlight-prop-get parent target nil call-p)))
6272 ((js2-name-node-p prop)
6273 ;; case 2c: complex target, simple name, e.g. x[y].bar
6274 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6276 (defun js2-parse-highlight-member-expr-fn-name (expr)
6277 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6278 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6279 We currently only handle the case where the last component is a prop-get
6280 of a simple name. Called before EXPR has a parent node."
6282 (name (and (js2-prop-get-node-p expr)
6283 (js2-prop-get-node-right expr))))
6284 (when (js2-name-node-p name)
6285 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6286 (js2-node-pos name)))
6287 (+ pos (js2-node-len name))
6288 'font-lock-function-name-face
6291 ;; source: http://jsdoc.sourceforge.net/
6292 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6293 ;; allows type specifications, and needs work before entering the wild.
6295 (defconst js2-jsdoc-param-tag-regexp
6296 (concat "^\\s-*\\*+\\s-*\\(@"
6297 "\\(?:param\\|argument\\)"
6299 "\\s-*\\({[^}]+}\\)?" ; optional type
6300 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6302 "Matches jsdoc tags with optional type and optional param name.")
6304 (defconst js2-jsdoc-typed-tag-regexp
6305 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6319 "\\)\\)\\s-*\\({[^}]+}\\)?")
6320 "Matches jsdoc tags with optional type.")
6322 (defconst js2-jsdoc-arg-tag-regexp
6323 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6346 "\\)\\)\\s-+\\([^ \t]+\\)")
6347 "Matches jsdoc tags with a single argument.")
6349 (defconst js2-jsdoc-empty-tag-regexp
6350 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6390 "Matches empty jsdoc tags.")
6392 (defconst js2-jsdoc-link-tag-regexp
6393 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6394 "Matches a jsdoc link or code tag.")
6396 (defconst js2-jsdoc-see-tag-regexp
6397 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6398 "Matches a jsdoc @see tag.")
6400 (defconst js2-jsdoc-html-tag-regexp
6401 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6402 "Matches a simple (no attributes) html start- or end-tag.")
6404 (defun js2-jsdoc-highlight-helper ()
6405 (js2-set-face (match-beginning 1)
6407 'js2-jsdoc-tag-face)
6408 (if (match-beginning 2)
6410 (goto-char (match-beginning 2))
6411 (= (char-after) ?{))
6412 (js2-set-face (1+ (match-beginning 2))
6414 'js2-jsdoc-type-face)
6415 (js2-set-face (match-beginning 2)
6417 'js2-jsdoc-value-face)))
6418 (if (match-beginning 3)
6419 (js2-set-face (match-beginning 3)
6421 'js2-jsdoc-value-face)))
6423 (defun js2-highlight-jsdoc (ast)
6424 "Highlight doc comment tags."
6425 (let ((comments (js2-ast-root-comments ast))
6428 (dolist (node comments)
6429 (when (eq (js2-comment-node-format node) 'jsdoc)
6430 (setq beg (js2-node-abs-pos node)
6431 end (+ beg (js2-node-len node)))
6433 (narrow-to-region beg end)
6434 (dolist (re (list js2-jsdoc-param-tag-regexp
6435 js2-jsdoc-typed-tag-regexp
6436 js2-jsdoc-arg-tag-regexp
6437 js2-jsdoc-link-tag-regexp
6438 js2-jsdoc-see-tag-regexp
6439 js2-jsdoc-empty-tag-regexp))
6441 (while (re-search-forward re nil t)
6442 (js2-jsdoc-highlight-helper)))
6443 ;; simple highlighting for html tags
6445 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6446 (js2-set-face (match-beginning 1)
6448 'js2-jsdoc-html-tag-delimiter-face)
6449 (js2-set-face (match-beginning 2)
6451 'js2-jsdoc-html-tag-name-face)
6452 (js2-set-face (match-beginning 3)
6454 'js2-jsdoc-html-tag-delimiter-face))))))))
6456 (defun js2-highlight-assign-targets (node left right)
6457 "Highlight function properties and external variables."
6458 (let (leftpos end name)
6459 ;; highlight vars and props assigned function values
6460 (when (js2-function-node-p right)
6462 ;; var foo = function() {...}
6463 ((js2-name-node-p left)
6465 ;; foo.bar.baz = function() {...}
6466 ((and (js2-prop-get-node-p left)
6467 (js2-name-node-p (js2-prop-get-node-right left)))
6468 (setq name (js2-prop-get-node-right left))))
6470 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6471 (+ leftpos (js2-node-len name))
6472 'font-lock-function-name-face
6475 (defun js2-record-name-node (node)
6476 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6477 later. NODE must be a name node."
6479 (push (list node js2-current-scope
6480 (setq leftpos (js2-node-abs-pos node))
6481 (setq end (+ leftpos (js2-node-len node))))
6482 js2-recorded-identifiers)))
6484 (defun js2-highlight-undeclared-vars ()
6485 "After entire parse is finished, look for undeclared variable references.
6486 We have to wait until entire buffer is parsed, since JavaScript permits var
6487 decls to occur after they're used.
6489 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6490 it is considered declared."
6492 (dolist (entry js2-recorded-identifiers)
6493 (destructuring-bind (name-node scope pos end) entry
6494 (setq name (js2-name-node-name name-node))
6495 (unless (or (member name js2-global-externs)
6496 (member name js2-default-externs)
6497 (member name js2-additional-externs)
6498 (js2-get-defining-scope scope name))
6499 (js2-set-face pos end 'js2-external-variable-face 'record)
6500 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6501 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6502 (setq js2-recorded-identifiers nil)))
6506 ;; We currently only support imenu, but eventually should support speedbar and
6507 ;; possibly other browsing mechanisms.
6509 ;; The basic strategy is to identify function assignment targets of the form
6510 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6511 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6512 ;; for imenu after parsing is finished.
6514 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6515 ;; JavaScript, and the general problem is undecidable. However, several forms
6516 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6519 ;; function foo() -- function declaration
6520 ;; foo = function() -- function expression assigned to variable
6521 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6522 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6523 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6524 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6525 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6526 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6527 ;; function foo() {function bar() {...}} -- nested function
6528 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6530 ;; This list boils down to a few forms that can be combined recursively.
6531 ;; Top-level named function declarations include both the left-hand (name)
6532 ;; and the right-hand (function value) expressions needed to produce an imenu
6533 ;; entry. The other "right-hand" forms we need to look for are:
6534 ;; - functions declared as props/getters/setters in object literals
6535 ;; - nested named function declarations
6536 ;; The "left-hand" expressions that functions can be assigned to include:
6537 ;; - local/global variables
6538 ;; - nested property-get expressions like a.b.c.d
6539 ;; - element gets like foo[10] or foo['bar'] where the index
6540 ;; expression can be trivially converted to a property name. They
6541 ;; effectively then become property gets.
6543 ;; All the different definition types are canonicalized into the form
6544 ;; foo.bar.baz = position-of-function-keyword
6546 ;; We need to build a trie-like structure for imenu. As an example,
6547 ;; consider the following JavaScript code:
6549 ;; a = function() {...} // function at position 5
6550 ;; b = function() {...} // function at position 25
6551 ;; foo = function() {...} // function at position 100
6552 ;; foo.bar = function() {...} // function at position 200
6553 ;; foo.bar.baz = function() {...} // function at position 300
6554 ;; foo.bar.zab = function() {...} // function at position 400
6556 ;; During parsing we accumulate an entry for each definition in
6557 ;; the variable `js2-imenu-recorder', like so:
6563 ;; (fn foo bar baz 300)
6564 ;; (fn foo bar zab 400))
6566 ;; Where 'fn' is the respective function node.
6567 ;; After parsing these entries are merged into this alist-trie:
6571 ;; (foo (<definition> . 3)
6572 ;; (bar (<definition> . 6)
6576 ;; Note the wacky need for a <definition> name. The token can be anything
6577 ;; that isn't a valid JavaScript identifier, because you might make foo
6578 ;; a function and then start setting properties on it that are also functions.
6580 (defun js2-prop-node-name (node)
6581 "Return the name of a node that may be a property-get/property-name.
6582 If NODE is not a valid name-node, string-node or integral number-node,
6583 returns nil. Otherwise returns the string name/value of the node."
6585 ((js2-name-node-p node)
6586 (js2-name-node-name node))
6587 ((js2-string-node-p node)
6588 (js2-string-node-value node))
6589 ((and (js2-number-node-p node)
6590 (string-match "^[0-9]+$" (js2-number-node-value node)))
6591 (js2-number-node-value node))
6592 ((js2-this-node-p node)
6595 (defun js2-node-qname-component (node)
6596 "Return the name of this node, if it contributes to a qname.
6597 Returns nil if the node doesn't contribute."
6599 (or (js2-prop-node-name node)
6600 (if (and (js2-function-node-p node)
6601 (js2-function-node-name node))
6602 (js2-name-node-name (js2-function-node-name node))))))
6604 (defun js2-record-imenu-entry (fn-node qname pos)
6605 "Add an entry to `js2-imenu-recorder'.
6606 FN-NODE should be the current item's function node.
6608 Associate FN-NODE with its QNAME for later lookup.
6609 This is used in postprocessing the chain list. For each chain, we find
6610 the parent function, look up its qname, then prepend a copy of it to the chain."
6611 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6612 (unless js2-imenu-function-map
6613 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6614 (puthash fn-node qname js2-imenu-function-map))
6616 (defun js2-record-imenu-functions (node &optional var)
6617 "Record function definitions for imenu.
6618 NODE is a function node or an object literal.
6619 VAR, if non-nil, is the expression that NODE is being assigned to."
6620 (when js2-parse-ide-mode
6621 (let ((fun-p (js2-function-node-p node))
6622 qname left fname-node pos)
6624 ;; non-anonymous function declaration?
6627 (setq fname-node (js2-function-node-name node)))
6628 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6629 ;; for remaining forms, compute left-side tree branch first
6630 ((and var (setq qname (js2-compute-nested-prop-get var)))
6632 ;; foo.bar.baz = function
6634 (js2-record-imenu-entry node qname (js2-node-pos node)))
6635 ;; foo.bar.baz = object-literal
6636 ;; look for nested functions: {a: {b: function() {...} }}
6637 ((js2-object-node-p node)
6638 ;; Node position here is still absolute, since the parser
6639 ;; passes the assignment target and value expressions
6640 ;; to us before they are added as children of the assignment node.
6641 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6643 (defun js2-compute-nested-prop-get (node)
6644 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6645 component nodes as a list. Otherwise return nil. Element-gets are treated
6646 as property-gets if the index expression is a string, or a positive integer."
6647 (let (left right head)
6649 ((or (js2-name-node-p node)
6650 (js2-this-node-p node))
6652 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6653 ((js2-prop-get-node-p node) ; foo.bar
6654 (setq left (js2-prop-get-node-left node)
6655 right (js2-prop-get-node-right node))
6656 (if (setq head (js2-compute-nested-prop-get left))
6657 (nconc head (list right))))
6658 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6659 (setq left (js2-elem-get-node-target node)
6660 right (js2-elem-get-node-element node))
6661 (if (or (js2-string-node-p right) ; ['bar']
6662 (and (js2-number-node-p right) ; [10]
6663 (string-match "^[0-9]+$"
6664 (js2-number-node-value right))))
6665 (if (setq head (js2-compute-nested-prop-get left))
6666 (nconc head (list right))))))))
6668 (defun js2-record-object-literal (node qname pos)
6669 "Recursively process an object literal looking for functions.
6670 NODE is an object literal that is the right-hand child of an assignment
6671 expression. QNAME is a list of nodes representing the assignment target,
6672 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6673 POS is the absolute position of the node.
6674 We do a depth-first traversal of NODE. For any functions we find,
6675 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6676 (let (left right prop-qname)
6677 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6678 (let ((left (js2-infix-node-left e))
6679 ;; Element positions are relative to the parent position.
6680 (pos (+ pos (js2-node-pos e))))
6682 ;; foo: function() {...}
6683 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6684 (when (js2-prop-node-name left)
6685 ;; As a policy decision, we record the position of the property,
6686 ;; not the position of the `function' keyword, since the property
6687 ;; is effectively the name of the function.
6688 (js2-record-imenu-entry right (append qname (list left)) pos)))
6689 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6690 ((js2-object-node-p right)
6691 (js2-record-object-literal right
6692 (append qname (list (js2-infix-node-left e)))
6693 (+ pos (js2-node-pos right)))))))))
6695 (defun js2-node-top-level-decl-p (node)
6696 "Return t if NODE's name is defined in the top-level scope.
6697 Also returns t if NODE's name is not defined in any scope, since it implies
6698 that it's an external variable, which must also be in the top-level scope."
6699 (let* ((name (js2-prop-node-name node))
6700 (this-scope (js2-node-get-enclosing-scope node))
6703 ((js2-this-node-p node)
6707 ((setq defining-scope (js2-get-defining-scope this-scope name))
6708 (js2-ast-root-p defining-scope))
6711 (defun js2-wrapper-function-p (node)
6712 "Returns t if NODE is a function expression that's immediately invoked.
6713 NODE must be `js2-function-node'."
6714 (let ((parent (js2-node-parent node)))
6716 ;; function(){...}();
6717 (js2-call-node-p parent)
6718 (and (js2-paren-node-p parent)
6719 ;; (function(){...})();
6720 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6721 ;; (function(){...}).call(this);
6722 (and (js2-prop-get-node-p parent)
6723 (member (js2-name-node-name (js2-prop-get-node-right parent))
6725 (js2-call-node-p (js2-node-parent parent))))))))
6727 (defun js2-browse-postprocess-chains (entries)
6728 "Modify function-declaration name chains after parsing finishes.
6729 Some of the information is only available after the parse tree is complete.
6730 For instance, processing a nested scope requires a parent function node."
6731 (let (result head fn current-fn parent-qname qname p elem)
6732 (dolist (entry entries)
6733 ;; function node goes first
6734 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6735 ;; examine its defining scope;
6736 ;; if top-level/external, keep as-is
6737 (if (js2-node-top-level-decl-p head)
6739 (when (js2-this-node-p head)
6740 (setq chain (cdr chain))) ; discard this-node
6741 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6742 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6743 (when (eq parent-qname 'not-found)
6744 ;; anonymous function expressions are not recorded
6745 ;; during the parse, so we need to handle this case here
6747 (if (js2-wrapper-function-p fn)
6748 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6749 (if (js2-ast-root-p grandparent)
6751 (gethash grandparent js2-imenu-function-map 'skip)))
6753 (puthash fn parent-qname js2-imenu-function-map))
6754 (unless (eq parent-qname 'skip)
6755 ;; prefix parent fn qname to this chain.
6756 (let ((qname (append parent-qname chain)))
6757 (puthash current-fn (butlast qname) js2-imenu-function-map)
6758 (push qname result)))))))
6759 ;; finally replace each node in each chain with its name.
6760 (dolist (chain result)
6763 (if (js2-node-p (setq elem (car p)))
6764 (setcar p (js2-node-qname-component elem)))
6768 ;; Merge name chains into a trie-like tree structure of nested lists.
6769 ;; To simplify construction of the trie, we first build it out using the rule
6770 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6771 ;; [key, num-or-list]. The second element can be a number; if so, this key
6772 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6773 ;; associated with the key at this level.) Otherwise the second element is
6774 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6775 ;; a simple recursive formulation.
6777 ;; js2-mode is building the data structure for imenu. The imenu documentation
6778 ;; claims that it's the structure above, but in practice it wants the children
6779 ;; at the same list level as the key for that level, which is how I've drawn
6780 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6781 ;; list wrapper around the children at each level.
6783 ;; A completed nested imenu-alist entry looks like this:
6785 ;; ("<definition>" . 7)
6790 ;; In particular, the documentation for `imenu--index-alist' says that
6791 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6792 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6794 (defun js2-treeify (lst)
6795 "Convert (a b c d) to (a ((b ((c d)))))."
6796 (if (null (cddr lst)) ; list length <= 2
6798 (list (car lst) (list (js2-treeify (cdr lst))))))
6800 (defun js2-build-alist-trie (chains trie)
6801 "Merge declaration name chains into a trie-like alist structure for imenu.
6802 CHAINS is the qname chain list produced during parsing. TRIE is a
6803 list of elements built up so far."
6804 (let (head tail pos branch kids)
6805 (dolist (chain chains)
6806 (setq head (car chain)
6808 pos (if (numberp (car tail)) (car tail))
6809 branch (js2-find-if (lambda (n)
6810 (string= (car n) head))
6812 kids (second branch))
6814 ;; case 1: this key isn't in the trie yet
6817 (setcdr (last trie) (list (js2-treeify chain)))
6818 (setq trie (list (js2-treeify chain)))))
6819 ;; case 2: key is present with a single number entry: replace w/ list
6820 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6821 ;; ("<definition>" 20)))
6823 (setcar (cdr branch)
6824 (list (list "<definition-1>" kids)
6826 (list "<definition-2>" pos)
6827 (js2-treeify tail)))))
6828 ;; case 3: key is there (with kids), and we're a number entry
6832 (list (format "<definition-%d>"
6833 (1+ (loop for kid in kids
6834 count (eq ?< (aref (car kid) 0)))))
6836 ;; case 4: key is there with kids, need to merge in our chain
6838 (js2-build-alist-trie (list tail) kids))))
6841 (defun js2-flatten-trie (trie)
6842 "Convert TRIE to imenu-format.
6843 Recurses through nodes, and for each one whose second element is a list,
6844 appends the list's flattened elements to the current element. Also
6845 changes the tails into conses. For instance, this pre-flattened trie
6857 Note that the root of the trie has no key, just a list of chains.
6858 This is also true for the value of any key with multiple children,
6859 e.g. key 'c' in the example above."
6862 (mapcar #'js2-flatten-trie trie))
6864 (if (numberp (second trie))
6865 (cons (car trie) (second trie))
6866 ;; else pop list and append its kids
6867 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6869 (defun js2-build-imenu-index ()
6870 "Turn `js2-imenu-recorder' into an imenu data structure."
6871 (unless (eq js2-imenu-recorder 'empty)
6872 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6873 (result (js2-build-alist-trie chains nil)))
6874 (js2-flatten-trie result))))
6876 (defun js2-test-print-chains (chains)
6877 "Print a list of qname chains.
6878 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6879 i.e. one or more nodes, and an integer position as the list tail."
6880 (mapconcat (lambda (chain)
6882 (mapconcat (lambda (elem)
6883 (if (js2-node-p elem)
6884 (or (js2-node-qname-component elem)
6886 (number-to-string elem)))
6895 (defconst js2-version "1.8.0"
6896 "Version of JavaScript supported, plus minor js2 version.")
6898 (defmacro js2-record-face (face)
6899 "Record a style run of FACE for the current token."
6900 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6902 (defsubst js2-node-end (n)
6903 "Computes the absolute end of node N.
6904 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6905 is only true until the node is added to its parent; i.e., while parsing."
6909 (defun js2-record-comment ()
6910 "Record a comment in `js2-scanned-comments'."
6911 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6912 :format js2-ts-comment-type)
6913 js2-scanned-comments)
6914 (when js2-parse-ide-mode
6915 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6917 'font-lock-comment-face))
6918 (when (memq js2-ts-comment-type '(html preprocessor))
6919 ;; Tell cc-engine the bounds of the comment.
6920 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6922 ;; This function is called depressingly often, so it should be fast.
6923 ;; Most of the time it's looking at the same token it peeked before.
6924 (defun js2-peek-token ()
6925 "Return the next token without consuming it.
6926 If previous token was consumed, calls scanner to get new token.
6927 If previous token was -not- consumed, returns it (idempotent).
6929 This function will not return a newline (js2-EOL) - instead, it
6930 gobbles newlines until it finds a non-newline token, and flags
6931 that token as appearing just after a newline.
6933 This function will also not return a js2-COMMENT. Instead, it
6934 records comments found in `js2-scanned-comments'. If the token
6935 returned by this function immediately follows a jsdoc comment,
6936 the token is flagged as such.
6938 Note that this function always returned the un-flagged token!
6939 The flags, if any, are saved in `js2-current-flagged-token'."
6940 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6941 js2-current-token ; most common case - return already-peeked token
6942 (let ((tt (js2-get-token)) ; call scanner
6945 ;; process comments and whitespace
6946 (while (or (= tt js2-EOL)
6951 (if js2-record-comments
6952 (js2-record-comment)))
6953 (setq tt (js2-get-token))) ; call scanner
6954 (setq js2-current-token tt
6955 js2-current-flagged-token (if saw-eol
6956 (logior tt js2-ti-after-eol)
6958 ;; perform lexical fontification as soon as token is scanned
6959 (when js2-parse-ide-mode
6962 (js2-record-face 'js2-error-face))
6963 ((setq face (aref js2-kwd-tokens tt))
6964 (js2-record-face face))
6965 ((and (= tt js2-NAME)
6966 (equal js2-ts-string "undefined"))
6967 (js2-record-face 'font-lock-constant-face))))
6968 tt))) ; return unflagged token
6970 (defun js2-peek-flagged-token ()
6971 "Returns the current token along with any flags set for it."
6973 js2-current-flagged-token)
6975 (defsubst js2-consume-token ()
6976 (setq js2-current-flagged-token js2-EOF))
6978 (defun js2-next-token ()
6981 (js2-consume-token)))
6983 (defun js2-next-flagged-token ()
6985 (prog1 js2-current-flagged-token
6986 (js2-consume-token)))
6988 (defun js2-match-token (match)
6989 "Consume and return t if next token matches MATCH, a bytecode.
6990 Returns nil and consumes nothing if MATCH is not the next token."
6991 (if (/= (js2-peek-token) match)
6996 (defun js2-valid-prop-name-token (tt)
6998 (and js2-allow-keywords-as-property-names
7000 (aref js2-kwd-tokens tt))))
7002 (defun js2-match-prop-name ()
7003 "Consume token and return t if next token is a valid property name.
7004 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7005 is non-nil and it's a keyword token."
7006 (if (js2-valid-prop-name-token (js2-peek-token))
7012 (defun js2-must-match-prop-name (msg-id &optional pos len)
7013 (if (js2-match-prop-name)
7015 (js2-report-error msg-id nil pos len)
7018 (defun js2-peek-token-or-eol ()
7019 "Return js2-EOL if the current token immediately follows a newline.
7020 Else returns the current token. Used in situations where we don't
7021 consider certain token types valid if they are preceded by a newline.
7022 One example is the postfix ++ or -- operator, which has to be on the
7023 same line as its operand."
7024 (let ((tt (js2-peek-token)))
7025 ;; Check for last peeked token flags
7026 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7030 (defun js2-set-check-for-label ()
7031 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7032 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7034 (defun js2-must-match (token msg-id &optional pos len)
7035 "Match next token to token code TOKEN, or record a syntax error.
7036 MSG-ID is the error message to report if the match fails.
7037 Returns t on match, nil if no match."
7038 (if (js2-match-token token)
7040 (js2-report-error msg-id nil pos len)
7043 (defsubst js2-inside-function ()
7044 (plusp js2-nesting-of-function))
7046 (defun js2-set-requires-activation ()
7047 (if (js2-function-node-p js2-current-script-or-fn)
7048 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7050 (defun js2-check-activation-name (name token)
7051 (when (js2-inside-function)
7052 ;; skip language-version 1.2 check from Rhino
7053 (if (or (string= "arguments" name)
7054 (and js2-compiler-activation-names ; only used in codegen
7055 (gethash name js2-compiler-activation-names)))
7056 (js2-set-requires-activation))))
7058 (defun js2-set-is-generator ()
7059 (if (js2-function-node-p js2-current-script-or-fn)
7060 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7062 (defun js2-must-have-xml ()
7063 (unless js2-compiler-xml-available
7064 (js2-report-error "msg.XML.not.available")))
7066 (defun js2-push-scope (scope)
7067 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7068 (assert (js2-scope-p scope))
7069 (assert (null (js2-scope-parent-scope scope)))
7070 (assert (not (eq js2-current-scope scope)))
7071 (setf (js2-scope-parent-scope scope) js2-current-scope
7072 js2-current-scope scope))
7074 (defsubst js2-pop-scope ()
7075 (setq js2-current-scope
7076 (js2-scope-parent-scope js2-current-scope)))
7078 (defun js2-enter-loop (loop-node)
7079 (push loop-node js2-loop-set)
7080 (push loop-node js2-loop-and-switch-set)
7081 (js2-push-scope loop-node)
7082 ;; Tell the current labeled statement (if any) its statement,
7083 ;; and set the jump target of the first label to the loop.
7084 ;; These are used in `js2-parse-continue' to verify that the
7085 ;; continue target is an actual labeled loop. (And for codegen.)
7086 (when js2-labeled-stmt
7087 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7088 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7089 js2-labeled-stmt))) loop-node)))
7091 (defun js2-exit-loop ()
7093 (pop js2-loop-and-switch-set)
7096 (defsubst js2-enter-switch (switch-node)
7097 (push switch-node js2-loop-and-switch-set))
7099 (defsubst js2-exit-switch ()
7100 (pop js2-loop-and-switch-set))
7102 (defun js2-parse (&optional buf cb)
7103 "Tell the js2 parser to parse a region of JavaScript.
7105 BUF is a buffer or buffer name containing the code to parse.
7106 Call `narrow-to-region' first to parse only part of the buffer.
7108 The returned AST root node is given some additional properties:
7109 `node-count' - total number of nodes in the AST
7110 `buffer' - BUF. The buffer it refers to may change or be killed,
7111 so the value is not necessarily reliable.
7113 An optional callback CB can be specified to report parsing
7114 progress. If `(functionp CB)' returns t, it will be called with
7115 the current line number once before parsing begins, then again
7116 each time the lexer reaches a new line number.
7118 CB can also be a list of the form `(symbol cb ...)' to specify
7119 multiple callbacks with different criteria. Each symbol is a
7120 criterion keyword, and the following element is the callback to
7123 :line - called whenever the line number changes
7124 :token - called for each new token consumed
7126 The list of criteria could be extended to include entering or
7127 leaving a statement, an expression, or a function definition."
7128 (if (and cb (not (functionp cb)))
7129 (error "criteria callbacks not yet implemented"))
7130 (let ((inhibit-point-motion-hooks t)
7131 (js2-compiler-xml-available (>= js2-language-version 160))
7132 ;; This is a recursive-descent parser, so give it a big stack.
7133 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7134 (max-specpdl-size (max max-specpdl-size 3000))
7135 (case-fold-search nil)
7137 (message nil) ; clear any error message from previous parse
7138 (with-current-buffer (or buf (current-buffer))
7139 (setq js2-scanned-comments nil
7140 js2-parsed-errors nil
7141 js2-parsed-warnings nil
7142 js2-imenu-recorder nil
7143 js2-imenu-function-map nil
7146 (setq ast (with-silent-modifications
7148 (unless js2-ts-hit-eof
7149 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7150 (setf (js2-ast-root-errors ast) js2-parsed-errors
7151 (js2-ast-root-warnings ast) js2-parsed-warnings)
7152 ;; if we didn't find any declarations, put a dummy in this list so we
7153 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7154 (unless js2-imenu-recorder
7155 (setq js2-imenu-recorder 'empty))
7156 (run-hooks 'js2-parse-finished-hook)
7159 ;; Corresponds to Rhino's Parser.parse() method.
7160 (defun js2-do-parse ()
7161 "Parse current buffer starting from current point.
7162 Scanner should be initialized."
7163 (let ((pos js2-ts-cursor)
7164 (end js2-ts-cursor) ; in case file is empty
7166 ;; initialize buffer-local parsing vars
7167 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7168 js2-current-script-or-fn root
7169 js2-current-scope root
7170 js2-current-flagged-token js2-EOF
7171 js2-nesting-of-function 0
7172 js2-labeled-stmt nil
7173 js2-recorded-identifiers nil) ; for js2-highlight
7174 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7175 (if (= tt js2-FUNCTION)
7178 (setq n (js2-parse-function (if js2-called-by-compile-function
7179 'FUNCTION_EXPRESSION
7180 'FUNCTION_STATEMENT))))
7181 ;; not a function - parse a statement
7182 (setq n (js2-parse-statement)))
7183 ;; add function or statement to script
7184 (setq end (js2-node-end n))
7185 (js2-block-node-push root n))
7186 ;; add comments to root in lexical order
7187 (when js2-scanned-comments
7188 ;; if we find a comment beyond end of normal kids, use its end
7189 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7190 (dolist (comment js2-scanned-comments)
7191 (push comment (js2-ast-root-comments root))
7192 (js2-node-add-children root comment)))
7193 (setf (js2-node-len root) (- end pos))
7194 ;; Give extensions a chance to muck with things before highlighting starts.
7195 (let ((js2-additional-externs js2-additional-externs))
7196 (dolist (callback js2-post-parse-callbacks)
7198 (js2-highlight-undeclared-vars))
7201 (defun js2-function-parser ()
7203 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7205 (defun js2-parse-function-closure-body (fn-node)
7206 "Parse a JavaScript 1.8 function closure body."
7207 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7209 (js2-report-error "msg.no.brace.body" nil
7210 (js2-node-pos fn-node)
7211 (- js2-ts-cursor (js2-node-pos fn-node)))
7212 (js2-node-add-children fn-node
7213 (setf (js2-function-node-body fn-node)
7214 (js2-parse-expr t))))))
7216 (defun js2-parse-function-body (fn-node)
7217 (js2-must-match js2-LC "msg.no.brace.body"
7218 (js2-node-pos fn-node)
7219 (- js2-ts-cursor (js2-node-pos fn-node)))
7220 (let ((pos js2-token-beg) ; LC position
7221 (pn (make-js2-block-node)) ; starts at LC position
7224 (incf js2-nesting-of-function)
7226 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7229 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7230 (js2-parse-statement)
7232 (js2-parse-function 'FUNCTION_STATEMENT))))
7233 (decf js2-nesting-of-function))
7234 (setq end js2-token-end) ; assume no curly and leave at current token
7235 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7236 (setq end js2-token-end))
7237 (setf (js2-node-pos pn) pos
7238 (js2-node-len pn) (- end pos))
7239 (setf (js2-function-node-body fn-node) pn)
7240 (js2-node-add-children fn-node pn)
7243 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7244 "Declare and fontify destructuring parameters inside NODE.
7245 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7247 ((js2-name-node-p node)
7249 (js2-define-symbol decl-type (js2-name-node-name node)
7250 node ignore-not-in-block)
7252 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7253 (+ leftpos (js2-node-len node))
7255 ((js2-object-node-p node)
7256 (dolist (elem (js2-object-node-elems node))
7257 (js2-define-destruct-symbols
7258 (if (js2-object-prop-node-p elem)
7259 (js2-object-prop-node-right elem)
7260 ;; abbreviated destructuring {a, b}
7262 decl-type face ignore-not-in-block)))
7263 ((js2-array-node-p node)
7264 (dolist (elem (js2-array-node-elems node))
7266 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7267 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7268 (js2-node-len node)))))
7270 (defun js2-parse-function-params (fn-node pos)
7271 (if (js2-match-token js2-RP)
7272 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7273 (let (params len param)
7274 (loop for tt = (js2-peek-token)
7277 ;; destructuring param
7278 ((or (= tt js2-LB) (= tt js2-LC))
7279 (setq param (js2-parse-primary-expr-lhs))
7280 (js2-define-destruct-symbols param
7282 'js2-function-param-face)
7283 (push param params))
7286 (js2-must-match js2-NAME "msg.no.parm")
7287 (js2-record-face 'js2-function-param-face)
7288 (setq param (js2-create-name-node))
7289 (js2-define-symbol js2-LP js2-ts-string param)
7290 (push param params)))
7292 (js2-match-token js2-COMMA))
7293 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7294 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7296 (js2-node-add-children fn-node p)
7297 (push p (js2-function-node-params fn-node))))))
7299 (defun js2-check-inconsistent-return-warning (fn-node name)
7300 "Possibly show inconsistent-return warning.
7301 Last token scanned is the close-curly for the function body."
7302 (when (and js2-mode-show-strict-warnings
7303 js2-strict-inconsistent-return-warning
7304 (not (js2-has-consistent-return-usage
7305 (js2-function-node-body fn-node))))
7306 ;; Have it extend from close-curly to bol or beginning of block.
7307 (let ((pos (save-excursion
7308 (goto-char js2-token-end)
7309 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7311 (end js2-token-end))
7312 (if (plusp (js2-name-node-length name))
7313 (js2-add-strict-warning "msg.no.return.value"
7314 (js2-name-node-name name) pos end)
7315 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7317 (defun js2-parse-function (function-type)
7318 "Function parser. FUNCTION-TYPE is a symbol."
7319 (let ((pos js2-token-beg) ; start of 'function' keyword
7320 name name-beg name-end fn-node lp
7321 (synthetic-type function-type)
7323 ;; parse function name, expression, or non-name (anonymous)
7325 ;; function foo(...)
7326 ((js2-match-token js2-NAME)
7327 (setq name (js2-create-name-node t)
7328 name-beg js2-token-beg
7329 name-end js2-token-end)
7330 (unless (js2-match-token js2-LP)
7331 (when js2-allow-member-expr-as-function-name
7332 ;; function foo.bar(...)
7333 (setq member-expr-node name
7335 member-expr-node (js2-parse-member-expr-tail
7336 nil member-expr-node)))
7337 (js2-must-match js2-LP "msg.no.paren.parms")))
7338 ((js2-match-token js2-LP)
7339 nil) ; anonymous function: leave name as null
7341 ;; function random-member-expr(...)
7342 (when js2-allow-member-expr-as-function-name
7343 ;; Note that memberExpr can not start with '(' like
7344 ;; in function (1+2).toString(), because 'function (' already
7345 ;; processed as anonymous function
7346 (setq member-expr-node (js2-parse-member-expr)))
7347 (js2-must-match js2-LP "msg.no.paren.parms")))
7348 (if (= js2-current-token js2-LP) ; eventually matched LP?
7349 (setq lp js2-token-beg))
7350 (if member-expr-node
7352 (setq synthetic-type 'FUNCTION_EXPRESSION)
7353 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7355 (js2-set-face name-beg name-end
7356 'font-lock-function-name-face 'record)))
7357 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7358 (plusp (js2-name-node-length name)))
7359 ;; Function statements define a symbol in the enclosing scope
7360 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7361 (setf fn-node (make-js2-function-node :pos pos
7364 :lp (if lp (- lp pos))))
7365 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7366 ;; 1. Nested functions are not affected by the dynamic scope flag
7367 ;; as dynamic scope is already a parent of their scope.
7368 ;; 2. Functions defined under the with statement also immune to
7369 ;; this setup, in which case dynamic scope is ignored in favor
7370 ;; of the with object.
7371 (setf (js2-function-node-ignore-dynamic fn-node) t))
7372 ;; dynamically bind all the per-function variables
7373 (let ((js2-current-script-or-fn fn-node)
7374 (js2-current-scope fn-node)
7375 (js2-nesting-of-with 0)
7379 js2-loop-and-switch-set)
7380 (js2-parse-function-params fn-node pos)
7381 (if (and (>= js2-language-version 180)
7382 (/= (js2-peek-token) js2-LC))
7383 (js2-parse-function-closure-body fn-node)
7384 (js2-parse-function-body fn-node))
7386 (js2-node-add-children fn-node name))
7387 (js2-check-inconsistent-return-warning fn-node name)
7388 ;; Function expressions define a name only in the body of the
7389 ;; function, and only if not hidden by a parameter name
7391 (eq synthetic-type 'FUNCTION_EXPRESSION)
7392 (null (js2-scope-get-symbol js2-current-scope
7393 (js2-name-node-name name))))
7394 (js2-define-symbol js2-FUNCTION
7395 (js2-name-node-name name)
7398 (not (eq function-type 'FUNCTION_EXPRESSION)))
7399 (js2-record-imenu-functions fn-node)))
7400 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7401 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7402 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7403 ;; We wait until after parsing the function to set its parent scope,
7404 ;; since `js2-define-symbol' needs the defining-scope check to stop
7405 ;; at the function boundary when checking for redeclarations.
7406 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7409 (defun js2-parse-statements (&optional parent)
7410 "Parse a statement list. Last token consumed must be js2-LC.
7412 PARENT can be a `js2-block-node', in which case the statements are
7413 appended to PARENT. Otherwise a new `js2-block-node' is created
7416 This function does not match the closing js2-RC: the caller
7417 matches the RC so it can provide a suitable error message if not
7418 matched. This means it's up to the caller to set the length of
7419 the node to include the closing RC. The node start pos is set to
7420 the absolute buffer start position, and the caller should fix it
7421 up to be relative to the parent node. All children of this block
7422 node are given relative start positions and correct lengths."
7423 (let ((pn (or parent (make-js2-block-node)))
7425 (setf (js2-node-pos pn) js2-token-beg)
7426 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7428 (js2-block-node-push pn (js2-parse-statement)))
7431 (defun js2-parse-statement ()
7432 (let (tt pn beg end)
7433 ;; coarse-grained user-interrupt check - needs work
7434 (and js2-parse-interruptable-p
7435 (zerop (% (incf js2-parse-stmt-count)
7436 js2-statements-per-pause))
7438 (throw 'interrupted t))
7439 (setq pn (js2-statement-helper))
7440 ;; no-side-effects warning check
7441 (unless (js2-node-has-side-effects pn)
7442 (setq end (js2-node-end pn))
7445 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7446 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7449 ;; These correspond to the switch cases in Parser.statementHelper
7450 (defconst js2-parsers
7451 (let ((parsers (make-vector js2-num-tokens
7452 #'js2-parse-expr-stmt)))
7453 (aset parsers js2-BREAK #'js2-parse-break)
7454 (aset parsers js2-CONST #'js2-parse-const-var)
7455 (aset parsers js2-CONTINUE #'js2-parse-continue)
7456 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7457 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7458 (aset parsers js2-DO #'js2-parse-do)
7459 (aset parsers js2-FOR #'js2-parse-for)
7460 (aset parsers js2-FUNCTION #'js2-function-parser)
7461 (aset parsers js2-IF #'js2-parse-if)
7462 (aset parsers js2-LC #'js2-parse-block)
7463 (aset parsers js2-LET #'js2-parse-let-stmt)
7464 (aset parsers js2-NAME #'js2-parse-name-or-label)
7465 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7466 (aset parsers js2-SEMI #'js2-parse-semi)
7467 (aset parsers js2-SWITCH #'js2-parse-switch)
7468 (aset parsers js2-THROW #'js2-parse-throw)
7469 (aset parsers js2-TRY #'js2-parse-try)
7470 (aset parsers js2-VAR #'js2-parse-const-var)
7471 (aset parsers js2-WHILE #'js2-parse-while)
7472 (aset parsers js2-WITH #'js2-parse-with)
7473 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7475 "A vector mapping token types to parser functions.")
7477 (defun js2-parse-warn-missing-semi (beg end)
7478 (and js2-mode-show-strict-warnings
7479 js2-strict-missing-semi-warning
7480 (js2-add-strict-warning
7481 "msg.missing.semi" nil
7482 ;; back up to beginning of statement or line
7483 (max beg (save-excursion
7488 (defconst js2-no-semi-insertion
7500 "List of tokens that don't do automatic semicolon insertion.")
7502 (defconst js2-autoinsert-semi-and-warn
7503 (list js2-ERROR js2-EOF js2-RC))
7505 (defun js2-statement-helper ()
7506 (let* ((tt (js2-peek-token))
7509 (parser (if (= tt js2-ERROR)
7511 (aref js2-parsers tt)))
7514 ;; If the statement is set, then it's been told its label by now.
7515 (and js2-labeled-stmt
7516 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7517 (setq js2-labeled-stmt nil))
7518 (setq pn (funcall parser))
7519 ;; Don't do auto semi insertion for certain statement types.
7520 (unless (or (memq first-tt js2-no-semi-insertion)
7521 (js2-labeled-stmt-node-p pn))
7522 (js2-auto-insert-semicolon pn))
7525 (defun js2-auto-insert-semicolon (pn)
7526 (let* ((tt-flagged (js2-peek-flagged-token))
7527 (tt (logand tt-flagged js2-clear-ti-mask))
7528 (pos (js2-node-pos pn)))
7531 ;; Consume ';' as a part of expression
7533 ;; extend the node bounds to include the semicolon.
7534 (setf (js2-node-len pn) (- js2-token-end pos)))
7535 ((memq tt js2-autoinsert-semi-and-warn)
7537 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7539 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7540 ;; Report error if no EOL or autoinsert ';' otherwise
7541 (js2-report-error "msg.no.semi.stmt")
7542 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7544 (defun js2-parse-condition ()
7545 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7546 The parens are discarded and the expression node is returned.
7547 The `pos' field of the return value is set to an absolute position
7548 that must be fixed up by the caller.
7549 Return value is a list (EXPR LP RP), with absolute paren positions."
7551 (if (js2-must-match js2-LP "msg.no.paren.cond")
7552 (setq lp js2-token-beg))
7553 (setq pn (js2-parse-expr))
7554 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7555 (setq rp js2-token-beg))
7556 ;; Report strict warning on code like "if (a = 7) ..."
7557 (if (and js2-strict-cond-assign-warning
7558 (js2-assign-node-p pn))
7559 (js2-add-strict-warning "msg.equal.as.assign" nil
7561 (+ (js2-node-pos pn)
7562 (js2-node-len pn))))
7565 (defun js2-parse-if ()
7566 "Parser for if-statement. Last matched token must be js2-IF."
7567 (let ((pos js2-token-beg)
7568 cond if-true if-false else-pos end pn)
7570 (setq cond (js2-parse-condition)
7571 if-true (js2-parse-statement)
7572 if-false (if (js2-match-token js2-ELSE)
7574 (setq else-pos (- js2-token-beg pos))
7575 (js2-parse-statement)))
7576 end (js2-node-end (or if-false if-true))
7577 pn (make-js2-if-node :pos pos
7579 :condition (car cond)
7583 :lp (js2-relpos (second cond) pos)
7584 :rp (js2-relpos (third cond) pos)))
7585 (js2-node-add-children pn (car cond) if-true if-false)
7588 (defun js2-parse-switch ()
7589 "Parser for if-statement. Last matched token must be js2-SWITCH."
7590 (let ((pos js2-token-beg)
7591 tt pn discriminant has-default case-expr case-node
7592 case-pos cases stmt lp rp)
7594 (if (js2-must-match js2-LP "msg.no.paren.switch")
7595 (setq lp js2-token-beg))
7596 (setq discriminant (js2-parse-expr)
7597 pn (make-js2-switch-node :discriminant discriminant
7599 :lp (js2-relpos lp pos)))
7600 (js2-node-add-children pn discriminant)
7601 (js2-enter-switch pn)
7604 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7605 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7606 (js2-must-match js2-LC "msg.no.brace.switch")
7609 (setq tt (js2-next-token)
7610 case-pos js2-token-beg)
7613 (setf (js2-node-len pn) (- js2-token-end pos))
7614 (throw 'break nil)) ; done
7616 (setq case-expr (js2-parse-expr))
7617 (js2-must-match js2-COLON "msg.no.colon.case"))
7620 (js2-report-error "msg.double.switch.default"))
7623 (js2-must-match js2-COLON "msg.no.colon.case"))
7625 (js2-report-error "msg.bad.switch")
7626 (throw 'break nil)))
7627 (setq case-node (make-js2-case-node :pos case-pos
7628 :len (- js2-token-end case-pos)
7630 (js2-node-add-children case-node case-expr)
7631 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7635 (setf stmt (js2-parse-statement)
7636 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7637 (js2-block-node-push case-node stmt))
7638 (push case-node cases)))
7639 ;; add cases last, as pushing reverses the order to be correct
7641 (js2-node-add-children pn kid)
7642 (push kid (js2-switch-node-cases pn)))
7644 (js2-exit-switch))))
7646 (defun js2-parse-while ()
7647 "Parser for while-statement. Last matched token must be js2-WHILE."
7648 (let ((pos js2-token-beg)
7649 (pn (make-js2-while-node))
7655 (setf cond (js2-parse-condition)
7656 (js2-while-node-condition pn) (car cond)
7657 body (js2-parse-statement)
7658 (js2-while-node-body pn) body
7659 (js2-node-len pn) (- (js2-node-end body) pos)
7660 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7661 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7662 (js2-node-add-children pn body (car cond)))
7666 (defun js2-parse-do ()
7667 "Parser for do-statement. Last matched token must be js2-DO."
7668 (let ((pos js2-token-beg)
7669 (pn (make-js2-do-node))
7675 (setq body (js2-parse-statement))
7676 (js2-must-match js2-WHILE "msg.no.while.do")
7677 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7678 cond (js2-parse-condition)
7679 (js2-do-node-condition pn) (car cond)
7680 (js2-do-node-body pn) body
7682 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7683 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7684 (js2-node-add-children pn (car cond) body))
7686 ;; Always auto-insert semicolon to follow SpiderMonkey:
7687 ;; It is required by ECMAScript but is ignored by the rest of
7688 ;; world; see bug 238945
7689 (if (js2-match-token js2-SEMI)
7690 (setq end js2-ts-cursor))
7691 (setf (js2-node-len pn) (- end pos))
7694 (defun js2-parse-for ()
7695 "Parser for for-statement. Last matched token must be js2-FOR.
7696 Parses for, for-in, and for each-in statements."
7697 (let ((for-pos js2-token-beg)
7698 pn is-for-each is-for-in in-pos each-pos tmp-pos
7699 init ; Node init is also foo in 'foo in object'
7700 cond ; Node cond is also object in 'foo in object'
7701 incr ; 3rd section of for-loop initializer
7704 ;; See if this is a for each () instead of just a for ()
7705 (when (js2-match-token js2-NAME)
7706 (if (string= "each" js2-ts-string)
7709 each-pos (- js2-token-beg for-pos)) ; relative
7710 (js2-record-face 'font-lock-keyword-face))
7711 (js2-report-error "msg.no.paren.for")))
7712 (if (js2-must-match js2-LP "msg.no.paren.for")
7713 (setq lp (- js2-token-beg for-pos)))
7714 (setq tt (js2-peek-token))
7715 ;; 'for' makes local scope
7716 (js2-push-scope (make-js2-scope))
7718 ;; parse init clause
7719 (let ((js2-in-for-init t)) ; set as dynamic variable
7722 (setq init (make-js2-empty-expr-node)))
7723 ((or (= tt js2-VAR) (= tt js2-LET))
7725 (setq init (js2-parse-variables tt js2-token-beg)))
7727 (setq init (js2-parse-expr)))))
7728 (if (js2-match-token js2-IN)
7730 in-pos (- js2-token-beg for-pos)
7731 ;; scope of iteration target object is not the scope we've created above.
7732 ;; stash current scope temporary.
7733 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7734 (js2-parse-expr))) ; object over which we're iterating
7735 ;; else ordinary for loop - parse cond and incr
7736 (js2-must-match js2-SEMI "msg.no.semi.for")
7737 (setq cond (if (= (js2-peek-token) js2-SEMI)
7738 (make-js2-empty-expr-node) ; no loop condition
7740 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7741 (setq tmp-pos js2-token-end
7742 incr (if (= (js2-peek-token) js2-RP)
7743 (make-js2-empty-expr-node :pos tmp-pos)
7745 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7746 (setq rp (- js2-token-beg for-pos)))
7748 (setq pn (make-js2-for-node :init init
7753 ;; cond could be null if 'in obj' got eaten by the init node.
7754 (if (js2-infix-node-p init)
7755 ;; it was (foo in bar) instead of (var foo in bar)
7756 (setq cond (js2-infix-node-right init)
7757 init (js2-infix-node-left init))
7758 (if (and (js2-var-decl-node-p init)
7759 (> (length (js2-var-decl-node-kids init)) 1))
7760 (js2-report-error "msg.mult.index")))
7761 (setq pn (make-js2-for-in-node :iterator init
7764 :foreach-p is-for-each
7771 ;; We have to parse the body -after- creating the loop node,
7772 ;; so that the loop node appears in the js2-loop-set, allowing
7773 ;; break/continue statements to find the enclosing loop.
7774 (setf body (js2-parse-statement)
7775 (js2-loop-node-body pn) body
7776 (js2-node-pos pn) for-pos
7777 (js2-node-len pn) (- (js2-node-end body) for-pos))
7778 (js2-node-add-children pn init cond incr body))
7784 (defun js2-parse-try ()
7785 "Parser for try-statement. Last matched token must be js2-TRY."
7786 (let ((try-pos js2-token-beg)
7804 (if (/= (js2-peek-token) js2-LC)
7805 (js2-report-error "msg.no.brace.try"))
7806 (setq try-block (js2-parse-statement)
7807 try-end (js2-node-end try-block)
7808 peek (js2-peek-token))
7811 (while (js2-match-token js2-CATCH)
7812 (setq catch-pos js2-token-beg
7817 (if saw-default-catch
7818 (js2-report-error "msg.catch.unreachable"))
7819 (if (js2-must-match js2-LP "msg.no.paren.catch")
7820 (setq lp (- js2-token-beg catch-pos)))
7821 (js2-push-scope (make-js2-scope))
7822 (let ((tt (js2-peek-token)))
7824 ;; destructuring pattern
7825 ;; catch ({ message, file }) { ... }
7826 ((or (= tt js2-LB) (= tt js2-LC))
7828 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
7832 (js2-must-match js2-NAME "msg.bad.catchcond")
7833 (setq param (js2-create-name-node))
7834 (js2-define-symbol js2-LET js2-ts-string param))))
7836 (if (js2-match-token js2-IF)
7837 (setq guard-kwd (- js2-token-beg catch-pos)
7838 catch-cond (js2-parse-expr))
7839 (setq saw-default-catch t))
7840 (if (js2-must-match js2-RP "msg.bad.catchcond")
7841 (setq rp (- js2-token-beg catch-pos)))
7842 (js2-must-match js2-LC "msg.no.brace.catchblock")
7843 (setq block (js2-parse-statements)
7844 try-end (js2-node-end block)
7845 catch-node (make-js2-catch-node :pos catch-pos
7847 :guard-expr catch-cond
7848 :guard-kwd guard-kwd
7853 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7854 (setq try-end js2-token-beg))
7855 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7856 (js2-node-len catch-node) (- try-end catch-pos))
7857 (js2-node-add-children catch-node param catch-cond block)
7858 (push catch-node catch-blocks)))
7859 ((/= peek js2-FINALLY)
7860 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7861 (js2-node-pos try-block)
7862 (- (setq try-end (js2-node-end try-block))
7863 (js2-node-pos try-block)))))
7864 (when (js2-match-token js2-FINALLY)
7865 (setq finally-pos js2-token-beg
7866 block (js2-parse-statement)
7867 try-end (js2-node-end block)
7868 finally-block (make-js2-finally-node :pos finally-pos
7869 :len (- try-end finally-pos)
7871 (js2-node-add-children finally-block block))
7872 (setq pn (make-js2-try-node :pos try-pos
7873 :len (- try-end try-pos)
7874 :try-block try-block
7875 :finally-block finally-block))
7876 (js2-node-add-children pn try-block finally-block)
7877 ;; push them onto the try-node, which reverses and corrects their order
7878 (dolist (cb catch-blocks)
7879 (js2-node-add-children pn cb)
7880 (push cb (js2-try-node-catch-clauses pn)))
7883 (defun js2-parse-throw ()
7884 "Parser for throw-statement. Last matched token must be js2-THROW."
7885 (let ((pos js2-token-beg)
7888 (if (= (js2-peek-token-or-eol) js2-EOL)
7889 ;; ECMAScript does not allow new lines before throw expression,
7891 (js2-report-error "msg.bad.throw.eol"))
7892 (setq expr (js2-parse-expr)
7893 pn (make-js2-throw-node :pos pos
7894 :len (- (js2-node-end expr) pos)
7896 (js2-node-add-children pn expr)
7899 (defun js2-match-jump-label-name (label-name)
7900 "If break/continue specified a label, return that label's labeled stmt.
7901 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7902 does not match an existing label, reports an error and returns nil."
7903 (let ((bundle (cdr (assoc label-name js2-label-set))))
7905 (js2-report-error "msg.undef.label"))
7908 (defun js2-parse-break ()
7909 "Parser for break-statement. Last matched token must be js2-BREAK."
7910 (let ((pos js2-token-beg)
7912 break-target ; statement to break from
7913 break-label ; in "break foo", name-node representing the foo
7914 labels ; matching labeled statement to break to
7916 (js2-consume-token) ; `break'
7917 (when (eq (js2-peek-token-or-eol) js2-NAME)
7919 (setq break-label (js2-create-name-node)
7920 end (js2-node-end break-label)
7921 ;; matchJumpLabelName only matches if there is one
7922 labels (js2-match-jump-label-name js2-ts-string)
7923 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7924 (unless (or break-target break-label)
7925 ;; no break target specified - try for innermost enclosing loop/switch
7926 (if (null js2-loop-and-switch-set)
7928 (js2-report-error "msg.bad.break" nil pos (length "break")))
7929 (setq break-target (car js2-loop-and-switch-set))))
7930 (setq pn (make-js2-break-node :pos pos
7933 :target break-target))
7934 (js2-node-add-children pn break-label) ; but not break-target
7937 (defun js2-parse-continue ()
7938 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7939 (let ((pos js2-token-beg)
7941 label ; optional user-specified label, a `js2-name-node'
7942 labels ; current matching labeled stmt, if any
7943 target ; the `js2-loop-node' target of this continue stmt
7945 (js2-consume-token) ; `continue'
7946 (when (= (js2-peek-token-or-eol) js2-NAME)
7948 (setq label (js2-create-name-node)
7949 end (js2-node-end label)
7950 ;; matchJumpLabelName only matches if there is one
7951 labels (js2-match-jump-label-name js2-ts-string)))
7953 ((null labels) ; no current label to go to
7954 (if (null js2-loop-set) ; no loop to continue to
7955 (js2-report-error "msg.continue.outside" nil pos
7956 (length "continue"))
7957 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7959 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7960 (setq target (js2-labeled-stmt-node-stmt labels))
7961 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7962 (setq pn (make-js2-continue-node :pos pos
7966 (js2-node-add-children pn label) ; but not target - it's not our child
7969 (defun js2-parse-with ()
7970 "Parser for with-statement. Last matched token must be js2-WITH."
7972 (let ((pos js2-token-beg)
7974 (if (js2-must-match js2-LP "msg.no.paren.with")
7975 (setq lp js2-token-beg))
7976 (setq obj (js2-parse-expr))
7977 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7978 (setq rp js2-token-beg))
7979 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7980 (setq body (js2-parse-statement)))
7981 (setq pn (make-js2-with-node :pos pos
7982 :len (- (js2-node-end body) pos)
7985 :lp (js2-relpos lp pos)
7986 :rp (js2-relpos rp pos)))
7987 (js2-node-add-children pn obj body)
7990 (defun js2-parse-const-var ()
7991 "Parser for var- or const-statement.
7992 Last matched token must be js2-CONST or js2-VAR."
7993 (let ((tt (js2-peek-token))
7997 (setq expr (js2-parse-variables tt js2-token-beg)
7998 pn (make-js2-expr-stmt-node :pos pos
7999 :len (- (js2-node-end expr) pos)
8001 (js2-node-add-children pn expr)
8004 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8005 (let ((pn (make-js2-expr-stmt-node :pos pos
8006 :len (js2-node-len expr)
8007 :type (if (js2-inside-function)
8012 (js2-node-add-children pn expr))
8015 (defun js2-parse-let-stmt ()
8016 "Parser for let-statement. Last matched token must be js2-LET."
8018 (let ((pos js2-token-beg)
8020 (if (= (js2-peek-token) js2-LP)
8021 ;; let expression in statement context
8022 (setq expr (js2-parse-let pos 'statement)
8023 pn (js2-wrap-with-expr-stmt pos expr t))
8024 ;; else we're looking at a statement like let x=6, y=7;
8025 (setf expr (js2-parse-variables js2-LET pos)
8026 pn (js2-wrap-with-expr-stmt pos expr t)
8027 (js2-node-type pn) js2-EXPR_RESULT))
8030 (defun js2-parse-ret-yield ()
8031 (js2-parse-return-or-yield (js2-peek-token) nil))
8033 (defconst js2-parse-return-stmt-enders
8034 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8036 (defsubst js2-now-all-set (before after mask)
8037 "Return whether or not the bits in the mask have changed to all set.
8038 BEFORE is bits before change, AFTER is bits after change, and MASK is
8039 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8041 (and (/= (logand before mask) mask)
8042 (= (logand after mask) mask)))
8044 (defun js2-parse-return-or-yield (tt expr-context)
8045 (let ((pos js2-token-beg)
8047 (before js2-end-flags)
8048 (inside-function (js2-inside-function))
8050 (unless inside-function
8051 (js2-report-error (if (eq tt js2-RETURN)
8055 ;; This is ugly, but we don't want to require a semicolon.
8056 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8057 (setq e (js2-parse-expr)
8058 end (js2-node-end e)))
8061 (js2-set-flag js2-end-flags (if (null e)
8063 js2-end-returns-value))
8064 (setq ret (make-js2-return-node :pos pos
8067 (js2-node-add-children ret e)
8068 ;; See if we need a strict mode warning.
8069 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8070 ;; more thorough and accurate than this before/after flag check.
8071 ;; E.g. if there's a finally-block that always returns, we shouldn't
8072 ;; show a warning generated by inconsistent returns in the catch blocks.
8073 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8074 ;; so we know which returns/yields to highlight, and we should get rid of
8075 ;; all the checking in `js2-parse-return-or-yield'.
8076 (if (and js2-strict-inconsistent-return-warning
8077 (js2-now-all-set before js2-end-flags
8078 (logior js2-end-returns js2-end-returns-value)))
8079 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8081 (unless (js2-inside-function)
8082 (js2-report-error "msg.bad.yield"))
8083 (js2-set-flag js2-end-flags js2-end-yields)
8084 (setq ret (make-js2-yield-node :pos pos
8087 (js2-node-add-children ret e)
8088 (unless expr-context
8090 ret (js2-wrap-with-expr-stmt pos e t))
8091 (js2-set-requires-activation)
8092 (js2-set-is-generator))))
8093 ;; see if we are mixing yields and value returns.
8094 (when (and inside-function
8095 (js2-now-all-set before js2-end-flags
8096 (logior js2-end-yields js2-end-returns-value)))
8097 (setq name (js2-function-name js2-current-script-or-fn))
8098 (if (zerop (length name))
8099 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8100 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8103 (defun js2-parse-debugger ()
8105 (make-js2-keyword-node :type js2-DEBUGGER))
8107 (defun js2-parse-block ()
8108 "Parser for a curly-delimited statement block.
8109 Last token matched must be `js2-LC'."
8110 (let ((pos js2-token-beg)
8111 (pn (make-js2-scope)))
8116 (js2-parse-statements pn)
8117 (js2-must-match js2-RC "msg.no.brace.block")
8118 (setf (js2-node-len pn) (- js2-token-end pos)))
8122 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8123 (defun js2-parse-semi ()
8124 "Parse a statement or handle an error.
8125 Last matched token is `js2-SEMI' or `js2-ERROR'."
8126 (let ((tt (js2-peek-token)) pos len)
8128 (if (eq tt js2-SEMI)
8129 (make-js2-empty-expr-node :len 1)
8130 (setq pos js2-token-beg
8131 len (- js2-token-beg pos))
8132 (js2-report-error "msg.syntax" nil pos len)
8133 (make-js2-error-node :pos pos :len len))))
8135 (defun js2-parse-default-xml-namespace ()
8136 "Parse a `default xml namespace = <expr>' e4x statement."
8137 (let ((pos js2-token-beg)
8138 end len expr unary es)
8141 (js2-set-requires-activation)
8142 (setq len (- js2-ts-cursor pos))
8143 (unless (and (js2-match-token js2-NAME)
8144 (string= js2-ts-string "xml"))
8145 (js2-report-error "msg.bad.namespace" nil pos len))
8146 (unless (and (js2-match-token js2-NAME)
8147 (string= js2-ts-string "namespace"))
8148 (js2-report-error "msg.bad.namespace" nil pos len))
8149 (unless (js2-match-token js2-ASSIGN)
8150 (js2-report-error "msg.bad.namespace" nil pos len))
8151 (setq expr (js2-parse-expr)
8152 end (js2-node-end expr)
8153 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8157 (js2-node-add-children unary expr)
8158 (make-js2-expr-stmt-node :pos pos
8162 (defun js2-record-label (label bundle)
8163 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8165 (let ((name (js2-label-node-name label))
8168 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8169 ;; flag both labels if possible when used in editing mode
8170 (if (and js2-parse-ide-mode
8171 (setq dup (js2-get-label-by-name labeled-stmt name)))
8172 (js2-report-error "msg.dup.label" nil
8173 (js2-node-abs-pos dup) (js2-node-len dup)))
8174 (js2-report-error "msg.dup.label" nil
8175 (js2-node-pos label) (js2-node-len label)))
8176 (js2-labeled-stmt-node-add-label bundle label)
8177 (js2-node-add-children bundle label)
8178 ;; Add one reference to the bundle per label in `js2-label-set'
8179 (push (cons name bundle) js2-label-set)))
8181 (defun js2-parse-name-or-label ()
8182 "Parser for identifier or label. Last token matched must be js2-NAME.
8183 Called when we found a name in a statement context. If it's a label, we gather
8184 up any following labels and the next non-label statement into a
8185 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8186 expression and return it wrapped in a `js2-expr-stmt-node'."
8187 (let ((pos js2-token-beg)
8191 ;; set check for label and call down to `js2-parse-primary-expr'
8192 (js2-set-check-for-label)
8193 (setq expr (js2-parse-expr))
8194 (if (/= (js2-node-type expr) js2-LABEL)
8195 ;; Parsed non-label expression - wrap with expression stmt.
8196 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8197 ;; else parsed a label
8198 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8199 (js2-record-label expr bundle)
8200 ;; look for more labels
8201 (while (and continue (= (js2-peek-token) js2-NAME))
8202 (js2-set-check-for-label)
8203 (setq expr (js2-parse-expr))
8204 (if (/= (js2-node-type expr) js2-LABEL)
8206 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8208 (js2-auto-insert-semicolon stmt))
8209 (js2-record-label expr bundle)))
8210 ;; no more labels; now parse the labeled statement
8213 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8214 (setq stmt (js2-statement-helper))))
8215 ;; remove the labels for this statement from the global set
8216 (dolist (label (js2-labeled-stmt-node-labels bundle))
8217 (setq js2-label-set (remove label js2-label-set))))
8218 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8219 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8220 (js2-node-add-children bundle stmt)
8223 (defun js2-parse-expr-stmt ()
8224 "Default parser in statement context, if no recognized statement found."
8225 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8227 (defun js2-parse-variables (decl-type pos)
8228 "Parse a comma-separated list of variable declarations.
8229 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8231 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8232 For 'var' or 'const', the keyword should be the token last scanned.
8234 POS is the position where the node should start. It's sometimes the
8235 var/const/let keyword, and other times the beginning of the first token
8236 in the first variable declaration.
8238 Returns the parsed `js2-var-decl-node' expression node."
8239 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8241 destructuring kid-pos tt init name end nbeg nend vi
8244 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8245 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8246 ;; var {a, b} = baz;
8248 (setq destructuring nil
8251 kid-pos js2-token-beg
8254 (if (or (= tt js2-LB) (= tt js2-LC))
8255 ;; Destructuring assignment, e.g., var [a, b] = ...
8256 (setq destructuring (js2-parse-primary-expr-lhs)
8257 end (js2-node-end destructuring))
8258 ;; Simple variable name
8259 (when (js2-must-match js2-NAME "msg.bad.var")
8260 (setq name (js2-create-name-node)
8264 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8265 (when (js2-match-token js2-ASSIGN)
8266 (setq init (js2-parse-assign-expr)
8267 end (js2-node-end init))
8268 (if (and js2-parse-ide-mode
8269 (or (js2-object-node-p init)
8270 (js2-function-node-p init)))
8271 (js2-record-imenu-functions init name)))
8273 (js2-set-face nbeg nend (if (js2-function-node-p init)
8274 'font-lock-function-name-face
8275 'font-lock-variable-name-face)
8277 (setq vi (make-js2-var-init-node :pos kid-pos
8278 :len (- end kid-pos)
8282 (if (and (null init) (not js2-in-for-init))
8283 (js2-report-error "msg.destruct.assign.no.init"))
8284 (js2-define-destruct-symbols destructuring
8286 'font-lock-variable-name-face)
8287 (setf (js2-var-init-node-target vi) destructuring))
8288 (setf (js2-var-init-node-target vi) name))
8289 (setf (js2-var-init-node-initializer vi) init)
8290 (js2-node-add-children vi name destructuring init)
8291 (js2-block-node-push result vi)
8292 (unless (js2-match-token js2-COMMA)
8293 (setq continue nil)))
8294 (setf (js2-node-len result) (- end pos))
8297 (defun js2-parse-let (pos &optional stmt-p)
8298 "Parse a let expression or statement.
8299 A let-expression is of the form `let (vars) expr'.
8300 A let-statment is of the form `let (vars) {statements}'.
8301 The third form of let is a variable declaration list, handled
8302 by `js2-parse-variables'."
8303 (let ((pn (make-js2-let-node :pos pos))
8305 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8306 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8310 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8311 (if (js2-must-match js2-RP "msg.no.paren.let")
8312 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8313 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8317 (setf beg js2-token-beg ; position stmt at LC
8318 body (js2-parse-statements))
8319 (js2-must-match js2-RC "msg.no.curly.let")
8320 (setf (js2-node-len body) (- js2-token-end beg)
8321 (js2-node-len pn) (- js2-token-end pos)
8322 (js2-let-node-body pn) body
8323 (js2-node-type pn) js2-LET))
8325 (setf body (js2-parse-expr)
8326 (js2-node-len pn) (- (js2-node-end body) pos)
8327 (js2-let-node-body pn) body))
8328 (js2-node-add-children pn vars body))
8332 (defun js2-define-new-symbol (decl-type name node &optional scope)
8333 (js2-scope-put-symbol (or scope js2-current-scope)
8335 (make-js2-symbol decl-type name node)))
8337 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8338 "Define a symbol in the current scope.
8339 If NODE is non-nil, it is the AST node associated with the symbol."
8340 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8341 (symbol (if defining-scope
8342 (js2-scope-get-symbol defining-scope name)))
8343 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8345 ((and symbol ; already defined
8346 (or (= sdt js2-CONST) ; old version is const
8347 (= decl-type js2-CONST) ; new version is const
8348 ;; two let-bound vars in this block have same name
8349 (and (= sdt js2-LET)
8350 (eq defining-scope js2-current-scope))))
8353 ((= sdt js2-CONST) "msg.const.redecl")
8354 ((= sdt js2-LET) "msg.let.redecl")
8355 ((= sdt js2-VAR) "msg.var.redecl")
8356 ((= sdt js2-FUNCTION) "msg.function.redecl")
8357 (t "msg.parm.redecl"))
8359 ((= decl-type js2-LET)
8360 (if (and (not ignore-not-in-block)
8361 (or (= (js2-node-type js2-current-scope) js2-IF)
8362 (js2-loop-node-p js2-current-scope)))
8363 (js2-report-error "msg.let.decl.not.in.block")
8364 (js2-define-new-symbol decl-type name node)))
8365 ((or (= decl-type js2-VAR)
8366 (= decl-type js2-CONST)
8367 (= decl-type js2-FUNCTION))
8369 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8370 (js2-add-strict-warning "msg.var.redecl" name)
8371 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8372 (js2-add-strict-warning "msg.var.hides.arg" name)))
8373 (js2-define-new-symbol decl-type name node
8374 js2-current-script-or-fn)))
8375 ((= decl-type js2-LP)
8377 ;; must be duplicate parameter. Second parameter hides the
8378 ;; first, so go ahead and add the second pararameter
8379 (js2-report-warning "msg.dup.parms" name))
8380 (js2-define-new-symbol decl-type name node))
8381 (t (js2-code-bug)))))
8383 (defun js2-parse-expr (&optional oneshot)
8384 (let* ((pn (js2-parse-assign-expr))
8385 (pos (js2-node-pos pn))
8389 (while (and (not oneshot)
8390 (js2-match-token js2-COMMA))
8391 (setq op-pos (- js2-token-beg pos)) ; relative
8392 (if (= (js2-peek-token) js2-YIELD)
8393 (js2-report-error "msg.yield.parenthesized"))
8394 (setq right (js2-parse-assign-expr)
8396 pn (make-js2-infix-node :type js2-COMMA
8398 :len (- js2-ts-cursor pos)
8402 (js2-node-add-children pn left right))
8405 (defun js2-parse-assign-expr ()
8406 (let ((tt (js2-peek-token))
8408 pn left right op-pos)
8409 (if (= tt js2-YIELD)
8410 (js2-parse-return-or-yield tt t)
8411 ;; not yield - parse assignment expression
8412 (setq pn (js2-parse-cond-expr)
8413 tt (js2-peek-token))
8414 (when (and (<= js2-first-assign tt)
8415 (<= tt js2-last-assign))
8416 ;; tt express assignment (=, |=, ^=, ..., %=)
8418 (setq op-pos (- js2-token-beg pos) ; relative
8420 right (js2-parse-assign-expr)
8421 pn (make-js2-assign-node :type tt
8423 :len (- (js2-node-end right) pos)
8427 (when js2-parse-ide-mode
8428 (js2-highlight-assign-targets pn left right)
8429 (if (or (js2-function-node-p right)
8430 (js2-object-node-p right))
8431 (js2-record-imenu-functions right left)))
8432 ;; do this last so ide checks above can use absolute positions
8433 (js2-node-add-children pn left right))
8436 (defun js2-parse-cond-expr ()
8437 (let ((pos js2-token-beg)
8438 (pn (js2-parse-or-expr))
8444 (when (js2-match-token js2-HOOK)
8445 (setq q-pos (- js2-token-beg pos)
8446 if-true (js2-parse-assign-expr))
8447 (js2-must-match js2-COLON "msg.no.colon.cond")
8448 (setq c-pos (- js2-token-beg pos)
8449 if-false (js2-parse-assign-expr)
8451 pn (make-js2-cond-node :pos pos
8452 :len (- (js2-node-end if-false) pos)
8453 :test-expr test-expr
8455 :false-expr if-false
8458 (js2-node-add-children pn test-expr if-true if-false))
8461 (defun js2-make-binary (type left parser)
8462 "Helper for constructing a binary-operator AST node.
8463 LEFT is the left-side-expression, already parsed, and the
8464 binary operator should have just been matched.
8465 PARSER is a function to call to parse the right operand,
8466 or a `js2-node' struct if it has already been parsed."
8467 (let* ((pos (js2-node-pos left))
8468 (op-pos (- js2-token-beg pos))
8469 (right (if (js2-node-p parser)
8472 (pn (make-js2-infix-node :type type
8474 :len (- (js2-node-end right) pos)
8478 (js2-node-add-children pn left right)
8481 (defun js2-parse-or-expr ()
8482 (let ((pn (js2-parse-and-expr)))
8483 (when (js2-match-token js2-OR)
8484 (setq pn (js2-make-binary js2-OR
8486 'js2-parse-or-expr)))
8489 (defun js2-parse-and-expr ()
8490 (let ((pn (js2-parse-bit-or-expr)))
8491 (when (js2-match-token js2-AND)
8492 (setq pn (js2-make-binary js2-AND
8494 'js2-parse-and-expr)))
8497 (defun js2-parse-bit-or-expr ()
8498 (let ((pn (js2-parse-bit-xor-expr)))
8499 (while (js2-match-token js2-BITOR)
8500 (setq pn (js2-make-binary js2-BITOR
8502 'js2-parse-bit-xor-expr)))
8505 (defun js2-parse-bit-xor-expr ()
8506 (let ((pn (js2-parse-bit-and-expr)))
8507 (while (js2-match-token js2-BITXOR)
8508 (setq pn (js2-make-binary js2-BITXOR
8510 'js2-parse-bit-and-expr)))
8513 (defun js2-parse-bit-and-expr ()
8514 (let ((pn (js2-parse-eq-expr)))
8515 (while (js2-match-token js2-BITAND)
8516 (setq pn (js2-make-binary js2-BITAND
8518 'js2-parse-eq-expr)))
8521 (defconst js2-parse-eq-ops
8522 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8524 (defun js2-parse-eq-expr ()
8525 (let ((pn (js2-parse-rel-expr))
8527 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8529 (setq pn (js2-make-binary tt
8531 'js2-parse-rel-expr)))
8534 (defconst js2-parse-rel-ops
8535 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8537 (defun js2-parse-rel-expr ()
8538 (let ((pn (js2-parse-shift-expr))
8542 (setq tt (js2-peek-token))
8544 ((and js2-in-for-init (= tt js2-IN))
8545 (setq continue nil))
8546 ((memq tt js2-parse-rel-ops)
8548 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8550 (setq continue nil))))
8553 (defconst js2-parse-shift-ops
8554 (list js2-LSH js2-URSH js2-RSH))
8556 (defun js2-parse-shift-expr ()
8557 (let ((pn (js2-parse-add-expr))
8561 (setq tt (js2-peek-token))
8562 (if (memq tt js2-parse-shift-ops)
8565 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8566 (setq continue nil)))
8569 (defun js2-parse-add-expr ()
8570 (let ((pn (js2-parse-mul-expr))
8574 (setq tt (js2-peek-token))
8575 (if (or (= tt js2-ADD) (= tt js2-SUB))
8578 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8579 (setq continue nil)))
8582 (defconst js2-parse-mul-ops
8583 (list js2-MUL js2-DIV js2-MOD))
8585 (defun js2-parse-mul-expr ()
8586 (let ((pn (js2-parse-unary-expr))
8590 (setq tt (js2-peek-token))
8591 (if (memq tt js2-parse-mul-ops)
8594 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8595 (setq continue nil)))
8598 (defun js2-make-unary (type parser &rest args)
8599 "Make a unary node of type TYPE.
8600 PARSER is either a node (for postfix operators) or a function to call
8601 to parse the operand (for prefix operators)."
8602 (let* ((pos js2-token-beg)
8603 (postfix (js2-node-p parser))
8606 (apply parser args)))
8609 (if postfix ; e.g. i++
8610 (setq pos (js2-node-pos expr)
8612 (setq end (js2-node-end expr)))
8613 (setq pn (make-js2-unary-node :type type
8617 (js2-node-add-children pn expr)
8620 (defconst js2-incrementable-node-types
8621 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8622 "Node types that can be the operand of a ++ or -- operator.")
8624 (defun js2-check-bad-inc-dec (tt beg end unary)
8625 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8626 js2-incrementable-node-types)
8627 (js2-report-error (if (= tt js2-INC)
8630 nil beg (- end beg))))
8632 (defun js2-parse-unary-expr ()
8633 (let ((tt (js2-peek-token))
8636 ((or (= tt js2-VOID)
8641 (js2-make-unary tt 'js2-parse-unary-expr))
8644 ;; Convert to special POS token in decompiler and parse tree
8645 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8648 ;; Convert to special NEG token in decompiler and parse tree
8649 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8654 (setq beg js2-token-beg
8656 expr (js2-make-unary tt 'js2-parse-member-expr t))
8657 (js2-check-bad-inc-dec tt beg end expr)))
8660 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8663 (make-js2-error-node)) ; try to continue
8665 js2-compiler-xml-available)
8666 ;; XML stream encountered in expression.
8668 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8670 (setq pn (js2-parse-member-expr t)
8671 ;; Don't look across a newline boundary for a postfix incop.
8672 tt (js2-peek-token-or-eol))
8673 (when (or (= tt js2-INC) (= tt js2-DEC))
8676 pn (js2-make-unary tt expr))
8677 (js2-node-set-prop pn 'postfix t)
8678 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8681 (defun js2-parse-xml-initializer ()
8682 "Parse an E4X XML initializer.
8683 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8684 Then I'll postprocess the result, depending on whether we're in IDE
8685 mode or codegen mode, and generate the appropriate rewritten AST.
8686 IDE mode uses a rich AST that models the XML structure. Codegen mode
8687 just concatenates everything and makes a new XML or XMLList out of it."
8688 (let ((tt (js2-get-first-xml-token))
8689 pn-xml pn expr kids expr-pos
8692 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8693 (js2-report-error "msg.syntax"))
8694 (setq pn-xml (make-js2-xml-node))
8697 (setq first-token nil)
8698 (setq tt (js2-get-next-xml-token)))
8700 ;; js2-XML means we found a {expr} in the XML stream.
8701 ;; The js2-ts-string is the XML up to the left-curly.
8703 (push (make-js2-string-node :pos js2-token-beg
8704 :len (- js2-ts-cursor js2-token-beg))
8706 (js2-must-match js2-LC "msg.syntax")
8707 (setq expr-pos js2-ts-cursor
8708 expr (if (eq (js2-peek-token) js2-RC)
8709 (make-js2-empty-expr-node :pos expr-pos)
8711 (js2-must-match js2-RC "msg.syntax")
8712 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8713 :len (js2-node-len expr)
8715 (js2-node-add-children pn expr)
8717 ;; a js2-XMLEND token means we hit the final close-tag.
8719 (push (make-js2-string-node :pos js2-token-beg
8720 :len (- js2-ts-cursor js2-token-beg))
8722 (dolist (kid (nreverse kids))
8723 (js2-block-node-push pn-xml kid))
8724 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8725 (js2-node-pos pn-xml))
8728 (js2-report-error "msg.syntax")
8729 (setq continue nil))))
8733 (defun js2-parse-argument-list ()
8734 "Parse an argument list and return it as a Lisp list of nodes.
8735 Returns the list in reverse order. Consumes the right-paren token."
8737 (unless (js2-match-token js2-RP)
8739 (if (= (js2-peek-token) js2-YIELD)
8740 (js2-report-error "msg.yield.parenthesized"))
8741 (push (js2-parse-assign-expr) result)
8743 (js2-match-token js2-COMMA))
8744 (js2-must-match js2-RP "msg.no.paren.arg")
8747 (defun js2-parse-member-expr (&optional allow-call-syntax)
8748 (let ((tt (js2-peek-token))
8749 pn pos target args beg end init tail)
8751 (setq pn (js2-parse-primary-expr))
8752 ;; parse a 'new' expression
8754 (setq pos js2-token-beg
8756 target (js2-parse-member-expr)
8757 end (js2-node-end target)
8758 pn (make-js2-new-node :pos pos
8761 (js2-node-add-children pn target)
8762 (when (js2-match-token js2-LP)
8763 ;; Add the arguments to pn, if any are supplied.
8764 (setf beg pos ; start of "new" keyword
8766 args (nreverse (js2-parse-argument-list))
8767 (js2-new-node-args pn) args
8769 (js2-new-node-lp pn) (- pos beg)
8770 (js2-new-node-rp pn) (- end 1 beg))
8771 (apply #'js2-node-add-children pn args))
8772 (when (and js2-allow-rhino-new-expr-initializer
8773 (js2-match-token js2-LC))
8774 (setf init (js2-parse-object-literal)
8775 end (js2-node-end init)
8776 (js2-new-node-initializer pn) init)
8777 (js2-node-add-children pn init))
8778 (setf (js2-node-len pn) (- end beg))) ; end outer if
8779 (js2-parse-member-expr-tail allow-call-syntax pn)))
8781 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8782 "Parse a chain of property/array accesses or function calls.
8783 Includes parsing for E4X operators like `..' and `.@'.
8784 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8785 Returns an expression tree that includes PN, the parent node."
8786 (let ((beg (js2-node-pos pn))
8790 (setq tt (js2-peek-token))
8792 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8793 (setq pn (js2-parse-property-access tt pn)))
8794 ((= tt js2-DOTQUERY)
8795 (setq pn (js2-parse-dot-query pn)))
8797 (setq pn (js2-parse-element-get pn)))
8799 (if allow-call-syntax
8800 (setq pn (js2-parse-function-call pn))
8801 (setq continue nil)))
8803 (setq continue nil))))
8804 (if (>= js2-highlight-level 2)
8805 (js2-parse-highlight-member-expr-node pn))
8808 (defun js2-parse-dot-query (pn)
8809 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8810 Last token parsed must be `js2-DOTQUERY'."
8811 (let ((pos (js2-node-pos pn))
8815 (js2-set-requires-activation)
8816 (setq op-pos js2-token-beg
8817 expr (js2-parse-expr)
8818 end (js2-node-end expr)
8819 pn (make-js2-xml-dot-query-node :left pn
8823 (js2-node-add-children pn
8824 (js2-xml-dot-query-node-left pn)
8825 (js2-xml-dot-query-node-right pn))
8826 (if (js2-must-match js2-RP "msg.no.paren")
8827 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8829 (setf (js2-node-len pn) (- end pos))
8832 (defun js2-parse-element-get (pn)
8833 "Parse an element-get expression, e.g. foo[bar].
8834 Last token parsed must be `js2-RB'."
8835 (let ((lb js2-token-beg)
8836 (pos (js2-node-pos pn))
8839 (setq expr (js2-parse-expr))
8840 (if (js2-must-match js2-RB "msg.no.bracket.index")
8841 (setq rb js2-token-beg))
8842 (setq pn (make-js2-elem-get-node :target pn
8845 :lb (js2-relpos lb pos)
8846 :rb (js2-relpos rb pos)
8847 :len (- js2-token-end pos)))
8848 (js2-node-add-children pn
8849 (js2-elem-get-node-target pn)
8850 (js2-elem-get-node-element pn))
8853 (defun js2-parse-function-call (pn)
8855 (pos (js2-node-pos pn)))
8857 (setq pn (make-js2-call-node :pos pos
8859 :lp (- js2-token-beg pos)))
8860 (js2-node-add-children pn (js2-call-node-target pn))
8861 ;; Add the arguments to pn, if any are supplied.
8862 (setf args (nreverse (js2-parse-argument-list))
8863 (js2-call-node-rp pn) (- js2-token-beg pos)
8864 (js2-call-node-args pn) args)
8865 (apply #'js2-node-add-children pn args)
8866 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8869 (defun js2-parse-property-access (tt pn)
8870 "Parse a property access, XML descendants access, or XML attr access."
8871 (let ((member-type-flags 0)
8872 (dot-pos js2-token-beg)
8873 (dot-len (if (= tt js2-DOTDOT) 2 1))
8875 ref ; right side of . or .. operator
8878 (when (= tt js2-DOTDOT)
8880 (setq member-type-flags js2-descendants-flag))
8881 (if (not js2-compiler-xml-available)
8883 (js2-must-match-prop-name "msg.no.name.after.dot")
8884 (setq name (js2-create-name-node t js2-GETPROP)
8885 result (make-js2-prop-get-node :left pn
8888 :len (- js2-token-end
8890 (js2-node-add-children result pn name)
8892 ;; otherwise look for XML operators
8893 (setf result (if (= tt js2-DOT)
8894 (make-js2-prop-get-node)
8895 (make-js2-infix-node :type js2-DOTDOT))
8896 (js2-node-pos result) (js2-node-pos pn)
8897 (js2-infix-node-op-pos result) dot-pos
8898 (js2-infix-node-left result) pn ; do this after setting position
8899 tt (js2-next-token))
8901 ;; needed for generator.throw()
8903 (js2-save-name-token-data js2-token-beg "throw")
8904 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8905 ;; handles: name, ns::name, ns::*, ns::[expr]
8906 ((js2-valid-prop-name-token tt)
8907 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8908 ;; handles: *, *::name, *::*, *::[expr]
8910 (js2-save-name-token-data js2-token-beg "*")
8911 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8912 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8914 (setq result (js2-parse-attribute-access)))
8916 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8918 (setf (js2-node-len result) (- (js2-node-end ref)
8919 (js2-node-pos result))
8920 (js2-infix-node-right result) ref))
8921 (if (js2-infix-node-p result)
8922 (js2-node-add-children result
8923 (js2-infix-node-left result)
8924 (js2-infix-node-right result)))
8927 (defun js2-parse-attribute-access ()
8928 "Parse an E4X XML attribute expression.
8929 This includes expressions of the forms:
8931 @attr @ns::attr @ns::*
8933 @[expr] @*::[expr] @ns::[expr]
8935 Called if we peeked an '@' token."
8936 (let ((tt (js2-next-token))
8937 (at-pos js2-token-beg))
8939 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8940 ((js2-valid-prop-name-token tt)
8941 (js2-parse-property-name at-pos js2-ts-string 0))
8942 ;; handles: @*, @*::name, @*::*, @*::[expr]
8944 (js2-save-name-token-data js2-token-beg "*")
8945 (js2-parse-property-name js2-token-beg "*" 0))
8948 (js2-parse-xml-elem-ref at-pos))
8950 (js2-report-error "msg.no.name.after.xmlAttr")
8951 ;; Avoid cascaded errors that happen if we make an error node here.
8952 (js2-save-name-token-data js2-token-beg "")
8953 (js2-parse-property-name js2-token-beg "" 0)))))
8955 (defun js2-parse-property-name (at-pos s member-type-flags)
8956 "Check if :: follows name in which case it becomes qualified name.
8958 AT-POS is a natural number if we just read an '@' token, else nil.
8959 S is the name or string that was matched: an identifier, 'throw' or '*'.
8960 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8962 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8963 operator, or the name is followed by ::. For a plain name, returns a
8964 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8965 (let ((pos (or at-pos js2-token-beg))
8967 (name (js2-create-name-node t js2-current-token))
8970 (when (js2-match-token js2-COLONCOLON)
8972 colon-pos js2-token-beg
8973 tt (js2-next-token))
8975 ;; handles name::name
8976 ((js2-valid-prop-name-token tt)
8977 (setq name (js2-create-name-node)))
8980 (js2-save-name-token-data js2-token-beg "*")
8981 (setq name (js2-create-name-node)))
8982 ;; handles name::[expr]
8984 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8986 (js2-report-error "msg.no.name.after.coloncolon"))))
8987 (if (and (null ns) (zerop member-type-flags))
8991 (make-js2-xml-prop-ref-node :pos pos
8992 :len (- (js2-node-end name) pos)
8994 :colon-pos colon-pos
8996 (js2-node-add-children pn name))))))
8998 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
8999 "Parse the [expr] portion of an xml element reference.
9000 For instance, @[expr], @*::[expr], or ns::[expr]."
9001 (let* ((lb js2-token-beg)
9002 (pos (or at-pos lb))
9004 (expr (js2-parse-expr))
9005 (end (js2-node-end expr))
9007 (if (js2-must-match js2-RB "msg.no.bracket.index")
9008 (setq rb js2-token-beg
9012 (make-js2-xml-elem-ref-node :pos pos
9014 :namespace namespace
9015 :colon-pos colon-pos
9018 :lb (js2-relpos lb pos)
9019 :rb (js2-relpos rb pos)))
9020 (js2-node-add-children pn namespace expr))))
9022 (defun js2-parse-primary-expr-lhs ()
9023 (let ((js2-is-in-lhs t))
9024 (js2-parse-primary-expr)))
9026 (defun js2-parse-primary-expr ()
9027 "Parse a literal (leaf) expression of some sort.
9028 Includes complex literals such as functions, object-literals,
9029 array-literals, array comprehensions and regular expressions."
9030 (let ((tt-flagged (js2-next-flagged-token))
9031 pn ; parent node (usually return value)
9033 px-pos ; paren-expr pos
9035 flags ; regexp flags
9037 (setq tt js2-current-token)
9039 ((= tt js2-FUNCTION)
9040 (js2-parse-function 'FUNCTION_EXPRESSION))
9042 (js2-parse-array-literal))
9044 (js2-parse-object-literal))
9046 (js2-parse-let js2-token-beg))
9048 (setq px-pos js2-token-beg
9049 expr (js2-parse-expr))
9050 (js2-must-match js2-RP "msg.no.paren")
9051 (setq pn (make-js2-paren-node :pos px-pos
9053 :len (- js2-token-end px-pos)))
9054 (js2-node-add-children pn (js2-paren-node-expr pn))
9058 (js2-parse-attribute-access))
9060 (js2-parse-name tt-flagged tt))
9062 (make-js2-number-node))
9065 (make-js2-string-node)
9066 (js2-record-face 'font-lock-string-face)))
9067 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9068 ;; Got / or /= which in this context means a regexp literal
9069 (setq px-pos js2-token-beg)
9070 (js2-read-regexp tt)
9071 (setq flags js2-ts-regexp-flags
9072 js2-ts-regexp-flags nil)
9074 (make-js2-regexp-node :pos px-pos
9075 :len (- js2-ts-cursor px-pos)
9076 :value js2-ts-string
9078 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9079 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9080 ((or (= tt js2-NULL)
9084 (make-js2-keyword-node :type tt))
9085 ((= tt js2-RESERVED)
9086 (js2-report-error "msg.reserved.id")
9087 (make-js2-name-node))
9089 ;; the scanner or one of its subroutines reported the error.
9090 (make-js2-error-node))
9092 (setq px-pos (point-at-bol)
9093 len (- js2-ts-cursor px-pos))
9094 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9095 (make-js2-error-node :pos px-pos :len len))
9097 (js2-report-error "msg.syntax")
9098 (make-js2-error-node)))))
9100 (defun js2-parse-name (tt-flagged tt)
9101 (let ((name js2-ts-string)
9102 (name-pos js2-token-beg)
9104 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9105 (= (js2-peek-token) js2-COLON))
9107 ;; Do not consume colon, it is used as unwind indicator
9108 ;; to return to statementHelper.
9109 (make-js2-label-node :pos name-pos
9110 :len (- js2-token-end name-pos)
9112 (js2-set-face name-pos
9114 'font-lock-variable-name-face 'record))
9115 ;; Otherwise not a label, just a name. Unfortunately peeking
9116 ;; the next token to check for a colon has biffed js2-token-beg
9117 ;; and js2-token-end. We store the name's bounds in buffer vars
9118 ;; and `js2-create-name-node' uses them.
9119 (js2-save-name-token-data name-pos name)
9120 (setq node (if js2-compiler-xml-available
9121 (js2-parse-property-name nil name 0)
9122 (js2-create-name-node 'check-activation)))
9123 (if js2-highlight-external-variables
9124 (js2-record-name-node node))
9127 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9128 (js2-add-strict-warning
9130 ;; back up from comma to beginning of line or array/objlit
9132 (js2-node-pos (car elems))
9135 (goto-char comma-pos)
9136 (back-to-indentation)
9140 (defun js2-parse-array-literal ()
9141 (let ((pos js2-token-beg)
9143 (after-lb-or-comma t)
9144 after-comma tt elems pn
9146 (unless js2-is-in-lhs
9147 (js2-push-scope (make-js2-scope))) ; for array comp
9149 (setq tt (js2-peek-token))
9154 (setq after-comma js2-token-end)
9155 (if (not after-lb-or-comma)
9156 (setq after-lb-or-comma t)
9160 (= tt js2-EOF)) ; prevent infinite loop
9162 (js2-report-error "msg.no.bracket.arg" nil pos)
9163 (js2-consume-token))
9166 pn (make-js2-array-node :pos pos
9167 :len (- js2-ts-cursor pos)
9168 :elems (nreverse elems)))
9169 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9170 (when (and after-comma (not js2-is-in-lhs))
9171 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9172 pos elems after-comma)))
9173 ;; destructuring binding
9175 (push (if (or (= tt js2-LC)
9178 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9179 (js2-parse-primary-expr-lhs)
9182 (js2-report-error "msg.bad.var")
9183 (make-js2-error-node))
9185 (setq after-lb-or-comma nil
9188 ((and (>= js2-language-version 170)
9189 (= tt js2-FOR) ; check for array comprehension
9190 (not after-lb-or-comma) ; "for" can't follow a comma
9191 elems ; must have at least 1 element
9192 (not (cdr elems))) ; but no 2nd element
9194 pn (js2-parse-array-comprehension (car elems) pos)))
9198 (unless after-lb-or-comma
9199 (js2-report-error "msg.no.bracket.arg"))
9200 (push (js2-parse-assign-expr) elems)
9201 (setq after-lb-or-comma nil
9203 (unless js2-is-in-lhs
9207 (defun js2-parse-array-comprehension (expr pos)
9208 "Parse a JavaScript 1.7 Array Comprehension.
9209 EXPR is the first expression after the opening left-bracket.
9210 POS is the beginning of the LB token preceding EXPR.
9211 We should have just parsed the 'for' keyword before calling this function."
9212 (let (loops loop first prev filter if-pos result)
9213 (while (= (js2-peek-token) js2-FOR)
9214 (let ((prev (car loops))) ; rearrange scope chain
9215 (push (setq loop (js2-parse-array-comp-loop)) loops)
9216 (if prev ; each loop is parent scope to the next one
9217 (setf (js2-scope-parent-scope loop) prev)
9218 ; first loop takes expr scope's parent
9219 (setf (js2-scope-parent-scope (setq first loop))
9220 (js2-scope-parent-scope js2-current-scope)))))
9221 ;; set expr scope's parent to the last loop
9222 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9223 (when (= (js2-peek-token) js2-IF)
9225 (setq if-pos (- js2-token-beg pos) ; relative
9226 filter (js2-parse-condition)))
9227 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9228 (setq result (make-js2-array-comp-node :pos pos
9229 :len (- js2-ts-cursor pos)
9231 :loops (nreverse loops)
9232 :filter (car filter)
9233 :lp (js2-relpos (second filter) pos)
9234 :rp (js2-relpos (third filter) pos)
9236 (apply #'js2-node-add-children result expr (car filter)
9237 (js2-array-comp-node-loops result))
9238 (setq js2-current-scope first) ; pop to the first loop
9241 (defun js2-parse-array-comp-loop ()
9242 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9243 Last token peeked should be the initial FOR."
9244 (let ((pos js2-token-beg)
9245 (pn (make-js2-array-comp-loop-node))
9246 tt iter obj foreach-p in-pos each-pos lp rp)
9247 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9251 (when (js2-match-token js2-NAME)
9252 (if (string= js2-ts-string "each")
9255 each-pos (- js2-token-beg pos)) ; relative
9256 (js2-record-face 'font-lock-keyword-face))
9257 (js2-report-error "msg.no.paren.for")))
9258 (if (js2-must-match js2-LP "msg.no.paren.for")
9259 (setq lp (- js2-token-beg pos)))
9260 (setq tt (js2-peek-token))
9264 ;; handle destructuring assignment
9265 (setq iter (js2-parse-primary-expr-lhs))
9266 (js2-define-destruct-symbols iter js2-LET
9267 'font-lock-variable-name-face t))
9268 ((js2-valid-prop-name-token tt)
9270 (setq iter (js2-create-name-node)))
9272 (js2-report-error "msg.bad.var")))
9273 ;; Define as a let since we want the scope of the variable to
9274 ;; be restricted to the array comprehension
9275 (if (js2-name-node-p iter)
9276 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9277 (if (js2-must-match js2-IN "msg.in.after.for.name")
9278 (setq in-pos (- js2-token-beg pos)))
9279 (setq obj (js2-parse-expr))
9280 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9281 (setq rp (- js2-token-beg pos)))
9282 (setf (js2-node-pos pn) pos
9283 (js2-node-len pn) (- js2-ts-cursor pos)
9284 (js2-array-comp-loop-node-iterator pn) iter
9285 (js2-array-comp-loop-node-object pn) obj
9286 (js2-array-comp-loop-node-in-pos pn) in-pos
9287 (js2-array-comp-loop-node-each-pos pn) each-pos
9288 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9289 (js2-array-comp-loop-node-lp pn) lp
9290 (js2-array-comp-loop-node-rp pn) rp)
9291 (js2-node-add-children pn iter obj))
9295 (defun js2-parse-object-literal ()
9296 (let ((pos js2-token-beg)
9297 tt elems result after-comma
9300 (setq tt (js2-peek-token))
9302 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9303 ;; {get foo() {...}}, or {set foo(x) {...}}
9304 ((or (js2-valid-prop-name-token tt)
9306 (setq after-comma nil
9307 result (js2-parse-named-prop tt))
9308 (if (and (null result)
9309 (not js2-recover-from-parse-errors))
9311 (push result elems)))
9312 ;; {12: x} or {10.7: x}
9315 (setq after-comma nil)
9316 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9321 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9322 pos elems after-comma)))
9324 (js2-report-error "msg.bad.prop")
9325 (unless js2-recover-from-parse-errors
9326 (setq continue nil)))) ; end switch
9327 (if (js2-match-token js2-COMMA)
9328 (setq after-comma js2-token-end)
9329 (setq continue nil))) ; end loop
9330 (js2-must-match js2-RC "msg.no.brace.prop")
9331 (setq result (make-js2-object-node :pos pos
9332 :len (- js2-ts-cursor pos)
9333 :elems (nreverse elems)))
9334 (apply #'js2-node-add-children result (js2-object-node-elems result))
9337 (defun js2-parse-named-prop (tt)
9338 "Parse a name, string, or getter/setter object property.
9339 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9341 (let ((string-prop (and (= tt js2-STRING)
9342 (make-js2-string-node)))
9344 (ppos js2-token-beg)
9345 (pend js2-token-end)
9346 (name (js2-create-name-node))
9347 (prop js2-ts-string))
9349 ;; getter/setter prop
9350 ((and (= tt js2-NAME)
9351 (= (js2-peek-token) js2-NAME)
9352 (or (string= prop "get")
9353 (string= prop "set")))
9355 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9356 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9357 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9358 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9359 ;; abbreviated destructuring bind e.g., {a, b} = c;
9360 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9361 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9362 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9363 ;; assignment but it's difficult because it requires looking ahead of expression.
9366 (let ((ctk (js2-peek-token)))
9367 (or (= ctk js2-COMMA)
9369 (js2-valid-prop-name-token ctk))))
9374 (setq expr (js2-parse-plain-property (or string-prop name)))
9375 (js2-set-face ppos pend
9376 (if (js2-function-node-p
9377 (js2-object-prop-node-right expr))
9378 'font-lock-function-name-face
9379 'font-lock-variable-name-face)
9382 (defun js2-parse-plain-property (prop)
9383 "Parse a non-getter/setter property in an object literal.
9384 PROP is the node representing the property: a number, name or string."
9385 (js2-must-match js2-COLON "msg.no.colon.prop")
9386 (let* ((pos (js2-node-pos prop))
9387 (colon (- js2-token-beg pos))
9388 (expr (js2-parse-assign-expr))
9389 (result (make-js2-object-prop-node
9391 ;; don't include last consumed token in length
9392 :len (- (+ (js2-node-pos expr)
9393 (js2-node-len expr))
9398 (js2-node-add-children result prop expr)
9401 (defun js2-parse-getter-setter-prop (pos prop get-p)
9402 "Parse getter or setter property in an object literal.
9403 JavaScript syntax is:
9405 { get foo() {...}, set foo(x) {...} }
9407 and expression closure style is also supported
9409 { get foo() x, set foo(x) _x = x }
9411 POS is the start position of the `get' or `set' keyword.
9412 PROP is the `js2-name-node' representing the property name.
9413 GET-P is non-nil if the keyword was `get'."
9414 (let ((type (if get-p js2-GET js2-SET))
9416 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9417 ;; it has to be an anonymous function, as we already parsed the name
9418 (if (/= (js2-node-type fn) js2-FUNCTION)
9419 (js2-report-error "msg.bad.prop")
9420 (if (plusp (length (js2-function-name fn)))
9421 (js2-report-error "msg.bad.prop")))
9422 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9423 (setq end (js2-node-end fn)
9424 result (make-js2-getter-setter-node :type type
9429 (js2-node-add-children result prop fn)
9432 (defun js2-create-name-node (&optional check-activation-p token)
9433 "Create a name node using the token info from last scanned name.
9434 In some cases we need to either synthesize a name node, or we lost
9435 the name token information by peeking. If the TOKEN parameter is
9436 not `js2-NAME', then we use the token info saved in instance vars."
9437 (let ((beg js2-token-beg)
9440 (when (/= js2-current-token js2-NAME)
9441 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9442 s js2-prev-name-token-string
9443 js2-prev-name-token-start nil
9444 js2-prev-name-token-string nil))
9445 (setq name (make-js2-name-node :pos beg
9448 (if check-activation-p
9449 (js2-check-activation-name s (or token js2-NAME)))
9452 ;;; Indentation support
9454 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9455 ;; Karl cleverly deduces that the desired indentation level is often a
9456 ;; function of paren/bracket/brace nesting depth, which can be determined
9457 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9458 ;; then does some equally clever checks to see if we're in the context of a
9459 ;; substatement of a possibly braceless statement keyword such as if, while,
9460 ;; or finally. This approach yields pretty good results.
9462 ;; The indenter is often "wrong", however, and needs to be overridden.
9463 ;; The right long-term solution is probably to emulate (or integrate
9464 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9465 ;; parse tree from `js2-parse' is present, which is not true at the
9466 ;; moment the user is typing, computing indentation is still thousands
9467 ;; of lines of code to handle every possible syntactic edge case.
9469 ;; In the meantime, the compromise solution is that we offer a "bounce
9470 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9471 ;; current line indent among various likely guess points. This approach
9472 ;; is far from perfect, but should at least make it slightly easier to
9473 ;; move the line towards its desired indentation when manually
9474 ;; overriding Karl's heuristic nesting guesser.
9476 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9477 ;; extensions such as `let' and Array comprehensions. Major kudos to
9478 ;; Karl for coming up with the initial approach, which packs a lot of
9479 ;; punch for so little code.
9481 (defconst js2-possibly-braceless-keywords-re
9482 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9483 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9484 "try" "while" "with" "let")))
9485 "Regular expression matching keywords that are optionally
9486 followed by an opening brace.")
9488 (defconst js2-indent-operator-re
9489 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9490 (regexp-opt '("in" "instanceof") 'words))
9491 "Regular expression matching operators that affect indentation
9492 of continued expressions.")
9494 (defconst js2-declaration-keyword-re
9495 (regexp-opt '("var" "let" "const") 'words)
9496 "Regular expression matching variable declaration keywords.")
9498 ;; This function has horrible results if you're typing an array
9499 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9500 ;; in conjunction with electric-indent, so just disabling it.
9501 (defsubst js2-code-at-bol-p ()
9502 "Return t if the first character on line is non-whitespace."
9505 (defun js2-insert-and-indent (key)
9506 "Run command bound to KEY and indent current line.
9507 Runs the command bound to KEY in the global keymap and indents
9509 (interactive (list (this-command-keys)))
9510 (let ((cmd (lookup-key (current-global-map) key)))
9512 (call-interactively cmd)))
9513 ;; don't do the electric keys inside comments or strings,
9514 ;; and don't do bounce-indent with them.
9515 (let ((parse-state (syntax-ppss (point)))
9516 (js2-bounce-indent-p (js2-code-at-bol-p)))
9517 (unless (or (nth 3 parse-state)
9518 (nth 4 parse-state))
9519 (indent-according-to-mode))))
9521 (defun js2-re-search-forward-inner (regexp &optional bound count)
9522 "Auxiliary function for `js2-re-search-forward'."
9523 (let (parse saved-point)
9525 (re-search-forward regexp bound)
9526 (setq parse (if saved-point
9527 (parse-partial-sexp saved-point (point))
9528 (syntax-ppss (point))))
9529 (cond ((nth 3 parse)
9531 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9532 (save-excursion (end-of-line) (point)) t))
9536 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9537 (re-search-forward "\\*/"))
9539 (setq count (1- count))))
9540 (setq saved-point (point))))
9543 (defun js2-re-search-forward (regexp &optional bound noerror count)
9544 "Search forward but ignore strings and comments.
9545 Invokes `re-search-forward' but treats the buffer as if strings
9546 and comments have been removed."
9547 (let ((saved-point (point))
9550 '(js2-re-search-forward-inner regexp bound 1))
9552 '(js2-re-search-backward-inner regexp bound (- count)))
9554 '(js2-re-search-forward-inner regexp bound count)))))
9558 (goto-char saved-point)
9560 (error (error-message-string err)))))))
9562 (defun js2-re-search-backward-inner (regexp &optional bound count)
9563 "Auxiliary function for `js2-re-search-backward'."
9566 (re-search-backward regexp bound)
9567 (setq parse (syntax-ppss (point)))
9568 (cond ((nth 3 parse)
9570 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9571 (line-beginning-position) t))
9573 (goto-char (nth 8 parse)))
9575 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9576 (re-search-backward "/\\*"))
9578 (setq count (1- count))))))
9581 (defun js2-re-search-backward (regexp &optional bound noerror count)
9582 "Search backward but ignore strings and comments.
9583 Invokes `re-search-backward' but treats the buffer as if strings
9584 and comments have been removed."
9585 (let ((saved-point (point))
9588 '(js2-re-search-backward-inner regexp bound 1))
9590 '(js2-re-search-forward-inner regexp bound (- count)))
9592 '(js2-re-search-backward-inner regexp bound count)))))
9596 (goto-char saved-point)
9598 (error (error-message-string err)))))))
9600 (defun js2-looking-at-operator-p ()
9601 "Return non-nil if text after point is a non-comma operator."
9602 (and (looking-at js2-indent-operator-re)
9603 (or (not (looking-at ":"))
9605 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9606 (looking-at "?"))))))
9608 (defun js2-continued-expression-p ()
9609 "Return non-nil if the current line continues an expression."
9611 (back-to-indentation)
9612 (or (js2-looking-at-operator-p)
9613 (when (js2-re-search-backward "\n" nil t) ;; comment
9614 (skip-chars-backward " \t")
9616 (when (js2-looking-at-operator-p)
9618 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9620 (defun js2-end-of-do-while-loop-p ()
9621 "Return non-nil if word after point is `while' of a do-while
9622 statement, else returns nil. A braceless do-while statement
9623 spanning several lines requires that the start of the loop is
9624 indented to the same column as the current line."
9627 (when (looking-at "\\s-*\\<while\\>")
9629 (skip-chars-backward "[ \t\n]*}")
9630 (looking-at "[ \t\n]*}"))
9632 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9633 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9634 (or (looking-at "\\<do\\>")
9635 (let ((saved-indent (current-indentation)))
9636 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9637 (/= (current-indentation) saved-indent)))
9638 (and (looking-at "[ \t]*\\<do\\>")
9639 (not (js2-re-search-forward
9640 "\\<while\\>" (point-at-eol) t))
9641 (= (current-indentation) saved-indent))))))))
9643 (defun js2-multiline-decl-indentation ()
9644 "Returns the declaration indentation column if the current line belongs
9645 to a multiline declaration statement. All declarations are lined up vertically:
9651 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9652 assigned expression is a function or array/object literal, it will be indented
9655 var o = { var bar = 2,
9660 (let (forward-sexp-function ; use Lisp version
9663 (back-to-indentation)
9664 (when (not (looking-at js2-declaration-keyword-re))
9665 (when (looking-at js2-indent-operator-re)
9666 (goto-char (match-end 0))) ; continued expressions are ok
9667 (while (and (not at-opening-bracket)
9669 (let ((pos (point)))
9672 (or (eq (char-before) ?,)
9673 (and (not (eq (char-before) ?\;))
9675 (prog2 (skip-chars-backward "[[:punct:]]")
9676 (looking-at js2-indent-operator-re)
9678 (not (eq (char-before) ?\;))))
9679 (js2-same-line pos)))))
9682 (scan-error (setq at-opening-bracket t))))
9683 (when (looking-at js2-declaration-keyword-re)
9684 (- (1+ (match-end 0)) (point-at-bol)))))))
9686 (defun js2-ctrl-statement-indentation ()
9687 "Return the proper indentation of current line if it is a control statement.
9688 Returns an indentation if this line starts the body of a control
9689 statement without braces, else returns nil."
9690 (let (forward-sexp-function)
9692 (back-to-indentation)
9693 (when (and (not (js2-same-line (point-min)))
9694 (not (looking-at "{"))
9695 (js2-re-search-backward "[[:graph:]]" nil t)
9696 (not (looking-at "[{([]"))
9699 (when (= (char-before) ?\))
9700 ;; scan-sexps sometimes throws an error
9701 (ignore-errors (backward-sexp))
9702 (skip-chars-backward " \t" (point-at-bol)))
9704 (back-to-indentation)
9705 (and (looking-at js2-possibly-braceless-keywords-re)
9706 (= (match-end 0) pt)
9707 (not (js2-end-of-do-while-loop-p))))))
9708 (+ (current-indentation) js2-basic-offset)))))
9710 (defun js2-indent-in-array-comp (parse-status)
9711 "Return non-nil if we think we're in an array comprehension.
9712 In particular, return the buffer position of the first `for' kwd."
9713 (let ((bracket (nth 1 parse-status))
9718 (when (looking-at "\\[")
9721 (if (looking-at "[[{]")
9722 (let (forward-sexp-function) ; use Lisp version
9723 (forward-sexp) ; skip destructuring form
9725 (if (and (/= (char-after) ?,) ; regular array
9727 (match-beginning 0)))
9728 ;; to skip arbitrary expressions we need the parser,
9729 ;; so we'll just guess at it.
9730 (if (and (> end (point)) ; not empty literal
9731 (re-search-forward "[^,]]* \\(for\\) " end t)
9732 ;; not inside a string literal
9733 (not (nth 3 (parse-partial-sexp bracket (point)))))
9734 (match-beginning 1))))))))
9736 (defun js2-array-comp-indentation (parse-status for-kwd)
9737 (if (js2-same-line for-kwd)
9738 ;; first continuation line
9740 (goto-char (nth 1 parse-status))
9742 (skip-chars-forward " \t")
9748 (defun js2-proper-indentation (parse-status)
9749 "Return the proper indentation for the current line."
9751 (back-to-indentation)
9752 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9753 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9754 (continued-expr-p (js2-continued-expression-p))
9755 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
9756 (js2-multiline-decl-indentation)))
9757 (bracket (nth 1 parse-status))
9760 ;; indent array comprehension continuation lines specially
9762 (not (js2-same-line bracket))
9763 (setq beg (js2-indent-in-array-comp parse-status))
9764 (>= (point) (save-excursion
9766 (point-at-bol)))) ; at or after first loop?
9767 (js2-array-comp-indentation parse-status beg))
9771 ((and declaration-indent continued-expr-p)
9772 (+ declaration-indent js2-basic-offset))
9774 (declaration-indent)
9779 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9780 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9781 (when (save-excursion (skip-chars-backward " \t)")
9785 (not js2-consistent-level-indent-inner-bracket-p))
9786 (progn (goto-char (1+ (nth 1 p)))
9787 (skip-chars-forward " \t"))
9788 (back-to-indentation)
9789 (when (and js2-pretty-multiline-decl-indentation-p
9790 js2-always-indent-assigned-expr-in-decls-p
9791 (looking-at js2-declaration-keyword-re))
9792 (goto-char (1+ (match-end 0)))))
9793 (cond (same-indent-p
9796 (+ (current-column) (* 2 js2-basic-offset)))
9798 (+ (current-column) js2-basic-offset)))))
9800 (unless same-indent-p
9802 (skip-chars-forward " \t"))
9805 (continued-expr-p js2-basic-offset)
9809 (defun js2-lineup-comment (parse-status)
9810 "Indent a multi-line block comment continuation line."
9811 (let* ((beg (nth 8 parse-status))
9812 (first-line (js2-same-line beg))
9813 (offset (save-excursion
9815 (if (looking-at "/\\*")
9816 (+ 1 (current-column))
9819 (indent-line-to offset))))
9821 (defun js2-backward-sws ()
9822 "Move backward through whitespace and comments."
9824 (while (forward-comment -1)))
9826 (defun js2-forward-sws ()
9827 "Move forward through whitespace and comments."
9829 (while (forward-comment 1)))
9831 (defun js2-current-indent (&optional pos)
9832 "Return column of indentation on current line.
9833 If POS is non-nil, go to that point and return indentation for that line."
9837 (back-to-indentation)
9840 (defun js2-arglist-close ()
9841 "Return non-nil if we're on a line beginning with a close-paren/brace."
9843 (goto-char (point-at-bol))
9845 (looking-at "[])}]")))
9847 (defun js2-indent-looks-like-label-p ()
9848 (goto-char (point-at-bol))
9850 (looking-at (concat js2-mode-identifier-re ":")))
9852 (defun js2-indent-in-objlit-p (parse-status)
9853 "Return non-nil if this looks like an object-literal entry."
9854 (let ((start (nth 1 parse-status)))
9858 (and (zerop (forward-line -1))
9859 (not (< (point) start)) ; crossed a {} boundary
9860 (js2-indent-looks-like-label-p)))
9862 (js2-indent-looks-like-label-p)))))
9864 ;; If prev line looks like foobar({ then we're passing an object
9865 ;; literal to a function call, and people pretty much always want to
9866 ;; de-dent back to the previous line, so move the 'basic-offset'
9867 ;; position to the front.
9868 (defun js2-indent-objlit-arg-p (parse-status)
9870 (back-to-indentation)
9872 (and (eq (1- (point)) (nth 1 parse-status))
9873 (eq (char-before) ?{)
9876 (skip-chars-backward " \t")
9877 (eq (char-before) ?\()))))
9879 (defun js2-indent-case-block-p ()
9881 (back-to-indentation)
9883 (goto-char (point-at-bol))
9884 (skip-chars-forward " \t")
9885 (looking-at "case\\s-.+:")))
9887 (defun js2-syntax-bol ()
9888 "Return the point at the first non-whitespace char on the line.
9889 Returns `point-at-bol' if the line is empty."
9892 (skip-chars-forward " \t")
9895 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9896 "Cycle among alternate computed indentation positions.
9897 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9898 of the buffer to the current point. NORMAL-COL is the indentation
9899 column computed by the heuristic guesser based on current paren,
9900 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9902 (let ((cur-indent (js2-current-indent))
9903 (old-buffer-undo-list buffer-undo-list)
9904 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9905 (current-line (save-excursion
9906 (forward-line 0) ; move to bol
9907 (1+ (count-lines (point-min) (point)))))
9908 positions pos main-pos anchor arglist-cont same-indent
9909 prev-line-col basic-offset computed-pos)
9910 ;; temporarily don't record undo info, if user requested this
9911 (when js2-mode-indent-inhibit-undo
9912 (setq buffer-undo-list t))
9915 ;; First likely point: indent from beginning of previous code line
9916 (push (setq basic-offset
9918 (back-to-indentation)
9920 (back-to-indentation)
9921 (setq prev-line-col (current-column)))
9925 ;; (First + epsilon) likely point: indent 2x from beginning of
9926 ;; previous code line. Google does it this way.
9927 (push (setq basic-offset
9929 (back-to-indentation)
9931 (back-to-indentation)
9932 (setq prev-line-col (current-column)))
9933 (* 2 js2-basic-offset)))
9936 ;; Second likely point: indent from assign-expr RHS. This
9937 ;; is just a crude guess based on finding " = " on the previous
9938 ;; line containing actual code.
9939 (setq pos (save-excursion
9941 (goto-char (point-at-bol))
9942 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9944 (goto-char (match-end 1))
9945 (skip-chars-forward " \t\r\n")
9948 (incf pos js2-basic-offset)
9949 (push pos positions))
9951 ;; Third likely point: same indent as previous line of code.
9952 ;; Make it the first likely point if we're not on an
9953 ;; arglist-close line and previous line ends in a comma, or
9954 ;; both this line and prev line look like object-literal
9956 (setq pos (save-excursion
9957 (goto-char (point-at-bol))
9959 (back-to-indentation)
9962 ;; while we're here, look for trailing comma
9964 (goto-char (point-at-eol))
9966 (eq (char-before) ?,))
9967 (setq arglist-cont (1- (point)))))))
9969 (if (and (or arglist-cont
9970 (js2-indent-in-objlit-p parse-status))
9971 (not (js2-arglist-close)))
9972 (setq same-indent pos))
9973 (push pos positions))
9975 ;; Fourth likely point: first preceding code with less indentation.
9976 ;; than the immediately preceding code line.
9977 (setq pos (save-excursion
9978 (back-to-indentation)
9980 (back-to-indentation)
9981 (setq anchor (current-column))
9982 (while (and (zerop (forward-line -1))
9984 (back-to-indentation)
9987 (setq pos (current-column))))
9988 (push pos positions)
9990 ;; nesting-heuristic position, main by default
9991 (push (setq main-pos normal-col) positions)
9993 ;; delete duplicates and sort positions list
9994 (setq positions (sort (delete-dups positions) '<))
9996 ;; comma-list continuation lines: prev line indent takes precedence
9998 (setq main-pos same-indent))
10000 ;; common special cases where we want to indent in from previous line
10001 (if (or (js2-indent-case-block-p)
10002 (js2-indent-objlit-arg-p parse-status))
10003 (setq main-pos basic-offset))
10005 ;; if bouncing backwards, reverse positions list
10007 (setq positions (reverse positions)))
10009 ;; record whether we're already sitting on one of the alternatives
10010 (setq pos (member cur-indent positions))
10013 ;; case 0: we're one one of the alternatives and this is the
10014 ;; first time they've pressed TAB on this line (best-guess).
10015 ((and js2-mode-indent-ignore-first-tab
10017 ;; first time pressing TAB on this line?
10018 (not (eq js2-mode-last-indented-line current-line)))
10020 (setq computed-pos nil))
10021 ;; case 1: only one computed position => use it
10022 ((null (cdr positions))
10023 (setq computed-pos 0))
10024 ;; case 2: not on any of the computed spots => use main spot
10026 (setq computed-pos (js2-position main-pos positions)))
10027 ;; case 3: on last position: cycle to first position
10029 (setq computed-pos 0))
10030 ;; case 4: on intermediate position: cycle to next position
10032 (setq computed-pos (js2-position (second pos) positions))))
10034 ;; see if any hooks want to indent; otherwise we do it
10035 (loop with result = nil
10036 for hook in js2-indent-hook
10037 while (null result)
10039 (setq result (funcall hook positions computed-pos))
10041 (unless (or result (null computed-pos))
10042 (indent-line-to (nth computed-pos positions)))))
10045 (if js2-mode-indent-inhibit-undo
10046 (setq buffer-undo-list old-buffer-undo-list))
10047 ;; see commentary for `js2-mode-last-indented-line'
10048 (setq js2-mode-last-indented-line current-line))))
10050 (defun js2-indent-bounce-backwards ()
10051 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10052 cycles between the computed indentation positions in reverse order."
10054 (js2-indent-line t))
10056 (defun js2-1-line-comment-continuation-p ()
10057 "Return t if we're in a 1-line comment continuation.
10058 If so, we don't ever want to use bounce-indent."
10062 (looking-at "\\s-*//"))
10066 (when (looking-at "\\s-*$")
10069 (looking-at "\\s-*//")))))
10071 (defun js2-indent-line (&optional bounce-backwards)
10072 "Indent the current line as JavaScript source text."
10074 (let (parse-status current-indent offset indent-col moved
10075 ;; Don't whine about errors/warnings when we're indenting.
10076 ;; This has to be set before calling parse-partial-sexp below.
10077 (inhibit-point-motion-hooks t))
10078 (setq parse-status (save-excursion
10079 (syntax-ppss (point-at-bol)))
10080 offset (- (point) (save-excursion
10081 (back-to-indentation)
10083 (js2-with-underscore-as-word-syntax
10084 (if (nth 4 parse-status)
10085 (js2-lineup-comment parse-status)
10086 (setq indent-col (js2-proper-indentation parse-status))
10087 ;; See comments below about `js2-mode-last-indented-line'.
10089 ;; bounce-indenting is disabled during electric-key indent.
10090 ;; It doesn't work well on first line of buffer.
10091 ((and js2-bounce-indent-p
10092 (not (js2-same-line (point-min)))
10093 (not (js2-1-line-comment-continuation-p)))
10094 (js2-bounce-indent indent-col parse-status bounce-backwards))
10095 ;; just indent to the guesser's likely spot
10096 (t (indent-line-to indent-col)))
10097 (when (plusp offset)
10098 (forward-char offset))))))
10100 (defun js2-indent-region (start end)
10101 "Indent the region, but don't use bounce indenting."
10102 (let ((js2-bounce-indent-p nil)
10103 (indent-region-function nil)
10104 (after-change-functions (remq 'js2-mode-edit
10105 after-change-functions)))
10106 (indent-region start end nil) ; nil for byte-compiler
10107 (js2-mode-edit start end (- end start))))
10109 (defvar js2-minor-mode-map
10110 (let ((map (make-sparse-keymap)))
10111 (define-key map (kbd "C-c C-`") #'js2-next-error)
10112 (define-key map [mouse-1] #'js2-mode-show-node)
10114 "Keymap used when `js2-minor-mode' is active.")
10116 (define-minor-mode js2-minor-mode
10117 "Minor mode for running js2 as a background linter.
10118 This allows you to use a different major mode for JavaScript editing,
10119 such as `espresso-mode', while retaining the asynchronous error/warning
10120 highlighting features of `js2-mode'."
10122 :lighter " js-lint"
10124 (js2-minor-mode-enter)
10125 (js2-minor-mode-exit)))
10127 (defun js2-minor-mode-enter ()
10128 "Initialization for `js2-minor-mode'."
10129 (set (make-local-variable 'max-lisp-eval-depth)
10130 (max max-lisp-eval-depth 3000))
10131 (setq next-error-function #'js2-next-error)
10132 (setq js2-default-externs
10133 (append js2-ecma-262-externs
10134 (if js2-include-browser-externs js2-browser-externs)
10135 (if js2-include-gears-externs js2-gears-externs)
10136 (if js2-include-rhino-externs js2-rhino-externs)))
10137 ;; Experiment: make reparse-delay longer for longer files.
10138 (if (plusp js2-dynamic-idle-timer-adjust)
10139 (setq js2-idle-timer-delay
10140 (* js2-idle-timer-delay
10141 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10142 (setq js2-mode-buffer-dirty-p t
10143 js2-mode-parsing nil
10144 js2-highlight-level 0) ; no syntax highlighting
10145 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10146 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10149 (defun js2-minor-mode-exit ()
10150 "Turn off `js2-minor-mode'."
10151 (setq next-error-function nil)
10152 (remove-hook 'after-change-functions #'js2-mode-edit t)
10153 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10154 (when js2-mode-node-overlay
10155 (delete-overlay js2-mode-node-overlay)
10156 (setq js2-mode-node-overlay nil))
10157 (js2-remove-overlays)
10158 (setq js2-mode-ast nil))
10160 (defun js2-display-error-list ()
10161 "Display a navigable buffer listing parse errors/warnings."
10163 (if (not (js2-have-errors-p))
10164 (message "No errors")
10165 (let ((srcbuf (current-buffer))
10166 (errbuf (get-buffer-create "*js-lint*"))
10167 (errs (js2-errors-and-warnings)))
10168 (setq errs (sort errs (lambda (e1 e2)
10169 (funcall '< (second e1) (second e2)))))
10170 (with-current-buffer errbuf
10171 (let ((inhibit-read-only t))
10174 (insert (format "%s\n" err)))
10175 (pop-to-buffer errbuf))))))
10178 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10179 ;; FIXME: Should derive from js-mode.
10180 "Major mode for editing JavaScript code."
10181 (setq comment-start "//" ; used by comment-region; don't change it
10183 (set (make-local-variable 'max-lisp-eval-depth)
10184 (max max-lisp-eval-depth 3000))
10185 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10186 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10187 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10188 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10189 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10190 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10191 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10192 ;; for characters inside regexp literals.
10193 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10194 ;; this is necessary to make `show-paren-function' work properly
10195 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10196 ;; needed for M-x rgrep, among other things
10197 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10199 (set (make-local-variable 'electric-indent-chars)
10200 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10201 electric-indent-chars))
10202 (set (make-local-variable 'electric-layout-rules)
10203 '((?\; . after) (?\{ . after) (?\} . before)))
10205 ;; some variables needed by cc-engine for paragraph-fill, etc.
10206 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10207 c-comment-start-regexp "/[*/]\\|\\s|"
10208 c-line-comment-starter "//"
10209 c-paragraph-start js2-paragraph-start
10210 c-paragraph-separate "$"
10211 comment-start-skip js2-comment-start-skip
10212 c-syntactic-ws-start js2-syntactic-ws-start
10213 c-syntactic-ws-end js2-syntactic-ws-end
10214 c-syntactic-eol js2-syntactic-eol)
10216 (let ((c-buffer-is-cc-mode t))
10217 ;; Copied from `js-mode'. Also see Bug#6071.
10218 (make-local-variable 'paragraph-start)
10219 (make-local-variable 'paragraph-separate)
10220 (make-local-variable 'paragraph-ignore-fill-prefix)
10221 (make-local-variable 'adaptive-fill-mode)
10222 (make-local-variable 'adaptive-fill-regexp)
10223 (c-setup-paragraph-variables))
10225 (setq js2-default-externs
10226 (append js2-ecma-262-externs
10227 (if js2-include-browser-externs js2-browser-externs)
10228 (if js2-include-gears-externs js2-gears-externs)
10229 (if js2-include-rhino-externs js2-rhino-externs)))
10231 (setq font-lock-defaults '(nil t))
10233 ;; Experiment: make reparse-delay longer for longer files.
10234 (when (plusp js2-dynamic-idle-timer-adjust)
10235 (setq js2-idle-timer-delay
10236 (* js2-idle-timer-delay
10237 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10239 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10240 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10241 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10242 (imenu-add-to-menubar (concat "IM-" mode-name))
10243 (add-to-invisibility-spec '(js2-outline . t))
10244 (set (make-local-variable 'line-move-ignore-invisible) t)
10245 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10247 (if (fboundp 'run-mode-hooks)
10248 (run-mode-hooks 'js2-mode-hook)
10249 (run-hooks 'js2-mode-hook))
10251 (setq js2-mode-functions-hidden nil
10252 js2-mode-comments-hidden nil
10253 js2-mode-buffer-dirty-p t
10254 js2-mode-parsing nil)
10257 (defun js2-mode-exit ()
10258 "Exit `js2-mode' and clean up."
10260 (when js2-mode-node-overlay
10261 (delete-overlay js2-mode-node-overlay)
10262 (setq js2-mode-node-overlay nil))
10263 (js2-remove-overlays)
10264 (setq js2-mode-ast nil)
10265 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10266 (remove-from-invisibility-spec '(js2-outline . t))
10267 (js2-mode-show-all)
10268 (with-silent-modifications
10269 (js2-clear-face (point-min) (point-max))))
10271 (defun js2-mode-reset-timer ()
10272 "Cancel any existing parse timer and schedule a new one."
10273 (if js2-mode-parse-timer
10274 (cancel-timer js2-mode-parse-timer))
10275 (setq js2-mode-parsing nil)
10276 (setq js2-mode-parse-timer
10277 (run-with-idle-timer js2-idle-timer-delay nil
10278 #'js2-mode-idle-reparse (current-buffer))))
10280 (defun js2-mode-idle-reparse (buffer)
10281 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10282 it to be reparsed when the buffer is selected."
10283 (if (eq buffer (current-buffer))
10285 ;; reparse when the buffer is selected again
10286 (with-current-buffer buffer
10287 (add-hook 'window-configuration-change-hook
10288 #'js2-mode-idle-reparse-inner
10291 (defun js2-mode-idle-reparse-inner ()
10292 (remove-hook 'window-configuration-change-hook
10293 #'js2-mode-idle-reparse-inner
10297 (defun js2-mode-edit (beg end len)
10298 "Schedule a new parse after buffer is edited.
10299 Buffer edit spans from BEG to END and is of length LEN."
10300 (setq js2-mode-buffer-dirty-p t)
10301 (js2-mode-hide-overlay)
10302 (js2-mode-reset-timer))
10304 (defun js2-minor-mode-edit (beg end len)
10305 "Callback for buffer edits in `js2-mode'.
10306 Schedules a new parse after buffer is edited.
10307 Buffer edit spans from BEG to END and is of length LEN."
10308 (setq js2-mode-buffer-dirty-p t)
10309 (js2-mode-hide-overlay)
10310 (js2-mode-reset-timer))
10312 (defun js2-reparse (&optional force)
10313 "Re-parse current buffer after user finishes some data entry.
10314 If we get any user input while parsing, including cursor motion,
10315 we discard the parse and reschedule it. If FORCE is nil, then the
10316 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10319 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10320 (unless js2-mode-parsing
10321 (setq js2-mode-parsing t)
10323 (when (or js2-mode-buffer-dirty-p force)
10324 (js2-remove-overlays)
10325 (with-silent-modifications
10326 (setq js2-mode-buffer-dirty-p nil
10327 js2-mode-fontifications nil
10328 js2-mode-deferred-properties nil)
10329 (if js2-mode-verbose-parse-p
10330 (message "parsing..."))
10333 (setq interrupted-p
10334 (catch 'interrupted
10335 (setq js2-mode-ast (js2-parse))
10336 ;; if parsing is interrupted, comments and regex
10337 ;; literals stay ignored by `parse-partial-sexp'
10338 (remove-text-properties (point-min) (point-max)
10340 (js2-mode-apply-deferred-properties)
10341 (js2-mode-remove-suppressed-warnings)
10342 (js2-mode-show-warnings)
10343 (js2-mode-show-errors)
10344 (if (>= js2-highlight-level 1)
10345 (js2-highlight-jsdoc js2-mode-ast))
10349 ;; unfinished parse => try again
10350 (setq js2-mode-buffer-dirty-p t)
10351 (js2-mode-reset-timer))
10352 (if js2-mode-verbose-parse-p
10353 (message "Parse time: %s" time)))))
10354 (setq js2-mode-parsing nil)
10355 (unless interrupted-p
10356 (setq js2-mode-parse-timer nil))))))
10358 (defun js2-mode-show-node ()
10359 "Debugging aid: highlight selected AST node on mouse click."
10361 (let ((node (js2-node-at-point))
10363 (when js2-mode-show-overlay
10365 (message "No node found at location %s" (point))
10366 (setq beg (js2-node-abs-pos node)
10367 end (+ beg (js2-node-len node)))
10368 (if js2-mode-node-overlay
10369 (move-overlay js2-mode-node-overlay beg end)
10370 (setq js2-mode-node-overlay (make-overlay beg end))
10371 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10372 (with-silent-modifications
10373 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10374 (message "%s, parent: %s"
10375 (js2-node-short-name node)
10376 (if (js2-node-parent node)
10377 (js2-node-short-name (js2-node-parent node))
10380 (defun js2-mode-hide-overlay (&optional p1 p2)
10381 "Remove the debugging overlay when the point moves.
10382 P1 and P2 are the old and new values of point, respectively."
10383 (when js2-mode-node-overlay
10384 (let ((beg (overlay-start js2-mode-node-overlay))
10385 (end (overlay-end js2-mode-node-overlay)))
10386 ;; Sometimes we're called spuriously.
10390 (with-silent-modifications
10391 (remove-text-properties beg end '(point-left nil)))
10392 (delete-overlay js2-mode-node-overlay)
10393 (setq js2-mode-node-overlay nil)))))
10395 (defun js2-mode-reset ()
10396 "Debugging helper: reset everything."
10401 (defun js2-mode-show-warn-or-err (e face)
10402 "Highlight a warning or error E with FACE.
10403 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10404 (let* ((key (first e))
10406 (end (+ beg (third e)))
10407 ;; Don't inadvertently go out of bounds.
10408 (beg (max (point-min) (min beg (point-max))))
10409 (end (max (point-min) (min end (point-max))))
10410 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10411 (ovl (make-overlay beg end)))
10412 (overlay-put ovl 'font-lock-face face)
10413 (overlay-put ovl 'js2-error t)
10414 (put-text-property beg end 'help-echo (js2-get-msg key))
10415 (put-text-property beg end 'point-entered #'js2-echo-error)))
10417 (defun js2-remove-overlays ()
10418 "Remove overlays from buffer that have a `js2-error' property."
10419 (let ((beg (point-min))
10422 (dolist (o (overlays-in beg end))
10423 (when (overlay-get o 'js2-error)
10424 (delete-overlay o))))))
10426 (defun js2-error-at-point (&optional pos)
10427 "Return non-nil if there's an error overlay at POS.
10428 Defaults to point."
10429 (loop with pos = (or pos (point))
10430 for o in (overlays-at pos)
10431 thereis (overlay-get o 'js2-error)))
10433 (defun js2-mode-apply-deferred-properties ()
10434 "Apply fontifications and other text properties recorded during parsing."
10435 (when (plusp js2-highlight-level)
10436 ;; We defer clearing faces as long as possible to eliminate flashing.
10437 (js2-clear-face (point-min) (point-max))
10438 ;; Have to reverse the recorded fontifications list so that errors
10439 ;; and warnings overwrite the normal fontifications.
10440 (dolist (f (nreverse js2-mode-fontifications))
10441 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10442 (setq js2-mode-fontifications nil))
10443 (dolist (p js2-mode-deferred-properties)
10444 (apply #'put-text-property p))
10445 (setq js2-mode-deferred-properties nil))
10447 (defun js2-mode-show-errors ()
10448 "Highlight syntax errors."
10449 (when js2-mode-show-parse-errors
10450 (dolist (e (js2-ast-root-errors js2-mode-ast))
10451 (js2-mode-show-warn-or-err e 'js2-error-face))))
10453 (defun js2-mode-remove-suppressed-warnings ()
10454 "Take suppressed warnings out of the AST warnings list.
10455 This ensures that the counts and `next-error' are correct."
10456 (setf (js2-ast-root-warnings js2-mode-ast)
10459 (let ((key (caar e)))
10461 (and (not js2-strict-trailing-comma-warning)
10462 (string-match "trailing\\.comma" key))
10463 (and (not js2-strict-cond-assign-warning)
10464 (string= key "msg.equal.as.assign"))
10465 (and js2-missing-semi-one-line-override
10466 (string= key "msg.missing.semi")
10467 (let* ((beg (second e))
10468 (node (js2-node-at-point beg))
10469 (fn (js2-mode-find-parent-fn node))
10470 (body (and fn (js2-function-node-body fn)))
10471 (lc (and body (js2-node-abs-pos body)))
10472 (rc (and lc (+ lc (js2-node-len body)))))
10477 (and (js2-same-line lc)
10478 (js2-same-line rc))))))))))
10479 (js2-ast-root-warnings js2-mode-ast))))
10481 (defun js2-mode-show-warnings ()
10482 "Highlight strict-mode warnings."
10483 (when js2-mode-show-strict-warnings
10484 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10485 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10487 (defun js2-echo-error (old-point new-point)
10488 "Called by point-motion hooks."
10489 (let ((msg (get-text-property new-point 'help-echo)))
10490 (if (and msg (or (not (current-message))
10491 (string= (current-message) "Quit")))
10494 (defalias #'js2-echo-help #'js2-echo-error)
10496 (defun js2-line-break (&optional soft)
10497 "Break line at point."
10498 (let ((parse-status (syntax-ppss)))
10500 ;; Check if we're inside a string.
10501 ((nth 3 parse-status)
10502 (js2-mode-split-string parse-status))
10503 ;; Check if inside a block comment.
10504 ((nth 4 parse-status)
10505 (js2-mode-extend-comment))
10509 (defun js2-mode-split-string (parse-status)
10510 "Turn a newline in mid-string into a string concatenation.
10511 PARSE-STATUS is as documented in `parse-partial-sexp'."
10512 (let* ((col (current-column))
10513 (quote-char (nth 3 parse-status))
10514 (quote-string (string quote-char))
10515 (string-beg (nth 8 parse-status))
10518 (back-to-indentation)
10519 (if (looking-at "\\+")
10522 (goto-char string-beg)
10523 (if (looking-back "\\+\\s-+")
10524 (goto-char (match-beginning 0)))
10525 (current-column)))))
10526 (insert quote-char "\n")
10528 (insert "+ " quote-string)
10530 (insert quote-string)
10531 (backward-char 1))))
10533 (defun js2-mode-extend-comment ()
10534 "Indent the line and, when inside a comment block, add comment prefix."
10535 (let (star single col first-line needs-close)
10537 (back-to-indentation)
10539 ((looking-at "\\*[^/]")
10541 col (current-column)))
10542 ((looking-at "/\\*")
10545 col (1+ (current-column))))
10548 col (current-column)))))
10549 ;; Heuristic for whether we need to close the comment:
10550 ;; if we've got a parse error here, assume it's an unterminated
10554 (eq (get-text-property (1- (point)) 'point-entered)
10556 ;; The heuristic above doesn't work well when we're
10557 ;; creating a comment and there's another one downstream,
10558 ;; as our parser thinks this one ends at the end of the
10559 ;; next one. (You can have a /* inside a js block comment.)
10560 ;; So just close it if the next non-ws char isn't a *.
10564 (skip-chars-forward " \t\r\n")
10565 (not (eq (char-after) ?*))))))
10571 (if (and first-line needs-close)
10578 (and (zerop (forward-line 1))
10579 (looking-at "\\s-*//"))))
10582 ;; don't need to extend the comment after all
10583 (js2-enter-indents-newline
10584 (js2-indent-line)))))
10586 (defun js2-beginning-of-line ()
10587 "Toggles point between bol and first non-whitespace char in line.
10588 Also moves past comment delimiters when inside comments."
10593 (back-to-indentation))
10595 (skip-chars-forward "/ \t"))
10596 ((and (eq (char-after) ?*)
10597 (setq node (js2-comment-at-point))
10598 (memq (js2-comment-node-format node) '(jsdoc block))
10600 (skip-chars-backward " \t")
10602 (skip-chars-forward "\* \t"))
10604 (goto-char (point-at-bol))))))
10606 (defun js2-end-of-line ()
10607 "Toggles point between eol and last non-whitespace char in line."
10610 (skip-chars-backward " \t")
10611 (goto-char (point-at-eol))))
10613 (defsubst js2-mode-inside-string ()
10614 "Return non-nil if inside a string.
10615 Actually returns the quote character that begins the string."
10616 (nth 3 (syntax-ppss)))
10618 (defun js2-mode-inside-comment-or-string ()
10619 "Return non-nil if inside a comment or string."
10621 (let ((comment-start
10623 (goto-char (point-at-bol))
10624 (if (re-search-forward "//" (point-at-eol) t)
10625 (match-beginning 0)))))
10627 (<= comment-start (point))))
10628 (let ((parse-state (syntax-ppss)))
10629 (or (nth 3 parse-state)
10630 (nth 4 parse-state)))))
10633 (defun js2-insert-catch-skel (try-pos)
10634 "Complete a try/catch block after inserting a { following a try keyword.
10635 Rationale is that a try always needs a catch or a finally, and the catch is
10636 the more likely of the two.
10638 TRY-POS is the buffer position of the try keyword. The open-curly should
10639 already have been inserted."
10641 (let ((try-col (save-excursion
10642 (goto-char try-pos)
10643 (current-column))))
10646 (js2-indent-line) ;; indent the blank line where cursor will end up
10649 (indent-to try-col)
10650 (insert "} catch (x) {\n\n")
10651 (indent-to try-col)
10655 (defun js2-mode-wait-for-parse (callback)
10656 "Invoke CALLBACK when parsing is finished.
10657 If parsing is already finished, calls CALLBACK immediately."
10658 (if (not js2-mode-buffer-dirty-p)
10660 (push callback js2-mode-pending-parse-callbacks)
10661 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10663 (defun js2-mode-parse-finished ()
10664 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10665 ;; We can't let errors propagate up, since it prevents the
10666 ;; `js2-parse' method from completing normally and returning
10667 ;; the ast, which makes things mysteriously not work right.
10669 (dolist (cb js2-mode-pending-parse-callbacks)
10670 (condition-case err
10672 (error (message "%s" err))))
10673 (setq js2-mode-pending-parse-callbacks nil)))
10675 (defun js2-mode-flag-region (from to flag)
10676 "Hide or show text from FROM to TO, according to FLAG.
10677 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10678 Returns the created overlay if FLAG is non-nil."
10679 (remove-overlays from to 'invisible 'js2-outline)
10681 (let ((o (make-overlay from to)))
10682 (overlay-put o 'invisible 'js2-outline)
10683 (overlay-put o 'isearch-open-invisible
10684 'js2-isearch-open-invisible)
10687 ;; Function to be set as an outline-isearch-open-invisible' property
10688 ;; to the overlay that makes the outline invisible (see
10689 ;; `js2-mode-flag-region').
10690 (defun js2-isearch-open-invisible (overlay)
10691 ;; We rely on the fact that isearch places point on the matched text.
10692 (js2-mode-show-element))
10694 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10695 "Return cons cell of bounds of folding overlay at POS.
10696 Returns nil if not found."
10697 (let ((overlays (overlays-at (or pos (point))))
10699 (while (and overlays
10701 (if (overlay-get (car overlays) 'invisible)
10702 (setq o (car overlays))
10703 (setq overlays (cdr overlays))))
10705 (cons (overlay-start o) (overlay-end o)))))
10707 (defun js2-mode-function-at-point (&optional pos)
10708 "Return the innermost function node enclosing current point.
10709 Returns nil if point is not in a function."
10710 (let ((node (js2-node-at-point pos)))
10711 (while (and node (not (js2-function-node-p node)))
10712 (setq node (js2-node-parent node)))
10713 (if (js2-function-node-p node)
10716 (defun js2-mode-toggle-element ()
10717 "Hide or show the foldable element at the point."
10719 (let (comment fn pos)
10722 ;; /* ... */ comment?
10723 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10724 (if (js2-mode-invisible-overlay-bounds
10725 (setq pos (+ 3 (js2-node-abs-pos comment))))
10728 (js2-mode-show-element))
10729 (js2-mode-hide-element)))
10732 (back-to-indentation)
10733 (looking-at js2-mode-//-comment-re))
10734 (js2-mode-toggle-//-comment))
10736 ((setq fn (js2-mode-function-at-point))
10737 (setq pos (and (js2-function-node-body fn)
10738 (js2-node-abs-pos (js2-function-node-body fn))))
10739 (goto-char (1+ pos))
10740 (if (js2-mode-invisible-overlay-bounds)
10741 (js2-mode-show-element)
10742 (js2-mode-hide-element)))
10744 (message "Nothing at point to hide or show"))))))
10746 (defun js2-mode-hide-element ()
10747 "Fold/hide contents of a block, showing ellipses.
10748 Show the hidden text with \\[js2-mode-show-element]."
10750 (if js2-mode-buffer-dirty-p
10751 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10752 (let (node body beg end)
10754 ((js2-mode-invisible-overlay-bounds)
10755 (message "already hidden"))
10757 (setq node (js2-node-at-point))
10759 ((js2-block-comment-p node)
10760 (js2-mode-hide-comment node))
10762 (while (and node (not (js2-function-node-p node)))
10763 (setq node (js2-node-parent node)))
10765 (setq body (js2-function-node-body node)))
10767 (setq beg (js2-node-abs-pos body)
10768 end (+ beg (js2-node-len body)))
10769 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10770 (message "No collapsable element found at point"))))))))
10772 (defun js2-mode-show-element ()
10773 "Show the hidden element at current point."
10775 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10777 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10778 (message "Nothing to un-hide"))))
10780 (defun js2-mode-show-all ()
10781 "Show all of the text in the buffer."
10783 (js2-mode-flag-region (point-min) (point-max) nil))
10785 (defun js2-mode-toggle-hide-functions ()
10787 (if js2-mode-functions-hidden
10788 (js2-mode-show-functions)
10789 (js2-mode-hide-functions)))
10791 (defun js2-mode-hide-functions ()
10792 "Hides all non-nested function bodies in the buffer.
10793 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10794 to open an individual entry."
10796 (if js2-mode-buffer-dirty-p
10797 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10798 (if (null js2-mode-ast)
10799 (message "Oops - parsing failed")
10800 (setq js2-mode-functions-hidden t)
10801 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10803 (defun js2-mode-function-hider (n endp)
10805 (let ((tt (js2-node-type n))
10808 ((and (= tt js2-FUNCTION)
10809 (setq body (js2-function-node-body n)))
10810 (setq beg (js2-node-abs-pos body)
10811 end (+ beg (js2-node-len body)))
10812 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10813 nil) ; don't process children of function
10815 t))))) ; keep processing other AST nodes
10817 (defun js2-mode-show-functions ()
10818 "Un-hide any folded function bodies in the buffer."
10820 (setq js2-mode-functions-hidden nil)
10822 (goto-char (point-min))
10823 (while (/= (goto-char (next-overlay-change (point)))
10825 (dolist (o (overlays-at (point)))
10826 (when (and (overlay-get o 'invisible)
10827 (not (overlay-get o 'comment)))
10828 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10830 (defun js2-mode-hide-comment (n)
10831 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10834 (beg (+ (js2-node-abs-pos n) head))
10835 (end (- (+ beg (js2-node-len n)) head 2))
10836 (o (js2-mode-flag-region beg end 'hide)))
10837 (overlay-put o 'comment t)))
10839 (defun js2-mode-toggle-hide-comments ()
10840 "Folds all block comments in the buffer.
10841 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10842 to open an individual entry."
10844 (if js2-mode-comments-hidden
10845 (js2-mode-show-comments)
10846 (js2-mode-hide-comments)))
10848 (defun js2-mode-hide-comments ()
10850 (if js2-mode-buffer-dirty-p
10851 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10852 (if (null js2-mode-ast)
10853 (message "Oops - parsing failed")
10854 (setq js2-mode-comments-hidden t)
10855 (dolist (n (js2-ast-root-comments js2-mode-ast))
10856 (let ((format (js2-comment-node-format n)))
10857 (when (js2-block-comment-p n)
10858 (js2-mode-hide-comment n))))
10859 (js2-mode-hide-//-comments)))
10861 (defun js2-mode-extend-//-comment (direction)
10862 "Find start or end of a block of similar //-comment lines.
10863 DIRECTION is -1 to look back, 1 to look forward.
10864 INDENT is the indentation level to match.
10865 Returns the end-of-line position of the furthest adjacent
10866 //-comment line with the same indentation as the current line.
10867 If there is no such matching line, returns current end of line."
10868 (let ((pos (point-at-eol))
10869 (indent (current-indentation)))
10871 (while (and (zerop (forward-line direction))
10872 (looking-at js2-mode-//-comment-re)
10873 (eq indent (length (match-string 1))))
10874 (setq pos (point-at-eol))
10877 (defun js2-mode-hide-//-comments ()
10878 "Fold adjacent 1-line comments, showing only snippet of first one."
10881 (goto-char (point-min))
10882 (while (re-search-forward js2-mode-//-comment-re nil t)
10884 end (js2-mode-extend-//-comment 1))
10885 (unless (eq beg end)
10886 (overlay-put (js2-mode-flag-region beg end 'hide)
10889 (forward-char 1)))))
10891 (defun js2-mode-toggle-//-comment ()
10892 "Fold or un-fold any multi-line //-comment at point.
10893 Caller should have determined that this line starts with a //-comment."
10894 (let* ((beg (point-at-eol))
10898 (if (js2-mode-invisible-overlay-bounds)
10899 (js2-mode-show-element)
10900 ;; else hide the comment
10901 (setq beg (js2-mode-extend-//-comment -1)
10902 end (js2-mode-extend-//-comment 1))
10903 (unless (eq beg end)
10904 (overlay-put (js2-mode-flag-region beg end 'hide)
10907 (defun js2-mode-show-comments ()
10908 "Un-hide any hidden comments, leaving other hidden elements alone."
10910 (setq js2-mode-comments-hidden nil)
10912 (goto-char (point-min))
10913 (while (/= (goto-char (next-overlay-change (point)))
10915 (dolist (o (overlays-at (point)))
10916 (when (overlay-get o 'comment)
10917 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10919 (defun js2-mode-display-warnings-and-errors ()
10920 "Turn on display of warnings and errors."
10922 (setq js2-mode-show-parse-errors t
10923 js2-mode-show-strict-warnings t)
10924 (js2-reparse 'force))
10926 (defun js2-mode-hide-warnings-and-errors ()
10927 "Turn off display of warnings and errors."
10929 (setq js2-mode-show-parse-errors nil
10930 js2-mode-show-strict-warnings nil)
10931 (js2-reparse 'force))
10933 (defun js2-mode-toggle-warnings-and-errors ()
10934 "Toggle the display of warnings and errors.
10935 Some users don't like having warnings/errors reported while they type."
10937 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10938 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10939 (if (called-interactively-p 'any)
10940 (message "warnings and errors %s"
10941 (if js2-mode-show-parse-errors
10944 (js2-reparse 'force))
10946 (defun js2-mode-customize ()
10948 (customize-group 'js2-mode))
10950 (defun js2-mode-forward-sexp (&optional arg)
10951 "Move forward across one statement or balanced expression.
10952 With ARG, do it that many times. Negative arg -N means
10953 move backward across N balanced expressions."
10955 (setq arg (or arg 1))
10956 (let (node end (start (point)))
10959 ;; could probably make this better for some cases:
10960 ;; - if in statement block (e.g. function body), go to parent
10961 ;; - infix exprs like (foo in bar) - maybe go to beginning
10962 ;; of infix expr if in the right-side expression?
10963 ((and arg (minusp arg))
10964 (dotimes (i (- arg))
10966 (forward-char -1) ; enter the node we backed up to
10967 (setq node (js2-node-at-point (point) t))
10968 (goto-char (if node
10969 (js2-node-abs-pos node)
10976 (setq node (js2-node-at-point (point) t)
10977 end (if node (+ (js2-node-abs-pos node)
10978 (js2-node-len node))))
10979 (goto-char (or end (point-max))))))))
10981 (defun js2-errors ()
10982 "Return a list of errors found."
10984 (js2-ast-root-errors js2-mode-ast)))
10986 (defun js2-warnings ()
10987 "Return a list of warnings found."
10989 (js2-ast-root-warnings js2-mode-ast)))
10991 (defun js2-have-errors-p ()
10992 "Return non-nil if any parse errors or warnings were found."
10993 (or (js2-errors) (js2-warnings)))
10995 (defun js2-errors-and-warnings ()
10996 "Return a copy of the concatenated errors and warnings lists."
10998 (append (js2-ast-root-errors js2-mode-ast)
10999 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11001 (defun js2-next-error (&optional arg reset)
11002 "Move to next parse error.
11003 Typically invoked via \\[next-error].
11004 ARG is the number of errors, forward or backward, to move.
11005 RESET means start over from the beginning."
11007 (if (not (or (js2-errors) (js2-warnings)))
11008 (message "No errors")
11010 (goto-char (point-min)))
11011 (let* ((errs (js2-errors-and-warnings))
11015 (backward (minusp count))
11016 (sorter (if backward '> '<))
11017 (stopper (if backward '< '>))
11018 (count (abs count))
11020 ;; Sort by start position.
11021 (setq errs (sort errs (lambda (e1 e2)
11022 (funcall sorter (second e1) (second e2))))
11024 ;; Find nth error with pos > start.
11025 (while (and errs continue)
11026 (when (funcall stopper (cadar errs) start)
11027 (setq err (car errs))
11028 (if (zerop (decf count))
11029 (setq continue nil)))
11030 (setq errs (cdr errs)))
11032 (goto-char (second err))
11033 ;; Wrap around to first error.
11034 (goto-char (second (car all-errs)))
11035 ;; If we were already on it, echo msg again.
11036 (if (= (point) start)
11037 (js2-echo-error (point) (point)))))))
11039 (defun js2-down-mouse-3 ()
11040 "Make right-click move the point to the click location.
11041 This makes right-click context menu operations a bit more intuitive.
11042 The point will not move if the region is active, however, to avoid
11043 destroying the region selection."
11045 (when (and js2-move-point-on-right-click
11047 (let ((e last-input-event))
11049 (goto-char (cadadr e))))))
11051 (defun js2-mode-create-imenu-index ()
11052 "Return an alist for `imenu--index-alist'."
11053 ;; This is built up in `js2-parse-record-imenu' during parsing.
11055 ;; if we have an ast but no recorder, they're requesting a rescan
11056 (unless js2-imenu-recorder
11057 (js2-reparse 'force))
11059 (js2-build-imenu-index)
11060 (setq js2-imenu-recorder nil
11061 js2-imenu-function-map nil))))
11063 (defun js2-mode-find-tag ()
11064 "Replacement for `find-tag-default'.
11065 `find-tag-default' returns a ridiculous answer inside comments."
11067 (js2-with-underscore-as-word-syntax
11069 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11070 (looking-back "[A-Za-z0-9_$]"))
11071 (setq beg (progn (forward-word -1) (point))
11072 end (progn (forward-word 1) (point)))
11073 (setq beg (progn (forward-word 1) (point))
11074 end (progn (forward-word -1) (point))))
11075 (replace-regexp-in-string
11077 (buffer-substring-no-properties beg end))))))
11079 (defun js2-mode-forward-sibling ()
11080 "Move to the end of the sibling following point in parent.
11081 Returns non-nil if successful, or nil if there was no following sibling."
11082 (let* ((node (js2-node-at-point))
11083 (parent (js2-mode-find-enclosing-fn node))
11085 (when (setq sib (js2-node-find-child-after (point) parent))
11086 (goto-char (+ (js2-node-abs-pos sib)
11087 (js2-node-len sib))))))
11089 (defun js2-mode-backward-sibling ()
11090 "Move to the beginning of the sibling node preceding point in parent.
11091 Parent is defined as the enclosing script or function."
11092 (let* ((node (js2-node-at-point))
11093 (parent (js2-mode-find-enclosing-fn node))
11095 (when (setq sib (js2-node-find-child-before (point) parent))
11096 (goto-char (js2-node-abs-pos sib)))))
11098 (defun js2-beginning-of-defun (&optional arg)
11099 "Go to line on which current function starts, and return t on success.
11100 If we're not in a function or already at the beginning of one, go
11101 to beginning of previous script-level element.
11102 With ARG N, do that N times. If N is negative, move forward."
11103 (setq arg (or arg 1))
11105 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11107 ((js2-function-node-p parent)
11108 (goto-char (js2-node-abs-pos parent)))
11110 (js2-mode-backward-sibling)))
11112 (js2-beginning-of-defun (1- arg))
11114 (when (js2-end-of-defun)
11116 (js2-beginning-of-defun 1)
11117 (js2-beginning-of-defun (1+ arg))))))
11119 (defun js2-end-of-defun ()
11120 "Go to the char after the last position of the current function
11121 or script-level element."
11122 (let* ((node (js2-node-at-point))
11123 (parent (or (and (js2-function-node-p node) node)
11124 (js2-node-parent-script-or-fn node)))
11126 (unless (js2-function-node-p parent)
11127 ;; Use current script-level node, or, if none, the next one.
11128 (setq script (or parent node)
11129 parent (js2-node-find-child-before (point) script))
11130 (when (or (null parent)
11131 (>= (point) (+ (js2-node-abs-pos parent)
11132 (js2-node-len parent))))
11133 (setq parent (js2-node-find-child-after (point) script))))
11135 (goto-char (+ (js2-node-abs-pos parent)
11136 (js2-node-len parent))))))
11138 (defun js2-mark-defun (&optional allow-extend)
11139 "Put mark at end of this function, point at beginning.
11140 The function marked is the one that contains point.
11142 Interactively, if this command is repeated,
11143 or (in Transient Mark mode) if the mark is active,
11144 it marks the next defun after the ones already marked."
11147 (when (and allow-extend
11148 (or (and (eq last-command this-command) (mark t))
11149 (and transient-mark-mode mark-active)))
11150 (let ((sib (save-excursion
11152 (if (js2-mode-forward-sibling)
11159 ;; no more siblings - try extending to enclosing node
11160 (goto-char (mark t)))))
11161 (when (not extended)
11162 (let ((node (js2-node-at-point (point) t)) ; skip comments
11163 ast fn stmt parent beg end)
11164 (when (js2-ast-root-p node)
11166 node (or (js2-node-find-child-after (point) node)
11167 (js2-node-find-child-before (point) node))))
11168 ;; only mark whole buffer if we can't find any children
11171 (if (js2-function-node-p node)
11173 (setq fn (js2-mode-find-enclosing-fn node)
11174 stmt (if (or (null fn)
11175 (js2-ast-root-p fn))
11176 (js2-mode-find-first-stmt node))
11177 parent (or stmt fn)))
11178 (setq beg (js2-node-abs-pos parent)
11179 end (+ beg (js2-node-len parent)))
11182 (exchange-point-and-mark)))))
11184 (defun js2-narrow-to-defun ()
11185 "Narrow to the function enclosing point."
11187 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11188 (fn (if (js2-script-node-p node)
11190 (js2-mode-find-enclosing-fn node)))
11191 (beg (js2-node-abs-pos fn)))
11192 (unless (js2-ast-root-p fn)
11193 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11195 (provide 'js2-mode)
11197 ;;; js2-mode.el ends here