1 ;;; js2-mode.el --- an improved JavaScript editing mode
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; This JavaScript editing mode supports:
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
46 ;; To customize how it works:
47 ;; M-x customize-group RET js2-mode RET
51 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
52 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
53 ;; `js2-mode' current as the EcmaScript language standard evolves.
55 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
56 ;; customizable. It is a surprising amount of work to support customizable
57 ;; indentation. The current compromise is that the tab key lets you cycle among
58 ;; various likely indentation points, similar to the behavior of python-mode.
60 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
61 ;; and `mumamo', although it could be made to do so with some effort.
62 ;; This means that `js2-mode' is currently only useful for editing JavaScript
63 ;; files, and not for editing JavaScript within <script> tags or templates.
71 (require 'cc-cmds) ; for `c-fill-paragraph'
74 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
75 (require 'cc-langs) ; it's here in Emacs 21...
76 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
78 ;;; Externs (variables presumed to be defined by the host system)
80 (defvar js2-ecma-262-externs
82 '(Array Boolean Date Error EvalError Function Infinity
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
90 (defvar js2-browser-externs
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
129 window alert confirm document java navigator prompt screen
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
147 DocumentRange Range RangeException
150 XPathResult XMLHttpRequest))
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
155 (defvar js2-rhino-externs
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
165 (defvar js2-gears-externs
168 ;; TODO(stevey): add these
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
175 (defun js2-mark-safe-local (name pred)
176 "Make the variable NAME buffer-local and mark it as safe file-local
177 variable with predicate PRED."
178 (make-variable-buffer-local name)
179 (put name 'safe-local-variable pred))
181 (defvar js2-emacs22 (>= emacs-major-version 22))
183 (defcustom js2-highlight-level 2
184 "Amount of syntax highlighting to perform.
185 0 or a negative value means do no highlighting.
186 1 adds basic syntax highlighting.
187 2 adds highlighting of some Ecma built-in properties.
188 3 adds highlighting of many Ecma built-in functions."
190 :type '(choice (const :tag "None" 0)
191 (const :tag "Basic" 1)
192 (const :tag "Include Properties" 2)
193 (const :tag "Include Functions" 3)))
195 (defvar js2-mode-dev-mode-p nil
196 "Non-nil if running in development mode. Normally nil.")
198 (defgroup js2-mode nil
199 "An improved JavaScript mode."
202 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
203 (numberp c-basic-offset))
206 "Number of spaces to indent nested statements.
207 Similar to `c-basic-offset'."
210 (js2-mark-safe-local 'js2-basic-offset 'integerp)
212 ;; TODO(stevey): move this code into a separate minor mode.
213 (defcustom js2-mirror-mode nil
214 "Non-nil to insert closing brackets, parens, etc. automatically."
218 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
237 (defcustom js2-consistent-level-indent-inner-bracket-p t
238 "Non-nil to make indentation level inner bracket consistent,
239 regardless of the beginning bracket position."
242 (js2-mark-safe-local 'js2-consistent-level-indent-inner-bracket-p 'booleanp)
244 (defcustom js2-pretty-multiline-decl-indentation-p t
245 "Non-nil to line up multiline declarations vertically. See the
246 function `js-multiline-decl-indentation' for details."
249 (js2-mark-safe-local 'js2-pretty-multiline-decl-indentation-p 'booleanp)
251 (defcustom js2-always-indent-assigned-expr-in-decls-p nil
252 "If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
253 always additionally indent function expression or array/object literal
254 assigned in a declaration, even when only one var is declared."
257 (js2-mark-safe-local 'js2-always-indent-assigned-expr-in-decls-p 'booleanp)
259 (defcustom js2-indent-on-enter-key nil
260 "Non-nil to have Enter/Return key indent the line.
261 This is unusual for Emacs modes but common in IDEs like Eclipse."
265 (defcustom js2-enter-indents-newline nil
266 "Non-nil to have Enter/Return key indent the newly-inserted line.
267 This is unusual for Emacs modes but common in IDEs like Eclipse."
271 (defcustom js2-rebind-eol-bol-keys t
272 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
273 If non-nil, bounce between bol/eol and first/last non-whitespace char."
277 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
278 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
279 Each value in the list is passed to `define-key'."
283 (defcustom js2-idle-timer-delay 0.2
284 "Delay in secs before re-parsing after user makes changes.
285 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
288 (make-variable-buffer-local 'js2-idle-timer-delay)
290 (defcustom js2-dynamic-idle-timer-adjust 0
291 "Positive to adjust `js2-idle-timer-delay' based on file size.
292 The idea is that for short files, parsing is faster so we can be
293 more responsive to user edits without interfering with editing.
294 The buffer length in characters (typically bytes) is divided by
295 this value and used to multiply `js2-idle-timer-delay' for the
296 buffer. For example, a 21k file and 10k adjust yields 21k/10k
297 == 2, so js2-idle-timer-delay is multiplied by 2.
298 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
299 `js2-idle-timer-delay' is not dependent on the file size."
303 (defcustom js2-mode-escape-quotes t
304 "Non-nil to disable automatic quote-escaping inside strings."
308 (defcustom js2-mode-squeeze-spaces t
309 "Non-nil to normalize whitespace when filling in comments.
310 Multiple runs of spaces are converted to a single space."
314 (defcustom js2-mode-show-parse-errors t
315 "True to highlight parse errors."
319 (defcustom js2-mode-show-strict-warnings t
320 "Non-nil to emit Ecma strict-mode warnings.
321 Some of the warnings can be individually disabled by other flags,
322 even if this flag is non-nil."
326 (defcustom js2-strict-trailing-comma-warning t
327 "Non-nil to warn about trailing commas in array literals.
328 Ecma-262 forbids them, but many browsers permit them. IE is the
329 big exception, and can produce bugs if you have trailing commas."
333 (defcustom js2-strict-missing-semi-warning t
334 "Non-nil to warn about semicolon auto-insertion after statement.
335 Technically this is legal per Ecma-262, but some style guides disallow
340 (defcustom js2-missing-semi-one-line-override nil
341 "Non-nil to permit missing semicolons in one-line functions.
342 In one-liner functions such as `function identity(x) {return x}'
343 people often omit the semicolon for a cleaner look. If you are
344 such a person, you can suppress the missing-semicolon warning
345 by setting this variable to t."
349 (defcustom js2-strict-inconsistent-return-warning t
350 "Non-nil to warn about mixing returns with value-returns.
351 It's perfectly legal to have a `return' and a `return foo' in the
352 same function, but it's often an indicator of a bug, and it also
353 interferes with type inference (in systems that support it.)"
357 (defcustom js2-strict-cond-assign-warning t
358 "Non-nil to warn about expressions like if (a = b).
359 This often should have been '==' instead of '='. If the warning
360 is enabled, you can suppress it on a per-expression basis by
361 parenthesizing the expression, e.g. if ((a = b)) ..."
365 (defcustom js2-strict-cond-assign-warning t
366 "Non-nil to warn about expressions like if (a = b).
367 This often should have been '==' instead of '='. If the warning
368 is enabled, you can suppress it on a per-expression basis by
369 parenthesizing the expression, e.g. if ((a = b)) ..."
373 (defcustom js2-strict-var-redeclaration-warning t
374 "Non-nil to warn about redeclaring variables in a script or function."
378 (defcustom js2-strict-var-hides-function-arg-warning t
379 "Non-nil to warn about a var decl hiding a function argument."
383 (defcustom js2-skip-preprocessor-directives nil
384 "Non-nil to treat lines beginning with # as comments.
385 Useful for viewing Mozilla JavaScript source code."
389 (defcustom js2-language-version 180
390 "Configures what JavaScript language version to recognize.
391 Currently versions 150, 160, 170 and 180 are supported, corresponding
392 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
393 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
394 and 1.8 adds function closures."
398 (defcustom js2-allow-keywords-as-property-names t
399 "If non-nil, you can use JavaScript keywords as object property names.
402 var foo = {int: 5, while: 6, continue: 7};
405 Ecma-262 forbids this syntax, but many browsers support it."
409 (defcustom js2-instanceof-has-side-effects nil
410 "If non-nil, treats the instanceof operator as having side effects.
411 This is useful for xulrunner apps."
415 (defcustom js2-cleanup-whitespace nil
416 "Non-nil to invoke `delete-trailing-whitespace' before saves."
420 (defcustom js2-move-point-on-right-click t
421 "Non-nil to move insertion point when you right-click.
422 This makes right-click context menu behavior a bit more intuitive,
423 since menu operations generally apply to the point. The exception
424 is if there is a region selection, in which case the point does -not-
425 move, so cut/copy/paste etc. can work properly.
427 Note that IntelliJ moves the point, and Eclipse leaves it alone,
428 so this behavior is customizable."
432 (defcustom js2-allow-rhino-new-expr-initializer t
433 "Non-nil to support a Rhino's experimental syntactic construct.
435 Rhino supports the ability to follow a `new' expression with an object
436 literal, which is used to set additional properties on the new object
437 after calling its constructor. Syntax:
439 new <expr> [ ( arglist ) ] [initializer]
441 Hence, this expression:
443 new Object {a: 1, b: 2}
445 results in an Object with properties a=1 and b=2. This syntax is
446 apparently not configurable in Rhino - it's currently always enabled,
447 as of Rhino version 1.7R2."
451 (defcustom js2-allow-member-expr-as-function-name nil
452 "Non-nil to support experimental Rhino syntax for function names.
454 Rhino supports an experimental syntax configured via the Rhino Context
455 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
457 function <member-expr> ( [ arg-list ] ) { <body> }
459 Where member-expr is a non-parenthesized 'member expression', which
460 is anything at the grammar level of a new-expression or lower, meaning
461 any expression that does not involve infix or unary operators.
463 When <member-expr> is not a simple identifier, then it is syntactic
464 sugar for assigning the anonymous function to the <member-expr>. Hence,
467 function a.b().c[2] (x, y) { ... }
471 a.b().c[2] = function(x, y) {...}
473 which doesn't seem particularly useful, but Rhino permits it."
477 (defvar js2-mode-version 20101228
478 "Release number for `js2-mode'.")
482 (defmacro js2-deflocal (name value &optional comment)
483 "Define a buffer-local variable NAME with VALUE and COMMENT."
485 (defvar ,name ,value ,comment)
486 (make-variable-buffer-local ',name)))
488 ;; We record the start and end position of each token.
489 (js2-deflocal js2-token-beg 1)
490 (js2-deflocal js2-token-end -1)
492 (defvar js2-EOF_CHAR -1
493 "Represents end of stream. Distinct from js2-EOF token type.")
495 ;; I originally used symbols to represent tokens, but Rhino uses
496 ;; ints and then sets various flag bits in them, so ints it is.
497 ;; The upshot is that we need a `js2-' prefix in front of each name.
498 (defvar js2-ERROR -1)
501 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
502 (defvar js2-LEAVEWITH 3)
503 (defvar js2-RETURN 4)
507 (defvar js2-SETNAME 8)
509 (defvar js2-BITXOR 10)
510 (defvar js2-BITAND 11)
520 (defvar js2-ADD 21) ; infix plus
521 (defvar js2-SUB 22) ; infix minus
526 (defvar js2-BITNOT 27)
527 (defvar js2-POS 28) ; unary plus
528 (defvar js2-NEG 29) ; unary minus
530 (defvar js2-DELPROP 31)
531 (defvar js2-TYPEOF 32)
532 (defvar js2-GETPROP 33)
533 (defvar js2-GETPROPNOWARN 34)
534 (defvar js2-SETPROP 35)
535 (defvar js2-GETELEM 36)
536 (defvar js2-SETELEM 37)
538 (defvar js2-NAME 39) ; an identifier
539 (defvar js2-NUMBER 40)
540 (defvar js2-STRING 41)
543 (defvar js2-FALSE 44)
545 (defvar js2-SHEQ 46) ; shallow equality (===)
546 (defvar js2-SHNE 47) ; shallow inequality (!==)
547 (defvar js2-REGEXP 48)
548 (defvar js2-BINDNAME 49)
549 (defvar js2-THROW 50)
550 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
552 (defvar js2-INSTANCEOF 53)
553 (defvar js2-LOCAL_LOAD 54)
554 (defvar js2-GETVAR 55)
555 (defvar js2-SETVAR 56)
556 (defvar js2-CATCH_SCOPE 57)
557 (defvar js2-ENUM_INIT_KEYS 58)
558 (defvar js2-ENUM_INIT_VALUES 59)
559 (defvar js2-ENUM_INIT_ARRAY 60)
560 (defvar js2-ENUM_NEXT 61)
561 (defvar js2-ENUM_ID 62)
562 (defvar js2-THISFN 63)
563 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
564 (defvar js2-ARRAYLIT 65) ; array literal
565 (defvar js2-OBJECTLIT 66) ; object literal
566 (defvar js2-GET_REF 67) ; *reference
567 (defvar js2-SET_REF 68) ; *reference = something
568 (defvar js2-DEL_REF 69) ; delete reference
569 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
570 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
571 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
574 (defvar js2-DEFAULTNAMESPACE 73)
575 (defvar js2-ESCXMLATTR 74)
576 (defvar js2-ESCXMLTEXT 75)
577 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
578 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
579 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
580 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
582 (defvar js2-first-bytecode js2-ENTERWITH)
583 (defvar js2-last-bytecode js2-REF_NS_NAME)
586 (defvar js2-SEMI 81) ; semicolon
587 (defvar js2-LB 82) ; left and right brackets
589 (defvar js2-LC 84) ; left and right curly-braces
591 (defvar js2-LP 86) ; left and right parens
593 (defvar js2-COMMA 88) ; comma operator
595 (defvar js2-ASSIGN 89) ; simple assignment (=)
596 (defvar js2-ASSIGN_BITOR 90) ; |=
597 (defvar js2-ASSIGN_BITXOR 91) ; ^=
598 (defvar js2-ASSIGN_BITAND 92) ; &=
599 (defvar js2-ASSIGN_LSH 93) ; <<=
600 (defvar js2-ASSIGN_RSH 94) ; >>=
601 (defvar js2-ASSIGN_URSH 95) ; >>>=
602 (defvar js2-ASSIGN_ADD 96) ; +=
603 (defvar js2-ASSIGN_SUB 97) ; -=
604 (defvar js2-ASSIGN_MUL 98) ; *=
605 (defvar js2-ASSIGN_DIV 99) ; /=
606 (defvar js2-ASSIGN_MOD 100) ; %=
608 (defvar js2-first-assign js2-ASSIGN)
609 (defvar js2-last-assign js2-ASSIGN_MOD)
611 (defvar js2-HOOK 101) ; conditional (?:)
612 (defvar js2-COLON 102)
613 (defvar js2-OR 103) ; logical or (||)
614 (defvar js2-AND 104) ; logical and (&&)
615 (defvar js2-INC 105) ; increment/decrement (++ --)
617 (defvar js2-DOT 107) ; member operator (.)
618 (defvar js2-FUNCTION 108) ; function keyword
619 (defvar js2-EXPORT 109) ; export keyword
620 (defvar js2-IMPORT 110) ; import keyword
621 (defvar js2-IF 111) ; if keyword
622 (defvar js2-ELSE 112) ; else keyword
623 (defvar js2-SWITCH 113) ; switch keyword
624 (defvar js2-CASE 114) ; case keyword
625 (defvar js2-DEFAULT 115) ; default keyword
626 (defvar js2-WHILE 116) ; while keyword
627 (defvar js2-DO 117) ; do keyword
628 (defvar js2-FOR 118) ; for keyword
629 (defvar js2-BREAK 119) ; break keyword
630 (defvar js2-CONTINUE 120) ; continue keyword
631 (defvar js2-VAR 121) ; var keyword
632 (defvar js2-WITH 122) ; with keyword
633 (defvar js2-CATCH 123) ; catch keyword
634 (defvar js2-FINALLY 124) ; finally keyword
635 (defvar js2-VOID 125) ; void keyword
636 (defvar js2-RESERVED 126) ; reserved keywords
638 (defvar js2-EMPTY 127)
640 ;; Types used for the parse tree - never returned by scanner.
642 (defvar js2-BLOCK 128) ; statement block
643 (defvar js2-LABEL 129) ; label
644 (defvar js2-TARGET 130)
645 (defvar js2-LOOP 131)
646 (defvar js2-EXPR_VOID 132) ; expression statement in functions
647 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
649 (defvar js2-SCRIPT 135) ; top-level node for entire script
650 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
651 (defvar js2-USE_STACK 137)
652 (defvar js2-SETPROP_OP 138) ; x.y op= something
653 (defvar js2-SETELEM_OP 139) ; x[y] op= something
654 (defvar js2-LOCAL_BLOCK 140)
655 (defvar js2-SET_REF_OP 141) ; *reference op= something
658 (defvar js2-DOTDOT 142) ; member operator (..)
659 (defvar js2-COLONCOLON 143) ; namespace::name
660 (defvar js2-XML 144) ; XML type
661 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
662 (defvar js2-XMLATTR 146) ; @
663 (defvar js2-XMLEND 147)
665 ;; Optimizer-only tokens
666 (defvar js2-TO_OBJECT 148)
667 (defvar js2-TO_DOUBLE 149)
669 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
670 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
671 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
672 (defvar js2-CONST 153)
673 (defvar js2-SETCONST 154)
674 (defvar js2-SETCONSTVAR 155)
675 (defvar js2-ARRAYCOMP 156)
676 (defvar js2-LETEXPR 157)
677 (defvar js2-WITHEXPR 158)
678 (defvar js2-DEBUGGER 159)
680 (defvar js2-COMMENT 160)
681 (defvar js2-ENUM 161) ; for "enum" reserved word
683 (defconst js2-num-tokens (1+ js2-ENUM))
685 (defconst js2-debug-print-trees nil)
687 ;; Rhino accepts any string or stream as input. Emacs character
688 ;; processing works best in buffers, so we'll assume the input is a
689 ;; buffer. JavaScript strings can be copied into temp buffers before
692 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
693 ;; They're the Emacs equivalent of instance variables, more or less.
695 (js2-deflocal js2-ts-dirty-line nil
696 "Token stream buffer-local variable.
697 Indicates stuff other than whitespace since start of line.")
699 (js2-deflocal js2-ts-regexp-flags nil
700 "Token stream buffer-local variable.")
702 (js2-deflocal js2-ts-string ""
703 "Token stream buffer-local variable.
704 Last string scanned.")
706 (js2-deflocal js2-ts-number nil
707 "Token stream buffer-local variable.
708 Last literal number scanned.")
710 (js2-deflocal js2-ts-hit-eof nil
711 "Token stream buffer-local variable.")
713 (js2-deflocal js2-ts-line-start 0
714 "Token stream buffer-local variable.")
716 (js2-deflocal js2-ts-lineno 1
717 "Token stream buffer-local variable.")
719 (js2-deflocal js2-ts-line-end-char -1
720 "Token stream buffer-local variable.")
722 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
723 "Token stream buffer-local variable.
724 Current scan position.")
726 (js2-deflocal js2-ts-is-xml-attribute nil
727 "Token stream buffer-local variable.")
729 (js2-deflocal js2-ts-xml-is-tag-content nil
730 "Token stream buffer-local variable.")
732 (js2-deflocal js2-ts-xml-open-tags-count 0
733 "Token stream buffer-local variable.")
735 (js2-deflocal js2-ts-string-buffer nil
736 "Token stream buffer-local variable.
737 List of chars built up while scanning various tokens.")
739 (js2-deflocal js2-ts-comment-type nil
740 "Token stream buffer-local variable.")
744 (js2-deflocal js2-parsed-errors nil
745 "List of errors produced during scanning/parsing.")
747 (js2-deflocal js2-parsed-warnings nil
748 "List of warnings produced during scanning/parsing.")
750 (js2-deflocal js2-recover-from-parse-errors t
751 "Non-nil to continue parsing after a syntax error.
753 In recovery mode, the AST will be built in full, and any error
754 nodes will be flagged with appropriate error information. If
755 this flag is nil, a syntax error will result in an error being
758 The variable is automatically buffer-local, because different
759 modes that use the parser will need different settings.")
761 (js2-deflocal js2-parse-hook nil
762 "List of callbacks for receiving parsing progress.")
764 (defvar js2-parse-finished-hook nil
765 "List of callbacks to notify when parsing finishes.
766 Not called if parsing was interrupted.")
768 (js2-deflocal js2-is-eval-code nil
769 "True if we're evaluating code in a string.
770 If non-nil, the tokenizer will record the token text, and the AST nodes
771 will record their source text. Off by default for IDE modes, since the
772 text is available in the buffer.")
774 (defvar js2-parse-ide-mode t
775 "Non-nil if the parser is being used for `js2-mode'.
776 If non-nil, the parser will set text properties for fontification
777 and the syntax table. The value should be nil when using the
778 parser as a frontend to an interpreter or byte compiler.")
780 ;;; Parser instance variables (buffer-local vars for js2-parse)
782 (defconst js2-clear-ti-mask #xFFFF
783 "Mask to clear token information bits.")
785 (defconst js2-ti-after-eol (lsh 1 16)
786 "Flag: first token of the source line.")
788 (defconst js2-ti-check-label (lsh 1 17)
789 "Flag: indicates to check for label.")
791 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
793 (js2-deflocal js2-compiler-generate-debug-info t)
794 (js2-deflocal js2-compiler-use-dynamic-scope nil)
795 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
796 (js2-deflocal js2-compiler-xml-available t)
797 (js2-deflocal js2-compiler-optimization-level 0)
798 (js2-deflocal js2-compiler-generating-source t)
799 (js2-deflocal js2-compiler-strict-mode nil)
800 (js2-deflocal js2-compiler-report-warning-as-error nil)
801 (js2-deflocal js2-compiler-generate-observer-count nil)
802 (js2-deflocal js2-compiler-activation-names nil)
806 ;; There's a compileFunction method in Context.java - may need it.
807 (js2-deflocal js2-called-by-compile-function nil
808 "True if `js2-parse' was called by `js2-compile-function'.
809 Will only be used when we finish implementing the interpreter.")
811 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
813 (js2-deflocal js2-current-flagged-token js2-EOF)
814 (js2-deflocal js2-current-token js2-EOF)
816 ;; SKIP: node factory - we're going to just call functions directly,
817 ;; and eventually go to a unified AST format.
819 (js2-deflocal js2-nesting-of-function 0)
821 (js2-deflocal js2-recorded-identifiers nil
822 "Tracks identifiers found during parsing.")
824 (defmacro js2-in-lhs (body)
825 `(let ((js2-is-in-lhs t))
828 (defmacro js2-in-rhs (body)
829 `(let ((js2-is-in-lhs nil))
832 (js2-deflocal js2-is-in-lhs nil
833 "True while parsing lhs statement")
835 (defcustom js2-global-externs nil
836 "A list of any extern names you'd like to consider always declared.
837 This list is global and is used by all js2-mode files.
838 You can create buffer-local externs list using `js2-additional-externs'.
840 There is also a buffer-local variable `js2-default-externs',
841 which is initialized by default to include the Ecma-262 externs
842 and the standard browser externs. The three lists are all
843 checked during highlighting."
847 (js2-deflocal js2-default-externs nil
848 "Default external declarations.
850 These are currently only used for highlighting undeclared variables,
851 which only worries about top-level (unqualified) references.
852 As js2-mode's processing improves, we will flesh out this list.
854 The initial value is set to `js2-ecma-262-externs', unless you
855 have set `js2-include-browser-externs', in which case the browser
856 externs are also included.
858 See `js2-additional-externs' for more information.")
860 (defcustom js2-include-browser-externs t
861 "Non-nil to include browser externs in the master externs list.
862 If you work on JavaScript files that are not intended for browsers,
863 such as Mozilla Rhino server-side JavaScript, set this to nil.
864 You can always include them on a per-file basis by calling
865 `js2-add-browser-externs' from a function on `js2-mode-hook'.
867 See `js2-additional-externs' for more information about externs."
871 (defcustom js2-include-rhino-externs t
872 "Non-nil to include Mozilla Rhino externs in the master externs list.
873 See `js2-additional-externs' for more information about externs."
877 (defcustom js2-include-gears-externs t
878 "Non-nil to include Google Gears externs in the master externs list.
879 See `js2-additional-externs' for more information about externs."
883 (js2-deflocal js2-additional-externs nil
884 "A buffer-local list of additional external declarations.
885 It is used to decide whether variables are considered undeclared
886 for purposes of highlighting.
888 Each entry is a lisp string. The string should be the fully qualified
889 name of an external entity. All externs should be added to this list,
890 so that as js2-mode's processing improves it can take advantage of them.
892 You may want to declare your externs in three ways.
893 First, you can add externs that are valid for all your JavaScript files.
894 You should probably do this by adding them to `js2-global-externs', which
895 is a global list used for all js2-mode files.
897 Next, you can add a function to `js2-mode-hook' that adds additional
898 externs appropriate for the specific file, perhaps based on its path.
899 These should go in `js2-additional-externs', which is buffer-local.
901 Finally, you can add a function to `js2-post-parse-callbacks',
902 which is called after parsing completes, and `root' is bound to
903 the root of the parse tree. At this stage you can set up an AST
904 node visitor using `js2-visit-ast' and examine the parse tree
905 for specific import patterns that may imply the existence of
906 other externs, possibly tied to your build system. These should also
907 be added to `js2-additional-externs'.
909 Your post-parse callback may of course also use the simpler and
910 faster (but perhaps less robust) approach of simply scanning the
911 buffer text for your imports, using regular expressions.")
914 ;; SKIP: encoded-source
916 ;;; The following variables are per-function and should be saved/restored
917 ;;; during function parsing...
919 (js2-deflocal js2-current-script-or-fn nil)
920 (js2-deflocal js2-current-scope nil)
921 (js2-deflocal js2-nesting-of-with 0)
922 (js2-deflocal js2-label-set nil
923 "An alist mapping label names to nodes.")
925 (js2-deflocal js2-loop-set nil)
926 (js2-deflocal js2-loop-and-switch-set nil)
927 (js2-deflocal js2-has-return-value nil)
928 (js2-deflocal js2-end-flags 0)
930 ;;; ...end of per function variables
932 ;; Without 2-token lookahead, labels are a problem.
933 ;; These vars store the token info of the last matched name,
934 ;; iff it wasn't the last matched token. Only valid in some contexts.
935 (defvar js2-prev-name-token-start nil)
936 (defvar js2-prev-name-token-string nil)
938 (defsubst js2-save-name-token-data (pos name)
939 (setq js2-prev-name-token-start pos
940 js2-prev-name-token-string name))
942 ;; These flags enumerate the possible ways a statement/function can
943 ;; terminate. These flags are used by endCheck() and by the Parser to
944 ;; detect inconsistent return usage.
946 ;; END_UNREACHED is reserved for code paths that are assumed to always be
947 ;; able to execute (example: throw, continue)
949 ;; END_DROPS_OFF indicates if the statement can transfer control to the
950 ;; next one. Statement such as return dont. A compound statement may have
951 ;; some branch that drops off control to the next statement.
953 ;; END_RETURNS indicates that the statement can return (without arguments)
954 ;; END_RETURNS_VALUE indicates that the statement can return a value.
956 ;; A compound statement such as
960 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
962 (defconst js2-end-unreached #x0)
963 (defconst js2-end-drops-off #x1)
964 (defconst js2-end-returns #x2)
965 (defconst js2-end-returns-value #x4)
966 (defconst js2-end-yields #x8)
968 ;; Rhino awkwardly passes a statementLabel parameter to the
969 ;; statementHelper() function, the main statement parser, which
970 ;; is then used by quite a few of the sub-parsers. We just make
971 ;; it a buffer-local variable and make sure it's cleaned up properly.
972 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
974 ;; Similarly, Rhino passes an inForInit boolean through about half
975 ;; the expression parsers. We use a dynamically-scoped variable,
976 ;; which makes it easier to funcall the parsers individually without
977 ;; worrying about whether they take the parameter or not.
978 (js2-deflocal js2-in-for-init nil)
979 (js2-deflocal js2-temp-name-counter 0)
980 (js2-deflocal js2-parse-stmt-count 0)
982 (defsubst js2-get-next-temp-name ()
983 (format "$%d" (incf js2-temp-name-counter)))
985 (defvar js2-parse-interruptable-p t
986 "Set this to nil to force parse to continue until finished.
987 This will mostly be useful for interpreters.")
989 (defvar js2-statements-per-pause 50
990 "Pause after this many statements to check for user input.
991 If user input is pending, stop the parse and discard the tree.
992 This makes for a smoother user experience for large files.
993 You may have to wait a second or two before the highlighting
994 and error-reporting appear, but you can always type ahead if
995 you wish. This appears to be more or less how Eclipse, IntelliJ
996 and other editors work.")
998 (js2-deflocal js2-record-comments t
999 "Instructs the scanner to record comments in `js2-scanned-comments'.")
1001 (js2-deflocal js2-scanned-comments nil
1002 "List of all comments from the current parse.")
1004 (defcustom js2-mode-indent-inhibit-undo nil
1005 "Non-nil to disable collection of Undo information when indenting lines.
1006 Some users have requested this behavior. It's nil by default because
1007 other Emacs modes don't work this way."
1011 (defcustom js2-mode-indent-ignore-first-tab nil
1012 "If non-nil, ignore first TAB keypress if we look indented properly.
1013 It's fairly common for users to navigate to an already-indented line
1014 and press TAB for reassurance that it's been indented. For this class
1015 of users, we want the first TAB press on a line to be ignored if the
1016 line is already indented to one of the precomputed alternatives.
1018 This behavior is only partly implemented. If you TAB-indent a line,
1019 navigate to another line, and then navigate back, it fails to clear
1020 the last-indented variable, so it thinks you've already hit TAB once,
1021 and performs the indent. A full solution would involve getting on the
1022 point-motion hooks for the entire buffer. If we come across another
1023 use cases that requires watching point motion, I'll consider doing it.
1025 If you set this variable to nil, then the TAB key will always change
1026 the indentation of the current line, if more than one alternative
1027 indentation spot exists."
1031 (defvar js2-indent-hook nil
1032 "A hook for user-defined indentation rules.
1034 Functions on this hook should expect two arguments: (LIST INDEX)
1035 The LIST argument is the list of computed indentation points for
1036 the current line. INDEX is the list index of the indentation point
1037 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1038 indent function is not going to change the current line indentation.
1040 If a hook function on this list returns a non-nil value, then
1041 `js2-bounce-indent' assumes the hook function has performed its own
1042 indentation, and will do nothing. If all hook functions on the list
1043 return nil, then `js2-bounce-indent' will use its computed indentation
1044 and reindent the line.
1046 When hook functions on this hook list are called, the variable
1047 `js2-mode-ast' may or may not be set, depending on whether the
1048 parse tree is available. If the variable is nil, you can pass a
1049 callback to `js2-mode-wait-for-parse', and your callback will be
1050 called after the new parse tree is built. This can take some time
1053 (defface js2-warning-face
1054 `((((class color) (background light))
1055 (:underline "orange"))
1056 (((class color) (background dark))
1057 (:underline "orange"))
1059 "Face for JavaScript warnings."
1062 (defface js2-error-face
1063 `((((class color) (background light))
1064 (:foreground "red"))
1065 (((class color) (background dark))
1066 (:foreground "red"))
1067 (t (:foreground "red")))
1068 "Face for JavaScript errors."
1071 (defface js2-jsdoc-tag-face
1072 '((t :foreground "SlateGray"))
1073 "Face used to highlight @whatever tags in jsdoc comments."
1076 (defface js2-jsdoc-type-face
1077 '((t :foreground "SteelBlue"))
1078 "Face used to highlight {FooBar} types in jsdoc comments."
1081 (defface js2-jsdoc-value-face
1082 '((t :foreground "PeachPuff3"))
1083 "Face used to highlight tag values in jsdoc comments."
1086 (defface js2-function-param-face
1087 '((t :foreground "SeaGreen"))
1088 "Face used to highlight function parameters in javascript."
1091 (defface js2-instance-member-face
1092 '((t :foreground "DarkOrchid"))
1093 "Face used to highlight instance variables in javascript.
1094 Not currently used."
1097 (defface js2-private-member-face
1098 '((t :foreground "PeachPuff3"))
1099 "Face used to highlight calls to private methods in javascript.
1100 Not currently used."
1103 (defface js2-private-function-call-face
1104 '((t :foreground "goldenrod"))
1105 "Face used to highlight calls to private functions in javascript.
1106 Not currently used."
1109 (defface js2-jsdoc-html-tag-name-face
1111 '((((class color) (min-colors 88) (background light))
1112 (:foreground "rosybrown"))
1113 (((class color) (min-colors 8) (background dark))
1114 (:foreground "yellow"))
1115 (((class color) (min-colors 8) (background light))
1116 (:foreground "magenta")))
1117 '((((type tty pc) (class color) (background light))
1118 (:foreground "magenta"))
1119 (((type tty pc) (class color) (background dark))
1120 (:foreground "yellow"))
1121 (t (:foreground "RosyBrown"))))
1122 "Face used to highlight jsdoc html tag names"
1125 (defface js2-jsdoc-html-tag-delimiter-face
1127 '((((class color) (min-colors 88) (background light))
1128 (:foreground "dark khaki"))
1129 (((class color) (min-colors 8) (background dark))
1130 (:foreground "green"))
1131 (((class color) (min-colors 8) (background light))
1132 (:foreground "green")))
1133 '((((type tty pc) (class color) (background light))
1134 (:foreground "green"))
1135 (((type tty pc) (class color) (background dark))
1136 (:foreground "green"))
1137 (t (:foreground "dark khaki"))))
1138 "Face used to highlight brackets in jsdoc html tags."
1141 (defface js2-magic-paren-face
1143 "Face used to color parens that will be auto-overwritten."
1146 (defcustom js2-post-parse-callbacks nil
1147 "A list of callback functions invoked after parsing finishes.
1148 Currently, the main use for this function is to add synthetic
1149 declarations to `js2-recorded-identifiers', which see."
1153 (defface js2-external-variable-face
1154 '((t :foreground "orange"))
1155 "Face used to highlight undeclared variable identifiers.
1156 An undeclared variable is any variable not declared with var or let
1157 in the current scope or any lexically enclosing scope. If you use
1158 such a variable, then you are either expecting it to originate from
1159 another file, or you've got a potential bug."
1162 (defcustom js2-highlight-external-variables t
1163 "Non-nil to highlight undeclared variable identifiers."
1167 (defcustom js2-auto-insert-catch-block t
1168 "Non-nil to insert matching catch block on open-curly after `try'."
1172 (defvar js2-mode-map
1173 (let ((map (make-sparse-keymap))
1175 (define-key map [mouse-1] #'js2-mode-show-node)
1176 (define-key map (kbd "C-m") #'js2-enter-key)
1177 (when js2-rebind-eol-bol-keys
1178 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1179 (define-key map (kbd "C-e") #'js2-end-of-line))
1180 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1181 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1182 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1183 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1184 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1185 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1186 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1187 (define-key map (kbd "C-c C-`") #'js2-next-error)
1188 ;; also define user's preference for next-error, if available
1189 (if (setq keys (where-is-internal #'next-error))
1190 (define-key map (car keys) #'js2-next-error))
1191 (define-key map (or (car (where-is-internal #'mark-defun))
1194 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1196 #'js2-narrow-to-defun)
1197 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1198 (when js2-auto-indent-p
1200 (define-key map key #'js2-insert-and-indent))
1202 (when js2-bounce-indent-p
1203 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1205 (define-key map [menu-bar javascript]
1206 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1208 (define-key map [menu-bar javascript customize-js2-mode]
1209 '(menu-item "Customize js2-mode" js2-mode-customize
1210 :help "Customize the behavior of this mode"))
1212 (define-key map [menu-bar javascript js2-force-refresh]
1213 '(menu-item "Force buffer refresh" js2-mode-reset
1214 :help "Re-parse the buffer from scratch"))
1216 (define-key map [menu-bar javascript separator-2]
1219 (define-key map [menu-bar javascript next-error]
1220 '(menu-item "Next warning or error" js2-next-error
1221 :enabled (and js2-mode-ast
1222 (or (js2-ast-root-errors js2-mode-ast)
1223 (js2-ast-root-warnings js2-mode-ast)))
1224 :help "Move to next warning or error"))
1226 (define-key map [menu-bar javascript display-errors]
1227 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1228 :visible (not js2-mode-show-parse-errors)
1229 :help "Turn on display of warnings and errors"))
1231 (define-key map [menu-bar javascript hide-errors]
1232 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1233 :visible js2-mode-show-parse-errors
1234 :help "Turn off display of warnings and errors"))
1236 (define-key map [menu-bar javascript separator-1]
1239 (define-key map [menu-bar javascript js2-toggle-function]
1240 '(menu-item "Show/collapse element" js2-mode-toggle-element
1241 :help "Hide or show function body or comment"))
1243 (define-key map [menu-bar javascript show-comments]
1244 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1245 :visible js2-mode-comments-hidden
1246 :help "Expand all hidden block comments"))
1248 (define-key map [menu-bar javascript hide-comments]
1249 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1250 :visible (not js2-mode-comments-hidden)
1251 :help "Show block comments as /*...*/"))
1253 (define-key map [menu-bar javascript show-all-functions]
1254 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1255 :visible js2-mode-functions-hidden
1256 :help "Expand all hidden function bodies"))
1258 (define-key map [menu-bar javascript hide-all-functions]
1259 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1260 :visible (not js2-mode-functions-hidden)
1261 :help "Show {...} for all top-level function bodies"))
1264 "Keymap used in `js2-mode' buffers.")
1266 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1268 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1269 "Matches a //-comment line. Must be first non-whitespace on line.
1270 First match-group is the leading whitespace.")
1272 (defvar js2-mode-hook nil)
1274 (js2-deflocal js2-mode-ast nil "Private variable.")
1275 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1276 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1277 (js2-deflocal js2-mode-parsing nil "Private variable.")
1278 (js2-deflocal js2-mode-node-overlay nil)
1280 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1281 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1283 (js2-deflocal js2-mode-fontifications nil "Private variable")
1284 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1285 (js2-deflocal js2-imenu-recorder nil "Private variable")
1286 (js2-deflocal js2-imenu-function-map nil "Private variable")
1288 (defvar js2-paragraph-start
1289 "\\(@[a-zA-Z]+\\>\\|$\\)")
1291 ;; Note that we also set a 'c-in-sws text property in html comments,
1292 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1293 (defvar js2-syntactic-ws-start
1294 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1296 (defvar js2-syntactic-ws-end
1297 "\\s \\|[\n\r/]\\|\\s!")
1299 (defvar js2-syntactic-eol
1300 (concat "\\s *\\(/\\*[^*\n\r]*"
1301 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1303 "\\(//\\|/\\*[^*\n\r]*"
1304 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1306 "Copied from `java-mode'. Needed for some cc-engine functions.")
1308 (defvar js2-comment-prefix-regexp
1311 (defvar js2-comment-start-skip
1312 "\\(//+\\|/\\*+\\)\\s *")
1314 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1315 "Non-nil to emit status messages during parsing.")
1317 (defvar js2-mode-functions-hidden nil "private variable")
1318 (defvar js2-mode-comments-hidden nil "private variable")
1320 (defvar js2-mode-syntax-table
1321 (let ((table (make-syntax-table)))
1322 (c-populate-syntax-table table)
1324 "Syntax table used in js2-mode buffers.")
1326 (defvar js2-mode-abbrev-table nil
1327 "Abbrev table in use in `js2-mode' buffers.")
1328 (define-abbrev-table 'js2-mode-abbrev-table ())
1330 (defvar js2-mode-pending-parse-callbacks nil
1331 "List of functions waiting to be notified that parse is finished.")
1333 (defvar js2-mode-last-indented-line -1)
1335 ;;; Localizable error and warning messages
1337 ;; Messages are copied from Rhino's Messages.properties.
1338 ;; Many of the Java-specific messages have been elided.
1339 ;; Add any js2-specific ones at the end, so we can keep
1340 ;; this file synced with changes to Rhino's.
1342 (defvar js2-message-table
1343 (make-hash-table :test 'equal :size 250)
1344 "Contains localized messages for js2-mode.")
1346 ;; TODO(stevey): construct this table at compile-time.
1347 (defmacro js2-msg (key &rest strings)
1348 `(puthash ,key (funcall #'concat ,@strings)
1351 (defun js2-get-msg (msg-key)
1352 "Look up a localized message.
1353 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1354 the correct number of ARGS must be provided."
1355 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1356 (args (if (listp msg-key) (cdr msg-key)))
1357 (msg (gethash key js2-message-table)))
1359 (apply #'format msg args)
1360 key))) ; default to showing the key
1362 (js2-msg "msg.dup.parms"
1363 "Duplicate parameter name '%s'.")
1365 (js2-msg "msg.too.big.jump"
1366 "Program too complex: jump offset too big.")
1368 (js2-msg "msg.too.big.index"
1369 "Program too complex: internal index exceeds 64K limit.")
1371 (js2-msg "msg.while.compiling.fn"
1372 "Encountered code generation error while compiling function '%s': %s")
1374 (js2-msg "msg.while.compiling.script"
1375 "Encountered code generation error while compiling script: %s")
1378 (js2-msg "msg.ctor.not.found"
1379 "Constructor for '%s' not found.")
1381 (js2-msg "msg.not.ctor"
1382 "'%s' is not a constructor.")
1385 (js2-msg "msg.varargs.ctor"
1386 "Method or constructor '%s' must be static "
1387 "with the signature (Context cx, Object[] args, "
1388 "Function ctorObj, boolean inNewExpr) "
1389 "to define a variable arguments constructor.")
1391 (js2-msg "msg.varargs.fun"
1392 "Method '%s' must be static with the signature "
1393 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1394 "to define a variable arguments function.")
1396 (js2-msg "msg.incompat.call"
1397 "Method '%s' called on incompatible object.")
1399 (js2-msg "msg.bad.parms"
1400 "Unsupported parameter type '%s' in method '%s'.")
1402 (js2-msg "msg.bad.method.return"
1403 "Unsupported return type '%s' in method '%s'.")
1405 (js2-msg "msg.bad.ctor.return"
1406 "Construction of objects of type '%s' is not supported.")
1408 (js2-msg "msg.no.overload"
1409 "Method '%s' occurs multiple times in class '%s'.")
1411 (js2-msg "msg.method.not.found"
1412 "Method '%s' not found in '%s'.")
1416 (js2-msg "msg.bad.for.in.lhs"
1417 "Invalid left-hand side of for..in loop.")
1419 (js2-msg "msg.mult.index"
1420 "Only one variable allowed in for..in loop.")
1422 (js2-msg "msg.bad.for.in.destruct"
1423 "Left hand side of for..in loop must be an array of "
1424 "length 2 to accept key/value pair.")
1426 (js2-msg "msg.cant.convert"
1427 "Can't convert to type '%s'.")
1429 (js2-msg "msg.bad.assign.left"
1430 "Invalid assignment left-hand side.")
1432 (js2-msg "msg.bad.decr"
1433 "Invalid decerement operand.")
1435 (js2-msg "msg.bad.incr"
1436 "Invalid increment operand.")
1438 (js2-msg "msg.bad.yield"
1439 "yield must be in a function.")
1441 (js2-msg "msg.yield.parenthesized"
1442 "yield expression must be parenthesized.")
1445 (js2-msg "msg.cant.call.indirect"
1446 "Function '%s' must be called directly, and not by way of a "
1447 "function of another name.")
1449 (js2-msg "msg.eval.nonstring"
1450 "Calling eval() with anything other than a primitive "
1451 "string value will simply return the value. "
1452 "Is this what you intended?")
1454 (js2-msg "msg.eval.nonstring.strict"
1455 "Calling eval() with anything other than a primitive "
1456 "string value is not allowed in strict mode.")
1458 (js2-msg "msg.bad.destruct.op"
1459 "Invalid destructuring assignment operator")
1462 (js2-msg "msg.only.from.new"
1463 "'%s' may only be invoked from a `new' expression.")
1465 (js2-msg "msg.deprec.ctor"
1466 "The '%s' constructor is deprecated.")
1469 (js2-msg "msg.no.function.ref.found"
1470 "no source found to decompile function reference %s")
1472 (js2-msg "msg.arg.isnt.array"
1473 "second argument to Function.prototype.apply must be an array")
1476 (js2-msg "msg.bad.esc.mask"
1477 "invalid string escape mask")
1480 (js2-msg "msg.bad.quant"
1481 "Invalid quantifier %s")
1483 (js2-msg "msg.overlarge.backref"
1484 "Overly large back reference %s")
1486 (js2-msg "msg.overlarge.min"
1487 "Overly large minimum %s")
1489 (js2-msg "msg.overlarge.max"
1490 "Overly large maximum %s")
1492 (js2-msg "msg.zero.quant"
1493 "Zero quantifier %s")
1495 (js2-msg "msg.max.lt.min"
1496 "Maximum %s less than minimum")
1498 (js2-msg "msg.unterm.quant"
1499 "Unterminated quantifier %s")
1501 (js2-msg "msg.unterm.paren"
1502 "Unterminated parenthetical %s")
1504 (js2-msg "msg.unterm.class"
1505 "Unterminated character class %s")
1507 (js2-msg "msg.bad.range"
1508 "Invalid range in character class.")
1510 (js2-msg "msg.trail.backslash"
1511 "Trailing \\ in regular expression.")
1513 (js2-msg "msg.re.unmatched.right.paren"
1514 "unmatched ) in regular expression.")
1516 (js2-msg "msg.no.regexp"
1517 "Regular expressions are not available.")
1519 (js2-msg "msg.bad.backref"
1520 "back-reference exceeds number of capturing parentheses.")
1522 (js2-msg "msg.bad.regexp.compile"
1523 "Only one argument may be specified if the first "
1524 "argument to RegExp.prototype.compile is a RegExp object.")
1527 (js2-msg "msg.got.syntax.errors"
1528 "Compilation produced %s syntax errors.")
1530 (js2-msg "msg.var.redecl"
1531 "TypeError: redeclaration of var %s.")
1533 (js2-msg "msg.const.redecl"
1534 "TypeError: redeclaration of const %s.")
1536 (js2-msg "msg.let.redecl"
1537 "TypeError: redeclaration of variable %s.")
1539 (js2-msg "msg.parm.redecl"
1540 "TypeError: redeclaration of formal parameter %s.")
1542 (js2-msg "msg.fn.redecl"
1543 "TypeError: redeclaration of function %s.")
1545 (js2-msg "msg.let.decl.not.in.block"
1546 "SyntaxError: let declaration not directly within block")
1549 (js2-msg "msg.dup.label"
1552 (js2-msg "msg.undef.label"
1555 (js2-msg "msg.bad.break"
1556 "unlabelled break must be inside loop or switch")
1558 (js2-msg "msg.continue.outside"
1559 "continue must be inside loop")
1561 (js2-msg "msg.continue.nonloop"
1562 "continue can only use labels of iteration statements")
1564 (js2-msg "msg.bad.throw.eol"
1565 "Line terminator is not allowed between the throw "
1566 "keyword and throw expression.")
1568 (js2-msg "msg.no.paren.parms"
1569 "missing ( before function parameters.")
1571 (js2-msg "msg.no.parm"
1572 "missing formal parameter")
1574 (js2-msg "msg.no.paren.after.parms"
1575 "missing ) after formal parameters")
1577 (js2-msg "msg.no.brace.body"
1578 "missing '{' before function body")
1580 (js2-msg "msg.no.brace.after.body"
1581 "missing } after function body")
1583 (js2-msg "msg.no.paren.cond"
1584 "missing ( before condition")
1586 (js2-msg "msg.no.paren.after.cond"
1587 "missing ) after condition")
1589 (js2-msg "msg.no.semi.stmt"
1590 "missing ; before statement")
1592 (js2-msg "msg.missing.semi"
1593 "missing ; after statement")
1595 (js2-msg "msg.no.name.after.dot"
1596 "missing name after . operator")
1598 (js2-msg "msg.no.name.after.coloncolon"
1599 "missing name after :: operator")
1601 (js2-msg "msg.no.name.after.dotdot"
1602 "missing name after .. operator")
1604 (js2-msg "msg.no.name.after.xmlAttr"
1605 "missing name after .@")
1607 (js2-msg "msg.no.bracket.index"
1608 "missing ] in index expression")
1610 (js2-msg "msg.no.paren.switch"
1611 "missing ( before switch expression")
1613 (js2-msg "msg.no.paren.after.switch"
1614 "missing ) after switch expression")
1616 (js2-msg "msg.no.brace.switch"
1617 "missing '{' before switch body")
1619 (js2-msg "msg.bad.switch"
1620 "invalid switch statement")
1622 (js2-msg "msg.no.colon.case"
1623 "missing : after case expression")
1625 (js2-msg "msg.double.switch.default"
1626 "double default label in the switch statement")
1628 (js2-msg "msg.no.while.do"
1629 "missing while after do-loop body")
1631 (js2-msg "msg.no.paren.for"
1632 "missing ( after for")
1634 (js2-msg "msg.no.semi.for"
1635 "missing ; after for-loop initializer")
1637 (js2-msg "msg.no.semi.for.cond"
1638 "missing ; after for-loop condition")
1640 (js2-msg "msg.in.after.for.name"
1641 "missing in after for")
1643 (js2-msg "msg.no.paren.for.ctrl"
1644 "missing ) after for-loop control")
1646 (js2-msg "msg.no.paren.with"
1647 "missing ( before with-statement object")
1649 (js2-msg "msg.no.paren.after.with"
1650 "missing ) after with-statement object")
1652 (js2-msg "msg.no.paren.after.let"
1653 "missing ( after let")
1655 (js2-msg "msg.no.paren.let"
1656 "missing ) after variable list")
1658 (js2-msg "msg.no.curly.let"
1659 "missing } after let statement")
1661 (js2-msg "msg.bad.return"
1664 (js2-msg "msg.no.brace.block"
1665 "missing } in compound statement")
1667 (js2-msg "msg.bad.label"
1670 (js2-msg "msg.bad.var"
1671 "missing variable name")
1673 (js2-msg "msg.bad.var.init"
1674 "invalid variable initialization")
1676 (js2-msg "msg.no.colon.cond"
1677 "missing : in conditional expression")
1679 (js2-msg "msg.no.paren.arg"
1680 "missing ) after argument list")
1682 (js2-msg "msg.no.bracket.arg"
1683 "missing ] after element list")
1685 (js2-msg "msg.bad.prop"
1686 "invalid property id")
1688 (js2-msg "msg.no.colon.prop"
1689 "missing : after property id")
1691 (js2-msg "msg.no.brace.prop"
1692 "missing } after property list")
1694 (js2-msg "msg.no.paren"
1695 "missing ) in parenthetical")
1697 (js2-msg "msg.reserved.id"
1698 "identifier is a reserved word")
1700 (js2-msg "msg.no.paren.catch"
1701 "missing ( before catch-block condition")
1703 (js2-msg "msg.bad.catchcond"
1704 "invalid catch block condition")
1706 (js2-msg "msg.catch.unreachable"
1707 "any catch clauses following an unqualified catch are unreachable")
1709 (js2-msg "msg.no.brace.try"
1710 "missing '{' before try block")
1712 (js2-msg "msg.no.brace.catchblock"
1713 "missing '{' before catch-block body")
1715 (js2-msg "msg.try.no.catchfinally"
1716 "'try' without 'catch' or 'finally'")
1718 (js2-msg "msg.no.return.value"
1719 "function %s does not always return a value")
1721 (js2-msg "msg.anon.no.return.value"
1722 "anonymous function does not always return a value")
1724 (js2-msg "msg.return.inconsistent"
1725 "return statement is inconsistent with previous usage")
1727 (js2-msg "msg.generator.returns"
1728 "TypeError: generator function '%s' returns a value")
1730 (js2-msg "msg.anon.generator.returns"
1731 "TypeError: anonymous generator function returns a value")
1733 (js2-msg "msg.syntax"
1736 (js2-msg "msg.unexpected.eof"
1737 "Unexpected end of file")
1739 (js2-msg "msg.XML.bad.form"
1740 "illegally formed XML syntax")
1742 (js2-msg "msg.XML.not.available"
1743 "XML runtime not available")
1745 (js2-msg "msg.too.deep.parser.recursion"
1746 "Too deep recursion while parsing")
1748 (js2-msg "msg.no.side.effects"
1749 "Code has no side effects")
1751 (js2-msg "msg.extra.trailing.comma"
1752 "Trailing comma is not legal in an ECMA-262 object initializer")
1754 (js2-msg "msg.array.trailing.comma"
1755 "Trailing comma yields different behavior across browsers")
1757 (js2-msg "msg.equal.as.assign"
1758 (concat "Test for equality (==) mistyped as assignment (=)?"
1759 " (parenthesize to suppress warning)"))
1761 (js2-msg "msg.var.hides.arg"
1762 "Variable %s hides argument")
1764 (js2-msg "msg.destruct.assign.no.init"
1765 "Missing = in destructuring declaration")
1768 (js2-msg "msg.no.properties"
1769 "%s has no properties.")
1771 (js2-msg "msg.invalid.iterator"
1772 "Invalid iterator value")
1774 (js2-msg "msg.iterator.primitive"
1775 "__iterator__ returned a primitive value")
1777 (js2-msg "msg.assn.create.strict"
1778 "Assignment to undeclared variable %s")
1780 (js2-msg "msg.ref.undefined.prop"
1781 "Reference to undefined property '%s'")
1783 (js2-msg "msg.prop.not.found"
1784 "Property %s not found.")
1786 (js2-msg "msg.invalid.type"
1787 "Invalid JavaScript value of type %s")
1789 (js2-msg "msg.primitive.expected"
1790 "Primitive type expected (had %s instead)")
1792 (js2-msg "msg.namespace.expected"
1793 "Namespace object expected to left of :: (found %s instead)")
1795 (js2-msg "msg.null.to.object"
1796 "Cannot convert null to an object.")
1798 (js2-msg "msg.undef.to.object"
1799 "Cannot convert undefined to an object.")
1801 (js2-msg "msg.cyclic.value"
1802 "Cyclic %s value not allowed.")
1804 (js2-msg "msg.is.not.defined"
1805 "'%s' is not defined.")
1807 (js2-msg "msg.undef.prop.read"
1808 "Cannot read property '%s' from %s")
1810 (js2-msg "msg.undef.prop.write"
1811 "Cannot set property '%s' of %s to '%s'")
1813 (js2-msg "msg.undef.prop.delete"
1814 "Cannot delete property '%s' of %s")
1816 (js2-msg "msg.undef.method.call"
1817 "Cannot call method '%s' of %s")
1819 (js2-msg "msg.undef.with"
1820 "Cannot apply 'with' to %s")
1822 (js2-msg "msg.isnt.function"
1823 "%s is not a function, it is %s.")
1825 (js2-msg "msg.isnt.function.in"
1826 "Cannot call property %s in object %s. "
1827 "It is not a function, it is '%s'.")
1829 (js2-msg "msg.function.not.found"
1830 "Cannot find function %s.")
1832 (js2-msg "msg.function.not.found.in"
1833 "Cannot find function %s in object %s.")
1835 (js2-msg "msg.isnt.xml.object"
1836 "%s is not an xml object.")
1838 (js2-msg "msg.no.ref.to.get"
1839 "%s is not a reference to read reference value.")
1841 (js2-msg "msg.no.ref.to.set"
1842 "%s is not a reference to set reference value to %s.")
1844 (js2-msg "msg.no.ref.from.function"
1845 "Function %s can not be used as the left-hand "
1846 "side of assignment or as an operand of ++ or -- operator.")
1848 (js2-msg "msg.bad.default.value"
1849 "Object's getDefaultValue() method returned an object.")
1851 (js2-msg "msg.instanceof.not.object"
1852 "Can't use instanceof on a non-object.")
1854 (js2-msg "msg.instanceof.bad.prototype"
1855 "'prototype' property of %s is not an object.")
1857 (js2-msg "msg.bad.radix"
1858 "illegal radix %s.")
1861 (js2-msg "msg.default.value"
1862 "Cannot find default value for object.")
1864 (js2-msg "msg.zero.arg.ctor"
1865 "Cannot load class '%s' which has no zero-parameter constructor.")
1867 (js2-msg "msg.ctor.multiple.parms"
1868 "Can't define constructor or class %s since more than "
1869 "one constructor has multiple parameters.")
1871 (js2-msg "msg.extend.scriptable"
1872 "%s must extend ScriptableObject in order to define property %s.")
1874 (js2-msg "msg.bad.getter.parms"
1875 "In order to define a property, getter %s must have zero "
1876 "parameters or a single ScriptableObject parameter.")
1878 (js2-msg "msg.obj.getter.parms"
1879 "Expected static or delegated getter %s to take "
1880 "a ScriptableObject parameter.")
1882 (js2-msg "msg.getter.static"
1883 "Getter and setter must both be static or neither be static.")
1885 (js2-msg "msg.setter.return"
1886 "Setter must have void return type: %s")
1888 (js2-msg "msg.setter2.parms"
1889 "Two-parameter setter must take a ScriptableObject as "
1890 "its first parameter.")
1892 (js2-msg "msg.setter1.parms"
1893 "Expected single parameter setter for %s")
1895 (js2-msg "msg.setter2.expected"
1896 "Expected static or delegated setter %s to take two parameters.")
1898 (js2-msg "msg.setter.parms"
1899 "Expected either one or two parameters for setter.")
1901 (js2-msg "msg.setter.bad.type"
1902 "Unsupported parameter type '%s' in setter '%s'.")
1904 (js2-msg "msg.add.sealed"
1905 "Cannot add a property to a sealed object: %s.")
1907 (js2-msg "msg.remove.sealed"
1908 "Cannot remove a property from a sealed object: %s.")
1910 (js2-msg "msg.modify.sealed"
1911 "Cannot modify a property of a sealed object: %s.")
1913 (js2-msg "msg.modify.readonly"
1914 "Cannot modify readonly property: %s.")
1917 (js2-msg "msg.missing.exponent"
1920 (js2-msg "msg.caught.nfe"
1921 "number format error")
1923 (js2-msg "msg.unterminated.string.lit"
1924 "unterminated string literal")
1926 (js2-msg "msg.unterminated.comment"
1927 "unterminated comment")
1929 (js2-msg "msg.unterminated.re.lit"
1930 "unterminated regular expression literal")
1932 (js2-msg "msg.invalid.re.flag"
1933 "invalid flag after regular expression")
1935 (js2-msg "msg.no.re.input.for"
1938 (js2-msg "msg.illegal.character"
1939 "illegal character")
1941 (js2-msg "msg.invalid.escape"
1942 "invalid Unicode escape sequence")
1944 (js2-msg "msg.bad.namespace"
1945 "not a valid default namespace statement. "
1946 "Syntax is: default xml namespace = EXPRESSION;")
1948 ;; TokensStream warnings
1949 (js2-msg "msg.bad.octal.literal"
1950 "illegal octal literal digit %s; "
1951 "interpreting it as a decimal digit")
1953 (js2-msg "msg.reserved.keyword"
1954 "illegal usage of future reserved keyword %s; "
1955 "interpreting it as ordinary identifier")
1957 (js2-msg "msg.script.is.not.constructor"
1958 "Script objects are not constructors.")
1961 (js2-msg "msg.arraylength.bad"
1962 "Inappropriate array length.")
1965 (js2-msg "msg.arraylength.too.big"
1966 "Array length %s exceeds supported capacity limit.")
1969 (js2-msg "msg.bad.uri"
1970 "Malformed URI sequence.")
1973 (js2-msg "msg.bad.precision"
1974 "Precision %s out of range.")
1977 (js2-msg "msg.send.newborn"
1978 "Attempt to send value to newborn generator")
1980 (js2-msg "msg.already.exec.gen"
1981 "Already executing generator")
1983 (js2-msg "msg.StopIteration.invalid"
1984 "StopIteration may not be changed to an arbitrary object.")
1987 (js2-msg "msg.yield.closing"
1988 "Yield from closing generator")
1992 (defun js2-delete-if (predicate list)
1993 "Remove all items satisfying PREDICATE in LIST."
1994 (loop for item in list
1995 if (not (funcall predicate item))
1998 (defun js2-position (element list)
1999 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
2000 Returns nil if element is not found in the list."
2003 (while (and list (not found))
2004 (if (eq element (car list))
2006 (setq count (1+ count)
2010 (defun js2-find-if (predicate list)
2011 "Find first item satisfying PREDICATE in LIST."
2013 (while (and list (not result))
2014 (if (funcall predicate (car list))
2015 (setq result (car list)))
2016 (setq list (cdr list)))
2019 (defmacro js2-time (form)
2020 "Evaluate FORM, discard result, and return elapsed time in sec"
2022 (let ((beg (make-symbol "--js2-time-beg--"))
2023 (delta (make-symbol "--js2-time-end--")))
2024 `(let ((,beg (current-time))
2027 (/ (truncate (* (- (float-time (current-time))
2032 (defsubst js2-same-line (pos)
2033 "Return t if POS is on the same line as current point."
2034 (and (>= pos (point-at-bol))
2035 (<= pos (point-at-eol))))
2037 (defsubst js2-same-line-2 (p1 p2)
2038 "Return t if p1 is on the same line as p2."
2041 (js2-same-line p2)))
2043 (defun js2-code-bug ()
2044 "Signal an error when we encounter an unexpected code path."
2045 (error "failed assertion"))
2047 (defsubst js2-record-text-property (beg end prop value)
2048 "Record a text property to set when parsing finishes."
2049 (push (list beg end prop value) js2-mode-deferred-properties))
2051 ;; I'd like to associate errors with nodes, but for now the
2052 ;; easiest thing to do is get the context info from the last token.
2053 (defsubst js2-record-parse-error (msg &optional arg pos len)
2054 (push (list (list msg arg)
2055 (or pos js2-token-beg)
2056 (or len (- js2-token-end js2-token-beg)))
2059 (defsubst js2-report-error (msg &optional msg-arg pos len)
2060 "Signal a syntax error or record a parse error."
2061 (if js2-recover-from-parse-errors
2062 (js2-record-parse-error msg msg-arg pos len)
2063 (signal 'js2-syntax-error
2067 (goto-char js2-ts-cursor)
2071 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2072 (if js2-compiler-report-warning-as-error
2073 (js2-report-error msg msg-arg pos len)
2074 (push (list (list msg msg-arg)
2075 (or pos js2-token-beg)
2076 (or len (- js2-token-end js2-token-beg)))
2077 js2-parsed-warnings)))
2079 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2080 (if js2-compiler-strict-mode
2081 (js2-report-warning msg-id msg-arg beg
2082 (and beg end (- end beg)))))
2084 (put 'js2-syntax-error 'error-conditions
2085 '(error syntax-error js2-syntax-error))
2086 (put 'js2-syntax-error 'error-message "Syntax error")
2088 (put 'js2-parse-error 'error-conditions
2089 '(error parse-error js2-parse-error))
2090 (put 'js2-parse-error 'error-message "Parse error")
2092 (defmacro js2-clear-flag (flags flag)
2093 `(setq ,flags (logand ,flags (lognot ,flag))))
2095 (defmacro js2-set-flag (flags flag)
2096 "Logical-or FLAG into FLAGS."
2097 `(setq ,flags (logior ,flags ,flag)))
2099 (defsubst js2-flag-set-p (flags flag)
2100 (/= 0 (logand flags flag)))
2102 (defsubst js2-flag-not-set-p (flags flag)
2103 (zerop (logand flags flag)))
2105 ;; Stolen shamelessly from James Clark's nxml-mode.
2106 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2107 "Evaluate BODY without any text property changes modifying the buffer.
2108 Any text properties changes happen as usual but the changes are not treated as
2109 modifications to the buffer."
2110 (declare (indent 0) (debug t))
2111 (let ((modified (make-symbol "modified")))
2112 `(let ((,modified (buffer-modified-p))
2113 (inhibit-read-only t)
2114 (inhibit-modification-hooks t)
2115 (buffer-undo-list t)
2116 (deactivate-mark nil)
2117 ;; Apparently these avoid file locking problems.
2118 (buffer-file-name nil)
2119 (buffer-file-truename nil))
2123 (restore-buffer-modified-p nil))))))
2125 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2126 "Evaluate BODY with the _ character set to be word-syntax."
2127 (declare (indent 0) (debug t))
2128 (let ((old-syntax (make-symbol "old-syntax")))
2129 `(let ((,old-syntax (string (char-syntax ?_))))
2132 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2134 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2136 (defsubst js2-char-uppercase-p (c)
2137 "Return t if C is an uppercase character.
2138 Handles unicode and latin chars properly."
2139 (/= c (downcase c)))
2141 (defsubst js2-char-lowercase-p (c)
2142 "Return t if C is an uppercase character.
2143 Handles unicode and latin chars properly."
2146 ;;; AST struct and function definitions
2148 ;; flags for ast node property 'member-type (used for e4x operators)
2149 (defvar js2-property-flag #x1 "property access: element is valid name")
2150 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2151 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2153 (defsubst js2-relpos (pos anchor)
2154 "Convert POS to be relative to ANCHOR.
2155 If POS is nil, returns nil."
2156 (and pos (- pos anchor)))
2158 (defsubst js2-make-pad (indent)
2161 (make-string (* indent js2-basic-offset) ? )))
2163 (defsubst js2-visit-ast (node callback)
2164 "Visit every node in ast NODE with visitor CALLBACK.
2166 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2167 called twice: once to visit the node, and again after all the node's
2168 children have been processed. The END-P argument is nil on the first
2169 call and non-nil on the second call. The return value of the callback
2170 affects the traversal: if non-nil, the children of NODE are processed.
2171 If the callback returns nil, or if the node has no children, then the
2172 callback is called immediately with a non-nil END-P argument.
2174 The node traversal is approximately lexical-order, although there
2175 are currently no guarantees around this."
2177 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2179 (when (funcall callback node nil)
2182 ((eq vfunc 'js2-visit-none)
2183 nil) ; don't even bother calling it
2184 ;; Each AST node type has to define a `js2-visitor' function
2185 ;; that takes a node and a callback, and calls `js2-visit-ast'
2186 ;; on each child of the node.
2188 (funcall vfunc node callback))
2190 (error "%s does not define a visitor-traversal function"
2192 ;; call the end-visit
2193 (funcall callback node t))))
2195 (defstruct (js2-node
2196 (:constructor nil)) ; abstract
2197 "Base AST node type."
2198 (type -1) ; token type
2199 (pos -1) ; start position of this AST node in parsed input
2200 (len 1) ; num characters spanned by the node
2201 props ; optional node property list (an alist)
2202 parent) ; link to parent node; null for root
2204 (defsubst js2-node-get-prop (node prop &optional default)
2205 (or (cadr (assoc prop (js2-node-props node))) default))
2207 (defsubst js2-node-set-prop (node prop value)
2208 (setf (js2-node-props node)
2209 (cons (list prop value) (js2-node-props node))))
2211 (defsubst js2-fixup-starts (n nodes)
2212 "Adjust the start positions of NODES to be relative to N.
2213 Any node in the list may be nil, for convenience."
2214 (dolist (node nodes)
2216 (setf (js2-node-pos node) (- (js2-node-pos node)
2217 (js2-node-pos n))))))
2219 (defsubst js2-node-add-children (parent &rest nodes)
2220 "Set parent node of NODES to PARENT, and return PARENT.
2221 Does nothing if we're not recording parent links.
2222 If any given node in NODES is nil, doesn't record that link."
2223 (js2-fixup-starts parent nodes)
2224 (dolist (node nodes)
2226 (setf (js2-node-parent node) parent))))
2228 ;; Non-recursive since it's called a frightening number of times.
2229 (defsubst js2-node-abs-pos (n)
2230 (let ((pos (js2-node-pos n)))
2231 (while (setq n (js2-node-parent n))
2232 (setq pos (+ pos (js2-node-pos n))))
2235 (defsubst js2-node-abs-end (n)
2236 "Return absolute buffer position of end of N."
2237 (+ (js2-node-abs-pos n) (js2-node-len n)))
2239 ;; It's important to make sure block nodes have a lisp list for the
2240 ;; child nodes, to limit printing recursion depth in an AST that
2241 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2242 ;; a sufficiently large vector tree.
2244 (defstruct (js2-block-node
2247 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2252 "A block of statements."
2253 kids) ; a lisp list of the child statement nodes
2255 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2256 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2258 (defsubst js2-visit-block (ast callback)
2259 "Visit the `js2-block-node' children of AST."
2260 (dolist (kid (js2-block-node-kids ast))
2261 (js2-visit-ast kid callback)))
2263 (defun js2-print-block (n i)
2264 (let ((pad (js2-make-pad i)))
2266 (dolist (kid (js2-block-node-kids n))
2267 (js2-print-ast kid (1+ i)))
2270 (defstruct (js2-scope
2271 (:include js2-block-node)
2273 (:constructor make-js2-scope (&key (type js2-BLOCK)
2277 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2278 ;; I don't have one of those handy, so I'll use an alist for now.
2279 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2280 ;; and is much lighter-weight to construct (both CPU and mem).
2281 ;; The keys are interned strings (symbols) for faster lookup.
2282 ;; Should switch to hybrid alist/hashtable eventually.
2283 symbol-table ; an alist of (symbol . js2-symbol)
2284 parent-scope ; a `js2-scope'
2285 top) ; top-level `js2-scope' (script/function)
2287 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2288 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2290 (defun js2-scope-set-parent-scope (scope parent)
2291 (setf (js2-scope-parent-scope scope) parent
2292 (js2-scope-top scope) (if (null parent)
2294 (js2-scope-top parent))))
2296 (defun js2-node-get-enclosing-scope (node)
2297 "Return the innermost `js2-scope' node surrounding NODE.
2298 Returns nil if there is no enclosing scope node."
2299 (let ((parent (js2-node-parent node)))
2300 (while (not (js2-scope-p parent))
2301 (setq parent (js2-node-parent parent)))
2304 (defun js2-get-defining-scope (scope name)
2305 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2306 Returns `js2-scope' in which NAME is defined, or nil if not found."
2307 (let ((sym (if (symbolp name)
2313 (while (and scope continue)
2314 (if (and (setq table (js2-scope-symbol-table scope))
2318 (setq scope (js2-scope-parent-scope scope))))
2321 (defsubst js2-scope-get-symbol (scope name)
2322 "Return symbol table entry for NAME in SCOPE.
2323 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2324 (and (js2-scope-symbol-table scope)
2325 (cdr (assq (if (symbolp name)
2328 (js2-scope-symbol-table scope)))))
2330 (defsubst js2-scope-put-symbol (scope name symbol)
2331 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2332 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2333 (let* ((table (js2-scope-symbol-table scope))
2334 (sym (if (symbolp name) name (intern name)))
2335 (entry (assq sym table)))
2337 (setcdr entry symbol)
2338 (push (cons sym symbol)
2339 (js2-scope-symbol-table scope)))))
2341 (defstruct (js2-symbol
2343 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2344 "A symbol table entry."
2345 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2346 ;; js2-LET, or js2-CONST
2349 ast-node) ; a `js2-node'
2351 (defstruct (js2-error-node
2353 (:constructor nil) ; silence emacs21 byte-compiler
2354 (:constructor make-js2-error-node (&key (type js2-ERROR)
2357 "AST node representing a parse error.")
2359 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2360 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2362 (defstruct (js2-script-node
2363 (:include js2-scope)
2365 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2370 functions ; lisp list of nested functions
2371 regexps ; lisp list of (string . flags)
2372 symbols ; alist (every symbol gets unique index)
2374 var-names ; vector of string names
2375 consts ; bool-vector matching var-decls
2376 (temp-number 0)) ; for generating temp variables
2378 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2379 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2381 (defun js2-print-script (node indent)
2382 (dolist (kid (js2-block-node-kids node))
2383 (js2-print-ast kid indent)))
2385 (defstruct (js2-ast-root
2386 (:include js2-script-node)
2388 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2392 "The root node of a js2 AST."
2393 buffer ; the source buffer from which the code was parsed
2394 comments ; a lisp list of comments, ordered by start position
2395 errors ; a lisp list of errors found during parsing
2396 warnings ; a lisp list of warnings found during parsing
2397 node-count) ; number of nodes in the tree, including the root
2399 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2400 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2402 (defun js2-visit-ast-root (ast callback)
2403 (dolist (kid (js2-ast-root-kids ast))
2404 (js2-visit-ast kid callback))
2405 (dolist (comment (js2-ast-root-comments ast))
2406 (js2-visit-ast comment callback)))
2408 (defstruct (js2-comment-node
2411 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2414 (format js2-ts-comment-type))))
2415 format) ; 'line, 'block, 'jsdoc or 'html
2417 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2418 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2420 (defun js2-print-comment (n i)
2421 ;; We really ought to link end-of-line comments to their nodes.
2422 ;; Or maybe we could add a new comment type, 'endline.
2423 (insert (js2-make-pad i)
2424 (js2-node-string n)))
2426 (defstruct (js2-expr-stmt-node
2429 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2433 "An expression statement."
2436 (defsubst js2-expr-stmt-node-set-has-result (node)
2437 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2438 (setf (js2-node-type node) js2-EXPR_RESULT))
2440 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2441 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2443 (defun js2-visit-expr-stmt-node (n v)
2444 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2446 (defun js2-print-expr-stmt-node (n indent)
2447 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2450 (defstruct (js2-loop-node
2451 (:include js2-scope)
2453 "Abstract supertype of loop nodes."
2454 body ; a `js2-block-node'
2455 lp ; position of left-paren, nil if omitted
2456 rp) ; position of right-paren, nil if omitted
2458 (defstruct (js2-do-node
2459 (:include js2-loop-node)
2461 (:constructor make-js2-do-node (&key (type js2-DO)
2469 "AST node for do-loop."
2470 condition ; while (expression)
2471 while-pos) ; buffer position of 'while' keyword
2473 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2474 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2476 (defun js2-visit-do-node (n v)
2477 (js2-visit-ast (js2-do-node-body n) v)
2478 (js2-visit-ast (js2-do-node-condition n) v))
2480 (defun js2-print-do-node (n i)
2481 (let ((pad (js2-make-pad i)))
2482 (insert pad "do {\n")
2483 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2484 (js2-print-ast kid (1+ i)))
2485 (insert pad "} while (")
2486 (js2-print-ast (js2-do-node-condition n) 0)
2489 (defstruct (js2-while-node
2490 (:include js2-loop-node)
2492 (:constructor make-js2-while-node (&key (type js2-WHILE)
2499 "AST node for while-loop."
2500 condition) ; while-condition
2502 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2503 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2505 (defun js2-visit-while-node (n v)
2506 (js2-visit-ast (js2-while-node-condition n) v)
2507 (js2-visit-ast (js2-while-node-body n) v))
2509 (defun js2-print-while-node (n i)
2510 (let ((pad (js2-make-pad i)))
2511 (insert pad "while (")
2512 (js2-print-ast (js2-while-node-condition n) 0)
2514 (js2-print-body (js2-while-node-body n) (1+ i))
2515 (insert pad "}\n")))
2517 (defstruct (js2-for-node
2518 (:include js2-loop-node)
2520 (:constructor make-js2-for-node (&key (type js2-FOR)
2529 "AST node for a C-style for-loop."
2530 init ; initialization expression
2531 condition ; loop condition
2532 update) ; update clause
2534 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2535 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2537 (defun js2-visit-for-node (n v)
2538 (js2-visit-ast (js2-for-node-init n) v)
2539 (js2-visit-ast (js2-for-node-condition n) v)
2540 (js2-visit-ast (js2-for-node-update n) v)
2541 (js2-visit-ast (js2-for-node-body n) v))
2543 (defun js2-print-for-node (n i)
2544 (let ((pad (js2-make-pad i)))
2545 (insert pad "for (")
2546 (js2-print-ast (js2-for-node-init n) 0)
2548 (js2-print-ast (js2-for-node-condition n) 0)
2550 (js2-print-ast (js2-for-node-update n) 0)
2552 (js2-print-body (js2-for-node-body n) (1+ i))
2553 (insert pad "}\n")))
2555 (defstruct (js2-for-in-node
2556 (:include js2-loop-node)
2558 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2569 "AST node for a for..in loop."
2570 iterator ; [var] foo in ...
2571 object ; object over which we're iterating
2572 in-pos ; buffer position of 'in' keyword
2573 each-pos ; buffer position of 'each' keyword, if foreach-p
2574 foreach-p) ; t if it's a for-each loop
2576 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2577 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2579 (defun js2-visit-for-in-node (n v)
2580 (js2-visit-ast (js2-for-in-node-iterator n) v)
2581 (js2-visit-ast (js2-for-in-node-object n) v)
2582 (js2-visit-ast (js2-for-in-node-body n) v))
2584 (defun js2-print-for-in-node (n i)
2585 (let ((pad (js2-make-pad i))
2586 (foreach (js2-for-in-node-foreach-p n)))
2591 (js2-print-ast (js2-for-in-node-iterator n) 0)
2593 (js2-print-ast (js2-for-in-node-object n) 0)
2595 (js2-print-body (js2-for-in-node-body n) (1+ i))
2596 (insert pad "}\n")))
2598 (defstruct (js2-return-node
2601 (:constructor make-js2-return-node (&key (type js2-RETURN)
2605 "AST node for a return statement."
2606 retval) ; expression to return, or 'undefined
2608 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2609 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2611 (defun js2-visit-return-node (n v)
2612 (js2-visit-ast (js2-return-node-retval n) v))
2614 (defun js2-print-return-node (n i)
2615 (insert (js2-make-pad i) "return")
2616 (when (js2-return-node-retval n)
2618 (js2-print-ast (js2-return-node-retval n) 0))
2621 (defstruct (js2-if-node
2624 (:constructor make-js2-if-node (&key (type js2-IF)
2633 "AST node for an if-statement."
2634 condition ; expression
2635 then-part ; statement or block
2636 else-pos ; optional buffer position of 'else' keyword
2637 else-part ; optional statement or block
2638 lp ; position of left-paren, nil if omitted
2639 rp) ; position of right-paren, nil if omitted
2641 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2642 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2644 (defun js2-visit-if-node (n v)
2645 (js2-visit-ast (js2-if-node-condition n) v)
2646 (js2-visit-ast (js2-if-node-then-part n) v)
2647 (js2-visit-ast (js2-if-node-else-part n) v))
2649 (defun js2-print-if-node (n i)
2650 (let ((pad (js2-make-pad i))
2651 (then-part (js2-if-node-then-part n))
2652 (else-part (js2-if-node-else-part n)))
2654 (js2-print-ast (js2-if-node-condition n) 0)
2656 (js2-print-body then-part (1+ i))
2661 ((js2-if-node-p else-part)
2663 (js2-print-body else-part i))
2665 (insert " else {\n")
2666 (js2-print-body else-part (1+ i))
2667 (insert pad "}\n")))))
2669 (defstruct (js2-try-node
2672 (:constructor make-js2-try-node (&key (type js2-TRY)
2678 "AST node for a try-statement."
2680 catch-clauses ; a lisp list of `js2-catch-node'
2681 finally-block) ; a `js2-finally-node'
2683 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2684 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2686 (defun js2-visit-try-node (n v)
2687 (js2-visit-ast (js2-try-node-try-block n) v)
2688 (dolist (clause (js2-try-node-catch-clauses n))
2689 (js2-visit-ast clause v))
2690 (js2-visit-ast (js2-try-node-finally-block n) v))
2692 (defun js2-print-try-node (n i)
2693 (let ((pad (js2-make-pad i))
2694 (catches (js2-try-node-catch-clauses n))
2695 (finally (js2-try-node-finally-block n)))
2696 (insert pad "try {\n")
2697 (js2-print-body (js2-try-node-try-block n) (1+ i))
2700 (dolist (catch catches)
2701 (js2-print-ast catch i)))
2703 (js2-print-ast finally i)
2706 (defstruct (js2-catch-node
2709 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2718 "AST node for a catch clause."
2719 param ; destructuring form or simple name node
2720 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2721 guard-expr ; catch condition, a `js2-node'
2722 block ; statements, a `js2-block-node'
2723 lp ; buffer position of left-paren, nil if omitted
2724 rp) ; buffer position of right-paren, nil if omitted
2726 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2727 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2729 (defun js2-visit-catch-node (n v)
2730 (js2-visit-ast (js2-catch-node-param n) v)
2731 (when (js2-catch-node-guard-kwd n)
2732 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2733 (js2-visit-ast (js2-catch-node-block n) v))
2735 (defun js2-print-catch-node (n i)
2736 (let ((pad (js2-make-pad i))
2737 (guard-kwd (js2-catch-node-guard-kwd n))
2738 (guard-expr (js2-catch-node-guard-expr n)))
2740 (js2-print-ast (js2-catch-node-param n) 0)
2743 (js2-print-ast guard-expr 0))
2745 (js2-print-body (js2-catch-node-block n) (1+ i))
2748 (defstruct (js2-finally-node
2751 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2755 "AST node for a finally clause."
2756 body) ; a `js2-node', often but not always a block node
2758 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2759 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2761 (defun js2-visit-finally-node (n v)
2762 (js2-visit-ast (js2-finally-node-body n) v))
2764 (defun js2-print-finally-node (n i)
2765 (let ((pad (js2-make-pad i)))
2766 (insert " finally {\n")
2767 (js2-print-body (js2-finally-node-body n) (1+ i))
2768 (insert pad "}\n")))
2770 (defstruct (js2-switch-node
2773 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2780 "AST node for a switch statement."
2781 discriminant ; a `js2-node' (switch expression)
2782 cases ; a lisp list of `js2-case-node'
2783 lp ; position of open-paren for discriminant, nil if omitted
2784 rp) ; position of close-paren for discriminant, nil if omitted
2786 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2787 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2789 (defun js2-visit-switch-node (n v)
2790 (js2-visit-ast (js2-switch-node-discriminant n) v)
2791 (dolist (c (js2-switch-node-cases n))
2792 (js2-visit-ast c v)))
2794 (defun js2-print-switch-node (n i)
2795 (let ((pad (js2-make-pad i))
2796 (cases (js2-switch-node-cases n)))
2797 (insert pad "switch (")
2798 (js2-print-ast (js2-switch-node-discriminant n) 0)
2800 (dolist (case cases)
2801 (js2-print-ast case i))
2802 (insert pad "}\n")))
2804 (defstruct (js2-case-node
2805 (:include js2-block-node)
2807 (:constructor make-js2-case-node (&key (type js2-CASE)
2812 "AST node for a case clause of a switch statement."
2813 expr) ; the case expression (nil for default)
2815 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2816 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2818 (defun js2-visit-case-node (n v)
2819 (js2-visit-ast (js2-case-node-expr n) v)
2820 (js2-visit-block n v))
2822 (defun js2-print-case-node (n i)
2823 (let ((pad (js2-make-pad i))
2824 (expr (js2-case-node-expr n)))
2827 (insert "default:\n")
2829 (js2-print-ast expr 0)
2831 (dolist (kid (js2-case-node-kids n))
2832 (js2-print-ast kid (1+ i)))))
2834 (defstruct (js2-throw-node
2837 (:constructor make-js2-throw-node (&key (type js2-THROW)
2841 "AST node for a throw statement."
2842 expr) ; the expression to throw
2844 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2845 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2847 (defun js2-visit-throw-node (n v)
2848 (js2-visit-ast (js2-throw-node-expr n) v))
2850 (defun js2-print-throw-node (n i)
2851 (insert (js2-make-pad i) "throw ")
2852 (js2-print-ast (js2-throw-node-expr n) 0)
2855 (defstruct (js2-with-node
2858 (:constructor make-js2-with-node (&key (type js2-WITH)
2865 "AST node for a with-statement."
2868 lp ; buffer position of left-paren around object, nil if omitted
2869 rp) ; buffer position of right-paren around object, nil if omitted
2871 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2872 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2874 (defun js2-visit-with-node (n v)
2875 (js2-visit-ast (js2-with-node-object n) v)
2876 (js2-visit-ast (js2-with-node-body n) v))
2878 (defun js2-print-with-node (n i)
2879 (let ((pad (js2-make-pad i)))
2880 (insert pad "with (")
2881 (js2-print-ast (js2-with-node-object n) 0)
2883 (js2-print-body (js2-with-node-body n) (1+ i))
2884 (insert pad "}\n")))
2886 (defstruct (js2-label-node
2889 (:constructor make-js2-label-node (&key (type js2-LABEL)
2893 "AST node for a statement label or case label."
2895 loop) ; for validating and code-generating continue-to-label
2897 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2898 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2900 (defun js2-print-label (n i)
2901 (insert (js2-make-pad i)
2902 (js2-label-node-name n)
2905 (defstruct (js2-labeled-stmt-node
2908 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2909 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2910 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2915 "AST node for a statement with one or more labels.
2916 Multiple labels for a statement are collapsed into the labels field."
2917 labels ; lisp list of `js2-label-node'
2918 stmt) ; the statement these labels are for
2920 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2921 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2923 (defun js2-get-label-by-name (lbl-stmt name)
2924 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2925 Returns nil if no such label is in the list."
2926 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2928 (while (and label-list (not result))
2929 (if (string= (js2-label-node-name (car label-list)) name)
2930 (setq result (car label-list))
2931 (setq label-list (cdr label-list))))
2934 (defun js2-visit-labeled-stmt (n v)
2935 (dolist (label (js2-labeled-stmt-node-labels n))
2936 (js2-visit-ast label v))
2937 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2939 (defun js2-print-labeled-stmt (n i)
2940 (dolist (label (js2-labeled-stmt-node-labels n))
2941 (js2-print-ast label i))
2942 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2944 (defun js2-labeled-stmt-node-contains (node label)
2945 "Return t if NODE contains LABEL in its label set.
2946 NODE is a `js2-labels-node'. LABEL is an identifier."
2947 (loop for nl in (js2-labeled-stmt-node-labels node)
2948 if (string= label (js2-label-node-name nl))
2950 finally return nil))
2952 (defsubst js2-labeled-stmt-node-add-label (node label)
2953 "Add a `js2-label-node' to the label set for this statement."
2954 (setf (js2-labeled-stmt-node-labels node)
2955 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2957 (defstruct (js2-jump-node
2960 "Abstract supertype of break and continue nodes."
2961 label ; `js2-name-node' for location of label identifier, if present
2962 target) ; target js2-labels-node or loop/switch statement
2964 (defun js2-visit-jump-node (n v)
2965 (js2-visit-ast (js2-jump-node-label n) v))
2967 (defstruct (js2-break-node
2968 (:include js2-jump-node)
2970 (:constructor make-js2-break-node (&key (type js2-BREAK)
2975 "AST node for a break statement.
2976 The label field is a `js2-name-node', possibly nil, for the named label
2977 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2978 is the target of the break - a label node or enclosing loop/switch statement.")
2980 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2981 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2983 (defun js2-print-break-node (n i)
2984 (insert (js2-make-pad i) "break")
2985 (when (js2-break-node-label n)
2987 (js2-print-ast (js2-break-node-label n) 0))
2990 (defstruct (js2-continue-node
2991 (:include js2-jump-node)
2993 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2998 "AST node for a continue statement.
2999 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3000 It is nil if continue specifies no label. The target field is the jump target:
3001 a `js2-label-node' or the innermost enclosing loop.")
3003 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3004 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3006 (defun js2-print-continue-node (n i)
3007 (insert (js2-make-pad i) "continue")
3008 (when (js2-continue-node-label n)
3010 (js2-print-ast (js2-continue-node-label n) 0))
3013 (defstruct (js2-function-node
3014 (:include js2-script-node)
3016 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3020 (form 'FUNCTION_STATEMENT)
3026 "AST node for a function declaration.
3027 The `params' field is a lisp list of nodes. Each node is either a simple
3028 `js2-name-node', or if it's a destructuring-assignment parameter, a
3029 `js2-array-node' or `js2-object-node'."
3030 ftype ; FUNCTION, GETTER or SETTER
3031 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3032 name ; function name (a `js2-name-node', or nil if anonymous)
3033 params ; a lisp list of destructuring forms or simple name nodes
3034 body ; a `js2-block-node' or expression node (1.8 only)
3035 lp ; position of arg-list open-paren, or nil if omitted
3036 rp ; position of arg-list close-paren, or nil if omitted
3037 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3038 needs-activation ; t if we need an activation object for this frame
3039 is-generator ; t if this function contains a yield
3040 member-expr) ; nonstandard Ecma extension from Rhino
3042 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3043 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3045 (defun js2-visit-function-node (n v)
3046 (js2-visit-ast (js2-function-node-name n) v)
3047 (dolist (p (js2-function-node-params n))
3048 (js2-visit-ast p v))
3049 (js2-visit-ast (js2-function-node-body n) v))
3051 (defun js2-print-function-node (n i)
3052 (let ((pad (js2-make-pad i))
3053 (getter (js2-node-get-prop n 'GETTER_SETTER))
3054 (name (js2-function-node-name n))
3055 (params (js2-function-node-params n))
3056 (body (js2-function-node-body n))
3057 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3059 (insert pad "function"))
3062 (js2-print-ast name 0))
3064 (loop with len = (length params)
3068 (js2-print-ast param 0)
3074 ;; TODO: fix this to be smarter about indenting, etc.
3075 (js2-print-body body (1+ i))
3080 (defsubst js2-function-name (node)
3081 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3082 (and (js2-function-node-name node)
3083 (js2-name-node-name (js2-function-node-name node))))
3085 ;; Having this be an expression node makes it more flexible.
3086 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3087 ;; that work better if you assume it's an expression. Whenever we have
3088 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3089 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3090 (defstruct (js2-var-decl-node
3093 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3098 "AST node for a variable declaration list (VAR, CONST or LET).
3099 The node bounds differ depending on the declaration type. For VAR or
3100 CONST declarations, the bounds include the var/const keyword. For LET
3101 declarations, the node begins at the position of the first child."
3102 kids ; a lisp list of `js2-var-init-node' structs.
3103 decl-type) ; js2-VAR, js2-CONST or js2-LET
3105 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3106 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3108 (defun js2-visit-var-decl (n v)
3109 (dolist (kid (js2-var-decl-node-kids n))
3110 (js2-visit-ast kid v)))
3112 (defun js2-print-var-decl (n i)
3113 (let ((pad (js2-make-pad i))
3114 (tt (js2-var-decl-node-decl-type n)))
3117 ((= tt js2-VAR) "var ")
3118 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3119 ((= tt js2-CONST) "const ")
3121 (error "malformed var-decl node"))))
3122 (loop with kids = (js2-var-decl-node-kids n)
3123 with len = (length kids)
3127 (js2-print-ast kid 0)
3131 (defstruct (js2-var-init-node
3134 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3139 "AST node for a variable declaration.
3140 The type field will be js2-CONST for a const decl."
3141 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3142 initializer) ; initializer expression, a `js2-node'
3144 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3145 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3147 (defun js2-visit-var-init-node (n v)
3148 (js2-visit-ast (js2-var-init-node-target n) v)
3149 (js2-visit-ast (js2-var-init-node-initializer n) v))
3151 (defun js2-print-var-init-node (n i)
3152 (let ((pad (js2-make-pad i))
3153 (name (js2-var-init-node-target n))
3154 (init (js2-var-init-node-initializer n)))
3156 (js2-print-ast name 0)
3159 (js2-print-ast init 0))))
3161 (defstruct (js2-cond-node
3164 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3172 "AST node for the ternary operator"
3176 q-pos ; buffer position of ?
3177 c-pos) ; buffer position of :
3179 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3180 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3182 (defun js2-visit-cond-node (n v)
3183 (js2-visit-ast (js2-cond-node-test-expr n) v)
3184 (js2-visit-ast (js2-cond-node-true-expr n) v)
3185 (js2-visit-ast (js2-cond-node-false-expr n) v))
3187 (defun js2-print-cond-node (n i)
3188 (let ((pad (js2-make-pad i)))
3190 (js2-print-ast (js2-cond-node-test-expr n) 0)
3192 (js2-print-ast (js2-cond-node-true-expr n) 0)
3194 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3196 (defstruct (js2-infix-node
3199 (:constructor make-js2-infix-node (&key type
3205 "Represents infix expressions.
3206 Includes assignment ops like `|=', and the comma operator.
3207 The type field inherited from `js2-node' holds the operator."
3208 op-pos ; buffer position where operator begins
3209 left ; any `js2-node'
3210 right) ; any `js2-node'
3212 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3213 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3215 (defun js2-visit-infix-node (n v)
3216 (js2-visit-ast (js2-infix-node-left n) v)
3217 (js2-visit-ast (js2-infix-node-right n) v))
3219 (defconst js2-operator-tokens
3220 (let ((table (make-hash-table :test 'eq))
3222 (list (cons js2-IN "in")
3223 (cons js2-TYPEOF "typeof")
3224 (cons js2-INSTANCEOF "instanceof")
3225 (cons js2-DELPROP "delete")
3226 (cons js2-COMMA ",")
3227 (cons js2-COLON ":")
3232 (cons js2-BITOR "|")
3233 (cons js2-BITXOR "^")
3234 (cons js2-BITAND "&")
3243 (cons js2-URSH ">>>")
3244 (cons js2-ADD "+") ; infix plus
3245 (cons js2-SUB "-") ; infix minus
3250 (cons js2-BITNOT "~")
3251 (cons js2-POS "+") ; unary plus
3252 (cons js2-NEG "-") ; unary minus
3253 (cons js2-SHEQ "===") ; shallow equality
3254 (cons js2-SHNE "!==") ; shallow inequality
3255 (cons js2-ASSIGN "=")
3256 (cons js2-ASSIGN_BITOR "|=")
3257 (cons js2-ASSIGN_BITXOR "^=")
3258 (cons js2-ASSIGN_BITAND "&=")
3259 (cons js2-ASSIGN_LSH "<<=")
3260 (cons js2-ASSIGN_RSH ">>=")
3261 (cons js2-ASSIGN_URSH ">>>=")
3262 (cons js2-ASSIGN_ADD "+=")
3263 (cons js2-ASSIGN_SUB "-=")
3264 (cons js2-ASSIGN_MUL "*=")
3265 (cons js2-ASSIGN_DIV "/=")
3266 (cons js2-ASSIGN_MOD "%="))))
3267 (loop for (k . v) in tokens do
3268 (puthash k v table))
3271 (defun js2-print-infix-node (n i)
3272 (let* ((tt (js2-node-type n))
3273 (op (gethash tt js2-operator-tokens)))
3275 (error "unrecognized infix operator %s" (js2-node-type n)))
3276 (insert (js2-make-pad i))
3277 (js2-print-ast (js2-infix-node-left n) 0)
3278 (unless (= tt js2-COMMA)
3282 (js2-print-ast (js2-infix-node-right n) 0)))
3284 (defstruct (js2-assign-node
3285 (:include js2-infix-node)
3287 (:constructor make-js2-assign-node (&key type
3293 "Represents any assignment.
3294 The type field holds the actual assignment operator.")
3296 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3297 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3299 (defstruct (js2-unary-node
3302 (:constructor make-js2-unary-node (&key type ; required
3306 "AST node type for unary operator nodes.
3307 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3308 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3309 property is added if the operator follows the operand."
3310 operand) ; a `js2-node' expression
3312 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3313 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3315 (defun js2-visit-unary-node (n v)
3316 (js2-visit-ast (js2-unary-node-operand n) v))
3318 (defun js2-print-unary-node (n i)
3319 (let* ((tt (js2-node-type n))
3320 (op (gethash tt js2-operator-tokens))
3321 (postfix (js2-node-get-prop n 'postfix)))
3323 (error "unrecognized unary operator %s" tt))
3324 (insert (js2-make-pad i))
3327 (if (or (= tt js2-TYPEOF)
3330 (js2-print-ast (js2-unary-node-operand n) 0)
3334 (defstruct (js2-let-node
3335 (:include js2-scope)
3337 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3344 "AST node for a let expression or a let statement.
3345 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3346 vars ; a `js2-var-decl-node'
3347 body ; a `js2-node' representing the expression or body block
3351 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3352 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3354 (defun js2-visit-let-node (n v)
3355 (js2-visit-ast (js2-let-node-vars n) v)
3356 (js2-visit-ast (js2-let-node-body n) v))
3358 (defun js2-print-let-node (n i)
3359 (insert (js2-make-pad i) "let (")
3360 (js2-print-ast (js2-let-node-vars n) 0)
3362 (js2-print-ast (js2-let-node-body n) i))
3364 (defstruct (js2-keyword-node
3367 (:constructor make-js2-keyword-node (&key type
3369 (len (- js2-ts-cursor pos)))))
3370 "AST node representing a literal keyword such as `null'.
3371 Used for `null', `this', `true', `false' and `debugger'.
3372 The node type is set to js2-NULL, js2-THIS, etc.")
3374 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3375 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3377 (defun js2-print-keyword-node (n i)
3378 (insert (js2-make-pad i)
3379 (let ((tt (js2-node-type n)))
3381 ((= tt js2-THIS) "this")
3382 ((= tt js2-NULL) "null")
3383 ((= tt js2-TRUE) "true")
3384 ((= tt js2-FALSE) "false")
3385 ((= tt js2-DEBUGGER) "debugger")
3386 (t (error "Invalid keyword literal type: %d" tt))))))
3388 (defsubst js2-this-node-p (node)
3389 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3390 (eq (js2-node-type node) js2-THIS))
3392 (defstruct (js2-new-node
3395 (:constructor make-js2-new-node (&key (type js2-NEW)
3403 "AST node for new-expression such as new Foo()."
3404 target ; an identifier or reference
3405 args ; a lisp list of argument nodes
3406 lp ; position of left-paren, nil if omitted
3407 rp ; position of right-paren, nil if omitted
3408 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3410 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3411 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3413 (defun js2-visit-new-node (n v)
3414 (js2-visit-ast (js2-new-node-target n) v)
3415 (dolist (arg (js2-new-node-args n))
3416 (js2-visit-ast arg v))
3417 (js2-visit-ast (js2-new-node-initializer n) v))
3419 (defun js2-print-new-node (n i)
3420 (insert (js2-make-pad i) "new ")
3421 (js2-print-ast (js2-new-node-target n))
3423 (js2-print-list (js2-new-node-args n))
3425 (when (js2-new-node-initializer n)
3427 (js2-print-ast (js2-new-node-initializer n))))
3429 (defstruct (js2-name-node
3432 (:constructor make-js2-name-node (&key (type js2-NAME)
3434 (len (- js2-ts-cursor
3436 (name js2-ts-string))))
3437 "AST node for a JavaScript identifier"
3439 scope) ; a `js2-scope' (optional, used for codegen)
3441 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3442 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3444 (defun js2-print-name-node (n i)
3445 (insert (js2-make-pad i)
3446 (js2-name-node-name n)))
3448 (defsubst js2-name-node-length (node)
3449 "Return identifier length of NODE, a `js2-name-node'.
3450 Returns 0 if NODE is nil or its identifier field is nil."
3452 (length (js2-name-node-name node))
3455 (defstruct (js2-number-node
3458 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3460 (len (- js2-ts-cursor
3462 (value js2-ts-string)
3463 (num-value js2-ts-number))))
3464 "AST node for a number literal."
3465 value ; the original string, e.g. "6.02e23"
3466 num-value) ; the parsed number value
3468 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3469 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3471 (defun js2-print-number-node (n i)
3472 (insert (js2-make-pad i)
3473 (number-to-string (js2-number-node-num-value n))))
3475 (defstruct (js2-regexp-node
3478 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3480 (len (- js2-ts-cursor
3484 "AST node for a regular expression literal."
3485 value ; the regexp string, without // delimiters
3486 flags) ; a string of flags, e.g. `mi'.
3488 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3489 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3491 (defun js2-print-regexp (n i)
3492 (insert (js2-make-pad i)
3494 (js2-regexp-node-value n)
3496 (if (js2-regexp-node-flags n)
3497 (insert (js2-regexp-node-flags n))))
3499 (defstruct (js2-string-node
3502 (:constructor make-js2-string-node (&key (type js2-STRING)
3504 (len (- js2-ts-cursor
3506 (value js2-ts-string))))
3508 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3509 You can tell the quote type by looking at the first character."
3510 value) ; the characters of the string, including the quotes
3512 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3513 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3515 (defun js2-print-string-node (n i)
3516 (insert (js2-make-pad i)
3517 (js2-node-string n)))
3519 (defstruct (js2-array-node
3522 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3526 "AST node for an array literal."
3527 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3529 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3530 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3532 (defun js2-visit-array-node (n v)
3533 (dolist (e (js2-array-node-elems n))
3534 (js2-visit-ast e v)))
3536 (defun js2-print-array-node (n i)
3537 (insert (js2-make-pad i) "[")
3538 (js2-print-list (js2-array-node-elems n))
3541 (defstruct (js2-object-node
3544 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3548 "AST node for an object literal expression.
3549 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3550 the latter represents abbreviation in destructuring expressions."
3553 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3554 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3556 (defun js2-visit-object-node (n v)
3557 (dolist (e (js2-object-node-elems n))
3558 (js2-visit-ast e v)))
3560 (defun js2-print-object-node (n i)
3561 (insert (js2-make-pad i) "{")
3562 (js2-print-list (js2-object-node-elems n))
3565 (defstruct (js2-object-prop-node
3566 (:include js2-infix-node)
3568 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3574 "AST node for an object literal prop:value entry.
3575 The `left' field is the property: a name node, string node or number node.
3576 The `right' field is a `js2-node' representing the initializer value.")
3578 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3579 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3581 (defun js2-print-object-prop-node (n i)
3582 (insert (js2-make-pad i))
3583 (js2-print-ast (js2-object-prop-node-left n) 0)
3585 (js2-print-ast (js2-object-prop-node-right n) 0))
3587 (defstruct (js2-getter-setter-node
3588 (:include js2-infix-node)
3590 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3595 "AST node for a getter/setter property in an object literal.
3596 The `left' field is the `js2-name-node' naming the getter/setter prop.
3597 The `right' field is always an anonymous `js2-function-node' with a node
3598 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3600 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3601 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3603 (defun js2-print-getter-setter (n i)
3604 (let ((pad (js2-make-pad i))
3605 (left (js2-getter-setter-node-left n))
3606 (right (js2-getter-setter-node-right n)))
3608 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3609 (js2-print-ast left 0)
3610 (js2-print-ast right 0)))
3612 (defstruct (js2-prop-get-node
3613 (:include js2-infix-node)
3615 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3620 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3622 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3623 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3625 (defun js2-visit-prop-get-node (n v)
3626 (js2-visit-ast (js2-prop-get-node-left n) v)
3627 (js2-visit-ast (js2-prop-get-node-right n) v))
3629 (defun js2-print-prop-get-node (n i)
3630 (insert (js2-make-pad i))
3631 (js2-print-ast (js2-prop-get-node-left n) 0)
3633 (js2-print-ast (js2-prop-get-node-right n) 0))
3635 (defstruct (js2-elem-get-node
3638 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3645 "AST node for an array index expression such as foo[bar]."
3646 target ; a `js2-node' - the expression preceding the "."
3647 element ; a `js2-node' - the expression in brackets
3648 lb ; position of left-bracket, nil if omitted
3649 rb) ; position of right-bracket, nil if omitted
3651 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3652 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3654 (defun js2-visit-elem-get-node (n v)
3655 (js2-visit-ast (js2-elem-get-node-target n) v)
3656 (js2-visit-ast (js2-elem-get-node-element n) v))
3658 (defun js2-print-elem-get-node (n i)
3659 (insert (js2-make-pad i))
3660 (js2-print-ast (js2-elem-get-node-target n) 0)
3662 (js2-print-ast (js2-elem-get-node-element n) 0)
3665 (defstruct (js2-call-node
3668 (:constructor make-js2-call-node (&key (type js2-CALL)
3675 "AST node for a JavaScript function call."
3676 target ; a `js2-node' evaluating to the function to call
3677 args ; a lisp list of `js2-node' arguments
3678 lp ; position of open-paren, or nil if missing
3679 rp) ; position of close-paren, or nil if missing
3681 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3682 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3684 (defun js2-visit-call-node (n v)
3685 (js2-visit-ast (js2-call-node-target n) v)
3686 (dolist (arg (js2-call-node-args n))
3687 (js2-visit-ast arg v)))
3689 (defun js2-print-call-node (n i)
3690 (insert (js2-make-pad i))
3691 (js2-print-ast (js2-call-node-target n) 0)
3693 (js2-print-list (js2-call-node-args n))
3696 (defstruct (js2-yield-node
3699 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3703 "AST node for yield statement or expression."
3704 value) ; optional: value to be yielded
3706 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3707 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3709 (defun js2-visit-yield-node (n v)
3710 (js2-visit-ast (js2-yield-node-value n) v))
3712 (defun js2-print-yield-node (n i)
3713 (insert (js2-make-pad i))
3715 (when (js2-yield-node-value n)
3717 (js2-print-ast (js2-yield-node-value n) 0)))
3719 (defstruct (js2-paren-node
3722 (:constructor make-js2-paren-node (&key (type js2-LP)
3726 "AST node for a parenthesized expression.
3727 In particular, used when the parens are syntactically optional,
3728 as opposed to required parens such as those enclosing an if-conditional."
3731 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3732 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3734 (defun js2-visit-paren-node (n v)
3735 (js2-visit-ast (js2-paren-node-expr n) v))
3737 (defun js2-print-paren-node (n i)
3738 (insert (js2-make-pad i))
3740 (js2-print-ast (js2-paren-node-expr n) 0)
3743 (defstruct (js2-array-comp-node
3744 (:include js2-scope)
3746 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3755 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3756 result ; result expression (just after left-bracket)
3757 loops ; a lisp list of `js2-array-comp-loop-node'
3758 filter ; guard/filter expression
3759 if-pos ; buffer pos of 'if' keyword, if present, else nil
3760 lp ; buffer position of if-guard left-paren, or nil if not present
3761 rp) ; buffer position of if-guard right-paren, or nil if not present
3763 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3764 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3766 (defun js2-visit-array-comp-node (n v)
3767 (js2-visit-ast (js2-array-comp-node-result n) v)
3768 (dolist (l (js2-array-comp-node-loops n))
3769 (js2-visit-ast l v))
3770 (js2-visit-ast (js2-array-comp-node-filter n) v))
3772 (defun js2-print-array-comp-node (n i)
3773 (let ((pad (js2-make-pad i))
3774 (result (js2-array-comp-node-result n))
3775 (loops (js2-array-comp-node-loops n))
3776 (filter (js2-array-comp-node-filter n)))
3778 (js2-print-ast result 0)
3781 (js2-print-ast l 0))
3784 (js2-print-ast filter 0))
3787 (defstruct (js2-array-comp-loop-node
3788 (:include js2-for-in-node)
3790 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3800 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3802 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3803 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3805 (defun js2-visit-array-comp-loop (n v)
3806 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3807 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3809 (defun js2-print-array-comp-loop (n i)
3811 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3813 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3816 (defstruct (js2-empty-expr-node
3819 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3822 "AST node for an empty expression.")
3824 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3825 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3827 (defstruct (js2-xml-node
3828 (:include js2-block-node)
3830 (:constructor make-js2-xml-node (&key (type js2-XML)
3834 "AST node for initial parse of E4X literals.
3835 The kids field is a list of XML fragments, each a `js2-string-node' or
3836 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3838 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3839 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3841 (defun js2-print-xml-node (n i)
3842 (dolist (kid (js2-xml-node-kids n))
3843 (js2-print-ast kid i)))
3845 (defstruct (js2-xml-js-expr-node
3846 (:include js2-xml-node)
3848 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3852 "AST node for an embedded JavaScript {expression} in an E4X literal.
3853 The start and end fields correspond to the curly-braces."
3854 expr) ; a `js2-expr-node' of some sort
3856 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3857 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3859 (defun js2-visit-xml-js-expr (n v)
3860 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3862 (defun js2-print-xml-js-expr (n i)
3863 (insert (js2-make-pad i))
3865 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3868 (defstruct (js2-xml-dot-query-node
3869 (:include js2-infix-node)
3871 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3878 "AST node for an E4X foo.(bar) filter expression.
3879 Note that the left-paren is automatically the character immediately
3880 following the dot (.) in the operator. No whitespace is permitted
3881 between the dot and the lp by the scanner."
3884 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3885 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3887 (defun js2-print-xml-dot-query (n i)
3888 (insert (js2-make-pad i))
3889 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3891 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3894 (defstruct (js2-xml-ref-node
3896 (:constructor nil)) ; abstract
3897 "Base type for E4X XML attribute-access or property-get expressions.
3898 Such expressions can take a variety of forms. The general syntax has
3901 - (optional) an @ (specifying an attribute access)
3902 - (optional) a namespace (a `js2-name-node') and double-colon
3903 - (required) either a `js2-name-node' or a bracketed [expression]
3905 The property-name expressions (examples: ns::name, @name) are
3906 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3907 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3909 This node type (or more specifically, its subclasses) will sometimes
3910 be the right-hand child of a `js2-prop-get-node' or a
3911 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3912 The `js2-xml-ref-node' may also be a standalone primary expression with
3913 no explicit target, which is valid in certain expression contexts such as
3915 company..employee.(@id < 100)
3917 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3918 expression whose parent is a `js2-xml-dot-query-node'."
3923 (defsubst js2-xml-ref-node-attr-access-p (node)
3924 "Return non-nil if this expression began with an @-token."
3925 (and (numberp (js2-xml-ref-node-at-pos node))
3926 (plusp (js2-xml-ref-node-at-pos node))))
3928 (defstruct (js2-xml-prop-ref-node
3929 (:include js2-xml-ref-node)
3931 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3938 "AST node for an E4X XML [expr] property-ref expression.
3939 The JavaScript syntax is an optional @, an optional ns::, and a name.
3941 [ '@' ] [ name '::' ] name
3943 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3944 @ns::*, @*::attr, @*::*, and @*.
3946 The node starts at the @ token, if present. Otherwise it starts at the
3947 namespace name. The node bounds extend through the closing right-bracket,
3948 or if it is missing due to a syntax error, through the end of the index
3952 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3953 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3955 (defun js2-visit-xml-prop-ref-node (n v)
3956 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3957 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3959 (defun js2-print-xml-prop-ref-node (n i)
3960 (insert (js2-make-pad i))
3961 (if (js2-xml-ref-node-attr-access-p n)
3963 (when (js2-xml-prop-ref-node-namespace n)
3964 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3966 (if (js2-xml-prop-ref-node-propname n)
3967 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3969 (defstruct (js2-xml-elem-ref-node
3970 (:include js2-xml-ref-node)
3972 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3981 "AST node for an E4X XML [expr] member-ref expression.
3984 [ '@' ] [ name '::' ] '[' expr ']'
3986 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3988 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3989 is not a legal E4X XML element-ref expression, since it's already used
3990 for standard JavaScript element-get array indexing. Hence, a
3991 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3992 non-nil namespace node, or both.
3994 The node starts at the @ token, if present. Otherwise it starts
3995 at the namespace name. The node bounds extend through the closing
3996 right-bracket, or if it is missing due to a syntax error, through the
3997 end of the index expression."
3998 expr ; the bracketed index expression
4002 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4003 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4005 (defun js2-visit-xml-elem-ref-node (n v)
4006 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4007 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4009 (defun js2-print-xml-elem-ref-node (n i)
4010 (insert (js2-make-pad i))
4011 (if (js2-xml-ref-node-attr-access-p n)
4013 (when (js2-xml-elem-ref-node-namespace n)
4014 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4017 (if (js2-xml-elem-ref-node-expr n)
4018 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4021 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4023 (defstruct (js2-xml-start-tag-node
4024 (:include js2-xml-node)
4026 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4033 "AST node for an XML start-tag. Not currently used.
4034 The `kids' field is a lisp list of child content nodes."
4035 name ; a `js2-xml-name-node'
4036 attrs ; a lisp list of `js2-xml-attr-node'
4037 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4039 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4040 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4042 (defun js2-visit-xml-start-tag (n v)
4043 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4044 (dolist (attr (js2-xml-start-tag-node-attrs n))
4045 (js2-visit-ast attr v))
4046 (js2-visit-block n v))
4048 (defun js2-print-xml-start-tag (n i)
4049 (insert (js2-make-pad i) "<")
4050 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4051 (when (js2-xml-start-tag-node-attrs n)
4053 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4056 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4057 ;; and add the end-tag to the kids list of the parent as well.
4058 (defstruct (js2-xml-end-tag-node
4059 (:include js2-xml-node)
4061 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4065 "AST node for an XML end-tag. Not currently used."
4066 name) ; a `js2-xml-name-node'
4068 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4069 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4071 (defun js2-visit-xml-end-tag (n v)
4072 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4074 (defun js2-print-xml-end-tag (n i)
4075 (insert (js2-make-pad i))
4077 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4080 (defstruct (js2-xml-name-node
4081 (:include js2-xml-node)
4083 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4088 "AST node for an E4X XML name. Not currently used.
4089 Any XML name can be qualified with a namespace, hence the namespace field.
4090 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4091 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4092 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4093 namespace) ; a `js2-string-node'
4095 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4096 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4098 (defun js2-visit-xml-name-node (n v)
4099 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4101 (defun js2-print-xml-name-node (n i)
4102 (insert (js2-make-pad i))
4103 (when (js2-xml-name-node-namespace n)
4104 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4106 (dolist (kid (js2-xml-name-node-kids n))
4107 (js2-print-ast kid 0)))
4109 (defstruct (js2-xml-pi-node
4110 (:include js2-xml-node)
4112 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4117 "AST node for an E4X XML processing instruction. Not currently used."
4118 name ; a `js2-xml-name-node'
4119 attrs) ; a list of `js2-xml-attr-node'
4121 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4122 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4124 (defun js2-visit-xml-pi-node (n v)
4125 (js2-visit-ast (js2-xml-pi-node-name n) v)
4126 (dolist (attr (js2-xml-pi-node-attrs n))
4127 (js2-visit-ast attr v)))
4129 (defun js2-print-xml-pi-node (n i)
4130 (insert (js2-make-pad i) "<?")
4131 (js2-print-ast (js2-xml-pi-node-name n))
4132 (when (js2-xml-pi-node-attrs n)
4134 (js2-print-list (js2-xml-pi-node-attrs n)))
4137 (defstruct (js2-xml-cdata-node
4138 (:include js2-xml-node)
4140 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4144 "AST node for a CDATA escape section. Not currently used."
4145 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4147 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4148 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4150 (defun js2-visit-xml-cdata-node (n v)
4151 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4153 (defun js2-print-xml-cdata-node (n i)
4154 (insert (js2-make-pad i))
4155 (js2-print-ast (js2-xml-cdata-node-content n)))
4157 (defstruct (js2-xml-attr-node
4158 (:include js2-xml-node)
4160 (:constructor make-js2-attr-node (&key (type js2-XML)
4167 "AST node representing a foo='bar' XML attribute value. Not yet used."
4168 name ; a `js2-xml-name-node'
4169 value ; a `js2-xml-name-node'
4170 eq-pos ; buffer position of "=" sign
4171 quote-type) ; 'single or 'double
4173 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4174 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4176 (defun js2-visit-xml-attr-node (n v)
4177 (js2-visit-ast (js2-xml-attr-node-name n) v)
4178 (js2-visit-ast (js2-xml-attr-node-value n) v))
4180 (defun js2-print-xml-attr-node (n i)
4181 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4184 (insert (js2-make-pad i))
4185 (js2-print-ast (js2-xml-attr-node-name n) 0)
4187 (js2-print-ast (js2-xml-attr-node-value n) 0)
4190 (defstruct (js2-xml-text-node
4191 (:include js2-xml-node)
4193 (:constructor make-js2-text-node (&key (type js2-XML)
4197 "AST node for an E4X XML text node. Not currently used."
4198 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4200 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4201 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4203 (defun js2-visit-xml-text-node (n v)
4204 (js2-visit-ast (js2-xml-text-node-content n) v))
4206 (defun js2-print-xml-text-node (n i)
4207 (insert (js2-make-pad i))
4208 (dolist (kid (js2-xml-text-node-content n))
4209 (js2-print-ast kid)))
4211 (defstruct (js2-xml-comment-node
4212 (:include js2-xml-node)
4214 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4217 "AST node for E4X XML comment. Not currently used.")
4219 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4220 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4222 (defun js2-print-xml-comment (n i)
4223 (insert (js2-make-pad i)
4224 (js2-node-string n)))
4228 (defsubst js2-node-line (n)
4229 "Fetch the source line number at the start of node N.
4230 This is O(n) in the length of the source buffer; use prudently."
4231 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4233 (defsubst js2-block-node-kid (n i)
4234 "Return child I of node N, or nil if there aren't that many."
4235 (nth i (js2-block-node-kids n)))
4237 (defsubst js2-block-node-first (n)
4238 "Return first child of block node N, or nil if there is none."
4239 (first (js2-block-node-kids n)))
4241 (defun js2-node-root (n)
4242 "Return the root of the AST containing N.
4243 If N has no parent pointer, returns N."
4244 (let ((parent (js2-node-parent n)))
4246 (js2-node-root parent)
4249 (defun js2-node-position-in-parent (node &optional parent)
4250 "Return the position of NODE in parent's block-kids list.
4251 PARENT can be supplied if known. Positioned returned is zero-indexed.
4252 Returns 0 if NODE is not a child of a block statement, or if NODE
4253 is not a statement node."
4254 (let ((p (or parent (js2-node-parent node)))
4256 (if (not (js2-block-node-p p))
4258 (or (js2-position node (js2-block-node-kids p))
4261 (defsubst js2-node-short-name (n)
4262 "Return the short name of node N as a string, e.g. `js2-if-node'."
4263 (substring (symbol-name (aref n 0))
4264 (length "cl-struct-")))
4266 (defsubst js2-node-child-list (node)
4267 "Return the child list for NODE, a lisp list of nodes.
4268 Works for block nodes, array nodes, obj literals, funarg lists,
4269 var decls and try nodes (for catch clauses). Note that you should call
4270 `js2-block-node-kids' on the function body for the body statements.
4271 Returns nil for zero-length child lists or unsupported nodes."
4273 ((js2-function-node-p node)
4274 (js2-function-node-params node))
4275 ((js2-block-node-p node)
4276 (js2-block-node-kids node))
4277 ((js2-try-node-p node)
4278 (js2-try-node-catch-clauses node))
4279 ((js2-array-node-p node)
4280 (js2-array-node-elems node))
4281 ((js2-object-node-p node)
4282 (js2-object-node-elems node))
4283 ((js2-call-node-p node)
4284 (js2-call-node-args node))
4285 ((js2-new-node-p node)
4286 (js2-new-node-args node))
4287 ((js2-var-decl-node-p node)
4288 (js2-var-decl-node-kids node))
4292 (defsubst js2-node-set-child-list (node kids)
4293 "Set the child list for NODE to KIDS."
4295 ((js2-function-node-p node)
4296 (setf (js2-function-node-params node) kids))
4297 ((js2-block-node-p node)
4298 (setf (js2-block-node-kids node) kids))
4299 ((js2-try-node-p node)
4300 (setf (js2-try-node-catch-clauses node) kids))
4301 ((js2-array-node-p node)
4302 (setf (js2-array-node-elems node) kids))
4303 ((js2-object-node-p node)
4304 (setf (js2-object-node-elems node) kids))
4305 ((js2-call-node-p node)
4306 (setf (js2-call-node-args node) kids))
4307 ((js2-new-node-p node)
4308 (setf (js2-new-node-args node) kids))
4309 ((js2-var-decl-node-p node)
4310 (setf (js2-var-decl-node-kids node) kids))
4312 (error "Unsupported node type: %s" (js2-node-short-name node))))
4315 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4316 (defconst js2-paren-expr-nodes
4317 '(cl-struct-js2-array-comp-loop-node
4318 cl-struct-js2-array-comp-node
4319 cl-struct-js2-call-node
4320 cl-struct-js2-catch-node
4321 cl-struct-js2-do-node
4322 cl-struct-js2-elem-get-node
4323 cl-struct-js2-for-in-node
4324 cl-struct-js2-for-node
4325 cl-struct-js2-function-node
4326 cl-struct-js2-if-node
4327 cl-struct-js2-let-node
4328 cl-struct-js2-new-node
4329 cl-struct-js2-paren-node
4330 cl-struct-js2-switch-node
4331 cl-struct-js2-while-node
4332 cl-struct-js2-with-node
4333 cl-struct-js2-xml-dot-query-node)
4334 "Node types that can have a parenthesized child expression.
4335 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4337 (defsubst js2-paren-expr-node-p (node)
4338 "Return t for nodes that typically have a parenthesized child expression.
4339 Useful for computing the indentation anchors for arg-lists and conditions.
4340 Note that it may return a false positive, for instance when NODE is
4341 a `js2-new-node' and there are no arguments or parentheses."
4342 (memq (aref node 0) js2-paren-expr-nodes))
4344 ;; Fake polymorphism... yech.
4345 (defsubst js2-node-lp (node)
4346 "Return relative left-paren position for NODE, if applicable.
4347 For `js2-elem-get-node' structs, returns left-bracket position.
4348 Note that the position may be nil in the case of a parse error."
4350 ((js2-elem-get-node-p node)
4351 (js2-elem-get-node-lb node))
4352 ((js2-loop-node-p node)
4353 (js2-loop-node-lp node))
4354 ((js2-function-node-p node)
4355 (js2-function-node-lp node))
4356 ((js2-if-node-p node)
4357 (js2-if-node-lp node))
4358 ((js2-new-node-p node)
4359 (js2-new-node-lp node))
4360 ((js2-call-node-p node)
4361 (js2-call-node-lp node))
4362 ((js2-paren-node-p node)
4363 (js2-node-pos node))
4364 ((js2-switch-node-p node)
4365 (js2-switch-node-lp node))
4366 ((js2-catch-node-p node)
4367 (js2-catch-node-lp node))
4368 ((js2-let-node-p node)
4369 (js2-let-node-lp node))
4370 ((js2-array-comp-node-p node)
4371 (js2-array-comp-node-lp node))
4372 ((js2-with-node-p node)
4373 (js2-with-node-lp node))
4374 ((js2-xml-dot-query-node-p node)
4375 (1+ (js2-infix-node-op-pos node)))
4377 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4379 ;; Fake polymorphism... blech.
4380 (defsubst js2-node-rp (node)
4381 "Return relative right-paren position for NODE, if applicable.
4382 For `js2-elem-get-node' structs, returns right-bracket position.
4383 Note that the position may be nil in the case of a parse error."
4385 ((js2-elem-get-node-p node)
4386 (js2-elem-get-node-lb node))
4387 ((js2-loop-node-p node)
4388 (js2-loop-node-rp node))
4389 ((js2-function-node-p node)
4390 (js2-function-node-rp node))
4391 ((js2-if-node-p node)
4392 (js2-if-node-rp node))
4393 ((js2-new-node-p node)
4394 (js2-new-node-rp node))
4395 ((js2-call-node-p node)
4396 (js2-call-node-rp node))
4397 ((js2-paren-node-p node)
4398 (+ (js2-node-pos node) (js2-node-len node)))
4399 ((js2-switch-node-p node)
4400 (js2-switch-node-rp node))
4401 ((js2-catch-node-p node)
4402 (js2-catch-node-rp node))
4403 ((js2-let-node-p node)
4404 (js2-let-node-rp node))
4405 ((js2-array-comp-node-p node)
4406 (js2-array-comp-node-rp node))
4407 ((js2-with-node-p node)
4408 (js2-with-node-rp node))
4409 ((js2-xml-dot-query-node-p node)
4410 (1+ (js2-xml-dot-query-node-rp node)))
4412 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4414 (defsubst js2-node-first-child (node)
4415 "Returns the first element of `js2-node-child-list' for NODE."
4416 (car (js2-node-child-list node)))
4418 (defsubst js2-node-last-child (node)
4419 "Returns the last element of `js2-node-last-child' for NODE."
4420 (car (last (js2-node-child-list node))))
4422 (defun js2-node-prev-sibling (node)
4423 "Return the previous statement in parent.
4424 Works for parents supported by `js2-node-child-list'.
4425 Returns nil if NODE is not in the parent, or PARENT is
4426 not a supported node, or if NODE is the first child."
4427 (let* ((p (js2-node-parent node))
4428 (kids (js2-node-child-list p))
4431 (not (eq node (cadr kids))))
4432 (setq kids (cdr kids)
4436 (defun js2-node-next-sibling (node)
4437 "Return the next statement in parent block.
4438 Returns nil if NODE is not in the block, or PARENT is not
4439 a block node, or if NODE is the last statement."
4440 (let* ((p (js2-node-parent node))
4441 (kids (js2-node-child-list p)))
4443 (not (eq node (car kids))))
4444 (setq kids (cdr kids)))
4447 (defun js2-node-find-child-before (pos parent &optional after)
4448 "Find the last child that starts before POS in parent.
4449 If AFTER is non-nil, returns first child starting after POS.
4450 POS is an absolute buffer position. PARENT is any node
4451 supported by `js2-node-child-list'.
4452 Returns nil if no applicable child is found."
4453 (let ((kids (if (js2-function-node-p parent)
4454 (js2-block-node-kids (js2-function-node-body parent))
4455 (js2-node-child-list parent)))
4456 (beg (if (js2-function-node-p parent)
4457 (js2-node-abs-pos (js2-function-node-body parent))
4458 (js2-node-abs-pos parent)))
4463 (setq fn (if after '> '<))
4464 (while (and kids continue)
4465 (setq kid (car kids))
4466 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4468 continue (if after nil t))
4469 (setq continue (if after t nil)))
4470 (setq kids (cdr kids)))
4473 (defun js2-node-find-child-after (pos parent)
4474 "Find first child that starts after POS in parent.
4475 POS is an absolute buffer position. PARENT is any node
4476 supported by `js2-node-child-list'.
4477 Returns nil if no applicable child is found."
4478 (js2-node-find-child-before pos parent 'after))
4480 (defun js2-node-replace-child (pos parent new-node)
4481 "Replace node at index POS in PARENT with NEW-NODE.
4482 Only works for parents supported by `js2-node-child-list'."
4483 (let ((kids (js2-node-child-list parent))
4486 (setq kids (cdr kids)
4488 (setcar kids new-node)
4489 (js2-node-add-children parent new-node)))
4491 (defun js2-node-buffer (n)
4492 "Return the buffer associated with AST N.
4493 Returns nil if the buffer is not set as a property on the root
4494 node, or if parent links were not recorded during parsing."
4495 (let ((root (js2-node-root n)))
4497 (js2-ast-root-p root)
4498 (js2-ast-root-buffer root))))
4500 (defsubst js2-block-node-push (n kid)
4501 "Push js2-node KID onto the end of js2-block-node N's child list.
4502 KID is always added to the -end- of the kids list.
4503 Function also calls `js2-node-add-children' to add the parent link."
4504 (let ((kids (js2-node-child-list n)))
4506 (setcdr kids (nconc (cdr kids) (list kid)))
4507 (js2-node-set-child-list n (list kid)))
4508 (js2-node-add-children n kid)))
4510 (defun js2-node-string (node)
4511 (let ((buf (js2-node-buffer node))
4514 (error "No buffer available for node %s" node))
4517 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4518 (+ pos (js2-node-len node))))))
4520 ;; Container for storing the node we're looking for in a traversal.
4521 (js2-deflocal js2-discovered-node nil)
4523 ;; Keep track of absolute node position during traversals.
4524 (js2-deflocal js2-visitor-offset nil)
4526 (js2-deflocal js2-node-search-point nil)
4528 (when js2-mode-dev-mode-p
4529 (defun js2-find-node-at-point ()
4531 (let ((node (js2-node-at-point)))
4532 (message "%s" (or node "No node found at point"))))
4533 (defun js2-node-name-at-point ()
4535 (let ((node (js2-node-at-point)))
4536 (message "%s" (if node
4537 (js2-node-short-name node)
4538 "No node found at point.")))))
4540 (defun js2-node-at-point (&optional pos skip-comments)
4541 "Return AST node at POS, a buffer position, defaulting to current point.
4542 The `js2-mode-ast' variable must be set to the current parse tree.
4543 Signals an error if the AST (`js2-mode-ast') is nil.
4544 Always returns a node - if it can't find one, it returns the root.
4545 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4546 (let ((ast js2-mode-ast)
4549 (error "No JavaScript AST available"))
4550 ;; Look through comments first, since they may be inside nodes that
4551 ;; would otherwise report a match.
4552 (setq pos (or pos (point))
4553 result (if (> pos (js2-node-abs-end ast))
4555 (if (not skip-comments)
4556 (js2-comment-at-point pos))))
4558 (setq js2-discovered-node nil
4559 js2-visitor-offset 0
4560 js2-node-search-point pos)
4562 (catch 'js2-visit-done
4563 (js2-visit-ast ast #'js2-node-at-point-visitor))
4564 (setq js2-visitor-offset nil
4565 js2-node-search-point nil))
4566 (setq result js2-discovered-node))
4567 ;; may have found a comment beyond end of last child node,
4568 ;; since visiting the ast-root looks at the comment-list last.
4569 (if (and skip-comments
4570 (js2-comment-node-p result))
4572 (or result js2-mode-ast)))
4574 (defun js2-node-at-point-visitor (node end-p)
4575 (let ((rel-pos (js2-node-pos node))
4578 (point js2-node-search-point))
4581 ;; this evaluates to a non-nil return value, even if it's zero
4582 (decf js2-visitor-offset rel-pos))
4583 ;; we already looked for comments before visiting, and don't want them now
4584 ((js2-comment-node-p node)
4587 (setq abs-pos (incf js2-visitor-offset rel-pos)
4588 ;; we only want to use the node if the point is before
4589 ;; the last character position in the node, so we decrement
4590 ;; the absolute end by 1.
4591 abs-end (+ abs-pos (js2-node-len node) -1))
4593 ;; If this node starts after search-point, stop the search.
4595 (throw 'js2-visit-done nil))
4596 ;; If this node ends before the search-point, don't check kids.
4600 ;; Otherwise point is within this node, possibly in a child.
4601 (setq js2-discovered-node node)
4602 t)))))) ; keep processing kids to look for more specific match
4604 (defsubst js2-block-comment-p (node)
4605 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4606 (and (js2-comment-node-p node)
4607 (memq (js2-comment-node-format node) '(jsdoc block))))
4609 ;; TODO: put the comments in a vector and binary-search them instead
4610 (defun js2-comment-at-point (&optional pos)
4611 "Look through scanned comment nodes for one containing POS.
4612 POS is a buffer position that defaults to current point.
4613 Function returns nil if POS was not in any comment node."
4614 (let ((ast js2-mode-ast)
4615 (x (or pos (point)))
4619 (error "No JavaScript AST available"))
4621 ;; Comments are stored in lexical order.
4622 (dolist (comment (js2-ast-root-comments ast) nil)
4623 (setq beg (js2-node-abs-pos comment)
4624 end (+ beg (js2-node-len comment)))
4627 (throw 'done comment))))))
4629 (defun js2-mode-find-parent-fn (node)
4630 "Find function enclosing NODE.
4631 Returns nil if NODE is not inside a function."
4632 (setq node (js2-node-parent node))
4633 (while (and node (not (js2-function-node-p node)))
4634 (setq node (js2-node-parent node)))
4635 (and (js2-function-node-p node) node))
4637 (defun js2-mode-find-enclosing-fn (node)
4638 "Find function or root enclosing NODE."
4639 (if (js2-ast-root-p node)
4641 (setq node (js2-node-parent node))
4642 (while (not (or (js2-ast-root-p node)
4643 (js2-function-node-p node)))
4644 (setq node (js2-node-parent node)))
4647 (defun js2-mode-find-enclosing-node (beg end)
4648 "Find script or function fully enclosing BEG and END."
4649 (let ((node (js2-node-at-point beg))
4653 (if (or (js2-ast-root-p node)
4654 (and (js2-function-node-p node)
4655 (<= (setq pos (js2-node-abs-pos node)) beg)
4656 (>= (+ pos (js2-node-len node)) end)))
4658 (setq node (js2-node-parent node))))
4661 (defun js2-node-parent-script-or-fn (node)
4662 "Find script or function immediately enclosing NODE.
4663 If NODE is the ast-root, returns nil."
4664 (if (js2-ast-root-p node)
4666 (setq node (js2-node-parent node))
4667 (while (and node (not (or (js2-function-node-p node)
4668 (js2-script-node-p node))))
4669 (setq node (js2-node-parent node)))
4672 (defsubst js2-nested-function-p (node)
4673 "Return t if NODE is a nested function, or is inside a nested function."
4674 (unless (js2-ast-root-p node)
4675 (js2-function-node-p (if (js2-function-node-p node)
4676 (js2-node-parent-script-or-fn node)
4677 (js2-node-parent-script-or-fn
4678 (js2-node-parent-script-or-fn node))))))
4680 (defsubst js2-function-param-node-p (node)
4681 "Return non-nil if NODE is a param node of a `js2-function-node'."
4682 (let ((parent (js2-node-parent node)))
4684 (js2-function-node-p parent)
4685 (memq node (js2-function-node-params parent)))))
4687 (defsubst js2-mode-shift-kids (kids start offset)
4689 (if (> (js2-node-pos kid) start)
4690 (incf (js2-node-pos kid) offset))))
4692 (defsubst js2-mode-shift-children (parent start offset)
4693 "Update start-positions of all children of PARENT beyond START."
4694 (let ((root (js2-node-root parent)))
4695 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4696 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4698 (defsubst js2-node-is-descendant (node ancestor)
4699 "Return t if NODE is a descendant of ANCESTOR."
4701 (not (eq node ancestor)))
4702 (setq node (js2-node-parent node)))
4705 ;;; visitor infrastructure
4707 (defun js2-visit-none (node callback)
4708 "Visitor for AST node that have no node children."
4711 (defun js2-print-none (node indent)
4712 "Visitor for AST node with no printed representation.")
4714 (defun js2-print-body (node indent)
4715 "Print a statement, or a block without braces."
4716 (if (js2-block-node-p node)
4717 (dolist (kid (js2-block-node-kids node))
4718 (js2-print-ast kid indent))
4719 (js2-print-ast node indent)))
4721 (defun js2-print-list (args &optional delimiter)
4722 (loop with len = (length args)
4726 (js2-print-ast arg 0)
4728 (insert (or delimiter ", ")))))
4730 (defun js2-print-tree (ast)
4731 "Prints an AST to the current buffer.
4732 Makes `js2-ast-parent-nodes' available to the printer functions."
4733 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4734 (js2-print-ast ast)))
4736 (defun js2-print-ast (node &optional indent)
4737 "Helper function for printing AST nodes.
4738 Requires `js2-ast-parent-nodes' to be non-nil.
4739 You should use `js2-print-tree' instead of this function."
4740 (let ((printer (get (aref node 0) 'js2-printer))
4742 (pos (js2-node-abs-pos node)))
4743 ;; TODO: wedge comments in here somewhere
4745 (funcall printer node i))))
4747 (defconst js2-side-effecting-tokens
4748 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4749 (dolist (tt (list js2-ASSIGN
4818 (if js2-instanceof-has-side-effects
4819 (aset tokens js2-INSTANCEOF t))
4822 (defun js2-node-has-side-effects (node)
4823 "Return t if NODE has side effects."
4824 (when node ; makes it easier to handle malformed expressions
4825 (let ((tt (js2-node-type node)))
4827 ;; This doubtless needs some work, since EXPR_VOID is used
4828 ;; in several ways in Rhino, and I may not have caught them all.
4829 ;; I'll wait for people to notice incorrect warnings.
4830 ((and (= tt js2-EXPR_VOID)
4831 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4832 (let ((expr (js2-expr-stmt-node-expr node)))
4833 (or (js2-node-has-side-effects expr)
4834 (when (js2-string-node-p expr)
4835 (string= "use strict" (js2-string-node-value expr))))))
4837 (js2-node-has-side-effects (js2-infix-node-right node)))
4840 (or (js2-node-has-side-effects (js2-infix-node-right node))
4841 (js2-node-has-side-effects (js2-infix-node-left node))))
4843 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4844 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4845 ((js2-paren-node-p node)
4846 (js2-node-has-side-effects (js2-paren-node-expr node)))
4847 ((= tt js2-ERROR) ; avoid cascaded error messages
4850 (aref js2-side-effecting-tokens tt))))))
4852 (defun js2-member-expr-leftmost-name (node)
4853 "For an expr such as foo.bar.baz, return leftmost node foo.
4854 NODE is any `js2-node' object. If it represents a member expression,
4855 which is any sequence of property gets, element-gets, function calls,
4856 or xml descendants/filter operators, then we look at the lexically
4857 leftmost (first) node in the chain. If it is a name-node we return it.
4858 Note that NODE can be a raw name-node and it will be returned as well.
4859 If NODE is not a name-node or member expression, or if it is a member
4860 expression whose leftmost target is not a name node, returns nil."
4863 (while (and continue (not result))
4865 ((js2-name-node-p node)
4867 ((js2-prop-get-node-p node)
4868 (setq node (js2-prop-get-node-left node)))
4869 ;; TODO: handle call-nodes, xml-nodes, others?
4871 (setq continue nil))))
4874 (defconst js2-stmt-node-types
4878 js2-DEFAULT ; e4x "default xml namespace" statement
4890 "Node types that only appear in statement contexts.
4891 The list does not include nodes that always appear as the child
4892 of another specific statement type, such as switch-cases,
4893 catch and finally blocks, and else-clauses. The list also excludes
4894 nodes like yield, let and var, which may appear in either expression
4895 or statement context, and in the latter context always have a
4896 `js2-expr-stmt-node' parent. Finally, the list does not include
4897 functions or scripts, which are treated separately from statements
4898 by the JavaScript parser and runtime.")
4900 (defun js2-stmt-node-p (node)
4901 "Heuristic for figuring out if NODE is a statement.
4902 Some node types can appear in either an expression context or a
4903 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4904 For these node types in a statement context, the parent will be a
4905 `js2-expr-stmt-node'.
4906 Functions aren't included in the check."
4907 (memq (js2-node-type node) js2-stmt-node-types))
4909 (defsubst js2-mode-find-first-stmt (node)
4910 "Search upward starting from NODE looking for a statement.
4911 For purposes of this function, a `js2-function-node' counts."
4912 (while (not (or (js2-stmt-node-p node)
4913 (js2-function-node-p node)))
4914 (setq node (js2-node-parent node)))
4917 (defun js2-node-parent-stmt (node)
4918 "Return the node's first ancestor that is a statement.
4919 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4920 appearing in a statement context will have a parent that is a
4921 `js2-expr-stmt-node' that will be returned by this function."
4922 (let ((parent (js2-node-parent node)))
4923 (if (or (null parent)
4924 (js2-stmt-node-p parent)
4925 (and (js2-function-node-p parent)
4926 (not (eq (js2-function-node-form parent)
4927 'FUNCTION_EXPRESSION))))
4929 (js2-node-parent-stmt parent))))
4931 ;; In the Mozilla Rhino sources, Roshan James writes:
4932 ;; Does consistent-return analysis on the function body when strict mode is
4935 ;; function (x) { return (x+1) }
4939 ;; function (x) { if (x < 0) return (x+1); }
4941 ;; is not because the function can potentially return a value when the
4942 ;; condition is satisfied and if not, the function does not explicitly
4945 ;; This extends to checking mismatches such as "return" and "return <value>"
4946 ;; used in the same function. Warnings are not emitted if inconsistent
4947 ;; returns exist in code that can be statically shown to be unreachable.
4949 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4951 ;; emits no warning. However if the loop had a break statement, then a
4952 ;; warning would be emitted.
4954 ;; The consistency analysis looks at control structures such as loops, ifs,
4955 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4956 ;; warns the user about an inconsistent set of termination possibilities.
4958 ;; These flags enumerate the possible ways a statement/function can
4959 ;; terminate. These flags are used by endCheck() and by the Parser to
4960 ;; detect inconsistent return usage.
4962 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4963 ;; able to execute (example: throw, continue)
4965 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4966 ;; next one. Statement such as return dont. A compound statement may have
4967 ;; some branch that drops off control to the next statement.
4969 ;; END_RETURNS indicates that the statement can return with no value.
4970 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4972 ;; A compound statement such as
4976 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4978 (defconst js2-END_UNREACHED 0)
4979 (defconst js2-END_DROPS_OFF 1)
4980 (defconst js2-END_RETURNS 2)
4981 (defconst js2-END_RETURNS_VALUE 4)
4982 (defconst js2-END_YIELDS 8)
4984 (defun js2-has-consistent-return-usage (node)
4985 "Check that every return usage in a function body is consistent.
4986 Returns t if the function satisfies strict mode requirement."
4987 (let ((n (js2-end-check node)))
4988 ;; either it doesn't return a value in any branch...
4989 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4990 ;; or it returns a value (or is unreached) at every branch
4991 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4995 (defun js2-end-check-if (node)
4996 "Returns in the then and else blocks must be consistent with each other.
4997 If there is no else block, then the return statement can fall through.
4998 Returns logical OR of END_* flags"
4999 (let ((th (js2-if-node-then-part node))
5000 (el (js2-if-node-else-part node)))
5003 (logior (js2-end-check th) (if el
5005 js2-END_DROPS_OFF)))))
5007 (defun js2-end-check-switch (node)
5008 "Consistency of return statements is checked between the case statements.
5009 If there is no default, then the switch can fall through. If there is a
5010 default, we check to see if all code paths in the default return or if
5011 there is a code path that can fall through.
5012 Returns logical OR of END_* flags."
5013 (let ((rv js2-END_UNREACHED)
5015 ;; examine the cases
5017 (dolist (c (js2-switch-node-cases node))
5018 (if (js2-case-node-expr c)
5019 (js2-set-flag rv (js2-end-check-block c))
5020 (setq default-case c)
5021 (throw 'break nil))))
5022 ;; we don't care how the cases drop into each other
5023 (js2-clear-flag rv js2-END_DROPS_OFF)
5024 ;; examine the default
5025 (js2-set-flag rv (if default-case
5026 (js2-end-check default-case)
5030 (defun js2-end-check-try (node)
5031 "If the block has a finally, return consistency is checked in the
5032 finally block. If all code paths in the finally return, then the
5033 returns in the try-catch blocks don't matter. If there is a code path
5034 that does not return or if there is no finally block, the returns
5035 of the try and catch blocks are checked for mismatch.
5036 Returns logical OR of END_* flags."
5037 (let ((finally (js2-try-node-finally-block node))
5039 ;; check the finally if it exists
5040 (setq rv (if finally
5041 (js2-end-check (js2-finally-node-body finally))
5043 ;; If the finally block always returns, then none of the returns
5044 ;; in the try or catch blocks matter.
5045 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5046 (js2-clear-flag rv js2-END_DROPS_OFF)
5047 ;; examine the try block
5048 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5049 ;; check each catch block
5050 (dolist (cb (js2-try-node-catch-clauses node))
5051 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5054 (defun js2-end-check-loop (node)
5055 "Return statement in the loop body must be consistent. The default
5056 assumption for any kind of a loop is that it will eventually terminate.
5057 The only exception is a loop with a constant true condition. Code that
5058 follows such a loop is examined only if one can statically determine
5059 that there is a break out of the loop.
5061 for(... ; ... ; ...) {}
5066 Returns logical OR of END_* flags."
5067 (let ((rv (js2-end-check (js2-loop-node-body node)))
5069 ((js2-while-node-p node)
5070 (js2-while-node-condition node))
5071 ((js2-do-node-p node)
5072 (js2-do-node-condition node))
5073 ((js2-for-node-p node)
5074 (js2-for-node-condition node)))))
5076 ;; check to see if the loop condition is always true
5078 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5079 (js2-clear-flag rv js2-END_DROPS_OFF))
5081 ;; look for effect of breaks
5082 (js2-set-flag rv (js2-node-get-prop node
5087 (defun js2-end-check-block (node)
5088 "A general block of code is examined statement by statement.
5089 If any statement (even a compound one) returns in all branches, then
5090 subsequent statements are not examined.
5091 Returns logical OR of END_* flags."
5092 (let* ((rv js2-END_DROPS_OFF)
5093 (kids (js2-block-node-kids node))
5095 ;; Check each statment. If the statement can continue onto the next
5096 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5097 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5098 (js2-clear-flag rv js2-END_DROPS_OFF)
5099 (js2-set-flag rv (js2-end-check n))
5100 (setq kids (cdr kids)
5104 (defun js2-end-check-label (node)
5105 "A labeled statement implies that there may be a break to the label.
5106 The function processes the labeled statement and then checks the
5107 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5109 Returns logical OR of END_* flags."
5110 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5111 (logior rv (js2-node-get-prop node
5113 js2-END_UNREACHED))))
5115 (defun js2-end-check-break (node)
5116 "When a break is encountered annotate the statement being broken
5117 out of by setting its CONTROL_BLOCK_PROP property.
5118 Returns logical OR of END_* flags."
5119 (and (js2-break-node-target node)
5120 (js2-node-set-prop (js2-break-node-target node)
5125 (defun js2-end-check (node)
5126 "Examine the body of a function, doing a basic reachability analysis.
5127 Returns a combination of flags END_* flags that indicate
5128 how the function execution can terminate. These constitute only the
5129 pessimistic set of termination conditions. It is possible that at
5130 runtime certain code paths will never be actually taken. Hence this
5131 analysis will flag errors in cases where there may not be errors.
5132 Returns logical OR of END_* flags"
5135 ((js2-break-node-p node)
5136 (js2-end-check-break node))
5137 ((js2-expr-stmt-node-p node)
5138 (if (setq kid (js2-expr-stmt-node-expr node))
5141 ((or (js2-continue-node-p node)
5142 (js2-throw-node-p node))
5144 ((js2-return-node-p node)
5145 (if (setq kid (js2-return-node-retval node))
5146 js2-END_RETURNS_VALUE
5148 ((js2-loop-node-p node)
5149 (js2-end-check-loop node))
5150 ((js2-switch-node-p node)
5151 (js2-end-check-switch node))
5152 ((js2-labeled-stmt-node-p node)
5153 (js2-end-check-label node))
5154 ((js2-if-node-p node)
5155 (js2-end-check-if node))
5156 ((js2-try-node-p node)
5157 (js2-end-check-try node))
5158 ((js2-block-node-p node)
5159 (if (null (js2-block-node-kids node))
5161 (js2-end-check-block node)))
5162 ((js2-yield-node-p node)
5165 js2-END_DROPS_OFF))))
5167 (defun js2-always-defined-boolean-p (node)
5168 "Check if NODE always evaluates to true or false in boolean context.
5169 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5171 (let ((tt (js2-node-type node))
5174 ((or (= tt js2-FALSE) (= tt js2-NULL))
5179 (setq num (js2-number-node-num-value node))
5180 (if (and (not (eq num 0.0e+NaN))
5187 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5188 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5190 (defvar js2-tokens nil
5191 "List of all defined token names.") ; initialized in `js2-token-names'
5193 (defconst js2-token-names
5194 (let* ((names (make-vector js2-num-tokens -1))
5195 (case-fold-search nil) ; only match js2-UPPER_CASE
5196 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5197 (loop for sym in syms
5200 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5202 (aset names (symbol-value sym) ; code, e.g. 152
5203 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5204 (push sym js2-tokens)))
5206 "Vector mapping int values to token string names, sans `js2-' prefix.")
5208 (defun js2-token-name (tok)
5209 "Return a string name for TOK, a token symbol or code.
5210 Signals an error if it's not a recognized token."
5213 (setq code (symbol-value tok)))
5216 (if (and (numberp code)
5218 (< code js2-num-tokens))
5219 (aref js2-token-names code)
5220 (error "Invalid token: %s" code)))))
5222 (defsubst js2-token-sym (tok)
5223 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5224 (intern (js2-token-name tok)))
5226 (defconst js2-token-codes
5227 (let ((table (make-hash-table :test 'eq :size 256)))
5228 (loop for name across js2-token-names
5229 for sym = (intern (concat "js2-" name))
5231 (puthash sym (symbol-value sym) table))
5232 ;; clean up a few that are "wrong" in Rhino's token codes
5233 (puthash 'js2-DELETE js2-DELPROP table)
5235 "Hashtable mapping token symbols to their bytecodes.")
5237 (defsubst js2-token-code (sym)
5238 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5239 (or (gethash sym js2-token-codes)
5240 (error "Invalid token symbol: %s " sym))) ; signal code bug
5242 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5243 (setq js2-token-end js2-ts-cursor)
5244 (js2-report-error msg nil
5245 (or beg js2-token-beg)
5246 (or len (- js2-token-end js2-token-beg)))
5248 (throw 'return js2-ERROR)))
5250 (defsubst js2-get-string-from-buffer ()
5251 "Reverse the char accumulator and return it as a string."
5252 (setq js2-token-end js2-ts-cursor)
5253 (if js2-ts-string-buffer
5254 (apply #'string (nreverse js2-ts-string-buffer))
5257 ;; TODO: could potentially avoid a lot of consing by allocating a
5258 ;; char buffer the way Rhino does.
5259 (defsubst js2-add-to-string (c)
5260 (push c js2-ts-string-buffer))
5262 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5263 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5264 ;; any other character: when it's not part of the current token, we
5265 ;; unget it, allowing it to be read again by the following call.
5266 (defsubst js2-unget-char ()
5267 (decf js2-ts-cursor))
5269 ;; Rhino distinguishes \r and \n line endings. We don't need to
5270 ;; because we only scan from Emacs buffers, which always use \n.
5271 (defsubst js2-get-char ()
5272 "Read and return the next character from the input buffer.
5273 Increments `js2-ts-lineno' if the return value is a newline char.
5274 Updates `js2-ts-cursor' to the point after the returned char.
5275 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5276 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5278 ;; check for end of buffer
5279 (if (>= js2-ts-cursor (point-max))
5280 (setq js2-ts-hit-eof t
5281 js2-ts-cursor (1+ js2-ts-cursor)
5282 c js2-EOF_CHAR) ; return value
5283 ;; otherwise read next char
5284 (setq c (char-before (incf js2-ts-cursor)))
5285 ;; if we read a newline, update counters
5287 (setq js2-ts-line-start js2-ts-cursor
5288 js2-ts-lineno (1+ js2-ts-lineno)))
5289 ;; TODO: skip over format characters
5292 (defsubst js2-read-unicode-escape ()
5293 "Read a \\uNNNN sequence from the input.
5294 Assumes the ?\ and ?u have already been read.
5295 Returns the unicode character, or nil if it wasn't a valid character.
5296 Doesn't change the values of any scanner variables."
5297 ;; I really wish I knew a better way to do this, but I can't
5298 ;; find the Emacs function that takes a 16-bit int and converts
5299 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5300 ;; Have to first check that it's 4 hex characters or it may stop
5303 (let ((s (buffer-substring-no-properties js2-ts-cursor
5304 (+ 4 js2-ts-cursor))))
5305 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5306 (read (concat "?\\u" s))))))
5308 (defsubst js2-match-char (test)
5309 "Consume and return next character if it matches TEST, a character.
5310 Returns nil and consumes nothing if TEST is not the next character."
5311 (let ((c (js2-get-char)))
5317 (defsubst js2-peek-char ()
5322 (defsubst js2-java-identifier-start-p (c)
5325 (js2-char-uppercase-p c)
5326 (js2-char-lowercase-p c)))
5328 (defsubst js2-java-identifier-part-p (c)
5329 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5330 ;; TODO: make me Unicode-friendly. See comments above.
5333 (js2-char-uppercase-p c)
5334 (js2-char-lowercase-p c)
5335 (and (>= c ?0) (<= c ?9))))
5337 (defsubst js2-alpha-p (c)
5338 (cond ((and (<= ?A c) (<= c ?Z)) t)
5339 ((and (<= ?a c) (<= c ?z)) t)
5342 (defsubst js2-digit-p (c)
5343 (and (<= ?0 c) (<= c ?9)))
5345 (defsubst js2-js-space-p (c)
5347 (memq c '(#x20 #x9 #xB #xC #xD))
5350 ;; TODO: change this nil to check for Unicode space character
5353 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5355 (defsubst js2-skip-line ()
5356 "Skip to end of line"
5358 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5360 (setq js2-token-end js2-ts-cursor)))
5362 (defun js2-init-scanner (&optional buf line)
5363 "Create token stream for BUF starting on LINE.
5364 BUF defaults to current-buffer and line defaults to 1.
5366 A buffer can only have one scanner active at a time, which yields
5367 dramatically simpler code than using a defstruct. If you need to
5368 have simultaneous scanners in a buffer, copy the regions to scan
5373 (setq js2-ts-dirty-line nil
5374 js2-ts-regexp-flags nil
5379 js2-ts-lineno (or line 1)
5380 js2-ts-line-end-char -1
5381 js2-ts-cursor (point-min)
5382 js2-ts-is-xml-attribute nil
5383 js2-ts-xml-is-tag-content nil
5384 js2-ts-xml-open-tags-count 0
5385 js2-ts-string-buffer nil)))
5387 ;; This function uses the cached op, string and number fields in
5388 ;; TokenStream; if getToken has been called since the passed token
5389 ;; was scanned, the op or string printed may be incorrect.
5390 (defun js2-token-to-string (token)
5391 ;; Not sure where this function is used in Rhino. Not tested.
5392 (if (not js2-debug-print-trees)
5394 (let ((name (js2-token-name token)))
5396 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5397 (concat name " `" js2-ts-string "'"))
5398 ((eq token js2-NUMBER)
5399 (format "NUMBER %g" js2-ts-number))
5403 (defconst js2-keywords
5405 case catch const continue
5406 debugger default delete do
5408 false finally for function
5409 if in instanceof import
5414 this throw true try typeof
5419 ;; Token names aren't exactly the same as the keywords, unfortunately.
5420 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5421 (defconst js2-kwd-tokens
5422 (let ((table (make-vector js2-num-tokens nil))
5425 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5426 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5428 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5429 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5434 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5439 (aset table i 'font-lock-keyword-face))
5440 (aset table js2-STRING 'font-lock-string-face)
5441 (aset table js2-REGEXP 'font-lock-string-face)
5442 (aset table js2-COMMENT 'font-lock-comment-face)
5443 (aset table js2-THIS 'font-lock-builtin-face)
5444 (aset table js2-VOID 'font-lock-constant-face)
5445 (aset table js2-NULL 'font-lock-constant-face)
5446 (aset table js2-TRUE 'font-lock-constant-face)
5447 (aset table js2-FALSE 'font-lock-constant-face)
5449 "Vector whose values are non-nil for tokens that are keywords.
5450 The values are default faces to use for highlighting the keywords.")
5452 (defconst js2-reserved-words
5460 implements import int interface
5463 package private protected public
5464 short static super synchronized
5468 (defconst js2-keyword-names
5469 (let ((table (make-hash-table :test 'equal)))
5470 (loop for k in js2-keywords
5472 (symbol-name k) ; instanceof
5473 (intern (concat "js2-"
5474 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5477 "JavaScript keywords by name, mapped to their symbols.")
5479 (defconst js2-reserved-word-names
5480 (let ((table (make-hash-table :test 'equal)))
5481 (loop for k in js2-reserved-words
5483 (puthash (symbol-name k) 'js2-RESERVED table))
5485 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5487 (defsubst js2-collect-string (buf)
5488 "Convert BUF, a list of chars, to a string.
5489 Reverses BUF before converting."
5493 ((null buf) ; for emacs21 compat
5497 (apply #'string (nreverse buf))
5500 (defun js2-string-to-keyword (s)
5501 "Return token for S, a string, if S is a keyword or reserved word.
5502 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5503 (or (gethash s js2-keyword-names)
5504 (gethash s js2-reserved-word-names)))
5506 (defsubst js2-ts-set-char-token-bounds ()
5507 "Used when next token is one character."
5508 (setq js2-token-beg (1- js2-ts-cursor)
5509 js2-token-end js2-ts-cursor))
5511 (defsubst js2-ts-return (token)
5512 "Return an N-character TOKEN from `js2-get-token'.
5513 Updates `js2-token-end' accordingly."
5514 (setq js2-token-end js2-ts-cursor)
5515 (throw 'return token))
5517 (defsubst js2-x-digit-to-int (c accumulator)
5518 "Build up a hex number.
5519 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5520 corresponding number. Otherwise return -1."
5523 ;; Use 0..9 < A..Z < a..z
5528 (throw 'check nil)))
5532 (throw 'check nil)))
5536 (throw 'check nil))))
5538 (logior c (lsh accumulator 4))))
5540 (defun js2-get-token ()
5541 "Return next JavaScript token, an int such as js2-RETURN."
5545 is-unicode-escape-start
5559 ;; Eat whitespace, possibly sensitive to newlines.
5562 (setq c (js2-get-char))
5564 ((eq c js2-EOF_CHAR)
5565 (js2-ts-set-char-token-bounds)
5566 (throw 'return js2-EOF))
5568 (js2-ts-set-char-token-bounds)
5569 (setq js2-ts-dirty-line nil)
5570 (throw 'return js2-EOL))
5571 ((not (js2-js-space-p c))
5572 (if (/= c ?-) ; in case end of HTML comment
5573 (setq js2-ts-dirty-line t))
5574 (setq continue nil))))
5575 ;; Assume the token will be 1 char - fixed up below.
5576 (js2-ts-set-char-token-bounds)
5578 (throw 'return js2-XMLATTR))
5579 ;; identifier/keyword/instanceof?
5580 ;; watch out for starting with a <backslash>
5583 (setq c (js2-get-char))
5585 (setq identifier-start t
5586 is-unicode-escape-start t
5587 js2-ts-string-buffer nil)
5588 (setq identifier-start nil)
5592 (when (setq identifier-start (js2-java-identifier-start-p c))
5593 (setq js2-ts-string-buffer nil)
5594 (js2-add-to-string c))))
5595 (when identifier-start
5596 (setq contains-escape is-unicode-escape-start)
5599 (if is-unicode-escape-start
5600 ;; strictly speaking we should probably push-back
5601 ;; all the bad characters if the <backslash>uXXXX
5602 ;; sequence is malformed. But since there isn't a
5603 ;; correct context(is there?) for a bad Unicode
5604 ;; escape sequence in an identifier, we can report
5609 (setq c (js2-get-char)
5610 escape-val (js2-x-digit-to-int c escape-val))
5611 ;; Next check takes care of c < 0 and bad escape
5612 (if (minusp escape-val)
5613 (throw 'break nil)))
5614 (if (minusp escape-val)
5615 (js2-report-scan-error "msg.invalid.escape" t))
5616 (js2-add-to-string escape-val)
5617 (setq is-unicode-escape-start nil))
5618 (setq c (js2-get-char))
5621 (setq c (js2-get-char))
5623 (setq is-unicode-escape-start t
5625 (js2-report-scan-error "msg.illegal.character" t)))
5627 (if (or (eq c js2-EOF_CHAR)
5628 (not (js2-java-identifier-part-p c)))
5630 (js2-add-to-string c))))))
5632 (setq str (js2-get-string-from-buffer))
5633 (unless contains-escape
5634 ;; OPT we shouldn't have to make a string (object!) to
5635 ;; check if it's a keyword.
5636 ;; Return the corresponding token if it's a keyword
5637 (when (setq result (js2-string-to-keyword str))
5638 (if (and (< js2-language-version 170)
5639 (memq result '(js2-LET js2-YIELD)))
5640 ;; LET and YIELD are tokens only in 1.7 and later
5641 (setq result 'js2-NAME))
5642 (if (not (eq result 'js2-RESERVED))
5643 (throw 'return (js2-token-code result)))
5644 (js2-report-warning "msg.reserved.keyword" str)))
5645 ;; If we want to intern these as Rhino does, just use (intern str)
5646 (setq js2-ts-string str)
5647 (throw 'return js2-NAME)) ; end identifier/kwd check
5649 (when (or (js2-digit-p c)
5650 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5651 (setq js2-ts-string-buffer nil
5654 (setq c (js2-get-char))
5656 ((or (eq c ?x) (eq c ?X))
5658 (setq c (js2-get-char)))
5662 (js2-add-to-string ?0))))
5664 (while (<= 0 (js2-x-digit-to-int c 0))
5665 (js2-add-to-string c)
5666 (setq c (js2-get-char)))
5667 (while (and (<= ?0 c) (<= c ?9))
5668 ;; We permit 08 and 09 as decimal numbers, which
5669 ;; makes our behavior a superset of the ECMA
5670 ;; numeric grammar. We might not always be so
5671 ;; permissive, so we warn about it.
5672 (when (and (eq base 8) (>= c ?8))
5673 (js2-report-warning "msg.bad.octal.literal"
5674 (if (eq c ?8) "8" "9"))
5676 (js2-add-to-string c)
5677 (setq c (js2-get-char))))
5679 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5680 (setq is-integer nil)
5683 (js2-add-to-string c)
5684 (setq c (js2-get-char))
5685 while (js2-digit-p c)))
5686 (when (memq c '(?e ?E))
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char))
5689 (when (memq c '(?+ ?-))
5690 (js2-add-to-string c)
5691 (setq c (js2-get-char)))
5692 (unless (js2-digit-p c)
5693 (js2-report-scan-error "msg.missing.exponent" t))
5695 (js2-add-to-string c)
5696 (setq c (js2-get-char))
5697 while (js2-digit-p c))))
5699 (setq js2-ts-string (js2-get-string-from-buffer)
5701 (if (and (eq base 10) (not is-integer))
5702 (string-to-number js2-ts-string)
5703 ;; TODO: call runtime number-parser. Some of it is in
5704 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5705 (string-to-number js2-ts-string)))
5706 (throw 'return js2-NUMBER))
5708 (when (memq c '(?\" ?\'))
5709 ;; We attempt to accumulate a string the fast way, by
5710 ;; building it directly out of the reader. But if there
5711 ;; are any escaped characters in the string, we revert to
5712 ;; building it out of a string buffer.
5714 js2-ts-string-buffer nil
5717 (while (/= c quote-char)
5719 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5721 (setq js2-token-end js2-ts-cursor)
5722 (js2-report-error "msg.unterminated.string.lit")
5723 (throw 'return js2-STRING))
5725 ;; We've hit an escaped character
5726 (setq c (js2-get-char))
5735 (setq c1 (js2-read-unicode-escape))
5736 (if js2-parse-ide-mode
5739 ;; just copy the string in IDE-mode
5740 (js2-add-to-string ?\\)
5741 (js2-add-to-string ?u)
5743 (js2-add-to-string (js2-get-char)))
5744 (setq c (js2-get-char))) ; added at end of loop
5745 ;; flag it as an invalid escape
5746 (js2-report-warning "msg.invalid.escape"
5747 nil (- js2-ts-cursor 2) 6))
5748 ;; Get 4 hex digits; if the u escape is not
5749 ;; followed by 4 hex digits, use 'u' + the
5750 ;; literal character sequence that follows.
5751 (js2-add-to-string ?u)
5754 (setq c (js2-get-char)
5755 escape-val (js2-x-digit-to-int c escape-val))
5756 (if (minusp escape-val)
5757 (throw 'continue nil))
5758 (js2-add-to-string c))
5759 ;; prepare for replace of stored 'u' sequence by escape value
5760 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5763 ;; Get 2 hex digits, defaulting to 'x'+literal
5764 ;; sequence, as above.
5765 (setq c (js2-get-char)
5766 escape-val (js2-x-digit-to-int c 0))
5767 (if (minusp escape-val)
5769 (js2-add-to-string ?x)
5770 (throw 'continue nil))
5773 escape-val (js2-x-digit-to-int c escape-val))
5774 (if (minusp escape-val)
5776 (js2-add-to-string ?x)
5777 (js2-add-to-string c1)
5778 (throw 'continue nil))
5780 (setq c escape-val))))
5782 ;; Remove line terminator after escape to follow
5783 ;; SpiderMonkey and C/C++
5784 (setq c (js2-get-char))
5785 (throw 'continue nil))
5787 (when (and (<= ?0 c) (< c ?8))
5790 (when (and (<= ?0 c) (< c ?8))
5791 (setq val (- (+ (* 8 val) c) ?0)
5793 (when (and (<= ?0 c)
5796 ;; c is 3rd char of octal sequence only
5797 ;; if the resulting val <= 0377
5798 (setq val (- (+ (* 8 val) c) ?0)
5802 (js2-add-to-string c)
5803 (setq c (js2-get-char)))))
5804 (setq js2-ts-string (js2-get-string-from-buffer))
5805 (throw 'return js2-STRING))
5808 (throw 'return js2-SEMI))
5810 (throw 'return js2-LB))
5812 (throw 'return js2-RB))
5814 (throw 'return js2-LC))
5816 (throw 'return js2-RC))
5818 (throw 'return js2-LP))
5820 (throw 'return js2-RP))
5822 (throw 'return js2-COMMA))
5824 (throw 'return js2-HOOK))
5826 (if (js2-match-char ?:)
5827 (js2-ts-return js2-COLONCOLON)
5828 (throw 'return js2-COLON)))
5830 (if (js2-match-char ?.)
5831 (js2-ts-return js2-DOTDOT)
5832 (if (js2-match-char ?\()
5833 (js2-ts-return js2-DOTQUERY)
5834 (throw 'return js2-DOT))))
5836 (if (js2-match-char ?|)
5837 (throw 'return js2-OR)
5838 (if (js2-match-char ?=)
5839 (js2-ts-return js2-ASSIGN_BITOR)
5840 (throw 'return js2-BITOR))))
5842 (if (js2-match-char ?=)
5843 (js2-ts-return js2-ASSIGN_BITOR)
5844 (throw 'return js2-BITXOR)))
5846 (if (js2-match-char ?&)
5847 (throw 'return js2-AND)
5848 (if (js2-match-char ?=)
5849 (js2-ts-return js2-ASSIGN_BITAND)
5850 (throw 'return js2-BITAND))))
5852 (if (js2-match-char ?=)
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-SHEQ)
5855 (throw 'return js2-EQ))
5856 (throw 'return js2-ASSIGN)))
5858 (if (js2-match-char ?=)
5859 (if (js2-match-char ?=)
5860 (js2-ts-return js2-SHNE)
5861 (js2-ts-return js2-NE))
5862 (throw 'return js2-NOT)))
5864 ;; NB:treat HTML begin-comment as comment-till-eol
5865 (when (js2-match-char ?!)
5866 (when (js2-match-char ?-)
5867 (when (js2-match-char ?-)
5869 (setq js2-ts-comment-type 'html)
5870 (throw 'return js2-COMMENT)))
5872 (if (js2-match-char ?<)
5873 (if (js2-match-char ?=)
5874 (js2-ts-return js2-ASSIGN_LSH)
5875 (js2-ts-return js2-LSH))
5876 (if (js2-match-char ?=)
5877 (js2-ts-return js2-LE)
5878 (throw 'return js2-LT))))
5880 (if (js2-match-char ?>)
5881 (if (js2-match-char ?>)
5882 (if (js2-match-char ?=)
5883 (js2-ts-return js2-ASSIGN_URSH)
5884 (js2-ts-return js2-URSH))
5885 (if (js2-match-char ?=)
5886 (js2-ts-return js2-ASSIGN_RSH)
5887 (js2-ts-return js2-RSH)))
5888 (if (js2-match-char ?=)
5889 (js2-ts-return js2-GE)
5890 (throw 'return js2-GT))))
5892 (if (js2-match-char ?=)
5893 (js2-ts-return js2-ASSIGN_MUL)
5894 (throw 'return js2-MUL)))
5896 ;; is it a // comment?
5897 (when (js2-match-char ?/)
5898 (setq js2-token-beg (- js2-ts-cursor 2))
5900 (setq js2-ts-comment-type 'line)
5901 ;; include newline so highlighting goes to end of window
5902 (incf js2-token-end)
5903 (throw 'return js2-COMMENT))
5904 ;; is it a /* comment?
5905 (when (js2-match-char ?*)
5906 (setq look-for-slash nil
5907 js2-token-beg (- js2-ts-cursor 2)
5909 (if (js2-match-char ?*)
5911 (setq look-for-slash t)
5915 (setq c (js2-get-char))
5917 ((eq c js2-EOF_CHAR)
5918 (setq js2-token-end (1- js2-ts-cursor))
5919 (js2-report-error "msg.unterminated.comment")
5920 (throw 'return js2-COMMENT))
5922 (setq look-for-slash t))
5925 (js2-ts-return js2-COMMENT)))
5927 (setq look-for-slash nil
5928 js2-token-end js2-ts-cursor)))))
5929 (if (js2-match-char ?=)
5930 (js2-ts-return js2-ASSIGN_DIV)
5931 (throw 'return js2-DIV)))
5933 (when js2-skip-preprocessor-directives
5935 (setq js2-ts-comment-type 'preprocessor
5936 js2-token-end js2-ts-cursor)
5937 (throw 'return js2-COMMENT))
5938 (throw 'return js2-ERROR))
5940 (if (js2-match-char ?=)
5941 (js2-ts-return js2-ASSIGN_MOD)
5942 (throw 'return js2-MOD)))
5944 (throw 'return js2-BITNOT))
5946 (if (js2-match-char ?=)
5947 (js2-ts-return js2-ASSIGN_ADD)
5948 (if (js2-match-char ?+)
5949 (js2-ts-return js2-INC)
5950 (throw 'return js2-ADD))))
5953 ((js2-match-char ?=)
5954 (setq c js2-ASSIGN_SUB))
5955 ((js2-match-char ?-)
5956 (unless js2-ts-dirty-line
5957 ;; treat HTML end-comment after possible whitespace
5958 ;; after line start as comment-until-eol
5959 (when (js2-match-char ?>)
5961 (setq js2-ts-comment-type 'html)
5962 (throw 'return js2-COMMENT)))
5966 (setq js2-ts-dirty-line t)
5969 (js2-report-scan-error "msg.illegal.character")))))))
5971 (defun js2-read-regexp (start-token)
5972 "Called by parser when it gets / or /= in literal context."
5975 in-class ; inside a '[' .. ']' character-class
5978 (setq js2-token-beg js2-ts-cursor
5979 js2-ts-string-buffer nil
5980 js2-ts-regexp-flags nil)
5981 (if (eq start-token js2-ASSIGN_DIV)
5983 (js2-add-to-string ?=)
5984 (if (not (eq start-token js2-DIV))
5985 (error "failed assertion")))
5986 (while (and (not err)
5987 (or (/= (setq c (js2-get-char)) ?/)
5992 (setq js2-token-end (1- js2-ts-cursor)
5994 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5995 (js2-report-error "msg.unterminated.re.lit"))
5998 (js2-add-to-string c)
5999 (setq c (js2-get-char)))
6003 (setq in-class nil)))
6004 (js2-add-to-string c))))
6008 ((js2-match-char ?g)
6010 ((js2-match-char ?i)
6012 ((js2-match-char ?m)
6015 (setq continue nil))))
6016 (if (js2-alpha-p (js2-peek-char))
6017 (js2-report-scan-error "msg.invalid.re.flag" t
6019 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6020 js2-ts-regexp-flags (js2-collect-string flags)
6021 js2-token-end js2-ts-cursor)
6022 ;; tell `parse-partial-sexp' to ignore this range of chars
6023 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6025 (defun js2-get-first-xml-token ()
6026 (setq js2-ts-xml-open-tags-count 0
6027 js2-ts-is-xml-attribute nil
6028 js2-ts-xml-is-tag-content nil)
6030 (js2-get-next-xml-token))
6032 (defsubst js2-xml-discard-string ()
6033 "Throw away the string in progress and flag an XML parse error."
6034 (setq js2-ts-string-buffer nil
6036 (js2-report-scan-error "msg.XML.bad.form" t))
6038 (defun js2-get-next-xml-token ()
6039 (setq js2-ts-string-buffer nil ; for recording the XML
6040 js2-token-beg js2-ts-cursor)
6045 (setq c (js2-get-char))
6048 (throw 'return js2-ERROR))
6049 (js2-ts-xml-is-tag-content
6052 (js2-add-to-string c)
6053 (setq js2-ts-xml-is-tag-content nil
6054 js2-ts-is-xml-attribute nil))
6056 (js2-add-to-string c)
6057 (when (eq ?> (js2-peek-char))
6058 (setq c (js2-get-char))
6059 (js2-add-to-string c)
6060 (setq js2-ts-xml-is-tag-content nil)
6061 (decf js2-ts-xml-open-tags-count)))
6064 (setq js2-ts-string (js2-get-string-from-buffer))
6065 (throw 'return js2-XML))
6067 (js2-add-to-string c)
6068 (unless (js2-read-quoted-string c)
6069 (throw 'return js2-ERROR)))
6071 (js2-add-to-string c)
6072 (setq js2-ts-is-xml-attribute t))
6074 (js2-add-to-string c))
6076 (js2-add-to-string c)
6077 (setq js2-ts-is-xml-attribute nil)))
6078 (when (and (not js2-ts-xml-is-tag-content)
6079 (zerop js2-ts-xml-open-tags-count))
6080 (setq js2-ts-string (js2-get-string-from-buffer))
6081 (throw 'return js2-XMLEND)))
6083 ;; else not tag content
6086 (js2-add-to-string c)
6087 (setq c (js2-peek-char))
6090 (setq c (js2-get-char)) ;; skip !
6091 (js2-add-to-string c)
6092 (setq c (js2-peek-char))
6095 (setq c (js2-get-char)) ;; skip -
6096 (js2-add-to-string c)
6099 (js2-add-to-string c)
6100 (unless (js2-read-xml-comment)
6101 (throw 'return js2-ERROR)))
6102 (js2-xml-discard-string)
6103 (throw 'return js2-ERROR)))
6105 (setq c (js2-get-char)) ;; skip [
6106 (js2-add-to-string c)
6107 (if (and (= (js2-get-char) ?C)
6108 (= (js2-get-char) ?D)
6109 (= (js2-get-char) ?A)
6110 (= (js2-get-char) ?T)
6111 (= (js2-get-char) ?A)
6112 (= (js2-get-char) ?\[))
6114 (js2-add-to-string ?C)
6115 (js2-add-to-string ?D)
6116 (js2-add-to-string ?A)
6117 (js2-add-to-string ?T)
6118 (js2-add-to-string ?A)
6119 (js2-add-to-string ?\[)
6120 (unless (js2-read-cdata)
6121 (throw 'return js2-ERROR)))
6122 (js2-xml-discard-string)
6123 (throw 'return js2-ERROR)))
6125 (unless (js2-read-entity)
6126 (throw 'return js2-ERROR))))
6127 ;; allow bare CDATA section
6128 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6129 (when (zerop js2-ts-xml-open-tags-count)
6130 (throw 'return js2-XMLEND)))
6132 (setq c (js2-get-char)) ;; skip ?
6133 (js2-add-to-string c)
6134 (unless (js2-read-PI)
6135 (throw 'return js2-ERROR)))
6138 (setq c (js2-get-char)) ;; skip /
6139 (js2-add-to-string c)
6140 (when (zerop js2-ts-xml-open-tags-count)
6141 (js2-xml-discard-string)
6142 (throw 'return js2-ERROR))
6143 (setq js2-ts-xml-is-tag-content t)
6144 (decf js2-ts-xml-open-tags-count))
6147 (setq js2-ts-xml-is-tag-content t)
6148 (incf js2-ts-xml-open-tags-count))))
6151 (setq js2-ts-string (js2-get-string-from-buffer))
6152 (throw 'return js2-XML))
6154 (js2-add-to-string c))))))))
6155 (setq js2-token-end js2-ts-cursor)
6158 (defun js2-read-quoted-string (quote)
6161 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6162 (js2-add-to-string c)
6165 (js2-xml-discard-string) ;; throw away string in progress
6168 (defun js2-read-xml-comment ()
6169 (let ((c (js2-get-char)))
6171 (while (/= c js2-EOF_CHAR)
6173 (js2-add-to-string c)
6174 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6175 (setq c (js2-get-char))
6176 (js2-add-to-string c)
6177 (if (eq (js2-peek-char) ?>)
6179 (setq c (js2-get-char)) ;; skip >
6180 (js2-add-to-string c)
6182 (throw 'continue nil)))
6183 (setq c (js2-get-char))))
6184 (js2-xml-discard-string)
6187 (defun js2-read-cdata ()
6188 (let ((c (js2-get-char)))
6190 (while (/= c js2-EOF_CHAR)
6192 (js2-add-to-string c)
6193 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6194 (setq c (js2-get-char))
6195 (js2-add-to-string c)
6196 (if (eq (js2-peek-char) ?>)
6198 (setq c (js2-get-char)) ;; Skip >
6199 (js2-add-to-string c)
6201 (throw 'continue nil)))
6202 (setq c (js2-get-char))))
6203 (js2-xml-discard-string)
6206 (defun js2-read-entity ()
6210 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6211 (js2-add-to-string c)
6217 (if (zerop decl-tags)
6218 (throw 'return t)))))
6219 (js2-xml-discard-string)
6222 (defun js2-read-PI ()
6223 "Scan an XML processing instruction."
6226 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6227 (js2-add-to-string c)
6228 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6229 (setq c (js2-get-char)) ;; Skip >
6230 (js2-add-to-string c)
6232 (js2-xml-discard-string)
6235 (defun js2-scanner-get-line ()
6236 "Return the text of the current scan line."
6237 (buffer-substring (point-at-bol) (point-at-eol)))
6241 (defsubst js2-set-face (beg end face &optional record)
6242 "Fontify a region. If RECORD is non-nil, record for later."
6243 (when (plusp js2-highlight-level)
6244 (setq beg (min (point-max) beg)
6245 beg (max (point-min) beg)
6246 end (min (point-max) end)
6247 end (max (point-min) end))
6249 (push (list beg end face) js2-mode-fontifications)
6250 (put-text-property beg end 'face face))))
6252 (defsubst js2-set-kid-face (pos kid len face)
6253 "Set-face on a child node.
6254 POS is absolute buffer position of parent.
6255 KID is the child node.
6256 LEN is the length to fontify.
6257 FACE is the face to fontify with."
6258 (js2-set-face (+ pos (js2-node-pos kid))
6259 (+ pos (js2-node-pos kid) (js2-node-len kid))
6262 (defsubst js2-fontify-kwd (start length)
6263 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6265 (defsubst js2-clear-face (beg end)
6266 (remove-text-properties beg end '(face nil
6271 (defconst js2-ecma-global-props
6274 '("Infinity" "NaN" "undefined" "arguments") t)
6276 "Value properties of the Ecma-262 Global Object.
6277 Shown at or above `js2-highlight-level' 2.")
6279 ;; might want to add the name "arguments" to this list?
6280 (defconst js2-ecma-object-props
6283 '("prototype" "__proto__" "__parent__") t)
6285 "Value properties of the Ecma-262 Object constructor.
6286 Shown at or above `js2-highlight-level' 2.")
6288 (defconst js2-ecma-global-funcs
6292 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6293 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6295 "Function properties of the Ecma-262 Global object.
6296 Shown at or above `js2-highlight-level' 2.")
6298 (defconst js2-ecma-number-props
6300 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6302 "POSITIVE_INFINITY") t)
6304 "Properties of the Ecma-262 Number constructor.
6305 Shown at or above `js2-highlight-level' 2.")
6307 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6308 "Properties of the Ecma-262 Date constructor.
6309 Shown at or above `js2-highlight-level' 2.")
6311 (defconst js2-ecma-math-props
6314 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6317 "Properties of the Ecma-262 Math object.
6318 Shown at or above `js2-highlight-level' 2.")
6320 (defconst js2-ecma-math-funcs
6323 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6324 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6326 "Function properties of the Ecma-262 Math object.
6327 Shown at or above `js2-highlight-level' 2.")
6329 (defconst js2-ecma-function-props
6333 '(;; properties of the Object prototype object
6334 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6335 "toLocaleString" "toString" "valueOf"
6336 ;; properties of the Function prototype object
6338 ;; properties of the Array prototype object
6339 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6341 ;; properties of the String prototype object
6342 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6343 "localeCompare" "match" "replace" "search" "split" "substring"
6344 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6346 ;; properties of the Number prototype object
6347 "toExponential" "toFixed" "toPrecision"
6348 ;; properties of the Date prototype object
6349 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6350 "getMinutes" "getMonth" "getSeconds" "getTime"
6351 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6352 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6353 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6354 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6355 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6356 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6357 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6358 "toTimeString" "toUTCString"
6359 ;; properties of the RegExp prototype object
6361 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6362 "toSource" "__defineGetter__" "__defineSetter__"
6363 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6364 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6367 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6368 Shown at or above `js2-highlight-level' 3.")
6370 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6371 (let ((target-name (and target
6372 (js2-name-node-p target)
6373 (js2-name-node-name target)))
6374 (prop-name (if prop (js2-name-node-name prop)))
6375 (level1 (>= js2-highlight-level 1))
6376 (level2 (>= js2-highlight-level 2))
6377 (level3 (>= js2-highlight-level 3))
6385 ((and level3 (string-match js2-ecma-function-props prop-name))
6386 (setq face 'font-lock-builtin-face))
6387 ((and target-name prop)
6389 ((string= target-name "Date")
6390 (if (string-match js2-ecma-date-props prop-name)
6391 (setq face 'font-lock-builtin-face)))
6392 ((string= target-name "Math")
6393 (if (string-match js2-ecma-math-funcs prop-name)
6394 (setq face 'font-lock-builtin-face)))))))
6396 (if (string-match js2-ecma-global-funcs prop-name)
6397 (setq face 'font-lock-builtin-face))))
6401 ((string= target-name "Number")
6402 (if (string-match js2-ecma-number-props prop-name)
6403 (setq face 'font-lock-constant-face)))
6404 ((string= target-name "Math")
6405 (if (string-match js2-ecma-math-props prop-name)
6406 (setq face 'font-lock-constant-face)))))
6408 (if (string-match js2-ecma-object-props prop-name)
6409 (setq face 'font-lock-constant-face)))))
6411 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6412 (js2-node-pos prop))) ; relative
6413 (+ pos (js2-node-len prop))
6416 (defun js2-parse-highlight-member-expr-node (node)
6417 "Perform syntax highlighting of EcmaScript built-in properties.
6418 The variable `js2-highlight-level' governs this highighting."
6419 (let (face target prop name pos end parent call-p callee)
6421 ;; case 1: simple name, e.g. foo
6422 ((js2-name-node-p node)
6423 (setq name (js2-name-node-name node))
6424 ;; possible for name to be nil in rare cases - saw it when
6425 ;; running js2-mode on an elisp buffer. Might as well try to
6426 ;; make it so js2-mode never barfs.
6428 (setq face (if (string-match js2-ecma-global-props name)
6429 'font-lock-constant-face))
6431 (setq pos (js2-node-pos node)
6432 end (+ pos (js2-node-len node)))
6433 (js2-set-face pos end face))))
6434 ;; case 2: property access or function call
6435 ((or (js2-prop-get-node-p node)
6436 ;; highlight function call if expr is a prop-get node
6437 ;; or a plain name (i.e. unqualified function call)
6438 (and (setq call-p (js2-call-node-p node))
6439 (setq callee (js2-call-node-target node)) ; separate setq!
6440 (or (js2-prop-get-node-p callee)
6441 (js2-name-node-p callee))))
6443 node (if call-p callee node))
6444 (if (and call-p (js2-name-node-p callee))
6446 (setq target (js2-prop-get-node-left node)
6447 prop (js2-prop-get-node-right node)))
6449 ((js2-name-node-p target)
6450 (if (js2-name-node-p prop)
6451 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6452 (js2-parse-highlight-prop-get parent target prop call-p)
6453 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6454 (js2-parse-highlight-prop-get parent target nil call-p)))
6455 ((js2-name-node-p prop)
6456 ;; case 2c: complex target, simple name, e.g. x[y].bar
6457 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6459 (defun js2-parse-highlight-member-expr-fn-name (expr)
6460 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6461 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6462 We currently only handle the case where the last component is a prop-get
6463 of a simple name. Called before EXPR has a parent node."
6465 (name (and (js2-prop-get-node-p expr)
6466 (js2-prop-get-node-right expr))))
6467 (when (js2-name-node-p name)
6468 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6469 (js2-node-pos name)))
6470 (+ pos (js2-node-len name))
6471 'font-lock-function-name-face
6474 ;; source: http://jsdoc.sourceforge.net/
6475 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6476 ;; allows type specifications, and needs work before entering the wild.
6478 (defconst js2-jsdoc-param-tag-regexp
6479 (concat "^\\s-*\\*+\\s-*\\(@"
6480 "\\(?:param\\|argument\\)"
6482 "\\s-*\\({[^}]+}\\)?" ; optional type
6483 "\\s-*\\[?\\([a-zA-Z0-9_$]+\\)?\\]?" ; name
6485 "Matches jsdoc tags with optional type and optional param name.")
6487 (defconst js2-jsdoc-typed-tag-regexp
6488 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6502 "\\)\\)\\s-*\\({[^}]+}\\)?")
6503 "Matches jsdoc tags with optional type.")
6505 (defconst js2-jsdoc-arg-tag-regexp
6506 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6529 "\\)\\)\\s-+\\([^ \t]+\\)")
6530 "Matches jsdoc tags with a single argument.")
6532 (defconst js2-jsdoc-empty-tag-regexp
6533 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6573 "Matches empty jsdoc tags.")
6575 (defconst js2-jsdoc-link-tag-regexp
6576 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6577 "Matches a jsdoc link or code tag.")
6579 (defconst js2-jsdoc-see-tag-regexp
6580 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6581 "Matches a jsdoc @see tag.")
6583 (defconst js2-jsdoc-html-tag-regexp
6584 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6585 "Matches a simple (no attributes) html start- or end-tag.")
6587 (defsubst js2-jsdoc-highlight-helper ()
6588 (js2-set-face (match-beginning 1)
6590 'js2-jsdoc-tag-face)
6591 (if (match-beginning 2)
6593 (goto-char (match-beginning 2))
6594 (= (char-after) ?{))
6595 (js2-set-face (1+ (match-beginning 2))
6597 'js2-jsdoc-type-face)
6598 (js2-set-face (match-beginning 2)
6600 'js2-jsdoc-value-face)))
6601 (if (match-beginning 3)
6602 (js2-set-face (match-beginning 3)
6604 'js2-jsdoc-value-face)))
6606 (defun js2-highlight-jsdoc (ast)
6607 "Highlight doc comment tags."
6608 (let ((comments (js2-ast-root-comments ast))
6611 (dolist (node comments)
6612 (when (eq (js2-comment-node-format node) 'jsdoc)
6613 (setq beg (js2-node-abs-pos node)
6614 end (+ beg (js2-node-len node)))
6616 (narrow-to-region beg end)
6617 (dolist (re (list js2-jsdoc-param-tag-regexp
6618 js2-jsdoc-typed-tag-regexp
6619 js2-jsdoc-arg-tag-regexp
6620 js2-jsdoc-link-tag-regexp
6621 js2-jsdoc-see-tag-regexp
6622 js2-jsdoc-empty-tag-regexp))
6624 (while (re-search-forward re nil t)
6625 (js2-jsdoc-highlight-helper)))
6626 ;; simple highlighting for html tags
6628 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6629 (js2-set-face (match-beginning 1)
6631 'js2-jsdoc-html-tag-delimiter-face)
6632 (js2-set-face (match-beginning 2)
6634 'js2-jsdoc-html-tag-name-face)
6635 (js2-set-face (match-beginning 3)
6637 'js2-jsdoc-html-tag-delimiter-face))))))))
6639 (defun js2-highlight-assign-targets (node left right)
6640 "Highlight function properties and external variables."
6641 (let (leftpos end name)
6642 ;; highlight vars and props assigned function values
6643 (when (js2-function-node-p right)
6645 ;; var foo = function() {...}
6646 ((js2-name-node-p left)
6648 ;; foo.bar.baz = function() {...}
6649 ((and (js2-prop-get-node-p left)
6650 (js2-name-node-p (js2-prop-get-node-right left)))
6651 (setq name (js2-prop-get-node-right left))))
6653 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6654 (+ leftpos (js2-node-len name))
6655 'font-lock-function-name-face
6658 (defun js2-record-name-node (node)
6659 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6660 later. NODE must be a name node."
6662 (push (list node js2-current-scope
6663 (setq leftpos (js2-node-abs-pos node))
6664 (setq end (+ leftpos (js2-node-len node))))
6665 js2-recorded-identifiers)))
6667 (defun js2-highlight-undeclared-vars ()
6668 "After entire parse is finished, look for undeclared variable references.
6669 We have to wait until entire buffer is parsed, since JavaScript permits var
6670 decls to occur after they're used.
6672 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6673 it is considered declared."
6675 (dolist (entry js2-recorded-identifiers)
6676 (destructuring-bind (name-node scope pos end) entry
6677 (setq name (js2-name-node-name name-node))
6678 (unless (or (member name js2-global-externs)
6679 (member name js2-default-externs)
6680 (member name js2-additional-externs)
6681 (js2-get-defining-scope scope name))
6682 (js2-set-face pos end 'js2-external-variable-face 'record)
6683 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6684 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6685 (setq js2-recorded-identifiers nil)))
6689 ;; We currently only support imenu, but eventually should support speedbar and
6690 ;; possibly other browsing mechanisms.
6692 ;; The basic strategy is to identify function assignment targets of the form
6693 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6694 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6695 ;; for imenu after parsing is finished.
6697 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6698 ;; JavaScript, and the general problem is undecidable. However, several forms
6699 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6702 ;; function foo() -- function declaration
6703 ;; foo = function() -- function expression assigned to variable
6704 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6705 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6706 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6707 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6708 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6709 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6710 ;; function foo() {function bar() {...}} -- nested function
6711 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6713 ;; This list boils down to a few forms that can be combined recursively.
6714 ;; Top-level named function declarations include both the left-hand (name)
6715 ;; and the right-hand (function value) expressions needed to produce an imenu
6716 ;; entry. The other "right-hand" forms we need to look for are:
6717 ;; - functions declared as props/getters/setters in object literals
6718 ;; - nested named function declarations
6719 ;; The "left-hand" expressions that functions can be assigned to include:
6720 ;; - local/global variables
6721 ;; - nested property-get expressions like a.b.c.d
6722 ;; - element gets like foo[10] or foo['bar'] where the index
6723 ;; expression can be trivially converted to a property name. They
6724 ;; effectively then become property gets.
6726 ;; All the different definition types are canonicalized into the form
6727 ;; foo.bar.baz = position-of-function-keyword
6729 ;; We need to build a trie-like structure for imenu. As an example,
6730 ;; consider the following JavaScript code:
6732 ;; a = function() {...} // function at position 5
6733 ;; b = function() {...} // function at position 25
6734 ;; foo = function() {...} // function at position 100
6735 ;; foo.bar = function() {...} // function at position 200
6736 ;; foo.bar.baz = function() {...} // function at position 300
6737 ;; foo.bar.zab = function() {...} // function at position 400
6739 ;; During parsing we accumulate an entry for each definition in
6740 ;; the variable `js2-imenu-recorder', like so:
6746 ;; (fn foo bar baz 300)
6747 ;; (fn foo bar zab 400))
6749 ;; Where 'fn' is the respective function node.
6750 ;; After parsing these entries are merged into this alist-trie:
6754 ;; (foo (<definition> . 3)
6755 ;; (bar (<definition> . 6)
6759 ;; Note the wacky need for a <definition> name. The token can be anything
6760 ;; that isn't a valid JavaScript identifier, because you might make foo
6761 ;; a function and then start setting properties on it that are also functions.
6763 (defsubst js2-prop-node-name (node)
6764 "Return the name of a node that may be a property-get/property-name.
6765 If NODE is not a valid name-node, string-node or integral number-node,
6766 returns nil. Otherwise returns the string name/value of the node."
6768 ((js2-name-node-p node)
6769 (js2-name-node-name node))
6770 ((js2-string-node-p node)
6771 (js2-string-node-value node))
6772 ((and (js2-number-node-p node)
6773 (string-match "^[0-9]+$" (js2-number-node-value node)))
6774 (js2-number-node-value node))
6775 ((js2-this-node-p node)
6778 (defsubst js2-node-qname-component (node)
6779 "Return the name of this node, if it contributes to a qname.
6780 Returns nil if the node doesn't contribute."
6782 (or (js2-prop-node-name node)
6783 (if (and (js2-function-node-p node)
6784 (js2-function-node-name node))
6785 (js2-name-node-name (js2-function-node-name node))))))
6787 (defsubst js2-record-imenu-entry (fn-node qname pos)
6788 "Add an entry to `js2-imenu-recorder'.
6789 FN-NODE should be the current item's function node.
6791 Associate FN-NODE with its QNAME for later lookup.
6792 This is used in postprocessing the chain list. For each chain, we find
6793 the parent function, look up its qname, then prepend a copy of it to the chain."
6794 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6795 (unless js2-imenu-function-map
6796 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6797 (puthash fn-node qname js2-imenu-function-map))
6799 (defun js2-record-imenu-functions (node &optional var)
6800 "Record function definitions for imenu.
6801 NODE is a function node or an object literal.
6802 VAR, if non-nil, is the expression that NODE is being assigned to."
6803 (when js2-parse-ide-mode
6804 (let ((fun-p (js2-function-node-p node))
6805 qname left fname-node pos)
6807 ;; non-anonymous function declaration?
6810 (setq fname-node (js2-function-node-name node)))
6811 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6812 ;; for remaining forms, compute left-side tree branch first
6813 ((and var (setq qname (js2-compute-nested-prop-get var)))
6815 ;; foo.bar.baz = function
6817 (js2-record-imenu-entry node qname (js2-node-pos node)))
6818 ;; foo.bar.baz = object-literal
6819 ;; look for nested functions: {a: {b: function() {...} }}
6820 ((js2-object-node-p node)
6821 ;; Node position here is still absolute, since the parser
6822 ;; passes the assignment target and value expressions
6823 ;; to us before they are added as children of the assignment node.
6824 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6826 (defun js2-compute-nested-prop-get (node)
6827 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6828 component nodes as a list. Otherwise return nil. Element-gets are treated
6829 as property-gets if the index expression is a string, or a positive integer."
6830 (let (left right head)
6832 ((or (js2-name-node-p node)
6833 (js2-this-node-p node))
6835 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6836 ((js2-prop-get-node-p node) ; foo.bar
6837 (setq left (js2-prop-get-node-left node)
6838 right (js2-prop-get-node-right node))
6839 (if (setq head (js2-compute-nested-prop-get left))
6840 (nconc head (list right))))
6841 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6842 (setq left (js2-elem-get-node-target node)
6843 right (js2-elem-get-node-element node))
6844 (if (or (js2-string-node-p right) ; ['bar']
6845 (and (js2-number-node-p right) ; [10]
6846 (string-match "^[0-9]+$"
6847 (js2-number-node-value right))))
6848 (if (setq head (js2-compute-nested-prop-get left))
6849 (nconc head (list right))))))))
6851 (defun js2-record-object-literal (node qname pos)
6852 "Recursively process an object literal looking for functions.
6853 NODE is an object literal that is the right-hand child of an assignment
6854 expression. QNAME is a list of nodes representing the assignment target,
6855 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6856 POS is the absolute position of the node.
6857 We do a depth-first traversal of NODE. For any functions we find,
6858 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6859 (let (left right prop-qname)
6860 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6861 (let ((left (js2-infix-node-left e))
6862 ;; Element positions are relative to the parent position.
6863 (pos (+ pos (js2-node-pos e))))
6865 ;; foo: function() {...}
6866 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6867 (when (js2-prop-node-name left)
6868 ;; As a policy decision, we record the position of the property,
6869 ;; not the position of the `function' keyword, since the property
6870 ;; is effectively the name of the function.
6871 (js2-record-imenu-entry right (append qname (list left)) pos)))
6872 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6873 ((js2-object-node-p right)
6874 (js2-record-object-literal right
6875 (append qname (list (js2-infix-node-left e)))
6876 (+ pos (js2-node-pos right)))))))))
6878 (defsubst js2-node-top-level-decl-p (node)
6879 "Return t if NODE's name is defined in the top-level scope.
6880 Also returns t if NODE's name is not defined in any scope, since it implies
6881 that it's an external variable, which must also be in the top-level scope."
6882 (let* ((name (js2-prop-node-name node))
6883 (this-scope (js2-node-get-enclosing-scope node))
6886 ((js2-this-node-p node)
6890 ((setq defining-scope (js2-get-defining-scope this-scope name))
6891 (js2-ast-root-p defining-scope))
6894 (defsubst js2-wrapper-function-p (node)
6895 "Returns t if NODE is a function expression that's immediately invoked.
6896 NODE must be `js2-function-node'."
6897 (let ((parent (js2-node-parent node)))
6899 ;; function(){...}();
6900 (js2-call-node-p parent)
6901 (and (js2-paren-node-p parent)
6902 ;; (function(){...})();
6903 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6904 ;; (function(){...}).call(this);
6905 (and (js2-prop-get-node-p parent)
6906 (member (js2-name-node-name (js2-prop-get-node-right parent))
6908 (js2-call-node-p (js2-node-parent parent))))))))
6910 (defun js2-browse-postprocess-chains (entries)
6911 "Modify function-declaration name chains after parsing finishes.
6912 Some of the information is only available after the parse tree is complete.
6913 For instance, processing a nested scope requires a parent function node."
6914 (let (result head fn current-fn parent-qname qname p elem)
6915 (dolist (entry entries)
6916 ;; function node goes first
6917 (destructuring-bind (current-fn &rest chain) entry
6918 ;; examine its defining scope;
6919 ;; if top-level/external, keep as-is
6920 (if (js2-node-top-level-decl-p (car chain))
6922 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6923 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6924 (when (eq parent-qname 'not-found)
6925 ;; anonymous function expressions are not recorded
6926 ;; during the parse, so we need to handle this case here
6928 (if (js2-wrapper-function-p fn)
6929 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6930 (if (js2-ast-root-p grandparent)
6932 (gethash grandparent js2-imenu-function-map 'skip)))
6934 (puthash fn parent-qname js2-imenu-function-map))
6935 (unless (eq parent-qname 'skip)
6936 ;; prefix parent fn qname to this chain.
6937 (let ((qname (append parent-qname chain)))
6938 (puthash current-fn (butlast qname) js2-imenu-function-map)
6939 (push qname result)))))))
6940 ;; finally replace each node in each chain with its name.
6941 (dolist (chain result)
6944 (if (js2-node-p (setq elem (car p)))
6945 (setcar p (js2-node-qname-component elem)))
6949 ;; Merge name chains into a trie-like tree structure of nested lists.
6950 ;; To simplify construction of the trie, we first build it out using the rule
6951 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6952 ;; [key, num-or-list]. The second element can be a number; if so, this key
6953 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6954 ;; associated with the key at this level.) Otherwise the second element is
6955 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6956 ;; a simple recursive formulation.
6958 ;; js2-mode is building the data structure for imenu. The imenu documentation
6959 ;; claims that it's the structure above, but in practice it wants the children
6960 ;; at the same list level as the key for that level, which is how I've drawn
6961 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6962 ;; list wrapper around the children at each level.
6964 ;; A completed nested imenu-alist entry looks like this:
6966 ;; ("<definition>" . 7)
6971 ;; In particular, the documentation for `imenu--index-alist' says that
6972 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6973 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6975 (defsubst js2-treeify (lst)
6976 "Convert (a b c d) to (a ((b ((c d)))))"
6977 (if (null (cddr lst)) ; list length <= 2
6979 (list (car lst) (list (js2-treeify (cdr lst))))))
6981 (defun js2-build-alist-trie (chains trie)
6982 "Merge declaration name chains into a trie-like alist structure for imenu.
6983 CHAINS is the qname chain list produced during parsing. TRIE is a
6984 list of elements built up so far."
6985 (let (head tail pos branch kids)
6986 (dolist (chain chains)
6987 (setq head (car chain)
6989 pos (if (numberp (car tail)) (car tail))
6990 branch (js2-find-if (lambda (n)
6991 (string= (car n) head))
6993 kids (second branch))
6995 ;; case 1: this key isn't in the trie yet
6998 (setcdr (last trie) (list (js2-treeify chain)))
6999 (setq trie (list (js2-treeify chain)))))
7000 ;; case 2: key is present with a single number entry: replace w/ list
7001 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7002 ;; ("<definition>" 20)))
7004 (setcar (cdr branch)
7005 (list (list "<definition-1>" kids)
7007 (list "<definition-2>" pos)
7008 (js2-treeify tail)))))
7009 ;; case 3: key is there (with kids), and we're a number entry
7013 (list (format "<definition-%d>"
7014 (1+ (loop for kid in kids
7015 count (eq ?< (aref (car kid) 0)))))
7017 ;; case 4: key is there with kids, need to merge in our chain
7019 (js2-build-alist-trie (list tail) kids))))
7022 (defun js2-flatten-trie (trie)
7023 "Convert TRIE to imenu-format.
7024 Recurses through nodes, and for each one whose second element is a list,
7025 appends the list's flattened elements to the current element. Also
7026 changes the tails into conses. For instance, this pre-flattened trie
7038 Note that the root of the trie has no key, just a list of chains.
7039 This is also true for the value of any key with multiple children,
7040 e.g. key 'c' in the example above."
7043 (mapcar #'js2-flatten-trie trie))
7045 (if (numberp (second trie))
7046 (cons (car trie) (second trie))
7047 ;; else pop list and append its kids
7048 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7050 (defun js2-build-imenu-index ()
7051 "Turn `js2-imenu-recorder' into an imenu data structure."
7052 (unless (eq js2-imenu-recorder 'empty)
7053 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7054 (result (js2-build-alist-trie chains nil)))
7055 (js2-flatten-trie result))))
7057 (defun js2-test-print-chains (chains)
7058 "Print a list of qname chains.
7059 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7060 i.e. one or more nodes, and an integer position as the list tail."
7061 (mapconcat (lambda (chain)
7063 (mapconcat (lambda (elem)
7064 (if (js2-node-p elem)
7065 (or (js2-node-qname-component elem)
7067 (number-to-string elem)))
7076 (defconst js2-version "1.8.0"
7077 "Version of JavaScript supported, plus minor js2 version.")
7079 (defmacro js2-record-face (face)
7080 "Record a style run of FACE for the current token."
7081 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7083 (defsubst js2-node-end (n)
7084 "Computes the absolute end of node N.
7085 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7086 is only true until the node is added to its parent; i.e., while parsing."
7090 (defsubst js2-record-comment ()
7091 "Record a comment in `js2-scanned-comments'."
7092 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7093 :format js2-ts-comment-type)
7094 js2-scanned-comments)
7095 (when js2-parse-ide-mode
7096 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7098 'font-lock-comment-face))
7099 (when (memq js2-ts-comment-type '(html preprocessor))
7100 ;; Tell cc-engine the bounds of the comment.
7101 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7103 ;; This function is called depressingly often, so it should be fast.
7104 ;; Most of the time it's looking at the same token it peeked before.
7105 (defsubst js2-peek-token ()
7106 "Returns the next token without consuming it.
7107 If previous token was consumed, calls scanner to get new token.
7108 If previous token was -not- consumed, returns it (idempotent).
7110 This function will not return a newline (js2-EOL) - instead, it
7111 gobbles newlines until it finds a non-newline token, and flags
7112 that token as appearing just after a newline.
7114 This function will also not return a js2-COMMENT. Instead, it
7115 records comments found in `js2-scanned-comments'. If the token
7116 returned by this function immediately follows a jsdoc comment,
7117 the token is flagged as such.
7119 Note that this function always returned the un-flagged token!
7120 The flags, if any, are saved in `js2-current-flagged-token'."
7121 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7122 js2-current-token ; most common case - return already-peeked token
7123 (let ((tt (js2-get-token)) ; call scanner
7126 ;; process comments and whitespace
7127 (while (or (= tt js2-EOL)
7132 (if js2-record-comments
7133 (js2-record-comment)))
7134 (setq tt (js2-get-token))) ; call scanner
7135 (setq js2-current-token tt
7136 js2-current-flagged-token (if saw-eol
7137 (logior tt js2-ti-after-eol)
7139 ;; perform lexical fontification as soon as token is scanned
7140 (when js2-parse-ide-mode
7143 (js2-record-face 'js2-error-face))
7144 ((setq face (aref js2-kwd-tokens tt))
7145 (js2-record-face face))
7146 ((and (= tt js2-NAME)
7147 (equal js2-ts-string "undefined"))
7148 (js2-record-face 'font-lock-constant-face))))
7149 tt))) ; return unflagged token
7151 (defsubst js2-peek-flagged-token ()
7152 "Returns the current token along with any flags set for it."
7154 js2-current-flagged-token)
7156 (defsubst js2-consume-token ()
7157 (setq js2-current-flagged-token js2-EOF))
7159 (defsubst js2-next-token ()
7162 (js2-consume-token)))
7164 (defsubst js2-next-flagged-token ()
7166 (prog1 js2-current-flagged-token
7167 (js2-consume-token)))
7169 (defsubst js2-match-token (match)
7170 "Consume and return t if next token matches MATCH, a bytecode.
7171 Returns nil and consumes nothing if MATCH is not the next token."
7172 (if (/= (js2-peek-token) match)
7177 (defsubst js2-valid-prop-name-token (tt)
7179 (and js2-allow-keywords-as-property-names
7181 (aref js2-kwd-tokens tt))))
7183 (defsubst js2-match-prop-name ()
7184 "Consume token and return t if next token is a valid property name.
7185 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7186 is non-nil and it's a keyword token."
7187 (if (js2-valid-prop-name-token (js2-peek-token))
7193 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7194 (if (js2-match-prop-name)
7196 (js2-report-error msg-id nil pos len)
7199 (defsubst js2-peek-token-or-eol ()
7200 "Return js2-EOL if the current token immediately follows a newline.
7201 Else returns the current token. Used in situations where we don't
7202 consider certain token types valid if they are preceded by a newline.
7203 One example is the postfix ++ or -- operator, which has to be on the
7204 same line as its operand."
7205 (let ((tt (js2-peek-token)))
7206 ;; Check for last peeked token flags
7207 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7211 (defsubst js2-set-check-for-label ()
7212 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7213 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7215 (defsubst js2-must-match (token msg-id &optional pos len)
7216 "Match next token to token code TOKEN, or record a syntax error.
7217 MSG-ID is the error message to report if the match fails.
7218 Returns t on match, nil if no match."
7219 (if (js2-match-token token)
7221 (js2-report-error msg-id nil pos len)
7224 (defsubst js2-inside-function ()
7225 (plusp js2-nesting-of-function))
7227 (defsubst js2-set-requires-activation ()
7228 (if (js2-function-node-p js2-current-script-or-fn)
7229 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7231 (defsubst js2-check-activation-name (name token)
7232 (when (js2-inside-function)
7233 ;; skip language-version 1.2 check from Rhino
7234 (if (or (string= "arguments" name)
7235 (and js2-compiler-activation-names ; only used in codegen
7236 (gethash name js2-compiler-activation-names)))
7237 (js2-set-requires-activation))))
7239 (defsubst js2-set-is-generator ()
7240 (if (js2-function-node-p js2-current-script-or-fn)
7241 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7243 (defsubst js2-must-have-xml ()
7244 (unless js2-compiler-xml-available
7245 (js2-report-error "msg.XML.not.available")))
7247 (defsubst js2-push-scope (scope)
7248 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7249 (assert (js2-scope-p scope))
7250 (assert (null (js2-scope-parent-scope scope)))
7251 (assert (not (eq js2-current-scope scope)))
7252 (setf (js2-scope-parent-scope scope) js2-current-scope
7253 js2-current-scope scope))
7255 (defsubst js2-pop-scope ()
7256 (setq js2-current-scope
7257 (js2-scope-parent-scope js2-current-scope)))
7259 (defsubst js2-enter-loop (loop-node)
7260 (push loop-node js2-loop-set)
7261 (push loop-node js2-loop-and-switch-set)
7262 (js2-push-scope loop-node)
7263 ;; Tell the current labeled statement (if any) its statement,
7264 ;; and set the jump target of the first label to the loop.
7265 ;; These are used in `js2-parse-continue' to verify that the
7266 ;; continue target is an actual labeled loop. (And for codegen.)
7267 (when js2-labeled-stmt
7268 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7269 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7270 js2-labeled-stmt))) loop-node)))
7272 (defsubst js2-exit-loop ()
7274 (pop js2-loop-and-switch-set)
7277 (defsubst js2-enter-switch (switch-node)
7278 (push switch-node js2-loop-and-switch-set))
7280 (defsubst js2-exit-switch ()
7281 (pop js2-loop-and-switch-set))
7283 (defun js2-parse (&optional buf cb)
7284 "Tells the js2 parser to parse a region of JavaScript.
7286 BUF is a buffer or buffer name containing the code to parse.
7287 Call `narrow-to-region' first to parse only part of the buffer.
7289 The returned AST root node is given some additional properties:
7290 `node-count' - total number of nodes in the AST
7291 `buffer' - BUF. The buffer it refers to may change or be killed,
7292 so the value is not necessarily reliable.
7294 An optional callback CB can be specified to report parsing
7295 progress. If `(functionp CB)' returns t, it will be called with
7296 the current line number once before parsing begins, then again
7297 each time the lexer reaches a new line number.
7299 CB can also be a list of the form `(symbol cb ...)' to specify
7300 multiple callbacks with different criteria. Each symbol is a
7301 criterion keyword, and the following element is the callback to
7304 :line - called whenever the line number changes
7305 :token - called for each new token consumed
7307 The list of criteria could be extended to include entering or
7308 leaving a statement, an expression, or a function definition."
7309 (if (and cb (not (functionp cb)))
7310 (error "criteria callbacks not yet implemented"))
7311 (let ((inhibit-point-motion-hooks t)
7312 (js2-compiler-xml-available (>= js2-language-version 160))
7313 ;; This is a recursive-descent parser, so give it a big stack.
7314 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7315 (max-specpdl-size (max max-specpdl-size 3000))
7316 (case-fold-search nil)
7318 (or buf (setq buf (current-buffer)))
7319 (message nil) ; clear any error message from previous parse
7322 (setq js2-scanned-comments nil
7323 js2-parsed-errors nil
7324 js2-parsed-warnings nil
7325 js2-imenu-recorder nil
7326 js2-imenu-function-map nil
7329 (setq ast (js2-with-unmodifying-text-property-changes
7331 (unless js2-ts-hit-eof
7332 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7333 (setf (js2-ast-root-errors ast) js2-parsed-errors
7334 (js2-ast-root-warnings ast) js2-parsed-warnings)
7335 ;; if we didn't find any declarations, put a dummy in this list so we
7336 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7337 (unless js2-imenu-recorder
7338 (setq js2-imenu-recorder 'empty))
7339 (run-hooks 'js2-parse-finished-hook)
7342 ;; Corresponds to Rhino's Parser.parse() method.
7343 (defun js2-do-parse ()
7344 "Parse current buffer starting from current point.
7345 Scanner should be initialized."
7346 (let ((pos js2-ts-cursor)
7347 (end js2-ts-cursor) ; in case file is empty
7349 ;; initialize buffer-local parsing vars
7350 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7351 js2-current-script-or-fn root
7352 js2-current-scope root
7353 js2-current-flagged-token js2-EOF
7354 js2-nesting-of-function 0
7355 js2-labeled-stmt nil
7356 js2-recorded-identifiers nil) ; for js2-highlight
7357 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7358 (if (= tt js2-FUNCTION)
7361 (setq n (js2-parse-function (if js2-called-by-compile-function
7362 'FUNCTION_EXPRESSION
7363 'FUNCTION_STATEMENT))))
7364 ;; not a function - parse a statement
7365 (setq n (js2-parse-statement)))
7366 ;; add function or statement to script
7367 (setq end (js2-node-end n))
7368 (js2-block-node-push root n))
7369 ;; add comments to root in lexical order
7370 (when js2-scanned-comments
7371 ;; if we find a comment beyond end of normal kids, use its end
7372 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7373 (dolist (comment js2-scanned-comments)
7374 (push comment (js2-ast-root-comments root))
7375 (js2-node-add-children root comment)))
7376 (setf (js2-node-len root) (- end pos))
7377 ;; Give extensions a chance to muck with things before highlighting starts.
7378 (let ((js2-additional-externs js2-additional-externs))
7379 (dolist (callback js2-post-parse-callbacks)
7381 (js2-highlight-undeclared-vars))
7384 (defun js2-function-parser ()
7386 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7388 (defun js2-parse-function-closure-body (fn-node)
7389 "Parse a JavaScript 1.8 function closure body."
7390 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7392 (js2-report-error "msg.no.brace.body" nil
7393 (js2-node-pos fn-node)
7394 (- js2-ts-cursor (js2-node-pos fn-node)))
7395 (js2-node-add-children fn-node
7396 (setf (js2-function-node-body fn-node)
7397 (js2-parse-expr t))))))
7399 (defun js2-parse-function-body (fn-node)
7400 (js2-must-match js2-LC "msg.no.brace.body"
7401 (js2-node-pos fn-node)
7402 (- js2-ts-cursor (js2-node-pos fn-node)))
7403 (let ((pos js2-token-beg) ; LC position
7404 (pn (make-js2-block-node)) ; starts at LC position
7407 (incf js2-nesting-of-function)
7409 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7412 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7413 (js2-parse-statement)
7415 (js2-parse-function 'FUNCTION_STATEMENT))))
7416 (decf js2-nesting-of-function))
7417 (setq end js2-token-end) ; assume no curly and leave at current token
7418 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7419 (setq end js2-token-end))
7420 (setf (js2-node-pos pn) pos
7421 (js2-node-len pn) (- end pos))
7422 (setf (js2-function-node-body fn-node) pn)
7423 (js2-node-add-children fn-node pn)
7426 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7427 "Declare and fontify destructuring parameters inside NODE.
7428 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7430 ((js2-name-node-p node)
7432 (js2-define-symbol decl-type (js2-name-node-name node)
7433 node ignore-not-in-block)
7435 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7436 (+ leftpos (js2-node-len node))
7438 ((js2-object-node-p node)
7439 (dolist (elem (js2-object-node-elems node))
7440 (js2-define-destruct-symbols
7441 (if (js2-object-prop-node-p elem)
7442 (js2-object-prop-node-right elem)
7443 ;; abbreviated destructuring {a, b}
7445 decl-type face ignore-not-in-block)))
7446 ((js2-array-node-p node)
7447 (dolist (elem (js2-array-node-elems node))
7449 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7450 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7451 (js2-node-len node)))))
7453 (defun js2-parse-function-params (fn-node pos)
7454 (if (js2-match-token js2-RP)
7455 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7456 (let (params len param)
7457 (loop for tt = (js2-peek-token)
7460 ;; destructuring param
7461 ((or (= tt js2-LB) (= tt js2-LC))
7462 (setq param (js2-parse-primary-expr-lhs))
7463 (js2-define-destruct-symbols param
7465 'js2-function-param-face)
7466 (push param params))
7469 (js2-must-match js2-NAME "msg.no.parm")
7470 (js2-record-face 'js2-function-param-face)
7471 (setq param (js2-create-name-node))
7472 (js2-define-symbol js2-LP js2-ts-string param)
7473 (push param params)))
7475 (js2-match-token js2-COMMA))
7476 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7477 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7479 (js2-node-add-children fn-node p)
7480 (push p (js2-function-node-params fn-node))))))
7482 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7483 "Possibly show inconsistent-return warning.
7484 Last token scanned is the close-curly for the function body."
7485 (when (and js2-mode-show-strict-warnings
7486 js2-strict-inconsistent-return-warning
7487 (not (js2-has-consistent-return-usage
7488 (js2-function-node-body fn-node))))
7489 ;; Have it extend from close-curly to bol or beginning of block.
7490 (let ((pos (save-excursion
7491 (goto-char js2-token-end)
7492 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7494 (end js2-token-end))
7495 (if (plusp (js2-name-node-length name))
7496 (js2-add-strict-warning "msg.no.return.value"
7497 (js2-name-node-name name) pos end)
7498 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7500 (defun js2-parse-function (function-type)
7501 "Function parser. FUNCTION-TYPE is a symbol."
7502 (let ((pos js2-token-beg) ; start of 'function' keyword
7508 (synthetic-type function-type)
7510 ;; parse function name, expression, or non-name (anonymous)
7512 ;; function foo(...)
7513 ((js2-match-token js2-NAME)
7514 (setq name (js2-create-name-node t)
7515 name-beg js2-token-beg
7516 name-end js2-token-end)
7517 (unless (js2-match-token js2-LP)
7518 (when js2-allow-member-expr-as-function-name
7519 ;; function foo.bar(...)
7520 (setq member-expr-node name
7522 member-expr-node (js2-parse-member-expr-tail
7523 nil member-expr-node)))
7524 (js2-must-match js2-LP "msg.no.paren.parms")))
7525 ((js2-match-token js2-LP)
7526 nil) ; anonymous function: leave name as null
7528 ;; function random-member-expr(...)
7529 (when js2-allow-member-expr-as-function-name
7530 ;; Note that memberExpr can not start with '(' like
7531 ;; in function (1+2).toString(), because 'function (' already
7532 ;; processed as anonymous function
7533 (setq member-expr-node (js2-parse-member-expr)))
7534 (js2-must-match js2-LP "msg.no.paren.parms")))
7535 (if (= js2-current-token js2-LP) ; eventually matched LP?
7536 (setq lp js2-token-beg))
7537 (if member-expr-node
7539 (setq synthetic-type 'FUNCTION_EXPRESSION)
7540 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7542 (js2-set-face name-beg name-end
7543 'font-lock-function-name-face 'record)))
7544 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7545 (plusp (js2-name-node-length name)))
7546 ;; Function statements define a symbol in the enclosing scope
7547 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7548 (setf fn-node (make-js2-function-node :pos pos
7551 :lp (if lp (- lp pos))))
7552 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7553 ;; 1. Nested functions are not affected by the dynamic scope flag
7554 ;; as dynamic scope is already a parent of their scope.
7555 ;; 2. Functions defined under the with statement also immune to
7556 ;; this setup, in which case dynamic scope is ignored in favor
7557 ;; of the with object.
7558 (setf (js2-function-node-ignore-dynamic fn-node) t))
7559 ;; dynamically bind all the per-function variables
7560 (let ((js2-current-script-or-fn fn-node)
7561 (js2-current-scope fn-node)
7562 (js2-nesting-of-with 0)
7566 js2-loop-and-switch-set)
7567 (js2-parse-function-params fn-node pos)
7568 (if (and (>= js2-language-version 180)
7569 (/= (js2-peek-token) js2-LC))
7570 (js2-parse-function-closure-body fn-node)
7571 (js2-parse-function-body fn-node))
7573 (js2-node-add-children fn-node name))
7574 (js2-check-inconsistent-return-warning fn-node name)
7575 ;; Function expressions define a name only in the body of the
7576 ;; function, and only if not hidden by a parameter name
7578 (eq synthetic-type 'FUNCTION_EXPRESSION)
7579 (null (js2-scope-get-symbol js2-current-scope
7580 (js2-name-node-name name))))
7581 (js2-define-symbol js2-FUNCTION
7582 (js2-name-node-name name)
7585 (not (eq function-type 'FUNCTION_EXPRESSION)))
7586 (js2-record-imenu-functions fn-node)))
7587 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7588 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7589 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7590 ;; We wait until after parsing the function to set its parent scope,
7591 ;; since `js2-define-symbol' needs the defining-scope check to stop
7592 ;; at the function boundary when checking for redeclarations.
7593 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7596 (defun js2-parse-statements (&optional parent)
7597 "Parse a statement list. Last token consumed must be js2-LC.
7599 PARENT can be a `js2-block-node', in which case the statements are
7600 appended to PARENT. Otherwise a new `js2-block-node' is created
7603 This function does not match the closing js2-RC: the caller
7604 matches the RC so it can provide a suitable error message if not
7605 matched. This means it's up to the caller to set the length of
7606 the node to include the closing RC. The node start pos is set to
7607 the absolute buffer start position, and the caller should fix it
7608 up to be relative to the parent node. All children of this block
7609 node are given relative start positions and correct lengths."
7610 (let ((pn (or parent (make-js2-block-node)))
7612 (setf (js2-node-pos pn) js2-token-beg)
7613 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7615 (js2-block-node-push pn (js2-parse-statement)))
7618 (defun js2-parse-statement ()
7619 (let (tt pn beg end)
7620 ;; coarse-grained user-interrupt check - needs work
7621 (and js2-parse-interruptable-p
7622 (zerop (% (incf js2-parse-stmt-count)
7623 js2-statements-per-pause))
7625 (throw 'interrupted t))
7626 (setq pn (js2-statement-helper))
7627 ;; no-side-effects warning check
7628 (unless (js2-node-has-side-effects pn)
7629 (setq end (js2-node-end pn))
7632 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7633 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7636 ;; These correspond to the switch cases in Parser.statementHelper
7637 (defconst js2-parsers
7638 (let ((parsers (make-vector js2-num-tokens
7639 #'js2-parse-expr-stmt)))
7640 (aset parsers js2-BREAK #'js2-parse-break)
7641 (aset parsers js2-CONST #'js2-parse-const-var)
7642 (aset parsers js2-CONTINUE #'js2-parse-continue)
7643 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7644 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7645 (aset parsers js2-DO #'js2-parse-do)
7646 (aset parsers js2-FOR #'js2-parse-for)
7647 (aset parsers js2-FUNCTION #'js2-function-parser)
7648 (aset parsers js2-IF #'js2-parse-if)
7649 (aset parsers js2-LC #'js2-parse-block)
7650 (aset parsers js2-LET #'js2-parse-let-stmt)
7651 (aset parsers js2-NAME #'js2-parse-name-or-label)
7652 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7653 (aset parsers js2-SEMI #'js2-parse-semi)
7654 (aset parsers js2-SWITCH #'js2-parse-switch)
7655 (aset parsers js2-THROW #'js2-parse-throw)
7656 (aset parsers js2-TRY #'js2-parse-try)
7657 (aset parsers js2-VAR #'js2-parse-const-var)
7658 (aset parsers js2-WHILE #'js2-parse-while)
7659 (aset parsers js2-WITH #'js2-parse-with)
7660 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7662 "A vector mapping token types to parser functions.")
7664 (defsubst js2-parse-warn-missing-semi (beg end)
7665 (and js2-mode-show-strict-warnings
7666 js2-strict-missing-semi-warning
7667 (js2-add-strict-warning
7668 "msg.missing.semi" nil
7669 ;; back up to beginning of statement or line
7670 (max beg (save-excursion
7675 (defconst js2-no-semi-insertion
7687 "List of tokens that don't do automatic semicolon insertion.")
7689 (defconst js2-autoinsert-semi-and-warn
7690 (list js2-ERROR js2-EOF js2-RC))
7692 (defun js2-statement-helper ()
7693 (let* ((tt (js2-peek-token))
7696 (parser (if (= tt js2-ERROR)
7698 (aref js2-parsers tt)))
7701 ;; If the statement is set, then it's been told its label by now.
7702 (and js2-labeled-stmt
7703 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7704 (setq js2-labeled-stmt nil))
7705 (setq pn (funcall parser))
7706 ;; Don't do auto semi insertion for certain statement types.
7707 (unless (or (memq first-tt js2-no-semi-insertion)
7708 (js2-labeled-stmt-node-p pn))
7709 (js2-auto-insert-semicolon pn))
7712 (defun js2-auto-insert-semicolon (pn)
7713 (let* ((tt-flagged (js2-peek-flagged-token))
7714 (tt (logand tt-flagged js2-clear-ti-mask))
7715 (pos (js2-node-pos pn)))
7718 ;; Consume ';' as a part of expression
7720 ;; extend the node bounds to include the semicolon.
7721 (setf (js2-node-len pn) (- js2-token-end pos)))
7722 ((memq tt js2-autoinsert-semi-and-warn)
7724 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7726 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7727 ;; Report error if no EOL or autoinsert ';' otherwise
7728 (js2-report-error "msg.no.semi.stmt")
7729 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7731 (defun js2-parse-condition ()
7732 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7733 The parens are discarded and the expression node is returned.
7734 The `pos' field of the return value is set to an absolute position
7735 that must be fixed up by the caller.
7736 Return value is a list (EXPR LP RP), with absolute paren positions."
7738 (if (js2-must-match js2-LP "msg.no.paren.cond")
7739 (setq lp js2-token-beg))
7740 (setq pn (js2-parse-expr))
7741 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7742 (setq rp js2-token-beg))
7743 ;; Report strict warning on code like "if (a = 7) ..."
7744 (if (and js2-strict-cond-assign-warning
7745 (js2-assign-node-p pn))
7746 (js2-add-strict-warning "msg.equal.as.assign" nil
7748 (+ (js2-node-pos pn)
7749 (js2-node-len pn))))
7752 (defun js2-parse-if ()
7753 "Parser for if-statement. Last matched token must be js2-IF."
7754 (let ((pos js2-token-beg)
7762 (setq cond (js2-parse-condition)
7763 if-true (js2-parse-statement)
7764 if-false (if (js2-match-token js2-ELSE)
7766 (setq else-pos (- js2-token-beg pos))
7767 (js2-parse-statement)))
7768 end (js2-node-end (or if-false if-true))
7769 pn (make-js2-if-node :pos pos
7771 :condition (car cond)
7775 :lp (js2-relpos (second cond) pos)
7776 :rp (js2-relpos (third cond) pos)))
7777 (js2-node-add-children pn (car cond) if-true if-false)
7780 (defun js2-parse-switch ()
7781 "Parser for if-statement. Last matched token must be js2-SWITCH."
7782 (let ((pos js2-token-beg)
7795 (if (js2-must-match js2-LP "msg.no.paren.switch")
7796 (setq lp js2-token-beg))
7797 (setq discriminant (js2-parse-expr)
7798 pn (make-js2-switch-node :discriminant discriminant
7800 :lp (js2-relpos lp pos)))
7801 (js2-node-add-children pn discriminant)
7802 (js2-enter-switch pn)
7805 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7806 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7807 (js2-must-match js2-LC "msg.no.brace.switch")
7810 (setq tt (js2-next-token)
7811 case-pos js2-token-beg)
7814 (setf (js2-node-len pn) (- js2-token-end pos))
7815 (throw 'break nil)) ; done
7817 (setq case-expr (js2-parse-expr))
7818 (js2-must-match js2-COLON "msg.no.colon.case"))
7821 (js2-report-error "msg.double.switch.default"))
7824 (js2-must-match js2-COLON "msg.no.colon.case"))
7826 (js2-report-error "msg.bad.switch")
7827 (throw 'break nil)))
7828 (setq case-node (make-js2-case-node :pos case-pos
7829 :len (- js2-token-end case-pos)
7831 (js2-node-add-children case-node case-expr)
7832 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7836 (setf stmt (js2-parse-statement)
7837 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7838 (js2-block-node-push case-node stmt))
7839 (push case-node cases)))
7840 ;; add cases last, as pushing reverses the order to be correct
7842 (js2-node-add-children pn kid)
7843 (push kid (js2-switch-node-cases pn)))
7845 (js2-exit-switch))))
7847 (defun js2-parse-while ()
7848 "Parser for while-statement. Last matched token must be js2-WHILE."
7849 (let ((pos js2-token-beg)
7850 (pn (make-js2-while-node))
7857 (setf cond (js2-parse-condition)
7858 (js2-while-node-condition pn) (car cond)
7859 body (js2-parse-statement)
7860 (js2-while-node-body pn) body
7861 (js2-node-len pn) (- (js2-node-end body) pos)
7862 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7863 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7864 (js2-node-add-children pn body (car cond)))
7868 (defun js2-parse-do ()
7869 "Parser for do-statement. Last matched token must be js2-DO."
7870 (let ((pos js2-token-beg)
7871 (pn (make-js2-do-node))
7879 (setq body (js2-parse-statement))
7880 (js2-must-match js2-WHILE "msg.no.while.do")
7881 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7882 cond (js2-parse-condition)
7883 (js2-do-node-condition pn) (car cond)
7884 (js2-do-node-body pn) body
7886 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7887 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7888 (js2-node-add-children pn (car cond) body))
7890 ;; Always auto-insert semicolon to follow SpiderMonkey:
7891 ;; It is required by ECMAScript but is ignored by the rest of
7892 ;; world; see bug 238945
7893 (if (js2-match-token js2-SEMI)
7894 (setq end js2-ts-cursor))
7895 (setf (js2-node-len pn) (- end pos))
7898 (defun js2-parse-for ()
7899 "Parser for for-statement. Last matched token must be js2-FOR.
7900 Parses for, for-in, and for each-in statements."
7901 (let ((for-pos js2-token-beg)
7908 init ; Node init is also foo in 'foo in object'
7909 cond ; Node cond is also object in 'foo in object'
7910 incr ; 3rd section of for-loop initializer
7916 ;; See if this is a for each () instead of just a for ()
7917 (when (js2-match-token js2-NAME)
7918 (if (string= "each" js2-ts-string)
7921 each-pos (- js2-token-beg for-pos)) ; relative
7922 (js2-record-face 'font-lock-keyword-face))
7923 (js2-report-error "msg.no.paren.for")))
7924 (if (js2-must-match js2-LP "msg.no.paren.for")
7925 (setq lp (- js2-token-beg for-pos)))
7926 (setq tt (js2-peek-token))
7927 ;; 'for' makes local scope
7928 (js2-push-scope (make-js2-scope))
7930 ;; parse init clause
7931 (let ((js2-in-for-init t)) ; set as dynamic variable
7934 (setq init (make-js2-empty-expr-node)))
7935 ((or (= tt js2-VAR) (= tt js2-LET))
7937 (setq init (js2-parse-variables tt js2-token-beg)))
7939 (setq init (js2-parse-expr)))))
7940 (if (js2-match-token js2-IN)
7942 in-pos (- js2-token-beg for-pos)
7943 ;; scope of iteration target object is not the scope we've created above.
7944 ;; stash current scope temporary.
7945 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7946 (js2-parse-expr))) ; object over which we're iterating
7947 ;; else ordinary for loop - parse cond and incr
7948 (js2-must-match js2-SEMI "msg.no.semi.for")
7949 (setq cond (if (= (js2-peek-token) js2-SEMI)
7950 (make-js2-empty-expr-node) ; no loop condition
7952 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7953 (setq tmp-pos js2-token-end
7954 incr (if (= (js2-peek-token) js2-RP)
7955 (make-js2-empty-expr-node :pos tmp-pos)
7957 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7958 (setq rp (- js2-token-beg for-pos)))
7960 (setq pn (make-js2-for-node :init init
7965 ;; cond could be null if 'in obj' got eaten by the init node.
7966 (if (js2-infix-node-p init)
7967 ;; it was (foo in bar) instead of (var foo in bar)
7968 (setq cond (js2-infix-node-right init)
7969 init (js2-infix-node-left init))
7970 (if (and (js2-var-decl-node-p init)
7971 (> (length (js2-var-decl-node-kids init)) 1))
7972 (js2-report-error "msg.mult.index")))
7973 (setq pn (make-js2-for-in-node :iterator init
7976 :foreach-p is-for-each
7983 ;; We have to parse the body -after- creating the loop node,
7984 ;; so that the loop node appears in the js2-loop-set, allowing
7985 ;; break/continue statements to find the enclosing loop.
7986 (setf body (js2-parse-statement)
7987 (js2-loop-node-body pn) body
7988 (js2-node-pos pn) for-pos
7989 (js2-node-len pn) (- (js2-node-end body) for-pos))
7990 (js2-node-add-children pn init cond incr body))
7996 (defun js2-parse-try ()
7997 "Parser for try-statement. Last matched token must be js2-TRY."
7998 (let ((try-pos js2-token-beg)
8016 (if (/= (js2-peek-token) js2-LC)
8017 (js2-report-error "msg.no.brace.try"))
8018 (setq try-block (js2-parse-statement)
8019 try-end (js2-node-end try-block)
8020 peek (js2-peek-token))
8023 (while (js2-match-token js2-CATCH)
8024 (setq catch-pos js2-token-beg
8029 (if saw-default-catch
8030 (js2-report-error "msg.catch.unreachable"))
8031 (if (js2-must-match js2-LP "msg.no.paren.catch")
8032 (setq lp (- js2-token-beg catch-pos)))
8033 (js2-push-scope (make-js2-scope))
8034 (let ((tt (js2-peek-token)))
8036 ;; destructuring pattern
8037 ;; catch ({ message, file }) { ... }
8038 ((or (= tt js2-LB) (= tt js2-LC))
8040 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8044 (js2-must-match js2-NAME "msg.bad.catchcond")
8045 (setq param (js2-create-name-node))
8046 (js2-define-symbol js2-LET js2-ts-string param))))
8048 (if (js2-match-token js2-IF)
8049 (setq guard-kwd (- js2-token-beg catch-pos)
8050 catch-cond (js2-parse-expr))
8051 (setq saw-default-catch t))
8052 (if (js2-must-match js2-RP "msg.bad.catchcond")
8053 (setq rp (- js2-token-beg catch-pos)))
8054 (js2-must-match js2-LC "msg.no.brace.catchblock")
8055 (setq block (js2-parse-statements)
8056 try-end (js2-node-end block)
8057 catch-node (make-js2-catch-node :pos catch-pos
8059 :guard-expr catch-cond
8060 :guard-kwd guard-kwd
8065 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8066 (setq try-end js2-token-beg))
8067 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8068 (js2-node-len catch-node) (- try-end catch-pos))
8069 (js2-node-add-children catch-node param catch-cond block)
8070 (push catch-node catch-blocks)))
8071 ((/= peek js2-FINALLY)
8072 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8073 (js2-node-pos try-block)
8074 (- (setq try-end (js2-node-end try-block))
8075 (js2-node-pos try-block)))))
8076 (when (js2-match-token js2-FINALLY)
8077 (setq finally-pos js2-token-beg
8078 block (js2-parse-statement)
8079 try-end (js2-node-end block)
8080 finally-block (make-js2-finally-node :pos finally-pos
8081 :len (- try-end finally-pos)
8083 (js2-node-add-children finally-block block))
8084 (setq pn (make-js2-try-node :pos try-pos
8085 :len (- try-end try-pos)
8086 :try-block try-block
8087 :finally-block finally-block))
8088 (js2-node-add-children pn try-block finally-block)
8089 ;; push them onto the try-node, which reverses and corrects their order
8090 (dolist (cb catch-blocks)
8091 (js2-node-add-children pn cb)
8092 (push cb (js2-try-node-catch-clauses pn)))
8095 (defun js2-parse-throw ()
8096 "Parser for throw-statement. Last matched token must be js2-THROW."
8097 (let ((pos js2-token-beg)
8101 (if (= (js2-peek-token-or-eol) js2-EOL)
8102 ;; ECMAScript does not allow new lines before throw expression,
8104 (js2-report-error "msg.bad.throw.eol"))
8105 (setq expr (js2-parse-expr)
8106 pn (make-js2-throw-node :pos pos
8107 :len (- (js2-node-end expr) pos)
8109 (js2-node-add-children pn expr)
8112 (defsubst js2-match-jump-label-name (label-name)
8113 "If break/continue specified a label, return that label's labeled stmt.
8114 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8115 does not match an existing label, reports an error and returns nil."
8116 (let ((bundle (cdr (assoc label-name js2-label-set))))
8118 (js2-report-error "msg.undef.label"))
8121 (defun js2-parse-break ()
8122 "Parser for break-statement. Last matched token must be js2-BREAK."
8123 (let ((pos js2-token-beg)
8125 break-target ; statement to break from
8126 break-label ; in "break foo", name-node representing the foo
8127 labels ; matching labeled statement to break to
8129 (js2-consume-token) ; `break'
8130 (when (eq (js2-peek-token-or-eol) js2-NAME)
8132 (setq break-label (js2-create-name-node)
8133 end (js2-node-end break-label)
8134 ;; matchJumpLabelName only matches if there is one
8135 labels (js2-match-jump-label-name js2-ts-string)
8136 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8137 (unless (or break-target break-label)
8138 ;; no break target specified - try for innermost enclosing loop/switch
8139 (if (null js2-loop-and-switch-set)
8141 (js2-report-error "msg.bad.break" nil pos (length "break")))
8142 (setq break-target (car js2-loop-and-switch-set))))
8143 (setq pn (make-js2-break-node :pos pos
8146 :target break-target))
8147 (js2-node-add-children pn break-label) ; but not break-target
8150 (defun js2-parse-continue ()
8151 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8152 (let ((pos js2-token-beg)
8154 label ; optional user-specified label, a `js2-name-node'
8155 labels ; current matching labeled stmt, if any
8156 target ; the `js2-loop-node' target of this continue stmt
8158 (js2-consume-token) ; `continue'
8159 (when (= (js2-peek-token-or-eol) js2-NAME)
8161 (setq label (js2-create-name-node)
8162 end (js2-node-end label)
8163 ;; matchJumpLabelName only matches if there is one
8164 labels (js2-match-jump-label-name js2-ts-string)))
8166 ((null labels) ; no current label to go to
8167 (if (null js2-loop-set) ; no loop to continue to
8168 (js2-report-error "msg.continue.outside" nil pos
8169 (length "continue"))
8170 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8172 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8173 (setq target (js2-labeled-stmt-node-stmt labels))
8174 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8175 (setq pn (make-js2-continue-node :pos pos
8179 (js2-node-add-children pn label) ; but not target - it's not our child
8182 (defun js2-parse-with ()
8183 "Parser for with-statement. Last matched token must be js2-WITH."
8185 (let ((pos js2-token-beg)
8187 (if (js2-must-match js2-LP "msg.no.paren.with")
8188 (setq lp js2-token-beg))
8189 (setq obj (js2-parse-expr))
8190 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8191 (setq rp js2-token-beg))
8192 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8193 (setq body (js2-parse-statement)))
8194 (setq pn (make-js2-with-node :pos pos
8195 :len (- (js2-node-end body) pos)
8198 :lp (js2-relpos lp pos)
8199 :rp (js2-relpos rp pos)))
8200 (js2-node-add-children pn obj body)
8203 (defun js2-parse-const-var ()
8204 "Parser for var- or const-statement.
8205 Last matched token must be js2-CONST or js2-VAR."
8206 (let ((tt (js2-peek-token))
8211 (setq expr (js2-parse-variables tt js2-token-beg)
8212 pn (make-js2-expr-stmt-node :pos pos
8213 :len (- (js2-node-end expr) pos)
8215 (js2-node-add-children pn expr)
8218 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8219 (let ((pn (make-js2-expr-stmt-node :pos pos
8220 :len (js2-node-len expr)
8221 :type (if (js2-inside-function)
8226 (js2-node-add-children pn expr))
8229 (defun js2-parse-let-stmt ()
8230 "Parser for let-statement. Last matched token must be js2-LET."
8232 (let ((pos js2-token-beg)
8235 (if (= (js2-peek-token) js2-LP)
8236 ;; let expression in statement context
8237 (setq expr (js2-parse-let pos 'statement)
8238 pn (js2-wrap-with-expr-stmt pos expr t))
8239 ;; else we're looking at a statement like let x=6, y=7;
8240 (setf expr (js2-parse-variables js2-LET pos)
8241 pn (js2-wrap-with-expr-stmt pos expr t)
8242 (js2-node-type pn) js2-EXPR_RESULT))
8245 (defun js2-parse-ret-yield ()
8246 (js2-parse-return-or-yield (js2-peek-token) nil))
8248 (defconst js2-parse-return-stmt-enders
8249 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8251 (defsubst js2-now-all-set (before after mask)
8252 "Return whether or not the bits in the mask have changed to all set.
8253 BEFORE is bits before change, AFTER is bits after change, and MASK is
8254 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8256 (and (/= (logand before mask) mask)
8257 (= (logand after mask) mask)))
8259 (defun js2-parse-return-or-yield (tt expr-context)
8260 (let ((pos js2-token-beg)
8262 (before js2-end-flags)
8263 (inside-function (js2-inside-function))
8267 (unless inside-function
8268 (js2-report-error (if (eq tt js2-RETURN)
8272 ;; This is ugly, but we don't want to require a semicolon.
8273 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8274 (setq e (js2-parse-expr)
8275 end (js2-node-end e)))
8278 (js2-set-flag js2-end-flags (if (null e)
8280 js2-end-returns-value))
8281 (setq ret (make-js2-return-node :pos pos
8284 (js2-node-add-children ret e)
8285 ;; See if we need a strict mode warning.
8286 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8287 ;; more thorough and accurate than this before/after flag check.
8288 ;; E.g. if there's a finally-block that always returns, we shouldn't
8289 ;; show a warning generated by inconsistent returns in the catch blocks.
8290 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8291 ;; so we know which returns/yields to highlight, and we should get rid of
8292 ;; all the checking in `js2-parse-return-or-yield'.
8293 (if (and js2-strict-inconsistent-return-warning
8294 (js2-now-all-set before js2-end-flags
8295 (logior js2-end-returns js2-end-returns-value)))
8296 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8298 (unless (js2-inside-function)
8299 (js2-report-error "msg.bad.yield"))
8300 (js2-set-flag js2-end-flags js2-end-yields)
8301 (setq ret (make-js2-yield-node :pos pos
8304 (js2-node-add-children ret e)
8305 (unless expr-context
8307 ret (js2-wrap-with-expr-stmt pos e t))
8308 (js2-set-requires-activation)
8309 (js2-set-is-generator))))
8310 ;; see if we are mixing yields and value returns.
8311 (when (and inside-function
8312 (js2-now-all-set before js2-end-flags
8313 (logior js2-end-yields js2-end-returns-value)))
8314 (setq name (js2-function-name js2-current-script-or-fn))
8315 (if (zerop (length name))
8316 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8317 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8320 (defun js2-parse-debugger ()
8322 (make-js2-keyword-node :type js2-DEBUGGER))
8324 (defun js2-parse-block ()
8325 "Parser for a curly-delimited statement block.
8326 Last token matched must be js2-LC."
8327 (let ((pos js2-token-beg)
8328 (pn (make-js2-scope)))
8333 (js2-parse-statements pn)
8334 (js2-must-match js2-RC "msg.no.brace.block")
8335 (setf (js2-node-len pn) (- js2-token-end pos)))
8339 ;; for js2-ERROR too, to have a node for error recovery to work on
8340 (defun js2-parse-semi ()
8341 "Parse a statement or handle an error.
8342 Last matched token is js-SEMI or js-ERROR."
8343 (let ((tt (js2-peek-token)) pos len)
8345 (if (eq tt js2-SEMI)
8346 (make-js2-empty-expr-node :len 1)
8347 (setq pos js2-token-beg
8348 len (- js2-token-beg pos))
8349 (js2-report-error "msg.syntax" nil pos len)
8350 (make-js2-error-node :pos pos :len len))))
8352 (defun js2-parse-default-xml-namespace ()
8353 "Parse a `default xml namespace = <expr>' e4x statement."
8354 (let ((pos js2-token-beg)
8355 end len expr unary es)
8358 (js2-set-requires-activation)
8359 (setq len (- js2-ts-cursor pos))
8360 (unless (and (js2-match-token js2-NAME)
8361 (string= js2-ts-string "xml"))
8362 (js2-report-error "msg.bad.namespace" nil pos len))
8363 (unless (and (js2-match-token js2-NAME)
8364 (string= js2-ts-string "namespace"))
8365 (js2-report-error "msg.bad.namespace" nil pos len))
8366 (unless (js2-match-token js2-ASSIGN)
8367 (js2-report-error "msg.bad.namespace" nil pos len))
8368 (setq expr (js2-parse-expr)
8369 end (js2-node-end expr)
8370 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8374 (js2-node-add-children unary expr)
8375 (make-js2-expr-stmt-node :pos pos
8379 (defun js2-record-label (label bundle)
8380 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8382 (let ((name (js2-label-node-name label))
8385 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8386 ;; flag both labels if possible when used in editing mode
8387 (if (and js2-parse-ide-mode
8388 (setq dup (js2-get-label-by-name labeled-stmt name)))
8389 (js2-report-error "msg.dup.label" nil
8390 (js2-node-abs-pos dup) (js2-node-len dup)))
8391 (js2-report-error "msg.dup.label" nil
8392 (js2-node-pos label) (js2-node-len label)))
8393 (js2-labeled-stmt-node-add-label bundle label)
8394 (js2-node-add-children bundle label)
8395 ;; Add one reference to the bundle per label in `js2-label-set'
8396 (push (cons name bundle) js2-label-set)))
8398 (defun js2-parse-name-or-label ()
8399 "Parser for identifier or label. Last token matched must be js2-NAME.
8400 Called when we found a name in a statement context. If it's a label, we gather
8401 up any following labels and the next non-label statement into a
8402 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8403 expression and return it wrapped in a `js2-expr-stmt-node'."
8404 (let ((pos js2-token-beg)
8411 ;; set check for label and call down to `js2-parse-primary-expr'
8412 (js2-set-check-for-label)
8413 (setq expr (js2-parse-expr))
8414 (if (/= (js2-node-type expr) js2-LABEL)
8415 ;; Parsed non-label expression - wrap with expression stmt.
8416 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8417 ;; else parsed a label
8418 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8419 (js2-record-label expr bundle)
8420 ;; look for more labels
8421 (while (and continue (= (js2-peek-token) js2-NAME))
8422 (js2-set-check-for-label)
8423 (setq expr (js2-parse-expr))
8424 (if (/= (js2-node-type expr) js2-LABEL)
8426 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8428 (js2-auto-insert-semicolon stmt))
8429 (js2-record-label expr bundle)))
8430 ;; no more labels; now parse the labeled statement
8433 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8434 (setq stmt (js2-statement-helper))))
8435 ;; remove the labels for this statement from the global set
8436 (dolist (label (js2-labeled-stmt-node-labels bundle))
8437 (setq js2-label-set (remove label js2-label-set))))
8438 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8439 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8440 (js2-node-add-children bundle stmt)
8443 (defun js2-parse-expr-stmt ()
8444 "Default parser in statement context, if no recognized statement found."
8445 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8447 (defun js2-parse-variables (decl-type pos)
8448 "Parse a comma-separated list of variable declarations.
8449 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8451 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8452 For 'var' or 'const', the keyword should be the token last scanned.
8454 POS is the position where the node should start. It's sometimes the
8455 var/const/let keyword, and other times the beginning of the first token
8456 in the first variable declaration.
8458 Returns the parsed `js2-var-decl-node' expression node."
8459 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8471 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8472 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8473 ;; var {a, b} = baz;
8475 (setq destructuring nil
8478 kid-pos js2-token-beg
8481 (if (or (= tt js2-LB) (= tt js2-LC))
8482 ;; Destructuring assignment, e.g., var [a, b] = ...
8483 (setq destructuring (js2-parse-primary-expr-lhs)
8484 end (js2-node-end destructuring))
8485 ;; Simple variable name
8486 (when (js2-must-match js2-NAME "msg.bad.var")
8487 (setq name (js2-create-name-node)
8491 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8492 (when (js2-match-token js2-ASSIGN)
8493 (setq init (js2-parse-assign-expr)
8494 end (js2-node-end init))
8495 (if (and js2-parse-ide-mode
8496 (or (js2-object-node-p init)
8497 (js2-function-node-p init)))
8498 (js2-record-imenu-functions init name)))
8500 (js2-set-face nbeg nend (if (js2-function-node-p init)
8501 'font-lock-function-name-face
8502 'font-lock-variable-name-face)
8504 (setq vi (make-js2-var-init-node :pos kid-pos
8505 :len (- end kid-pos)
8509 (if (and (null init) (not js2-in-for-init))
8510 (js2-report-error "msg.destruct.assign.no.init"))
8511 (js2-define-destruct-symbols destructuring
8513 'font-lock-variable-name-face)
8514 (setf (js2-var-init-node-target vi) destructuring))
8515 (setf (js2-var-init-node-target vi) name))
8516 (setf (js2-var-init-node-initializer vi) init)
8517 (js2-node-add-children vi name destructuring init)
8518 (js2-block-node-push result vi)
8519 (unless (js2-match-token js2-COMMA)
8520 (setq continue nil)))
8521 (setf (js2-node-len result) (- end pos))
8524 (defun js2-parse-let (pos &optional stmt-p)
8525 "Parse a let expression or statement.
8526 A let-expression is of the form `let (vars) expr'.
8527 A let-statment is of the form `let (vars) {statements}'.
8528 The third form of let is a variable declaration list, handled
8529 by `js2-parse-variables'."
8530 (let ((pn (make-js2-let-node :pos pos))
8532 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8533 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8537 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8538 (if (js2-must-match js2-RP "msg.no.paren.let")
8539 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8540 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8544 (setf beg js2-token-beg ; position stmt at LC
8545 body (js2-parse-statements))
8546 (js2-must-match js2-RC "msg.no.curly.let")
8547 (setf (js2-node-len body) (- js2-token-end beg)
8548 (js2-node-len pn) (- js2-token-end pos)
8549 (js2-let-node-body pn) body
8550 (js2-node-type pn) js2-LET))
8552 (setf body (js2-parse-expr)
8553 (js2-node-len pn) (- (js2-node-end body) pos)
8554 (js2-let-node-body pn) body))
8555 (js2-node-add-children pn vars body))
8559 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8560 (js2-scope-put-symbol (or scope js2-current-scope)
8562 (make-js2-symbol decl-type name node)))
8564 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8565 "Define a symbol in the current scope.
8566 If NODE is non-nil, it is the AST node associated with the symbol."
8567 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8568 (symbol (if defining-scope
8569 (js2-scope-get-symbol defining-scope name)))
8570 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8572 ((and symbol ; already defined
8573 (or (= sdt js2-CONST) ; old version is const
8574 (= decl-type js2-CONST) ; new version is const
8575 ;; two let-bound vars in this block have same name
8576 (and (= sdt js2-LET)
8577 (eq defining-scope js2-current-scope))))
8580 ((= sdt js2-CONST) "msg.const.redecl")
8581 ((= sdt js2-LET) "msg.let.redecl")
8582 ((= sdt js2-VAR) "msg.var.redecl")
8583 ((= sdt js2-FUNCTION) "msg.function.redecl")
8584 (t "msg.parm.redecl"))
8586 ((= decl-type js2-LET)
8587 (if (and (not ignore-not-in-block)
8588 (or (= (js2-node-type js2-current-scope) js2-IF)
8589 (js2-loop-node-p js2-current-scope)))
8590 (js2-report-error "msg.let.decl.not.in.block")
8591 (js2-define-new-symbol decl-type name node)))
8592 ((or (= decl-type js2-VAR)
8593 (= decl-type js2-CONST)
8594 (= decl-type js2-FUNCTION))
8596 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8597 (js2-add-strict-warning "msg.var.redecl" name)
8598 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8599 (js2-add-strict-warning "msg.var.hides.arg" name)))
8600 (js2-define-new-symbol decl-type name node
8601 js2-current-script-or-fn)))
8602 ((= decl-type js2-LP)
8604 ;; must be duplicate parameter. Second parameter hides the
8605 ;; first, so go ahead and add the second pararameter
8606 (js2-report-warning "msg.dup.parms" name))
8607 (js2-define-new-symbol decl-type name node))
8608 (t (js2-code-bug)))))
8610 (defun js2-parse-expr (&optional oneshot)
8611 (let* ((pn (js2-parse-assign-expr))
8612 (pos (js2-node-pos pn))
8616 (while (and (not oneshot)
8617 (js2-match-token js2-COMMA))
8618 (setq op-pos (- js2-token-beg pos)) ; relative
8619 (if (= (js2-peek-token) js2-YIELD)
8620 (js2-report-error "msg.yield.parenthesized"))
8621 (setq right (js2-parse-assign-expr)
8623 pn (make-js2-infix-node :type js2-COMMA
8625 :len (- js2-ts-cursor pos)
8629 (js2-node-add-children pn left right))
8632 (defun js2-parse-assign-expr ()
8633 (let ((tt (js2-peek-token))
8639 (if (= tt js2-YIELD)
8640 (js2-parse-return-or-yield tt t)
8641 ;; not yield - parse assignment expression
8642 (setq pn (js2-parse-cond-expr)
8643 tt (js2-peek-token))
8644 (when (and (<= js2-first-assign tt)
8645 (<= tt js2-last-assign))
8646 ;; tt express assignment (=, |=, ^=, ..., %=)
8648 (setq op-pos (- js2-token-beg pos) ; relative
8650 right (js2-parse-assign-expr)
8651 pn (make-js2-assign-node :type tt
8653 :len (- (js2-node-end right) pos)
8657 (when js2-parse-ide-mode
8658 (js2-highlight-assign-targets pn left right)
8659 (if (or (js2-function-node-p right)
8660 (js2-object-node-p right))
8661 (js2-record-imenu-functions right left)))
8662 ;; do this last so ide checks above can use absolute positions
8663 (js2-node-add-children pn left right))
8666 (defun js2-parse-cond-expr ()
8667 (let ((pos js2-token-beg)
8668 (pn (js2-parse-or-expr))
8674 (when (js2-match-token js2-HOOK)
8675 (setq q-pos (- js2-token-beg pos)
8676 if-true (js2-parse-assign-expr))
8677 (js2-must-match js2-COLON "msg.no.colon.cond")
8678 (setq c-pos (- js2-token-beg pos)
8679 if-false (js2-parse-assign-expr)
8681 pn (make-js2-cond-node :pos pos
8682 :len (- (js2-node-end if-false) pos)
8683 :test-expr test-expr
8685 :false-expr if-false
8688 (js2-node-add-children pn test-expr if-true if-false))
8691 (defun js2-make-binary (type left parser)
8692 "Helper for constructing a binary-operator AST node.
8693 LEFT is the left-side-expression, already parsed, and the
8694 binary operator should have just been matched.
8695 PARSER is a function to call to parse the right operand,
8696 or a `js2-node' struct if it has already been parsed."
8697 (let* ((pos (js2-node-pos left))
8698 (op-pos (- js2-token-beg pos))
8699 (right (if (js2-node-p parser)
8702 (pn (make-js2-infix-node :type type
8704 :len (- (js2-node-end right) pos)
8708 (js2-node-add-children pn left right)
8711 (defun js2-parse-or-expr ()
8712 (let ((pn (js2-parse-and-expr)))
8713 (when (js2-match-token js2-OR)
8714 (setq pn (js2-make-binary js2-OR
8716 'js2-parse-or-expr)))
8719 (defun js2-parse-and-expr ()
8720 (let ((pn (js2-parse-bit-or-expr)))
8721 (when (js2-match-token js2-AND)
8722 (setq pn (js2-make-binary js2-AND
8724 'js2-parse-and-expr)))
8727 (defun js2-parse-bit-or-expr ()
8728 (let ((pn (js2-parse-bit-xor-expr)))
8729 (while (js2-match-token js2-BITOR)
8730 (setq pn (js2-make-binary js2-BITOR
8732 'js2-parse-bit-xor-expr)))
8735 (defun js2-parse-bit-xor-expr ()
8736 (let ((pn (js2-parse-bit-and-expr)))
8737 (while (js2-match-token js2-BITXOR)
8738 (setq pn (js2-make-binary js2-BITXOR
8740 'js2-parse-bit-and-expr)))
8743 (defun js2-parse-bit-and-expr ()
8744 (let ((pn (js2-parse-eq-expr)))
8745 (while (js2-match-token js2-BITAND)
8746 (setq pn (js2-make-binary js2-BITAND
8748 'js2-parse-eq-expr)))
8751 (defconst js2-parse-eq-ops
8752 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8754 (defun js2-parse-eq-expr ()
8755 (let ((pn (js2-parse-rel-expr))
8757 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8759 (setq pn (js2-make-binary tt
8761 'js2-parse-rel-expr)))
8764 (defconst js2-parse-rel-ops
8765 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8767 (defun js2-parse-rel-expr ()
8768 (let ((pn (js2-parse-shift-expr))
8772 (setq tt (js2-peek-token))
8774 ((and js2-in-for-init (= tt js2-IN))
8775 (setq continue nil))
8776 ((memq tt js2-parse-rel-ops)
8778 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8780 (setq continue nil))))
8783 (defconst js2-parse-shift-ops
8784 (list js2-LSH js2-URSH js2-RSH))
8786 (defun js2-parse-shift-expr ()
8787 (let ((pn (js2-parse-add-expr))
8791 (setq tt (js2-peek-token))
8792 (if (memq tt js2-parse-shift-ops)
8795 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8796 (setq continue nil)))
8799 (defun js2-parse-add-expr ()
8800 (let ((pn (js2-parse-mul-expr))
8804 (setq tt (js2-peek-token))
8805 (if (or (= tt js2-ADD) (= tt js2-SUB))
8808 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8809 (setq continue nil)))
8812 (defconst js2-parse-mul-ops
8813 (list js2-MUL js2-DIV js2-MOD))
8815 (defun js2-parse-mul-expr ()
8816 (let ((pn (js2-parse-unary-expr))
8820 (setq tt (js2-peek-token))
8821 (if (memq tt js2-parse-mul-ops)
8824 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8825 (setq continue nil)))
8828 (defsubst js2-make-unary (type parser &rest args)
8829 "Make a unary node of type TYPE.
8830 PARSER is either a node (for postfix operators) or a function to call
8831 to parse the operand (for prefix operators)."
8832 (let* ((pos js2-token-beg)
8833 (postfix (js2-node-p parser))
8836 (apply parser args)))
8839 (if postfix ; e.g. i++
8840 (setq pos (js2-node-pos expr)
8842 (setq end (js2-node-end expr)))
8843 (setq pn (make-js2-unary-node :type type
8847 (js2-node-add-children pn expr)
8850 (defconst js2-incrementable-node-types
8851 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8852 "Node types that can be the operand of a ++ or -- operator.")
8854 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8855 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8856 js2-incrementable-node-types)
8857 (js2-report-error (if (= tt js2-INC)
8860 nil beg (- end beg))))
8862 (defun js2-parse-unary-expr ()
8863 (let ((tt (js2-peek-token))
8866 ((or (= tt js2-VOID)
8871 (js2-make-unary tt 'js2-parse-unary-expr))
8874 ;; Convert to special POS token in decompiler and parse tree
8875 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8878 ;; Convert to special NEG token in decompiler and parse tree
8879 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8884 (setq beg js2-token-beg
8886 expr (js2-make-unary tt 'js2-parse-member-expr t))
8887 (js2-check-bad-inc-dec tt beg end expr)))
8890 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8893 (make-js2-error-node)) ; try to continue
8895 js2-compiler-xml-available)
8896 ;; XML stream encountered in expression.
8898 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8900 (setq pn (js2-parse-member-expr t)
8901 ;; Don't look across a newline boundary for a postfix incop.
8902 tt (js2-peek-token-or-eol))
8903 (when (or (= tt js2-INC) (= tt js2-DEC))
8906 pn (js2-make-unary tt expr))
8907 (js2-node-set-prop pn 'postfix t)
8908 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8911 (defun js2-parse-xml-initializer ()
8912 "Parse an E4X XML initializer.
8913 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8914 Then I'll postprocess the result, depending on whether we're in IDE
8915 mode or codegen mode, and generate the appropriate rewritten AST.
8916 IDE mode uses a rich AST that models the XML structure. Codegen mode
8917 just concatenates everything and makes a new XML or XMLList out of it."
8918 (let ((tt (js2-get-first-xml-token))
8926 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8927 (js2-report-error "msg.syntax"))
8928 (setq pn-xml (make-js2-xml-node))
8931 (setq first-token nil)
8932 (setq tt (js2-get-next-xml-token)))
8934 ;; js2-XML means we found a {expr} in the XML stream.
8935 ;; The js2-ts-string is the XML up to the left-curly.
8937 (push (make-js2-string-node :pos js2-token-beg
8938 :len (- js2-ts-cursor js2-token-beg))
8940 (js2-must-match js2-LC "msg.syntax")
8941 (setq expr-pos js2-ts-cursor
8942 expr (if (eq (js2-peek-token) js2-RC)
8943 (make-js2-empty-expr-node :pos expr-pos)
8945 (js2-must-match js2-RC "msg.syntax")
8946 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8947 :len (js2-node-len expr)
8949 (js2-node-add-children pn expr)
8951 ;; a js2-XMLEND token means we hit the final close-tag.
8953 (push (make-js2-string-node :pos js2-token-beg
8954 :len (- js2-ts-cursor js2-token-beg))
8956 (dolist (kid (nreverse kids))
8957 (js2-block-node-push pn-xml kid))
8958 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8959 (js2-node-pos pn-xml))
8962 (js2-report-error "msg.syntax")
8963 (setq continue nil))))
8967 (defun js2-parse-argument-list ()
8968 "Parse an argument list and return it as a lisp list of nodes.
8969 Returns the list in reverse order. Consumes the right-paren token."
8971 (unless (js2-match-token js2-RP)
8973 (if (= (js2-peek-token) js2-YIELD)
8974 (js2-report-error "msg.yield.parenthesized"))
8975 (push (js2-parse-assign-expr) result)
8977 (js2-match-token js2-COMMA))
8978 (js2-must-match js2-RP "msg.no.paren.arg")
8981 (defun js2-parse-member-expr (&optional allow-call-syntax)
8982 (let ((tt (js2-peek-token))
8992 (setq pn (js2-parse-primary-expr))
8993 ;; parse a 'new' expression
8995 (setq pos js2-token-beg
8997 target (js2-parse-member-expr)
8998 end (js2-node-end target)
8999 pn (make-js2-new-node :pos pos
9002 (js2-node-add-children pn target)
9003 (when (js2-match-token js2-LP)
9004 ;; Add the arguments to pn, if any are supplied.
9005 (setf beg pos ; start of "new" keyword
9007 args (nreverse (js2-parse-argument-list))
9008 (js2-new-node-args pn) args
9010 (js2-new-node-lp pn) (- pos beg)
9011 (js2-new-node-rp pn) (- end 1 beg))
9012 (apply #'js2-node-add-children pn args))
9013 (when (and js2-allow-rhino-new-expr-initializer
9014 (js2-match-token js2-LC))
9015 (setf init (js2-parse-object-literal)
9016 end (js2-node-end init)
9017 (js2-new-node-initializer pn) init)
9018 (js2-node-add-children pn init))
9019 (setf (js2-node-len pn) (- end beg))) ; end outer if
9020 (js2-parse-member-expr-tail allow-call-syntax pn)))
9022 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9023 "Parse a chain of property/array accesses or function calls.
9024 Includes parsing for E4X operators like `..' and `.@'.
9025 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9026 Returns an expression tree that includes PN, the parent node."
9027 (let ((beg (js2-node-pos pn))
9031 (setq tt (js2-peek-token))
9033 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9034 (setq pn (js2-parse-property-access tt pn)))
9035 ((= tt js2-DOTQUERY)
9036 (setq pn (js2-parse-dot-query pn)))
9038 (setq pn (js2-parse-element-get pn)))
9040 (if allow-call-syntax
9041 (setq pn (js2-parse-function-call pn))
9042 (setq continue nil)))
9044 (setq continue nil))))
9045 (if (>= js2-highlight-level 2)
9046 (js2-parse-highlight-member-expr-node pn))
9049 (defun js2-parse-dot-query (pn)
9050 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9051 Last token parsed must be `js2-DOTQUERY'."
9052 (let ((pos (js2-node-pos pn))
9058 (js2-set-requires-activation)
9059 (setq op-pos js2-token-beg
9060 expr (js2-parse-expr)
9061 end (js2-node-end expr)
9062 pn (make-js2-xml-dot-query-node :left pn
9066 (js2-node-add-children pn
9067 (js2-xml-dot-query-node-left pn)
9068 (js2-xml-dot-query-node-right pn))
9069 (if (js2-must-match js2-RP "msg.no.paren")
9070 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9072 (setf (js2-node-len pn) (- end pos))
9075 (defun js2-parse-element-get (pn)
9076 "Parse an element-get expression, e.g. foo[bar].
9077 Last token parsed must be `js2-RB'."
9078 (let ((lb js2-token-beg)
9079 (pos (js2-node-pos pn))
9083 (setq expr (js2-parse-expr))
9084 (if (js2-must-match js2-RB "msg.no.bracket.index")
9085 (setq rb js2-token-beg))
9086 (setq pn (make-js2-elem-get-node :target pn
9089 :lb (js2-relpos lb pos)
9090 :rb (js2-relpos rb pos)
9091 :len (- js2-token-end pos)))
9092 (js2-node-add-children pn
9093 (js2-elem-get-node-target pn)
9094 (js2-elem-get-node-element pn))
9097 (defun js2-parse-function-call (pn)
9099 (pos (js2-node-pos pn)))
9101 (setq pn (make-js2-call-node :pos pos
9103 :lp (- js2-token-beg pos)))
9104 (js2-node-add-children pn (js2-call-node-target pn))
9105 ;; Add the arguments to pn, if any are supplied.
9106 (setf args (nreverse (js2-parse-argument-list))
9107 (js2-call-node-rp pn) (- js2-token-beg pos)
9108 (js2-call-node-args pn) args)
9109 (apply #'js2-node-add-children pn args)
9110 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9113 (defun js2-parse-property-access (tt pn)
9114 "Parse a property access, XML descendants access, or XML attr access."
9115 (let ((member-type-flags 0)
9116 (dot-pos js2-token-beg)
9117 (dot-len (if (= tt js2-DOTDOT) 2 1))
9119 ref ; right side of . or .. operator
9122 (when (= tt js2-DOTDOT)
9124 (setq member-type-flags js2-descendants-flag))
9125 (if (not js2-compiler-xml-available)
9127 (js2-must-match-prop-name "msg.no.name.after.dot")
9128 (setq name (js2-create-name-node t js2-GETPROP)
9129 result (make-js2-prop-get-node :left pn
9132 :len (- js2-token-end
9134 (js2-node-add-children result pn name)
9136 ;; otherwise look for XML operators
9137 (setf result (if (= tt js2-DOT)
9138 (make-js2-prop-get-node)
9139 (make-js2-infix-node :type js2-DOTDOT))
9140 (js2-node-pos result) (js2-node-pos pn)
9141 (js2-infix-node-op-pos result) dot-pos
9142 (js2-infix-node-left result) pn ; do this after setting position
9143 tt (js2-next-token))
9145 ;; needed for generator.throw()
9147 (js2-save-name-token-data js2-token-beg "throw")
9148 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9149 ;; handles: name, ns::name, ns::*, ns::[expr]
9150 ((js2-valid-prop-name-token tt)
9151 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9152 ;; handles: *, *::name, *::*, *::[expr]
9154 (js2-save-name-token-data js2-token-beg "*")
9155 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9156 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9158 (setq result (js2-parse-attribute-access)))
9160 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9162 (setf (js2-node-len result) (- (js2-node-end ref)
9163 (js2-node-pos result))
9164 (js2-infix-node-right result) ref))
9165 (if (js2-infix-node-p result)
9166 (js2-node-add-children result
9167 (js2-infix-node-left result)
9168 (js2-infix-node-right result)))
9171 (defun js2-parse-attribute-access ()
9172 "Parse an E4X XML attribute expression.
9173 This includes expressions of the forms:
9175 @attr @ns::attr @ns::*
9177 @[expr] @*::[expr] @ns::[expr]
9179 Called if we peeked an '@' token."
9180 (let ((tt (js2-next-token))
9181 (at-pos js2-token-beg))
9183 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9184 ((js2-valid-prop-name-token tt)
9185 (js2-parse-property-name at-pos js2-ts-string 0))
9186 ;; handles: @*, @*::name, @*::*, @*::[expr]
9188 (js2-save-name-token-data js2-token-beg "*")
9189 (js2-parse-property-name js2-token-beg "*" 0))
9192 (js2-parse-xml-elem-ref at-pos))
9194 (js2-report-error "msg.no.name.after.xmlAttr")
9195 ;; Avoid cascaded errors that happen if we make an error node here.
9196 (js2-save-name-token-data js2-token-beg "")
9197 (js2-parse-property-name js2-token-beg "" 0)))))
9199 (defun js2-parse-property-name (at-pos s member-type-flags)
9200 "Check if :: follows name in which case it becomes qualified name.
9202 AT-POS is a natural number if we just read an '@' token, else nil.
9203 S is the name or string that was matched: an identifier, 'throw' or '*'.
9204 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9206 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9207 operator, or the name is followed by ::. For a plain name, returns a
9208 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9209 (let ((pos (or at-pos js2-token-beg))
9211 (name (js2-create-name-node t js2-current-token))
9217 (when (js2-match-token js2-COLONCOLON)
9219 colon-pos js2-token-beg
9220 tt (js2-next-token))
9222 ;; handles name::name
9223 ((js2-valid-prop-name-token tt)
9224 (setq name (js2-create-name-node)))
9227 (js2-save-name-token-data js2-token-beg "*")
9228 (setq name (js2-create-name-node)))
9229 ;; handles name::[expr]
9231 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9233 (js2-report-error "msg.no.name.after.coloncolon"))))
9234 (if (and (null ns) (zerop member-type-flags))
9238 (make-js2-xml-prop-ref-node :pos pos
9239 :len (- (js2-node-end name) pos)
9241 :colon-pos colon-pos
9243 (js2-node-add-children pn name))))))
9245 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9246 "Parse the [expr] portion of an xml element reference.
9247 For instance, @[expr], @*::[expr], or ns::[expr]."
9248 (let* ((lb js2-token-beg)
9249 (pos (or at-pos lb))
9251 (expr (js2-parse-expr))
9252 (end (js2-node-end expr))
9254 (if (js2-must-match js2-RB "msg.no.bracket.index")
9255 (setq rb js2-token-beg
9259 (make-js2-xml-elem-ref-node :pos pos
9261 :namespace namespace
9262 :colon-pos colon-pos
9265 :lb (js2-relpos lb pos)
9266 :rb (js2-relpos rb pos)))
9267 (js2-node-add-children pn namespace expr))))
9269 (defsubst js2-parse-primary-expr-lhs ()
9270 (let ((js2-is-in-lhs t))
9271 (js2-parse-primary-expr)))
9273 (defun js2-parse-primary-expr ()
9274 "Parses a literal (leaf) expression of some sort.
9275 Includes complex literals such as functions, object-literals,
9276 array-literals, array comprehensions and regular expressions."
9277 (let ((tt-flagged (js2-next-flagged-token))
9278 pn ; parent node (usually return value)
9280 px-pos ; paren-expr pos
9282 flags ; regexp flags
9284 (setq tt js2-current-token)
9286 ((= tt js2-FUNCTION)
9287 (js2-parse-function 'FUNCTION_EXPRESSION))
9289 (js2-parse-array-literal))
9291 (js2-parse-object-literal))
9293 (js2-parse-let js2-token-beg))
9295 (setq px-pos js2-token-beg
9296 expr (js2-parse-expr))
9297 (js2-must-match js2-RP "msg.no.paren")
9298 (setq pn (make-js2-paren-node :pos px-pos
9300 :len (- js2-token-end px-pos)))
9301 (js2-node-add-children pn (js2-paren-node-expr pn))
9305 (js2-parse-attribute-access))
9307 (js2-parse-name tt-flagged tt))
9309 (make-js2-number-node))
9312 (make-js2-string-node)
9313 (js2-record-face 'font-lock-string-face)))
9314 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9315 ;; Got / or /= which in this context means a regexp literal
9316 (setq px-pos js2-token-beg)
9317 (js2-read-regexp tt)
9318 (setq flags js2-ts-regexp-flags
9319 js2-ts-regexp-flags nil)
9321 (make-js2-regexp-node :pos px-pos
9322 :len (- js2-ts-cursor px-pos)
9323 :value js2-ts-string
9325 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9326 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9327 ((or (= tt js2-NULL)
9331 (make-js2-keyword-node :type tt))
9332 ((= tt js2-RESERVED)
9333 (js2-report-error "msg.reserved.id")
9334 (make-js2-name-node))
9336 ;; the scanner or one of its subroutines reported the error.
9337 (make-js2-error-node))
9339 (setq px-pos (point-at-bol)
9340 len (- js2-ts-cursor px-pos))
9341 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9342 (make-js2-error-node :pos px-pos :len len))
9344 (js2-report-error "msg.syntax")
9345 (make-js2-error-node)))))
9347 (defun js2-parse-name (tt-flagged tt)
9348 (let ((name js2-ts-string)
9349 (name-pos js2-token-beg)
9351 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9352 (= (js2-peek-token) js2-COLON))
9354 ;; Do not consume colon, it is used as unwind indicator
9355 ;; to return to statementHelper.
9356 (make-js2-label-node :pos name-pos
9357 :len (- js2-token-end name-pos)
9359 (js2-set-face name-pos
9361 'font-lock-variable-name-face 'record))
9362 ;; Otherwise not a label, just a name. Unfortunately peeking
9363 ;; the next token to check for a colon has biffed js2-token-beg
9364 ;; and js2-token-end. We store the name's bounds in buffer vars
9365 ;; and `js2-create-name-node' uses them.
9366 (js2-save-name-token-data name-pos name)
9367 (setq node (if js2-compiler-xml-available
9368 (js2-parse-property-name nil name 0)
9369 (js2-create-name-node 'check-activation)))
9370 (if js2-highlight-external-variables
9371 (js2-record-name-node node))
9374 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9375 (js2-add-strict-warning
9377 ;; back up from comma to beginning of line or array/objlit
9379 (js2-node-pos (car elems))
9382 (goto-char comma-pos)
9383 (back-to-indentation)
9387 (defun js2-parse-array-literal ()
9388 (let ((pos js2-token-beg)
9390 (after-lb-or-comma t)
9396 (unless js2-is-in-lhs
9397 (js2-push-scope (make-js2-scope))) ; for array comp
9399 (setq tt (js2-peek-token))
9404 (setq after-comma js2-token-end)
9405 (if (not after-lb-or-comma)
9406 (setq after-lb-or-comma t)
9410 (= tt js2-EOF)) ; prevent infinite loop
9412 (js2-report-error "msg.no.bracket.arg" nil pos)
9413 (js2-consume-token))
9416 pn (make-js2-array-node :pos pos
9417 :len (- js2-ts-cursor pos)
9418 :elems (nreverse elems)))
9419 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9420 (when (and after-comma (not js2-is-in-lhs))
9421 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9422 pos elems after-comma)))
9423 ;; destructuring binding
9425 (push (if (or (= tt js2-LC)
9428 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9429 (js2-parse-primary-expr-lhs)
9432 (js2-report-error "msg.bad.var")
9433 (make-js2-error-node))
9435 (setq after-lb-or-comma nil
9438 ((and (>= js2-language-version 170)
9439 (= tt js2-FOR) ; check for array comprehension
9440 (not after-lb-or-comma) ; "for" can't follow a comma
9441 elems ; must have at least 1 element
9442 (not (cdr elems))) ; but no 2nd element
9444 pn (js2-parse-array-comprehension (car elems) pos)))
9448 (unless after-lb-or-comma
9449 (js2-report-error "msg.no.bracket.arg"))
9450 (push (js2-parse-assign-expr) elems)
9451 (setq after-lb-or-comma nil
9453 (unless js2-is-in-lhs
9457 (defun js2-parse-array-comprehension (expr pos)
9458 "Parse a JavaScript 1.7 Array Comprehension.
9459 EXPR is the first expression after the opening left-bracket.
9460 POS is the beginning of the LB token preceding EXPR.
9461 We should have just parsed the 'for' keyword before calling this function."
9469 (while (= (js2-peek-token) js2-FOR)
9470 (let ((prev (car loops))) ; rearrange scope chain
9471 (push (setq loop (js2-parse-array-comp-loop)) loops)
9472 (if prev ; each loop is parent scope to the next one
9473 (setf (js2-scope-parent-scope loop) prev)
9474 ; first loop takes expr scope's parent
9475 (setf (js2-scope-parent-scope (setq first loop))
9476 (js2-scope-parent-scope js2-current-scope)))))
9477 ;; set expr scope's parent to the last loop
9478 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9479 (when (= (js2-peek-token) js2-IF)
9481 (setq if-pos (- js2-token-beg pos) ; relative
9482 filter (js2-parse-condition)))
9483 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9484 (setq result (make-js2-array-comp-node :pos pos
9485 :len (- js2-ts-cursor pos)
9487 :loops (nreverse loops)
9488 :filter (car filter)
9489 :lp (js2-relpos (second filter) pos)
9490 :rp (js2-relpos (third filter) pos)
9492 (apply #'js2-node-add-children result expr (car filter)
9493 (js2-array-comp-node-loops result))
9494 (setq js2-current-scope first) ; pop to the first loop
9497 (defun js2-parse-array-comp-loop ()
9498 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9499 Last token peeked should be the initial FOR."
9500 (let ((pos js2-token-beg)
9501 (pn (make-js2-array-comp-loop-node))
9510 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9514 (when (js2-match-token js2-NAME)
9515 (if (string= js2-ts-string "each")
9518 each-pos (- js2-token-beg pos)) ; relative
9519 (js2-record-face 'font-lock-keyword-face))
9520 (js2-report-error "msg.no.paren.for")))
9521 (if (js2-must-match js2-LP "msg.no.paren.for")
9522 (setq lp (- js2-token-beg pos)))
9523 (setq tt (js2-peek-token))
9527 ;; handle destructuring assignment
9528 (setq iter (js2-parse-primary-expr-lhs))
9529 (js2-define-destruct-symbols iter js2-LET
9530 'font-lock-variable-name-face t))
9531 ((js2-valid-prop-name-token tt)
9533 (setq iter (js2-create-name-node)))
9535 (js2-report-error "msg.bad.var")))
9536 ;; Define as a let since we want the scope of the variable to
9537 ;; be restricted to the array comprehension
9538 (if (js2-name-node-p iter)
9539 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9540 (if (js2-must-match js2-IN "msg.in.after.for.name")
9541 (setq in-pos (- js2-token-beg pos)))
9542 (setq obj (js2-parse-expr))
9543 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9544 (setq rp (- js2-token-beg pos)))
9545 (setf (js2-node-pos pn) pos
9546 (js2-node-len pn) (- js2-ts-cursor pos)
9547 (js2-array-comp-loop-node-iterator pn) iter
9548 (js2-array-comp-loop-node-object pn) obj
9549 (js2-array-comp-loop-node-in-pos pn) in-pos
9550 (js2-array-comp-loop-node-each-pos pn) each-pos
9551 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9552 (js2-array-comp-loop-node-lp pn) lp
9553 (js2-array-comp-loop-node-rp pn) rp)
9554 (js2-node-add-children pn iter obj))
9558 (defun js2-parse-object-literal ()
9559 (let ((pos js2-token-beg)
9566 (setq tt (js2-peek-token))
9568 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9569 ((or (js2-valid-prop-name-token tt)
9571 (setq after-comma nil
9572 result (js2-parse-named-prop tt))
9573 (if (and (null result)
9574 (not js2-recover-from-parse-errors))
9576 (push result elems)))
9577 ;; {12: x} or {10.7: x}
9580 (setq after-comma nil)
9581 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9586 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9587 pos elems after-comma)))
9589 (js2-report-error "msg.bad.prop")
9590 (unless js2-recover-from-parse-errors
9591 (setq continue nil)))) ; end switch
9592 (if (js2-match-token js2-COMMA)
9593 (setq after-comma js2-token-end)
9594 (setq continue nil))) ; end loop
9595 (js2-must-match js2-RC "msg.no.brace.prop")
9596 (setq result (make-js2-object-node :pos pos
9597 :len (- js2-ts-cursor pos)
9598 :elems (nreverse elems)))
9599 (apply #'js2-node-add-children result (js2-object-node-elems result))
9602 (defun js2-parse-named-prop (tt)
9603 "Parse a name, string, or getter/setter object property.
9604 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9606 (let ((string-prop (and (= tt js2-STRING)
9607 (make-js2-string-node)))
9609 (ppos js2-token-beg)
9610 (pend js2-token-end)
9611 (name (js2-create-name-node))
9612 (prop js2-ts-string))
9614 ;; getter/setter prop
9615 ((and (= tt js2-NAME)
9616 (= (js2-peek-token) js2-NAME)
9617 (or (string= prop "get")
9618 (string= prop "set")))
9620 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9621 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9622 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9623 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9624 ;; abbreviated destructuring bind e.g., {a, b} = c;
9625 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9626 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9627 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9628 ;; assignment but it's difficult because it requires looking ahead of expression.
9631 (let ((ctk (js2-peek-token)))
9632 (or (= ctk js2-COMMA)
9634 (js2-valid-prop-name-token ctk))))
9639 (setq expr (js2-parse-plain-property (or string-prop name)))
9640 (js2-set-face ppos pend
9641 (if (js2-function-node-p
9642 (js2-object-prop-node-right expr))
9643 'font-lock-function-name-face
9644 'font-lock-variable-name-face)
9647 (defun js2-parse-plain-property (prop)
9648 "Parse a non-getter/setter property in an object literal.
9649 PROP is the node representing the property: a number, name or string."
9650 (js2-must-match js2-COLON "msg.no.colon.prop")
9651 (let* ((pos (js2-node-pos prop))
9652 (colon (- js2-token-beg pos))
9653 (expr (js2-parse-assign-expr))
9654 (result (make-js2-object-prop-node
9656 ;; don't include last consumed token in length
9657 :len (- (+ (js2-node-pos expr)
9658 (js2-node-len expr))
9663 (js2-node-add-children result prop expr)
9666 (defun js2-parse-getter-setter-prop (pos prop get-p)
9667 "Parse getter or setter property in an object literal.
9668 JavaScript syntax is:
9670 { get foo() {...}, set foo(x) {...} }
9672 and expression closure style is also supported
9674 { get foo() x, set foo(x) _x = x }
9676 POS is the start position of the `get' or `set' keyword.
9677 PROP is the `js2-name-node' representing the property name.
9678 GET-P is non-nil if the keyword was `get'."
9679 (let ((type (if get-p js2-GET js2-SET))
9682 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9683 ;; it has to be an anonymous function, as we already parsed the name
9684 (if (/= (js2-node-type fn) js2-FUNCTION)
9685 (js2-report-error "msg.bad.prop")
9686 (if (plusp (length (js2-function-name fn)))
9687 (js2-report-error "msg.bad.prop")))
9688 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9689 (setq end (js2-node-end fn)
9690 result (make-js2-getter-setter-node :type type
9695 (js2-node-add-children result prop fn)
9698 (defun js2-create-name-node (&optional check-activation-p token)
9699 "Create a name node using the token info from last scanned name.
9700 In some cases we need to either synthesize a name node, or we lost
9701 the name token information by peeking. If the TOKEN parameter is
9702 not `js2-NAME', then we use the token info saved in instance vars."
9703 (let ((beg js2-token-beg)
9706 (when (/= js2-current-token js2-NAME)
9707 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9708 s js2-prev-name-token-string
9709 js2-prev-name-token-start nil
9710 js2-prev-name-token-string nil))
9711 (setq name (make-js2-name-node :pos beg
9714 (if check-activation-p
9715 (js2-check-activation-name s (or token js2-NAME)))
9718 ;;; Indentation support
9720 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9721 ;; Karl cleverly deduces that the desired indentation level is often a
9722 ;; function of paren/bracket/brace nesting depth, which can be determined
9723 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9724 ;; then does some equally clever checks to see if we're in the context of a
9725 ;; substatement of a possibly braceless statement keyword such as if, while,
9726 ;; or finally. This approach yields pretty good results.
9728 ;; The indenter is often "wrong", however, and needs to be overridden.
9729 ;; The right long-term solution is probably to emulate (or integrate
9730 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9731 ;; parse tree from `js2-parse' is present, which is not true at the
9732 ;; moment the user is typing, computing indentation is still thousands
9733 ;; of lines of code to handle every possible syntactic edge case.
9735 ;; In the meantime, the compromise solution is that we offer a "bounce
9736 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9737 ;; current line indent among various likely guess points. This approach
9738 ;; is far from perfect, but should at least make it slightly easier to
9739 ;; move the line towards its desired indentation when manually
9740 ;; overriding Karl's heuristic nesting guesser.
9742 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9743 ;; extensions such as `let' and Array comprehensions. Major kudos to
9744 ;; Karl for coming up with the initial approach, which packs a lot of
9745 ;; punch for so little code.
9747 (defconst js-possibly-braceless-keywords-re
9748 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9749 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9750 "try" "while" "with" "let")))
9751 "Regular expression matching keywords that are optionally
9752 followed by an opening brace.")
9754 (defconst js-indent-operator-re
9755 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9756 (regexp-opt '("in" "instanceof") 'words))
9757 "Regular expression matching operators that affect indentation
9758 of continued expressions.")
9760 (defconst js-declaration-keyword-re
9761 (regexp-opt '("var" "let" "const") 'words)
9762 "Regular expression matching variable declaration keywords.")
9764 ;; This function has horrible results if you're typing an array
9765 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9766 ;; in conjunction with electric-indent, so just disabling it.
9767 (defsubst js2-code-at-bol-p ()
9768 "Return t if the first character on line is non-whitespace."
9771 (defun js2-insert-and-indent (key)
9772 "Run command bound to key and indent current line. Runs the command
9773 bound to KEY in the global keymap and indents the current line."
9774 (interactive (list (this-command-keys)))
9775 (let ((cmd (lookup-key (current-global-map) key)))
9777 (call-interactively cmd)))
9778 ;; don't do the electric keys inside comments or strings,
9779 ;; and don't do bounce-indent with them.
9780 (let ((parse-state (syntax-ppss (point)))
9781 (js2-bounce-indent-p (js2-code-at-bol-p)))
9782 (unless (or (nth 3 parse-state)
9783 (nth 4 parse-state))
9784 (indent-according-to-mode))))
9786 (defun js-re-search-forward-inner (regexp &optional bound count)
9787 "Auxiliary function for `js-re-search-forward'."
9788 (let (parse saved-point)
9790 (re-search-forward regexp bound)
9791 (setq parse (if saved-point
9792 (parse-partial-sexp saved-point (point))
9793 (syntax-ppss (point))))
9794 (cond ((nth 3 parse)
9796 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9797 (save-excursion (end-of-line) (point)) t))
9801 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9802 (re-search-forward "\\*/"))
9804 (setq count (1- count))))
9805 (setq saved-point (point))))
9808 (defun js-re-search-forward (regexp &optional bound noerror count)
9809 "Search forward but ignore strings and comments. Invokes
9810 `re-search-forward' but treats the buffer as if strings and
9811 comments have been removed."
9812 (let ((saved-point (point))
9815 '(js-re-search-forward-inner regexp bound 1))
9817 '(js-re-search-backward-inner regexp bound (- count)))
9819 '(js-re-search-forward-inner regexp bound count)))))
9823 (goto-char saved-point)
9825 (error (error-message-string err)))))))
9827 (defun js-re-search-backward-inner (regexp &optional bound count)
9828 "Auxiliary function for `js-re-search-backward'."
9829 (let (parse saved-point)
9831 (re-search-backward regexp bound)
9832 (setq parse (if saved-point
9833 (parse-partial-sexp saved-point (point))
9834 (syntax-ppss (point))))
9835 (cond ((nth 3 parse)
9837 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9838 (save-excursion (beginning-of-line) (point)) t))
9840 (goto-char (nth 8 parse)))
9842 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9843 (re-search-backward "/\\*"))
9845 (setq count (1- count))))))
9848 (defun js-re-search-backward (regexp &optional bound noerror count)
9849 "Search backward but ignore strings and comments. Invokes
9850 `re-search-backward' but treats the buffer as if strings and
9851 comments have been removed."
9852 (let ((saved-point (point))
9855 '(js-re-search-backward-inner regexp bound 1))
9857 '(js-re-search-forward-inner regexp bound (- count)))
9859 '(js-re-search-backward-inner regexp bound count)))))
9863 (goto-char saved-point)
9865 (error (error-message-string err)))))))
9867 (defun js-looking-at-operator-p ()
9868 "Return non-nil if text after point is an operator (that is not
9871 (and (looking-at js-indent-operator-re)
9872 (or (not (looking-at ":"))
9874 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9875 (looking-at "?")))))))
9877 (defun js-continued-expression-p ()
9878 "Returns non-nil if the current line continues an expression."
9880 (back-to-indentation)
9881 (or (js-looking-at-operator-p)
9883 (and (js-re-search-backward "\n" nil t)
9885 (skip-chars-backward " \t")
9888 (and (js-looking-at-operator-p)
9891 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9893 (defun js-end-of-do-while-loop-p ()
9894 "Returns non-nil if word after point is `while' of a do-while
9895 statement, else returns nil. A braceless do-while statement
9896 spanning several lines requires that the start of the loop is
9897 indented to the same column as the current line."
9901 (when (looking-at "\\s-*\\<while\\>")
9903 (skip-chars-backward "[ \t\n]*}")
9904 (looking-at "[ \t\n]*}"))
9906 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9907 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9908 (or (looking-at "\\<do\\>")
9909 (let ((saved-indent (current-indentation)))
9910 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9911 (/= (current-indentation) saved-indent)))
9912 (and (looking-at "[ \t]*\\<do\\>")
9913 (not (js-re-search-forward
9914 "\\<while\\>" (point-at-eol) t))
9915 (= (current-indentation) saved-indent)))))))))
9917 (defun js-multiline-decl-indentation ()
9918 "Returns the declaration indentation column if the current line belongs
9919 to a multiline declaration statement. All declarations are lined up vertically:
9925 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9926 assigned expression is a function or array/object literal, it will be indented
9929 var o = { var bar = 2,
9934 (let (forward-sexp-function ; use lisp version
9937 (back-to-indentation)
9938 (when (not (looking-at js-declaration-keyword-re))
9939 (when (looking-at js-indent-operator-re)
9940 (goto-char (match-end 0))) ; continued expressions are ok
9941 (while (and (not at-opening-bracket)
9943 (let ((pos (point)))
9946 (or (eq (char-before) ?,)
9947 (and (not (eq (char-before) ?\;))
9949 (prog2 (skip-chars-backward "[[:punct:]]")
9950 (looking-at js-indent-operator-re)
9952 (not (eq (char-before) ?\;))))
9953 (js2-same-line pos)))))
9956 (scan-error (setq at-opening-bracket t))))
9957 (when (looking-at js-declaration-keyword-re)
9958 (- (1+ (match-end 0)) (point-at-bol)))))))
9960 (defun js-ctrl-statement-indentation ()
9961 "Returns the proper indentation of the current line if it
9962 starts the body of a control statement without braces, else
9964 (let (forward-sexp-function) ; temporarily unbind it
9966 (back-to-indentation)
9967 (when (and (not (js2-same-line (point-min)))
9968 (not (looking-at "{"))
9969 (js-re-search-backward "[[:graph:]]" nil t)
9970 (not (looking-at "[{([]"))
9973 (when (= (char-before) ?\))
9974 ;; scan-sexps sometimes throws an error
9975 (ignore-errors (backward-sexp))
9976 (skip-chars-backward " \t" (point-at-bol)))
9978 (back-to-indentation)
9979 (and (looking-at js-possibly-braceless-keywords-re)
9980 (= (match-end 0) pt)
9981 (not (js-end-of-do-while-loop-p))))))
9982 (+ (current-indentation) js2-basic-offset)))))
9984 (defun js2-indent-in-array-comp (parse-status)
9985 "Return non-nil if we think we're in an array comprehension.
9986 In particular, return the buffer position of the first `for' kwd."
9987 (let ((end (point)))
9988 (when (nth 1 parse-status)
9990 (goto-char (nth 1 parse-status))
9991 (when (looking-at "\\[")
9994 (if (looking-at "[[{]")
9995 (let (forward-sexp-function) ; use lisp version
9996 (forward-sexp) ; skip destructuring form
9998 (if (and (/= (char-after) ?,) ; regular array
10000 (match-beginning 0)))
10001 ;; to skip arbitrary expressions we need the parser,
10002 ;; so we'll just guess at it.
10003 (if (and (> end (point)) ; not empty literal
10004 (re-search-forward "[^,]]* \\(for\\) " end t))
10005 (match-beginning 1))))))))
10007 (defun js2-array-comp-indentation (parse-status for-kwd)
10008 (if (js2-same-line for-kwd)
10009 ;; first continuation line
10011 (goto-char (nth 1 parse-status))
10013 (skip-chars-forward " \t")
10016 (goto-char for-kwd)
10017 (current-column))))
10019 (defun js-proper-indentation (parse-status)
10020 "Return the proper indentation for the current line."
10022 (back-to-indentation)
10023 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10024 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10025 (continued-expr-p (js-continued-expression-p))
10026 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10027 (js-multiline-decl-indentation)))
10028 (bracket (nth 1 parse-status))
10031 ;; indent array comprehension continuation lines specially
10033 (not (js2-same-line bracket))
10034 (setq beg (js2-indent-in-array-comp parse-status))
10035 (>= (point) (save-excursion
10037 (point-at-bol)))) ; at or after first loop?
10038 (js2-array-comp-indentation parse-status beg))
10042 ((and declaration-indent continued-expr-p)
10043 (+ declaration-indent js2-basic-offset))
10045 (declaration-indent)
10048 (goto-char bracket)
10050 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10051 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10052 (when (save-excursion (skip-chars-backward " \t)")
10056 (not js2-consistent-level-indent-inner-bracket-p))
10057 (progn (goto-char (1+ (nth 1 p)))
10058 (skip-chars-forward " \t"))
10059 (back-to-indentation)
10060 (when (and js2-pretty-multiline-decl-indentation-p
10061 js2-always-indent-assigned-expr-in-decls-p
10062 (looking-at js-declaration-keyword-re))
10063 (goto-char (1+ (match-end 0)))))
10064 (cond (same-indent-p
10067 (+ (current-column) (* 2 js2-basic-offset)))
10069 (+ (current-column) js2-basic-offset)))))
10071 (unless same-indent-p
10073 (skip-chars-forward " \t"))
10074 (current-column))))
10076 (continued-expr-p js2-basic-offset)
10080 (defun js2-lineup-comment (parse-status)
10081 "Indent a multi-line block comment continuation line."
10082 (let* ((beg (nth 8 parse-status))
10083 (first-line (js2-same-line beg))
10084 (offset (save-excursion
10086 (if (looking-at "/\\*")
10087 (+ 1 (current-column))
10090 (indent-line-to offset))))
10092 (defun js2-backward-sws ()
10093 "Move backward through whitespace and comments."
10095 (while (forward-comment -1)))
10097 (defun js2-forward-sws ()
10098 "Move forward through whitespace and comments."
10100 (while (forward-comment 1)))
10102 (defsubst js2-current-indent (&optional pos)
10103 "Return column of indentation on current line.
10104 If POS is non-nil, go to that point and return indentation for that line."
10108 (back-to-indentation)
10111 (defsubst js2-arglist-close ()
10112 "Return non-nil if we're on a line beginning with a close-paren/brace."
10115 (goto-char (point-at-bol))
10117 (looking-at "[])}]"))))
10119 (defsubst js2-indent-looks-like-label-p ()
10120 (goto-char (point-at-bol))
10122 (looking-at (concat js2-mode-identifier-re ":")))
10124 (defun js2-indent-in-objlit-p (parse-status)
10125 "Return non-nil if this looks like an object-literal entry."
10126 (let ((start (nth 1 parse-status)))
10130 (and (zerop (forward-line -1))
10131 (not (< (point) start)) ; crossed a {} boundary
10132 (js2-indent-looks-like-label-p)))
10134 (js2-indent-looks-like-label-p)))))
10136 ;; if prev line looks like foobar({ then we're passing an object
10137 ;; literal to a function call, and people pretty much always want to
10138 ;; de-dent back to the previous line, so move the 'basic-offset'
10139 ;; position to the front.
10140 (defsubst js2-indent-objlit-arg-p (parse-status)
10142 (back-to-indentation)
10144 (and (eq (1- (point)) (nth 1 parse-status))
10145 (eq (char-before) ?{)
10148 (skip-chars-backward " \t")
10149 (eq (char-before) ?\()))))
10151 (defsubst js2-indent-case-block-p ()
10153 (back-to-indentation)
10155 (goto-char (point-at-bol))
10156 (skip-chars-forward " \t")
10158 (looking-at "case\\s-.+:"))))
10160 (defsubst js2-syntax-bol ()
10161 "Return the point at the first non-whitespace char on the line.
10162 Returns `point-at-bol' if the line is empty."
10164 (beginning-of-line)
10165 (skip-chars-forward " \t")
10168 (defun js2-bounce-indent (normal-col parse-status backwards)
10169 "Cycle among alternate computed indentation positions.
10170 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10171 of the buffer to the current point. NORMAL-COL is the indentation
10172 column computed by the heuristic guesser based on current paren,
10173 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10175 (let ((cur-indent (js2-current-indent))
10176 (old-buffer-undo-list buffer-undo-list)
10177 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10178 (current-line (save-excursion
10179 (forward-line 0) ; move to bol
10180 (1+ (count-lines (point-min) (point)))))
10190 ;; temporarily don't record undo info, if user requested this
10191 (if js2-mode-indent-inhibit-undo
10192 (setq buffer-undo-list t))
10195 ;; first likely point: indent from beginning of previous code line
10196 (push (setq basic-offset
10198 (back-to-indentation)
10200 (back-to-indentation)
10201 (setq prev-line-col (current-column)))
10205 ;; (first + epsilon) likely point: indent 2x from beginning of
10206 ;; previous code line. Some companies like this approach. Ahem.
10207 ;; Seriously, though -- 4-space indent for expression continuation
10208 ;; lines isn't a bad idea. We should eventually implement it
10210 (push (setq basic-offset
10212 (back-to-indentation)
10214 (back-to-indentation)
10215 (setq prev-line-col (current-column)))
10216 (* 2 js2-basic-offset)))
10219 ;; second likely point: indent from assign-expr RHS. This
10220 ;; is just a crude guess based on finding " = " on the previous
10221 ;; line containing actual code.
10222 (setq pos (save-excursion
10225 (goto-char (point-at-bol))
10226 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10228 (goto-char (match-end 1))
10229 (skip-chars-forward " \t\r\n")
10230 (current-column)))))
10232 (incf pos js2-basic-offset)
10233 (push pos positions))
10235 ;; third likely point: same indent as previous line of code.
10236 ;; Make it the first likely point if we're not on an
10237 ;; arglist-close line and previous line ends in a comma, or
10238 ;; both this line and prev line look like object-literal
10240 (setq pos (save-excursion
10241 (goto-char (point-at-bol))
10243 (back-to-indentation)
10246 ;; while we're here, look for trailing comma
10247 (if (save-excursion
10248 (goto-char (point-at-eol))
10250 (eq (char-before) ?,))
10251 (setq arglist-cont (1- (point)))))))
10253 (if (and (or arglist-cont
10254 (js2-indent-in-objlit-p parse-status))
10255 (not (js2-arglist-close)))
10256 (setq same-indent pos))
10257 (push pos positions))
10259 ;; fourth likely point: first preceding code with less indentation
10260 ;; than the immediately preceding code line.
10261 (setq pos (save-excursion
10262 (back-to-indentation)
10264 (back-to-indentation)
10265 (setq anchor (current-column))
10266 (while (and (zerop (forward-line -1))
10268 (back-to-indentation)
10271 (setq pos (current-column))))
10272 (push pos positions)
10274 ;; nesting-heuristic position, main by default
10275 (push (setq main-pos normal-col) positions)
10277 ;; delete duplicates and sort positions list
10278 (setq positions (sort (delete-dups positions) '<))
10280 ;; comma-list continuation lines: prev line indent takes precedence
10282 (setq main-pos same-indent))
10284 ;; common special cases where we want to indent in from previous line
10285 (if (or (js2-indent-case-block-p)
10286 (js2-indent-objlit-arg-p parse-status))
10287 (setq main-pos basic-offset))
10289 ;; if bouncing backwards, reverse positions list
10291 (setq positions (reverse positions)))
10293 ;; record whether we're already sitting on one of the alternatives
10294 (setq pos (member cur-indent positions))
10297 ;; case 0: we're one one of the alternatives and this is the
10298 ;; first time they've pressed TAB on this line (best-guess).
10299 ((and js2-mode-indent-ignore-first-tab
10301 ;; first time pressing TAB on this line?
10302 (not (eq js2-mode-last-indented-line current-line)))
10304 (setq computed-pos nil))
10305 ;; case 1: only one computed position => use it
10306 ((null (cdr positions))
10307 (setq computed-pos 0))
10308 ;; case 2: not on any of the computed spots => use main spot
10310 (setq computed-pos (js2-position main-pos positions)))
10311 ;; case 3: on last position: cycle to first position
10313 (setq computed-pos 0))
10314 ;; case 4: on intermediate position: cycle to next position
10316 (setq computed-pos (js2-position (second pos) positions))))
10318 ;; see if any hooks want to indent; otherwise we do it
10319 (loop with result = nil
10320 for hook in js2-indent-hook
10321 while (null result)
10323 (setq result (funcall hook positions computed-pos))
10325 (unless (or result (null computed-pos))
10326 (indent-line-to (nth computed-pos positions)))))
10329 (if js2-mode-indent-inhibit-undo
10330 (setq buffer-undo-list old-buffer-undo-list))
10331 ;; see commentary for `js2-mode-last-indented-line'
10332 (setq js2-mode-last-indented-line current-line))))
10334 (defun js2-indent-bounce-backwards ()
10335 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10336 cycles between the computed indentation positions in reverse order."
10338 (js2-indent-line t))
10340 (defsubst js2-1-line-comment-continuation-p ()
10341 "Return t if we're in a 1-line comment continuation.
10342 If so, we don't ever want to use bounce-indent."
10347 (looking-at "\\s-*//"))
10351 (when (looking-at "\\s-*$")
10354 (looking-at "\\s-*//"))))))
10356 (defun js2-indent-line (&optional bounce-backwards)
10357 "Indent the current line as JavaScript source text."
10363 ;; don't whine about errors/warnings when we're indenting.
10364 ;; This has to be set before calling parse-partial-sexp below.
10365 (inhibit-point-motion-hooks t))
10366 (setq parse-status (save-excursion
10367 (syntax-ppss (point-at-bol)))
10368 offset (- (point) (save-excursion
10369 (back-to-indentation)
10371 (js2-with-underscore-as-word-syntax
10372 (if (nth 4 parse-status)
10373 (js2-lineup-comment parse-status)
10374 (setq indent-col (js-proper-indentation parse-status))
10375 ;; see comments below about js2-mode-last-indented-line
10377 ;; bounce-indenting is disabled during electric-key indent.
10378 ;; It doesn't work well on first line of buffer.
10379 ((and js2-bounce-indent-p
10380 (not (js2-same-line (point-min)))
10381 (not (js2-1-line-comment-continuation-p)))
10382 (js2-bounce-indent indent-col parse-status bounce-backwards))
10383 ;; just indent to the guesser's likely spot
10384 (t (indent-line-to indent-col)))
10385 (when (plusp offset)
10386 (forward-char offset))))))
10388 (defun js2-indent-region (start end)
10389 "Indent the region, but don't use bounce indenting."
10390 (let ((js2-bounce-indent-p nil)
10391 (indent-region-function nil)
10392 (after-change-functions (remq 'js2-mode-edit
10393 after-change-functions)))
10394 (indent-region start end nil) ; nil for byte-compiler
10395 (js2-mode-edit start end (- end start))))
10397 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10401 "Major mode for editing JavaScript code."
10403 (kill-all-local-variables)
10404 (set-syntax-table js2-mode-syntax-table)
10405 (use-local-map js2-mode-map)
10406 (make-local-variable 'comment-start)
10407 (make-local-variable 'comment-end)
10408 (make-local-variable 'comment-start-skip)
10409 (setq major-mode 'js2-mode
10410 mode-name "JavaScript-IDE"
10411 comment-start "//" ; used by comment-region; don't change it
10413 (setq local-abbrev-table js2-mode-abbrev-table)
10414 (set (make-local-variable 'max-lisp-eval-depth)
10415 (max max-lisp-eval-depth 3000))
10416 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10417 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10419 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10420 ;; on most platforms other than the one I originally wrote it on. So it's
10421 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10422 ;; with our binding of the RET key inside comments: short lines stay short.
10423 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10425 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10426 (set (make-local-variable 'next-error-function) #'js2-next-error)
10427 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10428 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10429 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10430 ;; for characters inside regexp literals.
10431 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10432 ;; this is necessary to make `show-paren-function' work properly
10433 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10434 ;; needed for M-x rgrep, among other things
10435 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10437 ;; some variables needed by cc-engine for paragraph-fill, etc.
10438 (setq c-buffer-is-cc-mode t
10439 c-comment-prefix-regexp js2-comment-prefix-regexp
10440 c-comment-start-regexp "/[*/]\\|\\s|"
10441 c-paragraph-start js2-paragraph-start
10442 c-paragraph-separate "$"
10443 comment-start-skip js2-comment-start-skip
10444 c-syntactic-ws-start js2-syntactic-ws-start
10445 c-syntactic-ws-end js2-syntactic-ws-end
10446 c-syntactic-eol js2-syntactic-eol)
10448 (setq js2-default-externs
10449 (append js2-ecma-262-externs
10450 (if js2-include-browser-externs
10451 js2-browser-externs)
10452 (if js2-include-gears-externs
10454 (if js2-include-rhino-externs
10455 js2-rhino-externs)))
10457 ;; We do our own syntax highlighting based on the parse tree.
10458 ;; However, we want minor modes that add keywords to highlight properly
10459 ;; (examples: doxymacs, column-marker). We do this by not letting
10460 ;; font-lock unfontify anything, and telling it to fontify after we
10461 ;; re-parse and re-highlight the buffer. (We currently don't do any
10462 ;; work with regions other than the whole buffer.)
10463 (dolist (var '(font-lock-unfontify-buffer-function
10464 font-lock-unfontify-region-function))
10465 (set (make-local-variable var) (lambda (&rest args) t)))
10467 ;; Don't let font-lock do syntactic (string/comment) fontification.
10468 (set (make-local-variable #'font-lock-syntactic-face-function)
10469 (lambda (state) nil))
10471 ;; Experiment: make reparse-delay longer for longer files.
10472 (if (plusp js2-dynamic-idle-timer-adjust)
10473 (setq js2-idle-timer-delay
10474 (* js2-idle-timer-delay
10475 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10477 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10478 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10479 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10480 (imenu-add-to-menubar (concat "IM-" mode-name))
10481 (when js2-mirror-mode
10482 (js2-enter-mirror-mode))
10483 (add-to-invisibility-spec '(js2-outline . t))
10484 (set (make-local-variable 'line-move-ignore-invisible) t)
10485 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10487 (if (fboundp 'run-mode-hooks)
10488 (run-mode-hooks 'js2-mode-hook)
10489 (run-hooks 'js2-mode-hook))
10491 (setq js2-mode-functions-hidden nil
10492 js2-mode-comments-hidden nil
10493 js2-mode-buffer-dirty-p t
10494 js2-mode-parsing nil)
10497 (defun js2-mode-exit ()
10498 "Exit `js2-mode' and clean up."
10500 (when js2-mode-node-overlay
10501 (delete-overlay js2-mode-node-overlay)
10502 (setq js2-mode-node-overlay nil))
10503 (js2-remove-overlays)
10504 (setq js2-mode-ast nil)
10505 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10506 (remove-from-invisibility-spec '(js2-outline . t))
10507 (js2-mode-show-all)
10508 (js2-with-unmodifying-text-property-changes
10509 (js2-clear-face (point-min) (point-max))))
10511 (defun js2-before-save ()
10512 "Clean up whitespace before saving file.
10513 You can disable this by customizing `js2-cleanup-whitespace'."
10514 (when js2-cleanup-whitespace
10515 (let ((col (current-column)))
10516 (delete-trailing-whitespace)
10517 ;; don't change trailing whitespace on current line
10518 (unless (eq (current-column) col)
10519 (indent-to col)))))
10521 (defsubst js2-mode-reset-timer ()
10522 "Cancel any existing parse timer and schedule a new one."
10523 (if js2-mode-parse-timer
10524 (cancel-timer js2-mode-parse-timer))
10525 (setq js2-mode-parsing nil)
10526 (setq js2-mode-parse-timer
10527 (run-with-idle-timer js2-idle-timer-delay nil
10528 #'js2-mode-idle-reparse (current-buffer))))
10530 (defun js2-mode-idle-reparse (buffer)
10531 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10532 it to be reparsed when the buffer is selected."
10533 (if (eq buffer (current-buffer))
10535 ;; reparse when the buffer is selected again
10536 (with-current-buffer buffer
10537 (add-hook 'window-configuration-change-hook
10538 #'js2-mode-idle-reparse-inner
10541 (defun js2-mode-idle-reparse-inner ()
10542 (remove-hook 'window-configuration-change-hook
10543 #'js2-mode-idle-reparse-inner
10547 (defun js2-mode-edit (beg end len)
10548 "Schedule a new parse after buffer is edited.
10549 Buffer edit spans from BEG to END and is of length LEN.
10550 Also clears the `js2-magic' bit on autoinserted parens/brackets
10551 if the edit occurred on a line different from the magic paren."
10552 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10553 (line (if magic-pos (line-number-at-pos magic-pos))))
10555 (or (/= (line-number-at-pos beg) line)
10557 (/= (line-number-at-pos end) line)))
10558 (js2-mode-mundanify-parens)))
10559 (setq js2-mode-buffer-dirty-p t)
10560 (js2-mode-hide-overlay)
10561 (js2-mode-reset-timer))
10563 (defun js2-mode-run-font-lock ()
10564 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10565 This is intended to allow modes that install their own font-lock keywords
10566 to work with js2-mode. In practice it never seems to work for long.
10567 Hopefully the Emacs maintainers can help figure out a way to make it work."
10568 (when (and (boundp 'font-lock-keywords)
10570 (boundp 'font-lock-mode)
10572 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10573 ;; play nicely with js2-mode. They go out of their way to fail to
10574 ;; provide any option for saying "look, fontify the farging buffer
10575 ;; with just the keywords already". Argh.
10576 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10577 (let (font-lock-verbose)
10578 (font-lock-fontify-buffer))))
10580 (defun js2-reparse (&optional force)
10581 "Re-parse current buffer after user finishes some data entry.
10582 If we get any user input while parsing, including cursor motion,
10583 we discard the parse and reschedule it. If FORCE is nil, then the
10584 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10587 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10588 (unless js2-mode-parsing
10589 (setq js2-mode-parsing t)
10591 (when (or js2-mode-buffer-dirty-p force)
10592 (js2-remove-overlays)
10593 (js2-with-unmodifying-text-property-changes
10594 (setq js2-mode-buffer-dirty-p nil
10595 js2-mode-fontifications nil
10596 js2-mode-deferred-properties nil)
10597 (if js2-mode-verbose-parse-p
10598 (message "parsing..."))
10601 (setq interrupted-p
10602 (catch 'interrupted
10603 (setq js2-mode-ast (js2-parse))
10604 ;; if parsing is interrupted, comments and regex
10605 ;; literals stay ignored by `parse-partial-sexp'
10606 (remove-text-properties (point-min) (point-max)
10608 (js2-mode-apply-deferred-properties)
10609 (js2-mode-remove-suppressed-warnings)
10610 (js2-mode-show-warnings)
10611 (js2-mode-show-errors)
10612 (js2-mode-run-font-lock) ; note: doesn't work
10613 (js2-mode-highlight-magic-parens)
10614 (if (>= js2-highlight-level 1)
10615 (js2-highlight-jsdoc js2-mode-ast))
10619 ;; unfinished parse => try again
10620 (setq js2-mode-buffer-dirty-p t)
10621 (js2-mode-reset-timer))
10622 (if js2-mode-verbose-parse-p
10623 (message "Parse time: %s" time)))))
10624 (setq js2-mode-parsing nil)
10625 (unless interrupted-p
10626 (setq js2-mode-parse-timer nil))))))
10628 (defun js2-mode-show-node ()
10629 "Debugging aid: highlight selected AST node on mouse click."
10631 (let ((node (js2-node-at-point))
10634 (when js2-mode-show-overlay
10636 (message "No node found at location %s" (point))
10637 (setq beg (js2-node-abs-pos node)
10638 end (+ beg (js2-node-len node)))
10639 (if js2-mode-node-overlay
10640 (move-overlay js2-mode-node-overlay beg end)
10641 (setq js2-mode-node-overlay (make-overlay beg end))
10642 (overlay-put js2-mode-node-overlay 'face 'highlight))
10643 (js2-with-unmodifying-text-property-changes
10644 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10645 (message "%s, parent: %s"
10646 (js2-node-short-name node)
10647 (if (js2-node-parent node)
10648 (js2-node-short-name (js2-node-parent node))
10651 (defun js2-mode-hide-overlay (&optional p1 p2)
10652 "Remove the debugging overlay when the point moves.
10653 P1 and P2 are the old and new values of point, respectively."
10654 (when js2-mode-node-overlay
10655 (let ((beg (overlay-start js2-mode-node-overlay))
10656 (end (overlay-end js2-mode-node-overlay)))
10657 ;; Sometimes we're called spuriously.
10661 (js2-with-unmodifying-text-property-changes
10662 (remove-text-properties beg end '(point-left nil)))
10663 (delete-overlay js2-mode-node-overlay)
10664 (setq js2-mode-node-overlay nil)))))
10666 (defun js2-mode-reset ()
10667 "Debugging helper: reset everything."
10672 (defsubst js2-mode-show-warn-or-err (e face)
10673 "Highlight a warning or error E with FACE.
10674 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10675 (let* ((key (first e))
10677 (end (+ beg (third e)))
10678 ;; Don't inadvertently go out of bounds.
10679 (beg (max (point-min) (min beg (point-max))))
10680 (end (max (point-min) (min end (point-max))))
10681 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10682 (ovl (make-overlay beg end)))
10683 (overlay-put ovl 'face face)
10684 (overlay-put ovl 'js2-error t)
10685 (put-text-property beg end 'help-echo (js2-get-msg key))
10686 (put-text-property beg end 'point-entered #'js2-echo-error)))
10688 (defun js2-remove-overlays ()
10689 "Remove overlays from buffer that have a `js2-error' property."
10690 (let ((beg (point-min))
10693 (dolist (o (overlays-in beg end))
10694 (when (overlay-get o 'js2-error)
10695 (delete-overlay o))))))
10697 (defun js2-error-at-point (&optional pos)
10698 "Return non-nil if there's an error overlay at POS.
10699 Defaults to point."
10700 (loop with pos = (or pos (point))
10701 for o in (overlays-at pos)
10702 thereis (overlay-get o 'js2-error)))
10704 (defun js2-mode-apply-deferred-properties ()
10705 "Apply fontifications and other text properties recorded during parsing."
10706 (when (plusp js2-highlight-level)
10707 ;; We defer clearing faces as long as possible to eliminate flashing.
10708 (js2-clear-face (point-min) (point-max))
10709 ;; Have to reverse the recorded fontifications list so that errors
10710 ;; and warnings overwrite the normal fontifications.
10711 (dolist (f (nreverse js2-mode-fontifications))
10712 (put-text-property (first f) (second f) 'face (third f)))
10713 (setq js2-mode-fontifications nil))
10714 (dolist (p js2-mode-deferred-properties)
10715 (apply #'put-text-property p))
10716 (setq js2-mode-deferred-properties nil))
10718 (defun js2-mode-show-errors ()
10719 "Highlight syntax errors."
10720 (when js2-mode-show-parse-errors
10721 (dolist (e (js2-ast-root-errors js2-mode-ast))
10722 (js2-mode-show-warn-or-err e 'js2-error-face))))
10724 (defun js2-mode-remove-suppressed-warnings ()
10725 "Take suppressed warnings out of the AST warnings list.
10726 This ensures that the counts and `next-error' are correct."
10727 (setf (js2-ast-root-warnings js2-mode-ast)
10730 (let ((key (caar e)))
10732 (and (not js2-strict-trailing-comma-warning)
10733 (string-match "trailing\\.comma" key))
10734 (and (not js2-strict-cond-assign-warning)
10735 (string= key "msg.equal.as.assign"))
10736 (and js2-missing-semi-one-line-override
10737 (string= key "msg.missing.semi")
10738 (let* ((beg (second e))
10739 (node (js2-node-at-point beg))
10740 (fn (js2-mode-find-parent-fn node))
10741 (body (and fn (js2-function-node-body fn)))
10742 (lc (and body (js2-node-abs-pos body)))
10743 (rc (and lc (+ lc (js2-node-len body)))))
10748 (and (js2-same-line lc)
10749 (js2-same-line rc))))))))))
10750 (js2-ast-root-warnings js2-mode-ast))))
10752 (defun js2-mode-show-warnings ()
10753 "Highlight strict-mode warnings."
10754 (when js2-mode-show-strict-warnings
10755 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10756 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10758 (defun js2-echo-error (old-point new-point)
10759 "Called by point-motion hooks."
10760 (let ((msg (get-text-property new-point 'help-echo)))
10761 (if (and msg (or (not (current-message))
10762 (string= (current-message) "Quit")))
10765 (defalias #'js2-echo-help #'js2-echo-error)
10767 (defun js2-enter-key ()
10768 "Handle user pressing the Enter key."
10770 (let ((parse-status (save-excursion
10771 (syntax-ppss (point))))
10772 (js2-bounce-indent-p nil))
10774 ;; check if we're inside a string
10775 ((nth 3 parse-status)
10776 (js2-mode-split-string parse-status))
10777 ;; check if inside a block comment
10778 ((nth 4 parse-status)
10779 (js2-mode-extend-comment))
10781 ;; should probably figure out what the mode-map says we should do
10782 (if js2-indent-on-enter-key
10785 (if js2-enter-indents-newline
10786 (js2-indent-line))))))
10788 (defun js2-mode-split-string (parse-status)
10789 "Turn a newline in mid-string into a string concatenation.
10790 PARSE-STATUS is as documented in `parse-partial-sexp'."
10791 (let* ((col (current-column))
10792 (quote-char (nth 3 parse-status))
10793 (quote-string (string quote-char))
10794 (string-beg (nth 8 parse-status))
10795 (indent (save-match-data
10798 (back-to-indentation)
10799 (if (looking-at "\\+")
10802 (goto-char string-beg)
10803 (if (looking-back "\\+\\s-+")
10804 (goto-char (match-beginning 0)))
10805 (current-column))))))
10806 (insert quote-char "\n")
10808 (insert "+ " quote-string)
10810 (insert quote-string)
10811 (backward-char 1))))
10813 (defun js2-mode-extend-comment ()
10814 "Indent the line and, when inside a comment block, add comment prefix."
10815 (let (star single col first-line needs-close)
10817 (back-to-indentation)
10819 ((looking-at "\\*[^/]")
10821 col (current-column)))
10822 ((looking-at "/\\*")
10825 col (1+ (current-column))))
10828 col (current-column)))))
10829 ;; Heuristic for whether we need to close the comment:
10830 ;; if we've got a parse error here, assume it's an unterminated
10834 (eq (get-text-property (1- (point)) 'point-entered)
10836 ;; The heuristic above doesn't work well when we're
10837 ;; creating a comment and there's another one downstream,
10838 ;; as our parser thinks this one ends at the end of the
10839 ;; next one. (You can have a /* inside a js block comment.)
10840 ;; So just close it if the next non-ws char isn't a *.
10844 (skip-chars-forward " \t\r\n")
10845 (not (eq (char-after) ?*))))))
10851 (if (and first-line needs-close)
10858 (and (zerop (forward-line 1))
10859 (looking-at "\\s-*//"))))
10862 ;; don't need to extend the comment after all
10863 (js2-enter-indents-newline
10864 (js2-indent-line)))))
10866 (defun js2-beginning-of-line ()
10867 "Toggles point between bol and first non-whitespace char in line.
10868 Also moves past comment delimiters when inside comments."
10873 (back-to-indentation))
10875 (skip-chars-forward "/ \t"))
10876 ((and (eq (char-after) ?*)
10877 (setq node (js2-comment-at-point))
10878 (memq (js2-comment-node-format node) '(jsdoc block))
10880 (skip-chars-backward " \t")
10882 (skip-chars-forward "\* \t"))
10884 (goto-char (point-at-bol))))))
10886 (defun js2-end-of-line ()
10887 "Toggles point between eol and last non-whitespace char in line."
10890 (skip-chars-backward " \t")
10891 (goto-char (point-at-eol))))
10893 (defun js2-enter-mirror-mode()
10894 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10897 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10898 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10899 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10900 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10901 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10902 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10903 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10904 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10906 (defun js2-leave-mirror-mode()
10907 "Turns off mirror mode."
10909 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10910 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10912 (defsubst js2-mode-inside-string ()
10913 "Return non-nil if inside a string.
10914 Actually returns the quote character that begins the string."
10915 (let ((parse-state (save-excursion
10916 (syntax-ppss (point)))))
10917 (nth 3 parse-state)))
10919 (defsubst js2-mode-inside-comment-or-string ()
10920 "Return non-nil if inside a comment or string."
10922 (let ((comment-start
10924 (goto-char (point-at-bol))
10925 (if (re-search-forward "//" (point-at-eol) t)
10926 (match-beginning 0)))))
10928 (<= comment-start (point))))
10929 (let ((parse-state (save-excursion
10930 (syntax-ppss (point)))))
10931 (or (nth 3 parse-state)
10932 (nth 4 parse-state)))))
10934 (defsubst js2-make-magic-delimiter (delim &optional pos)
10935 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10936 Sets value of `js2-magic' text property to line number at POS."
10938 'js2-magic (line-number-at-pos pos)
10939 'face 'js2-magic-paren-face))
10941 (defun js2-mode-match-delimiter (open close)
10942 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10943 The rule we use, which as far as we can tell is how Eclipse works,
10944 is that we insert the match if we're not in a comment or string,
10945 and the next non-whitespace character is either punctuation or
10946 occurs on another line."
10948 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10949 (not (js2-mode-inside-comment-or-string)))
10951 (insert (js2-make-magic-delimiter close)))
10952 (when js2-auto-indent-p
10953 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10954 (js2-indent-line)))))
10956 (defun js2-mode-match-bracket ()
10957 "Insert matching bracket."
10959 (js2-mode-match-delimiter "[" "]"))
10961 (defun js2-mode-match-paren ()
10962 "Insert matching paren unless already inserted."
10964 (js2-mode-match-delimiter "(" ")"))
10966 (defun js2-mode-match-curly (arg)
10967 "Insert matching curly-brace.
10968 With prefix arg, no formatting or indentation will occur -- the close-brace
10969 is simply inserted directly at the point."
10973 (current-prefix-arg
10974 (js2-mode-match-delimiter "{" "}"))
10975 ((and js2-auto-insert-catch-block
10976 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10978 (match-beginning 1))))
10979 (js2-insert-catch-skel try-pos))
10981 ;; Otherwise try to do something smarter.
10983 (unless (or (not (looking-at "\\s-*$"))
10985 (skip-chars-forward " \t\r\n")
10986 (and (looking-at "}")
10987 (js2-error-at-point)))
10988 (js2-mode-inside-comment-or-string))
10990 ;; absolutely mystifying bug: when inserting the next "\n",
10991 ;; the buffer-undo-list is given two new entries: the inserted range,
10992 ;; and the incorrect position of the point. It's recorded incorrectly
10993 ;; as being before the opening "{", not after it. But it's recorded
10994 ;; as the correct value if you're debugging `js2-mode-match-curly'
10995 ;; in edebug. I have no idea why it's doing this, but incrementing
10996 ;; the inserted position fixes the problem, so that the undo takes us
10997 ;; back to just after the user-inserted "{".
11000 (incf (cadr buffer-undo-list)))
11004 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11005 (js2-indent-line))))))))
11007 (defun js2-insert-catch-skel (try-pos)
11008 "Complete a try/catch block after inserting a { following a try keyword.
11009 Rationale is that a try always needs a catch or a finally, and the catch is
11010 the more likely of the two.
11012 TRY-POS is the buffer position of the try keyword. The open-curly should
11013 already have been inserted."
11015 (let ((try-col (save-excursion
11016 (goto-char try-pos)
11017 (current-column))))
11020 (js2-indent-line) ;; indent the blank line where cursor will end up
11023 (indent-to try-col)
11024 (insert "} catch (x) {\n\n")
11025 (indent-to try-col)
11028 (defun js2-mode-highlight-magic-parens ()
11029 "Re-highlight magic parens after parsing nukes the 'face prop."
11030 (let ((beg (point-min))
11032 (while (setq beg (next-single-property-change beg 'js2-magic))
11033 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11034 (if (get-text-property beg 'js2-magic)
11035 (js2-with-unmodifying-text-property-changes
11036 (put-text-property beg (or end (1+ beg))
11037 'face 'js2-magic-paren-face))))))
11039 (defun js2-mode-mundanify-parens ()
11040 "Clear all magic parens and brackets."
11041 (let ((beg (point-min))
11043 (while (setq beg (next-single-property-change beg 'js2-magic))
11044 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11045 (remove-text-properties beg (or end (1+ beg))
11046 '(js2-magic face)))))
11048 (defsubst js2-match-quote (quote-string)
11049 (let ((start-quote (js2-mode-inside-string)))
11051 ;; inside a comment - don't do quote-matching, since we can't
11052 ;; reliably figure out if we're in a string inside the comment
11053 ((js2-comment-at-point)
11054 (insert quote-string))
11056 ;; not in string => insert matched quotes
11057 (insert quote-string)
11058 ;; exception: if we're just before a word, don't double it.
11059 (unless (looking-at "[^ \t\r\n]")
11061 (insert quote-string))))
11062 ((looking-at quote-string)
11063 (if (looking-back "[^\\]\\\\")
11064 (insert quote-string)
11066 ((and js2-mode-escape-quotes
11069 (re-search-forward quote-string (point-at-eol) t))))
11070 ;; inside terminated string, escape quote (unless already escaped)
11071 (insert (if (looking-back "[^\\]\\\\")
11073 (concat "\\" quote-string))))
11075 (insert quote-string))))) ; else terminate the string
11077 (defun js2-mode-match-single-quote ()
11078 "Insert matching single-quote."
11080 (let ((parse-status (syntax-ppss (point))))
11081 ;; don't match inside comments, since apostrophe is more common
11082 (if (nth 4 parse-status)
11084 (js2-match-quote "'"))))
11086 (defun js2-mode-match-double-quote ()
11087 "Insert matching double-quote."
11089 (js2-match-quote "\""))
11091 ;; Eclipse works as follows:
11092 ;; * type an open-paren and it auto-inserts close-paren
11093 ;; - auto-inserted paren gets a green bracket
11094 ;; - green bracket means typing close-paren there will skip it
11095 ;; * if you insert any text on a different line, it turns off
11096 (defun js2-mode-magic-close-paren ()
11097 "Skip over close-paren rather than inserting, where appropriate."
11099 (let* ((here (point))
11100 (parse-status (syntax-ppss here))
11101 (open-pos (nth 1 parse-status))
11102 (close last-input-event)
11111 (if (and (eq (char-after) close)
11112 (eq open (char-after open-pos))
11113 (js2-same-line open-pos)
11114 (get-text-property here 'js2-magic))
11116 (remove-text-properties here (1+ here) '(js2-magic face))
11118 (insert-char close 1))
11119 (blink-matching-open)))
11121 (defun js2-mode-wait-for-parse (callback)
11122 "Invoke CALLBACK when parsing is finished.
11123 If parsing is already finished, calls CALLBACK immediately."
11124 (if (not js2-mode-buffer-dirty-p)
11126 (push callback js2-mode-pending-parse-callbacks)
11127 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11129 (defun js2-mode-parse-finished ()
11130 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11131 ;; We can't let errors propagate up, since it prevents the
11132 ;; `js2-parse' method from completing normally and returning
11133 ;; the ast, which makes things mysteriously not work right.
11135 (dolist (cb js2-mode-pending-parse-callbacks)
11136 (condition-case err
11138 (error (message "%s" err))))
11139 (setq js2-mode-pending-parse-callbacks nil)))
11141 (defun js2-mode-flag-region (from to flag)
11142 "Hide or show text from FROM to TO, according to FLAG.
11143 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11144 Returns the created overlay if FLAG is non-nil."
11145 (remove-overlays from to 'invisible 'js2-outline)
11147 (let ((o (make-overlay from to)))
11148 (overlay-put o 'invisible 'js2-outline)
11149 (overlay-put o 'isearch-open-invisible
11150 'js2-isearch-open-invisible)
11153 ;; Function to be set as an outline-isearch-open-invisible' property
11154 ;; to the overlay that makes the outline invisible (see
11155 ;; `js2-mode-flag-region').
11156 (defun js2-isearch-open-invisible (overlay)
11157 ;; We rely on the fact that isearch places point on the matched text.
11158 (js2-mode-show-element))
11160 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11161 "Return cons cell of bounds of folding overlay at POS.
11162 Returns nil if not found."
11163 (let ((overlays (overlays-at (or pos (point))))
11165 (while (and overlays
11167 (if (overlay-get (car overlays) 'invisible)
11168 (setq o (car overlays))
11169 (setq overlays (cdr overlays))))
11171 (cons (overlay-start o) (overlay-end o)))))
11173 (defun js2-mode-function-at-point (&optional pos)
11174 "Return the innermost function node enclosing current point.
11175 Returns nil if point is not in a function."
11176 (let ((node (js2-node-at-point pos)))
11177 (while (and node (not (js2-function-node-p node)))
11178 (setq node (js2-node-parent node)))
11179 (if (js2-function-node-p node)
11182 (defun js2-mode-toggle-element ()
11183 "Hide or show the foldable element at the point."
11185 (let (comment fn pos)
11189 ;; /* ... */ comment?
11190 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11191 (if (js2-mode-invisible-overlay-bounds
11192 (setq pos (+ 3 (js2-node-abs-pos comment))))
11195 (js2-mode-show-element))
11196 (js2-mode-hide-element)))
11199 (back-to-indentation)
11200 (looking-at js2-mode-//-comment-re))
11201 (js2-mode-toggle-//-comment))
11203 ((setq fn (js2-mode-function-at-point))
11204 (setq pos (and (js2-function-node-body fn)
11205 (js2-node-abs-pos (js2-function-node-body fn))))
11206 (goto-char (1+ pos))
11207 (if (js2-mode-invisible-overlay-bounds)
11208 (js2-mode-show-element)
11209 (js2-mode-hide-element)))
11211 (message "Nothing at point to hide or show")))))))
11213 (defun js2-mode-hide-element ()
11214 "Fold/hide contents of a block, showing ellipses.
11215 Show the hidden text with \\[js2-mode-show-element]."
11217 (if js2-mode-buffer-dirty-p
11218 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11219 (let (node body beg end)
11221 ((js2-mode-invisible-overlay-bounds)
11222 (message "already hidden"))
11224 (setq node (js2-node-at-point))
11226 ((js2-block-comment-p node)
11227 (js2-mode-hide-comment node))
11229 (while (and node (not (js2-function-node-p node)))
11230 (setq node (js2-node-parent node)))
11232 (setq body (js2-function-node-body node)))
11234 (setq beg (js2-node-abs-pos body)
11235 end (+ beg (js2-node-len body)))
11236 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11237 (message "No collapsable element found at point"))))))))
11239 (defun js2-mode-show-element ()
11240 "Show the hidden element at current point."
11242 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11244 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11245 (message "Nothing to un-hide"))))
11247 (defun js2-mode-show-all ()
11248 "Show all of the text in the buffer."
11250 (js2-mode-flag-region (point-min) (point-max) nil))
11252 (defun js2-mode-toggle-hide-functions ()
11254 (if js2-mode-functions-hidden
11255 (js2-mode-show-functions)
11256 (js2-mode-hide-functions)))
11258 (defun js2-mode-hide-functions ()
11259 "Hides all non-nested function bodies in the buffer.
11260 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11261 to open an individual entry."
11263 (if js2-mode-buffer-dirty-p
11264 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11265 (if (null js2-mode-ast)
11266 (message "Oops - parsing failed")
11267 (setq js2-mode-functions-hidden t)
11268 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11270 (defun js2-mode-function-hider (n endp)
11272 (let ((tt (js2-node-type n))
11275 ((and (= tt js2-FUNCTION)
11276 (setq body (js2-function-node-body n)))
11277 (setq beg (js2-node-abs-pos body)
11278 end (+ beg (js2-node-len body)))
11279 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11280 nil) ; don't process children of function
11282 t))))) ; keep processing other AST nodes
11284 (defun js2-mode-show-functions ()
11285 "Un-hide any folded function bodies in the buffer."
11287 (setq js2-mode-functions-hidden nil)
11289 (goto-char (point-min))
11290 (while (/= (goto-char (next-overlay-change (point)))
11292 (dolist (o (overlays-at (point)))
11293 (when (and (overlay-get o 'invisible)
11294 (not (overlay-get o 'comment)))
11295 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11297 (defun js2-mode-hide-comment (n)
11298 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11301 (beg (+ (js2-node-abs-pos n) head))
11302 (end (- (+ beg (js2-node-len n)) head 2))
11303 (o (js2-mode-flag-region beg end 'hide)))
11304 (overlay-put o 'comment t)))
11306 (defun js2-mode-toggle-hide-comments ()
11307 "Folds all block comments in the buffer.
11308 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11309 to open an individual entry."
11311 (if js2-mode-comments-hidden
11312 (js2-mode-show-comments)
11313 (js2-mode-hide-comments)))
11315 (defun js2-mode-hide-comments ()
11317 (if js2-mode-buffer-dirty-p
11318 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11319 (if (null js2-mode-ast)
11320 (message "Oops - parsing failed")
11321 (setq js2-mode-comments-hidden t)
11322 (dolist (n (js2-ast-root-comments js2-mode-ast))
11323 (let ((format (js2-comment-node-format n)))
11324 (when (js2-block-comment-p n)
11325 (js2-mode-hide-comment n))))
11326 (js2-mode-hide-//-comments)))
11328 (defsubst js2-mode-extend-//-comment (direction)
11329 "Find start or end of a block of similar //-comment lines.
11330 DIRECTION is -1 to look back, 1 to look forward.
11331 INDENT is the indentation level to match.
11332 Returns the end-of-line position of the furthest adjacent
11333 //-comment line with the same indentation as the current line.
11334 If there is no such matching line, returns current end of line."
11335 (let ((pos (point-at-eol))
11336 (indent (current-indentation)))
11339 (while (and (zerop (forward-line direction))
11340 (looking-at js2-mode-//-comment-re)
11341 (eq indent (length (match-string 1))))
11342 (setq pos (point-at-eol)))
11345 (defun js2-mode-hide-//-comments ()
11346 "Fold adjacent 1-line comments, showing only snippet of first one."
11350 (goto-char (point-min))
11351 (while (re-search-forward js2-mode-//-comment-re nil t)
11353 end (js2-mode-extend-//-comment 1))
11354 (unless (eq beg end)
11355 (overlay-put (js2-mode-flag-region beg end 'hide)
11358 (forward-char 1))))))
11360 (defun js2-mode-toggle-//-comment ()
11361 "Fold or un-fold any multi-line //-comment at point.
11362 Caller should have determined that this line starts with a //-comment."
11363 (let* ((beg (point-at-eol))
11367 (if (js2-mode-invisible-overlay-bounds)
11368 (js2-mode-show-element)
11369 ;; else hide the comment
11370 (setq beg (js2-mode-extend-//-comment -1)
11371 end (js2-mode-extend-//-comment 1))
11372 (unless (eq beg end)
11373 (overlay-put (js2-mode-flag-region beg end 'hide)
11376 (defun js2-mode-show-comments ()
11377 "Un-hide any hidden comments, leaving other hidden elements alone."
11379 (setq js2-mode-comments-hidden nil)
11381 (goto-char (point-min))
11382 (while (/= (goto-char (next-overlay-change (point)))
11384 (dolist (o (overlays-at (point)))
11385 (when (overlay-get o 'comment)
11386 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11388 (defun js2-mode-display-warnings-and-errors ()
11389 "Turn on display of warnings and errors."
11391 (setq js2-mode-show-parse-errors t
11392 js2-mode-show-strict-warnings t)
11393 (js2-reparse 'force))
11395 (defun js2-mode-hide-warnings-and-errors ()
11396 "Turn off display of warnings and errors."
11398 (setq js2-mode-show-parse-errors nil
11399 js2-mode-show-strict-warnings nil)
11400 (js2-reparse 'force))
11402 (defun js2-mode-toggle-warnings-and-errors ()
11403 "Toggle the display of warnings and errors.
11404 Some users don't like having warnings/errors reported while they type."
11406 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11407 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11408 (if (interactive-p)
11409 (message "warnings and errors %s"
11410 (if js2-mode-show-parse-errors
11413 (js2-reparse 'force))
11415 (defun js2-mode-customize ()
11417 (customize-group 'js2-mode))
11419 (defun js2-mode-forward-sexp (&optional arg)
11420 "Move forward across one statement or balanced expression.
11421 With ARG, do it that many times. Negative arg -N means
11422 move backward across N balanced expressions."
11424 (setq arg (or arg 1))
11425 (if js2-mode-buffer-dirty-p
11426 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11427 (let (node end (start (point)))
11430 ;; could probably make this better for some cases:
11431 ;; - if in statement block (e.g. function body), go to parent
11432 ;; - infix exprs like (foo in bar) - maybe go to beginning
11433 ;; of infix expr if in the right-side expression?
11434 ((and arg (minusp arg))
11435 (dotimes (i (- arg))
11437 (forward-char -1) ; enter the node we backed up to
11438 (setq node (js2-node-at-point (point) t))
11439 (goto-char (if node
11440 (js2-node-abs-pos node)
11447 (setq node (js2-node-at-point (point) t)
11448 end (if node (+ (js2-node-abs-pos node)
11449 (js2-node-len node))))
11450 (goto-char (or end (point-max))))))))
11452 (defun js2-next-error (&optional arg reset)
11453 "Move to next parse error.
11454 Typically invoked via \\[next-error].
11455 ARG is the number of errors, forward or backward, to move.
11456 RESET means start over from the beginning."
11458 (if (or (null js2-mode-ast)
11459 (and (null (js2-ast-root-errors js2-mode-ast))
11460 (null (js2-ast-root-warnings js2-mode-ast))))
11461 (message "No errors")
11463 (goto-char (point-min)))
11464 (let* ((errs (copy-sequence
11465 (append (js2-ast-root-errors js2-mode-ast)
11466 (js2-ast-root-warnings js2-mode-ast))))
11470 (backward (minusp count))
11471 (sorter (if backward '> '<))
11472 (stopper (if backward '< '>))
11473 (count (abs count))
11476 ;; sort by start position
11477 (setq errs (sort errs (lambda (e1 e2)
11478 (funcall sorter (second e1) (second e2))))
11480 ;; find nth error with pos > start
11481 (while (and errs continue)
11482 (when (funcall stopper (cadar errs) start)
11483 (setq err (car errs))
11484 (if (zerop (decf count))
11485 (setq continue nil)))
11486 (setq errs (cdr errs)))
11488 (goto-char (second err))
11489 ;; wrap around to first error
11490 (goto-char (second (car all-errs)))
11491 ;; if we were already on it, echo msg again
11492 (if (= (point) start)
11493 (js2-echo-error (point) (point)))))))
11495 (defun js2-down-mouse-3 ()
11496 "Make right-click move the point to the click location.
11497 This makes right-click context menu operations a bit more intuitive.
11498 The point will not move if the region is active, however, to avoid
11499 destroying the region selection."
11501 (when (and js2-move-point-on-right-click
11503 (let ((e last-input-event))
11505 (goto-char (cadadr e))))))
11507 (defun js2-mode-create-imenu-index ()
11508 "Return an alist for `imenu--index-alist'."
11509 ;; This is built up in `js2-parse-record-imenu' during parsing.
11511 ;; if we have an ast but no recorder, they're requesting a rescan
11512 (unless js2-imenu-recorder
11513 (js2-reparse 'force))
11515 (js2-build-imenu-index)
11516 (setq js2-imenu-recorder nil
11517 js2-imenu-function-map nil))))
11519 (defun js2-mode-find-tag ()
11520 "Replacement for `find-tag-default'.
11521 `find-tag-default' returns a ridiculous answer inside comments."
11523 (js2-with-underscore-as-word-syntax
11525 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11526 (looking-back "[A-Za-z0-9_$]"))
11527 (setq beg (progn (forward-word -1) (point))
11528 end (progn (forward-word 1) (point)))
11529 (setq beg (progn (forward-word 1) (point))
11530 end (progn (forward-word -1) (point))))
11531 (replace-regexp-in-string
11533 (buffer-substring-no-properties beg end))))))
11535 (defun js2-mode-forward-sibling ()
11536 "Move to the end of the sibling following point in parent.
11537 Returns non-nil if successful, or nil if there was no following sibling."
11538 (let* ((node (js2-node-at-point))
11539 (parent (js2-mode-find-enclosing-fn node))
11541 (when (setq sib (js2-node-find-child-after (point) parent))
11542 (goto-char (+ (js2-node-abs-pos sib)
11543 (js2-node-len sib))))))
11545 (defun js2-mode-backward-sibling ()
11546 "Move to the beginning of the sibling node preceding point in parent.
11547 Parent is defined as the enclosing script or function."
11548 (let* ((node (js2-node-at-point))
11549 (parent (js2-mode-find-enclosing-fn node))
11551 (when (setq sib (js2-node-find-child-before (point) parent))
11552 (goto-char (js2-node-abs-pos sib)))))
11554 (defun js2-beginning-of-defun ()
11555 "Go to line on which current function starts, and return non-nil.
11556 If we're not in a function, go to beginning of previous script-level element."
11558 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11561 ((and (js2-function-node-p parent)
11562 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11565 (js2-mode-backward-sibling)))))
11567 (defun js2-end-of-defun ()
11568 "Go to the char after the last position of the current function.
11569 If we're not in a function, skips over the next script-level element."
11571 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11572 (if (not (js2-function-node-p parent))
11573 ;; punt: skip over next script-level element beyond point
11574 (js2-mode-forward-sibling)
11575 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11576 (js2-node-len parent)))))))
11578 (defun js2-mark-defun (&optional allow-extend)
11579 "Put mark at end of this function, point at beginning.
11580 The function marked is the one that contains point.
11582 Interactively, if this command is repeated,
11583 or (in Transient Mark mode) if the mark is active,
11584 it marks the next defun after the ones already marked."
11587 (when (and allow-extend
11588 (or (and (eq last-command this-command) (mark t))
11589 (and transient-mark-mode mark-active)))
11590 (let ((sib (save-excursion
11592 (if (js2-mode-forward-sibling)
11599 ;; no more siblings - try extending to enclosing node
11600 (goto-char (mark t)))))
11601 (when (not extended)
11602 (let ((node (js2-node-at-point (point) t)) ; skip comments
11603 ast fn stmt parent beg end)
11604 (when (js2-ast-root-p node)
11606 node (or (js2-node-find-child-after (point) node)
11607 (js2-node-find-child-before (point) node))))
11608 ;; only mark whole buffer if we can't find any children
11611 (if (js2-function-node-p node)
11613 (setq fn (js2-mode-find-enclosing-fn node)
11614 stmt (if (or (null fn)
11615 (js2-ast-root-p fn))
11616 (js2-mode-find-first-stmt node))
11617 parent (or stmt fn)))
11618 (setq beg (js2-node-abs-pos parent)
11619 end (+ beg (js2-node-len parent)))
11622 (exchange-point-and-mark)))))
11624 (defun js2-narrow-to-defun ()
11625 "Narrow to the function enclosing point."
11627 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11628 (fn (if (js2-script-node-p node)
11630 (js2-mode-find-enclosing-fn node)))
11631 (beg (js2-node-abs-pos fn)))
11632 (unless (js2-ast-root-p fn)
11633 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11635 (provide 'js2-mode)
11637 ;;; js2-mode.el ends here