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 (defvar js2-emacs22 (>= emacs-major-version 22))
177 (defcustom js2-highlight-level 2
178 "Amount of syntax highlighting to perform.
179 0 or a negative value means do no highlighting.
180 1 adds basic syntax highlighting.
181 2 adds highlighting of some Ecma built-in properties.
182 3 adds highlighting of many Ecma built-in functions."
184 :type '(choice (const :tag "None" 0)
185 (const :tag "Basic" 1)
186 (const :tag "Include Properties" 2)
187 (const :tag "Include Functions" 3)))
189 (defvar js2-mode-dev-mode-p nil
190 "Non-nil if running in development mode. Normally nil.")
192 (defgroup js2-mode nil
193 "An improved JavaScript mode."
196 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
197 (numberp c-basic-offset))
200 "Number of spaces to indent nested statements.
201 Similar to `c-basic-offset'."
204 (make-variable-buffer-local 'js2-basic-offset)
206 ;; TODO(stevey): move this code into a separate minor mode.
207 (defcustom js2-mirror-mode nil
208 "Non-nil to insert closing brackets, parens, etc. automatically."
212 (defcustom js2-auto-indent-p nil
213 "Automatic indentation with punctuation characters.
214 If non-nil, the current line is indented when certain punctuations
219 (defcustom js2-bounce-indent-p nil
220 "Non-nil to have indent-line function choose among alternatives.
221 If nil, the indent-line function will indent to a predetermined column
222 based on heuristic guessing. If non-nil, then if the current line is
223 already indented to that predetermined column, indenting will choose
224 another likely column and indent to that spot. Repeated invocation of
225 the indent-line function will cycle among the computed alternatives.
226 See the function `js2-bounce-indent' for details. When it is non-nil,
227 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
231 (defcustom js2-consistent-level-indent-inner-bracket-p t
232 "Non-nil to make indentation level inner bracket consistent,
233 regardless of the beginning bracket position."
237 (defcustom js2-pretty-multiline-decl-indentation-p t
238 "Non-nil to line up multiline declarations vertically. See the
239 function `js-multiline-decl-indentation' for details."
243 (defcustom js2-indent-on-enter-key nil
244 "Non-nil to have Enter/Return key indent the line.
245 This is unusual for Emacs modes but common in IDEs like Eclipse."
249 (defcustom js2-enter-indents-newline nil
250 "Non-nil to have Enter/Return key indent the newly-inserted line.
251 This is unusual for Emacs modes but common in IDEs like Eclipse."
255 (defcustom js2-rebind-eol-bol-keys t
256 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
257 If non-nil, bounce between bol/eol and first/last non-whitespace char."
261 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
262 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
263 Each value in the list is passed to `define-key'."
267 (defcustom js2-idle-timer-delay 0.2
268 "Delay in secs before re-parsing after user makes changes.
269 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
272 (make-variable-buffer-local 'js2-idle-timer-delay)
274 (defcustom js2-dynamic-idle-timer-adjust 0
275 "Positive to adjust `js2-idle-timer-delay' based on file size.
276 The idea is that for short files, parsing is faster so we can be
277 more responsive to user edits without interfering with editing.
278 The buffer length in characters (typically bytes) is divided by
279 this value and used to multiply `js2-idle-timer-delay' for the
280 buffer. For example, a 21k file and 10k adjust yields 21k/10k
281 == 2, so js2-idle-timer-delay is multiplied by 2.
282 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
283 `js2-idle-timer-delay' is not dependent on the file size."
287 (defcustom js2-mode-escape-quotes t
288 "Non-nil to disable automatic quote-escaping inside strings."
292 (defcustom js2-mode-squeeze-spaces t
293 "Non-nil to normalize whitespace when filling in comments.
294 Multiple runs of spaces are converted to a single space."
298 (defcustom js2-mode-show-parse-errors t
299 "True to highlight parse errors."
303 (defcustom js2-mode-show-strict-warnings t
304 "Non-nil to emit Ecma strict-mode warnings.
305 Some of the warnings can be individually disabled by other flags,
306 even if this flag is non-nil."
310 (defcustom js2-strict-trailing-comma-warning t
311 "Non-nil to warn about trailing commas in array literals.
312 Ecma-262 forbids them, but many browsers permit them. IE is the
313 big exception, and can produce bugs if you have trailing commas."
317 (defcustom js2-strict-missing-semi-warning t
318 "Non-nil to warn about semicolon auto-insertion after statement.
319 Technically this is legal per Ecma-262, but some style guides disallow
324 (defcustom js2-missing-semi-one-line-override nil
325 "Non-nil to permit missing semicolons in one-line functions.
326 In one-liner functions such as `function identity(x) {return x}'
327 people often omit the semicolon for a cleaner look. If you are
328 such a person, you can suppress the missing-semicolon warning
329 by setting this variable to t."
333 (defcustom js2-strict-inconsistent-return-warning t
334 "Non-nil to warn about mixing returns with value-returns.
335 It's perfectly legal to have a `return' and a `return foo' in the
336 same function, but it's often an indicator of a bug, and it also
337 interferes with type inference (in systems that support it.)"
341 (defcustom js2-strict-cond-assign-warning t
342 "Non-nil to warn about expressions like if (a = b).
343 This often should have been '==' instead of '='. If the warning
344 is enabled, you can suppress it on a per-expression basis by
345 parenthesizing the expression, e.g. if ((a = b)) ..."
349 (defcustom js2-strict-cond-assign-warning t
350 "Non-nil to warn about expressions like if (a = b).
351 This often should have been '==' instead of '='. If the warning
352 is enabled, you can suppress it on a per-expression basis by
353 parenthesizing the expression, e.g. if ((a = b)) ..."
357 (defcustom js2-strict-var-redeclaration-warning t
358 "Non-nil to warn about redeclaring variables in a script or function."
362 (defcustom js2-strict-var-hides-function-arg-warning t
363 "Non-nil to warn about a var decl hiding a function argument."
367 (defcustom js2-skip-preprocessor-directives nil
368 "Non-nil to treat lines beginning with # as comments.
369 Useful for viewing Mozilla JavaScript source code."
373 (defcustom js2-language-version 180
374 "Configures what JavaScript language version to recognize.
375 Currently versions 150, 160, 170 and 180 are supported, corresponding
376 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
377 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
378 and 1.8 adds function closures."
382 (defcustom js2-allow-keywords-as-property-names t
383 "If non-nil, you can use JavaScript keywords as object property names.
386 var foo = {int: 5, while: 6, continue: 7};
389 Ecma-262 forbids this syntax, but many browsers support it."
393 (defcustom js2-instanceof-has-side-effects nil
394 "If non-nil, treats the instanceof operator as having side effects.
395 This is useful for xulrunner apps."
399 (defcustom js2-cleanup-whitespace nil
400 "Non-nil to invoke `delete-trailing-whitespace' before saves."
404 (defcustom js2-move-point-on-right-click t
405 "Non-nil to move insertion point when you right-click.
406 This makes right-click context menu behavior a bit more intuitive,
407 since menu operations generally apply to the point. The exception
408 is if there is a region selection, in which case the point does -not-
409 move, so cut/copy/paste etc. can work properly.
411 Note that IntelliJ moves the point, and Eclipse leaves it alone,
412 so this behavior is customizable."
416 (defcustom js2-allow-rhino-new-expr-initializer t
417 "Non-nil to support a Rhino's experimental syntactic construct.
419 Rhino supports the ability to follow a `new' expression with an object
420 literal, which is used to set additional properties on the new object
421 after calling its constructor. Syntax:
423 new <expr> [ ( arglist ) ] [initializer]
425 Hence, this expression:
427 new Object {a: 1, b: 2}
429 results in an Object with properties a=1 and b=2. This syntax is
430 apparently not configurable in Rhino - it's currently always enabled,
431 as of Rhino version 1.7R2."
435 (defcustom js2-allow-member-expr-as-function-name nil
436 "Non-nil to support experimental Rhino syntax for function names.
438 Rhino supports an experimental syntax configured via the Rhino Context
439 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
441 function <member-expr> ( [ arg-list ] ) { <body> }
443 Where member-expr is a non-parenthesized 'member expression', which
444 is anything at the grammar level of a new-expression or lower, meaning
445 any expression that does not involve infix or unary operators.
447 When <member-expr> is not a simple identifier, then it is syntactic
448 sugar for assigning the anonymous function to the <member-expr>. Hence,
451 function a.b().c[2] (x, y) { ... }
455 a.b().c[2] = function(x, y) {...}
457 which doesn't seem particularly useful, but Rhino permits it."
461 (defvar js2-mode-version 20101228
462 "Release number for `js2-mode'.")
466 (defmacro js2-deflocal (name value &optional comment)
467 "Define a buffer-local variable NAME with VALUE and COMMENT."
469 (defvar ,name ,value ,comment)
470 (make-variable-buffer-local ',name)))
472 ;; We record the start and end position of each token.
473 (js2-deflocal js2-token-beg 1)
474 (js2-deflocal js2-token-end -1)
476 (defvar js2-EOF_CHAR -1
477 "Represents end of stream. Distinct from js2-EOF token type.")
479 ;; I originally used symbols to represent tokens, but Rhino uses
480 ;; ints and then sets various flag bits in them, so ints it is.
481 ;; The upshot is that we need a `js2-' prefix in front of each name.
482 (defvar js2-ERROR -1)
485 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
486 (defvar js2-LEAVEWITH 3)
487 (defvar js2-RETURN 4)
491 (defvar js2-SETNAME 8)
493 (defvar js2-BITXOR 10)
494 (defvar js2-BITAND 11)
504 (defvar js2-ADD 21) ; infix plus
505 (defvar js2-SUB 22) ; infix minus
510 (defvar js2-BITNOT 27)
511 (defvar js2-POS 28) ; unary plus
512 (defvar js2-NEG 29) ; unary minus
514 (defvar js2-DELPROP 31)
515 (defvar js2-TYPEOF 32)
516 (defvar js2-GETPROP 33)
517 (defvar js2-GETPROPNOWARN 34)
518 (defvar js2-SETPROP 35)
519 (defvar js2-GETELEM 36)
520 (defvar js2-SETELEM 37)
522 (defvar js2-NAME 39) ; an identifier
523 (defvar js2-NUMBER 40)
524 (defvar js2-STRING 41)
527 (defvar js2-FALSE 44)
529 (defvar js2-SHEQ 46) ; shallow equality (===)
530 (defvar js2-SHNE 47) ; shallow inequality (!==)
531 (defvar js2-REGEXP 48)
532 (defvar js2-BINDNAME 49)
533 (defvar js2-THROW 50)
534 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
536 (defvar js2-INSTANCEOF 53)
537 (defvar js2-LOCAL_LOAD 54)
538 (defvar js2-GETVAR 55)
539 (defvar js2-SETVAR 56)
540 (defvar js2-CATCH_SCOPE 57)
541 (defvar js2-ENUM_INIT_KEYS 58)
542 (defvar js2-ENUM_INIT_VALUES 59)
543 (defvar js2-ENUM_INIT_ARRAY 60)
544 (defvar js2-ENUM_NEXT 61)
545 (defvar js2-ENUM_ID 62)
546 (defvar js2-THISFN 63)
547 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
548 (defvar js2-ARRAYLIT 65) ; array literal
549 (defvar js2-OBJECTLIT 66) ; object literal
550 (defvar js2-GET_REF 67) ; *reference
551 (defvar js2-SET_REF 68) ; *reference = something
552 (defvar js2-DEL_REF 69) ; delete reference
553 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
554 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
555 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
558 (defvar js2-DEFAULTNAMESPACE 73)
559 (defvar js2-ESCXMLATTR 74)
560 (defvar js2-ESCXMLTEXT 75)
561 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
562 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
563 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
564 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
566 (defvar js2-first-bytecode js2-ENTERWITH)
567 (defvar js2-last-bytecode js2-REF_NS_NAME)
570 (defvar js2-SEMI 81) ; semicolon
571 (defvar js2-LB 82) ; left and right brackets
573 (defvar js2-LC 84) ; left and right curly-braces
575 (defvar js2-LP 86) ; left and right parens
577 (defvar js2-COMMA 88) ; comma operator
579 (defvar js2-ASSIGN 89) ; simple assignment (=)
580 (defvar js2-ASSIGN_BITOR 90) ; |=
581 (defvar js2-ASSIGN_BITXOR 91) ; ^=
582 (defvar js2-ASSIGN_BITAND 92) ; &=
583 (defvar js2-ASSIGN_LSH 93) ; <<=
584 (defvar js2-ASSIGN_RSH 94) ; >>=
585 (defvar js2-ASSIGN_URSH 95) ; >>>=
586 (defvar js2-ASSIGN_ADD 96) ; +=
587 (defvar js2-ASSIGN_SUB 97) ; -=
588 (defvar js2-ASSIGN_MUL 98) ; *=
589 (defvar js2-ASSIGN_DIV 99) ; /=
590 (defvar js2-ASSIGN_MOD 100) ; %=
592 (defvar js2-first-assign js2-ASSIGN)
593 (defvar js2-last-assign js2-ASSIGN_MOD)
595 (defvar js2-HOOK 101) ; conditional (?:)
596 (defvar js2-COLON 102)
597 (defvar js2-OR 103) ; logical or (||)
598 (defvar js2-AND 104) ; logical and (&&)
599 (defvar js2-INC 105) ; increment/decrement (++ --)
601 (defvar js2-DOT 107) ; member operator (.)
602 (defvar js2-FUNCTION 108) ; function keyword
603 (defvar js2-EXPORT 109) ; export keyword
604 (defvar js2-IMPORT 110) ; import keyword
605 (defvar js2-IF 111) ; if keyword
606 (defvar js2-ELSE 112) ; else keyword
607 (defvar js2-SWITCH 113) ; switch keyword
608 (defvar js2-CASE 114) ; case keyword
609 (defvar js2-DEFAULT 115) ; default keyword
610 (defvar js2-WHILE 116) ; while keyword
611 (defvar js2-DO 117) ; do keyword
612 (defvar js2-FOR 118) ; for keyword
613 (defvar js2-BREAK 119) ; break keyword
614 (defvar js2-CONTINUE 120) ; continue keyword
615 (defvar js2-VAR 121) ; var keyword
616 (defvar js2-WITH 122) ; with keyword
617 (defvar js2-CATCH 123) ; catch keyword
618 (defvar js2-FINALLY 124) ; finally keyword
619 (defvar js2-VOID 125) ; void keyword
620 (defvar js2-RESERVED 126) ; reserved keywords
622 (defvar js2-EMPTY 127)
624 ;; Types used for the parse tree - never returned by scanner.
626 (defvar js2-BLOCK 128) ; statement block
627 (defvar js2-LABEL 129) ; label
628 (defvar js2-TARGET 130)
629 (defvar js2-LOOP 131)
630 (defvar js2-EXPR_VOID 132) ; expression statement in functions
631 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
633 (defvar js2-SCRIPT 135) ; top-level node for entire script
634 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
635 (defvar js2-USE_STACK 137)
636 (defvar js2-SETPROP_OP 138) ; x.y op= something
637 (defvar js2-SETELEM_OP 139) ; x[y] op= something
638 (defvar js2-LOCAL_BLOCK 140)
639 (defvar js2-SET_REF_OP 141) ; *reference op= something
642 (defvar js2-DOTDOT 142) ; member operator (..)
643 (defvar js2-COLONCOLON 143) ; namespace::name
644 (defvar js2-XML 144) ; XML type
645 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
646 (defvar js2-XMLATTR 146) ; @
647 (defvar js2-XMLEND 147)
649 ;; Optimizer-only tokens
650 (defvar js2-TO_OBJECT 148)
651 (defvar js2-TO_DOUBLE 149)
653 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
654 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
655 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
656 (defvar js2-CONST 153)
657 (defvar js2-SETCONST 154)
658 (defvar js2-SETCONSTVAR 155)
659 (defvar js2-ARRAYCOMP 156)
660 (defvar js2-LETEXPR 157)
661 (defvar js2-WITHEXPR 158)
662 (defvar js2-DEBUGGER 159)
664 (defvar js2-COMMENT 160)
665 (defvar js2-ENUM 161) ; for "enum" reserved word
667 (defconst js2-num-tokens (1+ js2-ENUM))
669 (defconst js2-debug-print-trees nil)
671 ;; Rhino accepts any string or stream as input. Emacs character
672 ;; processing works best in buffers, so we'll assume the input is a
673 ;; buffer. JavaScript strings can be copied into temp buffers before
676 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
677 ;; They're the Emacs equivalent of instance variables, more or less.
679 (js2-deflocal js2-ts-dirty-line nil
680 "Token stream buffer-local variable.
681 Indicates stuff other than whitespace since start of line.")
683 (js2-deflocal js2-ts-regexp-flags nil
684 "Token stream buffer-local variable.")
686 (js2-deflocal js2-ts-string ""
687 "Token stream buffer-local variable.
688 Last string scanned.")
690 (js2-deflocal js2-ts-number nil
691 "Token stream buffer-local variable.
692 Last literal number scanned.")
694 (js2-deflocal js2-ts-hit-eof nil
695 "Token stream buffer-local variable.")
697 (js2-deflocal js2-ts-line-start 0
698 "Token stream buffer-local variable.")
700 (js2-deflocal js2-ts-lineno 1
701 "Token stream buffer-local variable.")
703 (js2-deflocal js2-ts-line-end-char -1
704 "Token stream buffer-local variable.")
706 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
707 "Token stream buffer-local variable.
708 Current scan position.")
710 (js2-deflocal js2-ts-is-xml-attribute nil
711 "Token stream buffer-local variable.")
713 (js2-deflocal js2-ts-xml-is-tag-content nil
714 "Token stream buffer-local variable.")
716 (js2-deflocal js2-ts-xml-open-tags-count 0
717 "Token stream buffer-local variable.")
719 (js2-deflocal js2-ts-string-buffer nil
720 "Token stream buffer-local variable.
721 List of chars built up while scanning various tokens.")
723 (js2-deflocal js2-ts-comment-type nil
724 "Token stream buffer-local variable.")
728 (js2-deflocal js2-parsed-errors nil
729 "List of errors produced during scanning/parsing.")
731 (js2-deflocal js2-parsed-warnings nil
732 "List of warnings produced during scanning/parsing.")
734 (js2-deflocal js2-recover-from-parse-errors t
735 "Non-nil to continue parsing after a syntax error.
737 In recovery mode, the AST will be built in full, and any error
738 nodes will be flagged with appropriate error information. If
739 this flag is nil, a syntax error will result in an error being
742 The variable is automatically buffer-local, because different
743 modes that use the parser will need different settings.")
745 (js2-deflocal js2-parse-hook nil
746 "List of callbacks for receiving parsing progress.")
748 (defvar js2-parse-finished-hook nil
749 "List of callbacks to notify when parsing finishes.
750 Not called if parsing was interrupted.")
752 (js2-deflocal js2-is-eval-code nil
753 "True if we're evaluating code in a string.
754 If non-nil, the tokenizer will record the token text, and the AST nodes
755 will record their source text. Off by default for IDE modes, since the
756 text is available in the buffer.")
758 (defvar js2-parse-ide-mode t
759 "Non-nil if the parser is being used for `js2-mode'.
760 If non-nil, the parser will set text properties for fontification
761 and the syntax table. The value should be nil when using the
762 parser as a frontend to an interpreter or byte compiler.")
764 ;;; Parser instance variables (buffer-local vars for js2-parse)
766 (defconst js2-clear-ti-mask #xFFFF
767 "Mask to clear token information bits.")
769 (defconst js2-ti-after-eol (lsh 1 16)
770 "Flag: first token of the source line.")
772 (defconst js2-ti-check-label (lsh 1 17)
773 "Flag: indicates to check for label.")
775 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
777 (js2-deflocal js2-compiler-generate-debug-info t)
778 (js2-deflocal js2-compiler-use-dynamic-scope nil)
779 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
780 (js2-deflocal js2-compiler-xml-available t)
781 (js2-deflocal js2-compiler-optimization-level 0)
782 (js2-deflocal js2-compiler-generating-source t)
783 (js2-deflocal js2-compiler-strict-mode nil)
784 (js2-deflocal js2-compiler-report-warning-as-error nil)
785 (js2-deflocal js2-compiler-generate-observer-count nil)
786 (js2-deflocal js2-compiler-activation-names nil)
790 ;; There's a compileFunction method in Context.java - may need it.
791 (js2-deflocal js2-called-by-compile-function nil
792 "True if `js2-parse' was called by `js2-compile-function'.
793 Will only be used when we finish implementing the interpreter.")
795 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
797 (js2-deflocal js2-current-flagged-token js2-EOF)
798 (js2-deflocal js2-current-token js2-EOF)
800 ;; SKIP: node factory - we're going to just call functions directly,
801 ;; and eventually go to a unified AST format.
803 (js2-deflocal js2-nesting-of-function 0)
805 (js2-deflocal js2-recorded-identifiers nil
806 "Tracks identifiers found during parsing.")
808 (defmacro js2-in-lhs (body)
809 `(let ((js2-is-in-lhs t))
812 (defmacro js2-in-rhs (body)
813 `(let ((js2-is-in-lhs nil))
816 (js2-deflocal js2-is-in-lhs nil
817 "True while parsing lhs statement")
819 (defcustom js2-global-externs nil
820 "A list of any extern names you'd like to consider always declared.
821 This list is global and is used by all js2-mode files.
822 You can create buffer-local externs list using `js2-additional-externs'.
824 There is also a buffer-local variable `js2-default-externs',
825 which is initialized by default to include the Ecma-262 externs
826 and the standard browser externs. The three lists are all
827 checked during highlighting."
831 (js2-deflocal js2-default-externs nil
832 "Default external declarations.
834 These are currently only used for highlighting undeclared variables,
835 which only worries about top-level (unqualified) references.
836 As js2-mode's processing improves, we will flesh out this list.
838 The initial value is set to `js2-ecma-262-externs', unless you
839 have set `js2-include-browser-externs', in which case the browser
840 externs are also included.
842 See `js2-additional-externs' for more information.")
844 (defcustom js2-include-browser-externs t
845 "Non-nil to include browser externs in the master externs list.
846 If you work on JavaScript files that are not intended for browsers,
847 such as Mozilla Rhino server-side JavaScript, set this to nil.
848 You can always include them on a per-file basis by calling
849 `js2-add-browser-externs' from a function on `js2-mode-hook'.
851 See `js2-additional-externs' for more information about externs."
855 (defcustom js2-include-rhino-externs t
856 "Non-nil to include Mozilla Rhino externs in the master externs list.
857 See `js2-additional-externs' for more information about externs."
861 (defcustom js2-include-gears-externs t
862 "Non-nil to include Google Gears externs in the master externs list.
863 See `js2-additional-externs' for more information about externs."
867 (js2-deflocal js2-additional-externs nil
868 "A buffer-local list of additional external declarations.
869 It is used to decide whether variables are considered undeclared
870 for purposes of highlighting.
872 Each entry is a lisp string. The string should be the fully qualified
873 name of an external entity. All externs should be added to this list,
874 so that as js2-mode's processing improves it can take advantage of them.
876 You may want to declare your externs in three ways.
877 First, you can add externs that are valid for all your JavaScript files.
878 You should probably do this by adding them to `js2-global-externs', which
879 is a global list used for all js2-mode files.
881 Next, you can add a function to `js2-mode-hook' that adds additional
882 externs appropriate for the specific file, perhaps based on its path.
883 These should go in `js2-additional-externs', which is buffer-local.
885 Finally, you can add a function to `js2-post-parse-callbacks',
886 which is called after parsing completes, and `root' is bound to
887 the root of the parse tree. At this stage you can set up an AST
888 node visitor using `js2-visit-ast' and examine the parse tree
889 for specific import patterns that may imply the existence of
890 other externs, possibly tied to your build system. These should also
891 be added to `js2-additional-externs'.
893 Your post-parse callback may of course also use the simpler and
894 faster (but perhaps less robust) approach of simply scanning the
895 buffer text for your imports, using regular expressions.")
898 ;; SKIP: encoded-source
900 ;;; The following variables are per-function and should be saved/restored
901 ;;; during function parsing...
903 (js2-deflocal js2-current-script-or-fn nil)
904 (js2-deflocal js2-current-scope nil)
905 (js2-deflocal js2-nesting-of-with 0)
906 (js2-deflocal js2-label-set nil
907 "An alist mapping label names to nodes.")
909 (js2-deflocal js2-loop-set nil)
910 (js2-deflocal js2-loop-and-switch-set nil)
911 (js2-deflocal js2-has-return-value nil)
912 (js2-deflocal js2-end-flags 0)
914 ;;; ...end of per function variables
916 ;; Without 2-token lookahead, labels are a problem.
917 ;; These vars store the token info of the last matched name,
918 ;; iff it wasn't the last matched token. Only valid in some contexts.
919 (defvar js2-prev-name-token-start nil)
920 (defvar js2-prev-name-token-string nil)
922 (defsubst js2-save-name-token-data (pos name)
923 (setq js2-prev-name-token-start pos
924 js2-prev-name-token-string name))
926 ;; These flags enumerate the possible ways a statement/function can
927 ;; terminate. These flags are used by endCheck() and by the Parser to
928 ;; detect inconsistent return usage.
930 ;; END_UNREACHED is reserved for code paths that are assumed to always be
931 ;; able to execute (example: throw, continue)
933 ;; END_DROPS_OFF indicates if the statement can transfer control to the
934 ;; next one. Statement such as return dont. A compound statement may have
935 ;; some branch that drops off control to the next statement.
937 ;; END_RETURNS indicates that the statement can return (without arguments)
938 ;; END_RETURNS_VALUE indicates that the statement can return a value.
940 ;; A compound statement such as
944 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
946 (defconst js2-end-unreached #x0)
947 (defconst js2-end-drops-off #x1)
948 (defconst js2-end-returns #x2)
949 (defconst js2-end-returns-value #x4)
950 (defconst js2-end-yields #x8)
952 ;; Rhino awkwardly passes a statementLabel parameter to the
953 ;; statementHelper() function, the main statement parser, which
954 ;; is then used by quite a few of the sub-parsers. We just make
955 ;; it a buffer-local variable and make sure it's cleaned up properly.
956 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
958 ;; Similarly, Rhino passes an inForInit boolean through about half
959 ;; the expression parsers. We use a dynamically-scoped variable,
960 ;; which makes it easier to funcall the parsers individually without
961 ;; worrying about whether they take the parameter or not.
962 (js2-deflocal js2-in-for-init nil)
963 (js2-deflocal js2-temp-name-counter 0)
964 (js2-deflocal js2-parse-stmt-count 0)
966 (defsubst js2-get-next-temp-name ()
967 (format "$%d" (incf js2-temp-name-counter)))
969 (defvar js2-parse-interruptable-p t
970 "Set this to nil to force parse to continue until finished.
971 This will mostly be useful for interpreters.")
973 (defvar js2-statements-per-pause 50
974 "Pause after this many statements to check for user input.
975 If user input is pending, stop the parse and discard the tree.
976 This makes for a smoother user experience for large files.
977 You may have to wait a second or two before the highlighting
978 and error-reporting appear, but you can always type ahead if
979 you wish. This appears to be more or less how Eclipse, IntelliJ
980 and other editors work.")
982 (js2-deflocal js2-record-comments t
983 "Instructs the scanner to record comments in `js2-scanned-comments'.")
985 (js2-deflocal js2-scanned-comments nil
986 "List of all comments from the current parse.")
988 (defcustom js2-mode-indent-inhibit-undo nil
989 "Non-nil to disable collection of Undo information when indenting lines.
990 Some users have requested this behavior. It's nil by default because
991 other Emacs modes don't work this way."
995 (defcustom js2-mode-indent-ignore-first-tab nil
996 "If non-nil, ignore first TAB keypress if we look indented properly.
997 It's fairly common for users to navigate to an already-indented line
998 and press TAB for reassurance that it's been indented. For this class
999 of users, we want the first TAB press on a line to be ignored if the
1000 line is already indented to one of the precomputed alternatives.
1002 This behavior is only partly implemented. If you TAB-indent a line,
1003 navigate to another line, and then navigate back, it fails to clear
1004 the last-indented variable, so it thinks you've already hit TAB once,
1005 and performs the indent. A full solution would involve getting on the
1006 point-motion hooks for the entire buffer. If we come across another
1007 use cases that requires watching point motion, I'll consider doing it.
1009 If you set this variable to nil, then the TAB key will always change
1010 the indentation of the current line, if more than one alternative
1011 indentation spot exists."
1015 (defvar js2-indent-hook nil
1016 "A hook for user-defined indentation rules.
1018 Functions on this hook should expect two arguments: (LIST INDEX)
1019 The LIST argument is the list of computed indentation points for
1020 the current line. INDEX is the list index of the indentation point
1021 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1022 indent function is not going to change the current line indentation.
1024 If a hook function on this list returns a non-nil value, then
1025 `js2-bounce-indent' assumes the hook function has performed its own
1026 indentation, and will do nothing. If all hook functions on the list
1027 return nil, then `js2-bounce-indent' will use its computed indentation
1028 and reindent the line.
1030 When hook functions on this hook list are called, the variable
1031 `js2-mode-ast' may or may not be set, depending on whether the
1032 parse tree is available. If the variable is nil, you can pass a
1033 callback to `js2-mode-wait-for-parse', and your callback will be
1034 called after the new parse tree is built. This can take some time
1037 (defface js2-warning-face
1038 `((((class color) (background light))
1039 (:underline "orange"))
1040 (((class color) (background dark))
1041 (:underline "orange"))
1043 "Face for JavaScript warnings."
1046 (defface js2-error-face
1047 `((((class color) (background light))
1048 (:foreground "red"))
1049 (((class color) (background dark))
1050 (:foreground "red"))
1051 (t (:foreground "red")))
1052 "Face for JavaScript errors."
1055 (defface js2-jsdoc-tag-face
1056 '((t :foreground "SlateGray"))
1057 "Face used to highlight @whatever tags in jsdoc comments."
1060 (defface js2-jsdoc-type-face
1061 '((t :foreground "SteelBlue"))
1062 "Face used to highlight {FooBar} types in jsdoc comments."
1065 (defface js2-jsdoc-value-face
1066 '((t :foreground "PeachPuff3"))
1067 "Face used to highlight tag values in jsdoc comments."
1070 (defface js2-function-param-face
1071 '((t :foreground "SeaGreen"))
1072 "Face used to highlight function parameters in javascript."
1075 (defface js2-instance-member-face
1076 '((t :foreground "DarkOrchid"))
1077 "Face used to highlight instance variables in javascript.
1078 Not currently used."
1081 (defface js2-private-member-face
1082 '((t :foreground "PeachPuff3"))
1083 "Face used to highlight calls to private methods in javascript.
1084 Not currently used."
1087 (defface js2-private-function-call-face
1088 '((t :foreground "goldenrod"))
1089 "Face used to highlight calls to private functions in javascript.
1090 Not currently used."
1093 (defface js2-jsdoc-html-tag-name-face
1095 '((((class color) (min-colors 88) (background light))
1096 (:foreground "rosybrown"))
1097 (((class color) (min-colors 8) (background dark))
1098 (:foreground "yellow"))
1099 (((class color) (min-colors 8) (background light))
1100 (:foreground "magenta")))
1101 '((((type tty pc) (class color) (background light))
1102 (:foreground "magenta"))
1103 (((type tty pc) (class color) (background dark))
1104 (:foreground "yellow"))
1105 (t (:foreground "RosyBrown"))))
1106 "Face used to highlight jsdoc html tag names"
1109 (defface js2-jsdoc-html-tag-delimiter-face
1111 '((((class color) (min-colors 88) (background light))
1112 (:foreground "dark khaki"))
1113 (((class color) (min-colors 8) (background dark))
1114 (:foreground "green"))
1115 (((class color) (min-colors 8) (background light))
1116 (:foreground "green")))
1117 '((((type tty pc) (class color) (background light))
1118 (:foreground "green"))
1119 (((type tty pc) (class color) (background dark))
1120 (:foreground "green"))
1121 (t (:foreground "dark khaki"))))
1122 "Face used to highlight brackets in jsdoc html tags."
1125 (defface js2-magic-paren-face
1127 "Face used to color parens that will be auto-overwritten."
1130 (defcustom js2-post-parse-callbacks nil
1131 "A list of callback functions invoked after parsing finishes.
1132 Currently, the main use for this function is to add synthetic
1133 declarations to `js2-recorded-identifiers', which see."
1137 (defface js2-external-variable-face
1138 '((t :foreground "orange"))
1139 "Face used to highlight undeclared variable identifiers.
1140 An undeclared variable is any variable not declared with var or let
1141 in the current scope or any lexically enclosing scope. If you use
1142 such a variable, then you are either expecting it to originate from
1143 another file, or you've got a potential bug."
1146 (defcustom js2-highlight-external-variables t
1147 "Non-nil to highlight undeclared variable identifiers."
1151 (defcustom js2-auto-insert-catch-block t
1152 "Non-nil to insert matching catch block on open-curly after `try'."
1156 (defvar js2-mode-map
1157 (let ((map (make-sparse-keymap))
1159 (define-key map [mouse-1] #'js2-mode-show-node)
1160 (define-key map (kbd "C-m") #'js2-enter-key)
1161 (when js2-rebind-eol-bol-keys
1162 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1163 (define-key map (kbd "C-e") #'js2-end-of-line))
1164 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1165 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1166 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1167 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1168 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1169 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1170 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1171 (define-key map (kbd "C-c C-`") #'js2-next-error)
1172 ;; also define user's preference for next-error, if available
1173 (if (setq keys (where-is-internal #'next-error))
1174 (define-key map (car keys) #'js2-next-error))
1175 (define-key map (or (car (where-is-internal #'mark-defun))
1178 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1180 #'js2-narrow-to-defun)
1181 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1182 (when js2-auto-indent-p
1184 (define-key map key #'js2-insert-and-indent))
1186 (when js2-bounce-indent-p
1187 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1189 (define-key map [menu-bar javascript]
1190 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1192 (define-key map [menu-bar javascript customize-js2-mode]
1193 '(menu-item "Customize js2-mode" js2-mode-customize
1194 :help "Customize the behavior of this mode"))
1196 (define-key map [menu-bar javascript js2-force-refresh]
1197 '(menu-item "Force buffer refresh" js2-mode-reset
1198 :help "Re-parse the buffer from scratch"))
1200 (define-key map [menu-bar javascript separator-2]
1203 (define-key map [menu-bar javascript next-error]
1204 '(menu-item "Next warning or error" js2-next-error
1205 :enabled (and js2-mode-ast
1206 (or (js2-ast-root-errors js2-mode-ast)
1207 (js2-ast-root-warnings js2-mode-ast)))
1208 :help "Move to next warning or error"))
1210 (define-key map [menu-bar javascript display-errors]
1211 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1212 :visible (not js2-mode-show-parse-errors)
1213 :help "Turn on display of warnings and errors"))
1215 (define-key map [menu-bar javascript hide-errors]
1216 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1217 :visible js2-mode-show-parse-errors
1218 :help "Turn off display of warnings and errors"))
1220 (define-key map [menu-bar javascript separator-1]
1223 (define-key map [menu-bar javascript js2-toggle-function]
1224 '(menu-item "Show/collapse element" js2-mode-toggle-element
1225 :help "Hide or show function body or comment"))
1227 (define-key map [menu-bar javascript show-comments]
1228 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1229 :visible js2-mode-comments-hidden
1230 :help "Expand all hidden block comments"))
1232 (define-key map [menu-bar javascript hide-comments]
1233 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1234 :visible (not js2-mode-comments-hidden)
1235 :help "Show block comments as /*...*/"))
1237 (define-key map [menu-bar javascript show-all-functions]
1238 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1239 :visible js2-mode-functions-hidden
1240 :help "Expand all hidden function bodies"))
1242 (define-key map [menu-bar javascript hide-all-functions]
1243 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1244 :visible (not js2-mode-functions-hidden)
1245 :help "Show {...} for all top-level function bodies"))
1248 "Keymap used in `js2-mode' buffers.")
1250 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1252 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1253 "Matches a //-comment line. Must be first non-whitespace on line.
1254 First match-group is the leading whitespace.")
1256 (defvar js2-mode-hook nil)
1258 (js2-deflocal js2-mode-ast nil "Private variable.")
1259 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1260 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1261 (js2-deflocal js2-mode-parsing nil "Private variable.")
1262 (js2-deflocal js2-mode-node-overlay nil)
1264 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1265 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1267 (js2-deflocal js2-mode-fontifications nil "Private variable")
1268 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1269 (js2-deflocal js2-imenu-recorder nil "Private variable")
1270 (js2-deflocal js2-imenu-function-map nil "Private variable")
1272 (defvar js2-paragraph-start
1273 "\\(@[a-zA-Z]+\\>\\|$\\)")
1275 ;; Note that we also set a 'c-in-sws text property in html comments,
1276 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1277 (defvar js2-syntactic-ws-start
1278 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1280 (defvar js2-syntactic-ws-end
1281 "\\s \\|[\n\r/]\\|\\s!")
1283 (defvar js2-syntactic-eol
1284 (concat "\\s *\\(/\\*[^*\n\r]*"
1285 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1287 "\\(//\\|/\\*[^*\n\r]*"
1288 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1290 "Copied from `java-mode'. Needed for some cc-engine functions.")
1292 (defvar js2-comment-prefix-regexp
1295 (defvar js2-comment-start-skip
1296 "\\(//+\\|/\\*+\\)\\s *")
1298 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1299 "Non-nil to emit status messages during parsing.")
1301 (defvar js2-mode-functions-hidden nil "private variable")
1302 (defvar js2-mode-comments-hidden nil "private variable")
1304 (defvar js2-mode-syntax-table
1305 (let ((table (make-syntax-table)))
1306 (c-populate-syntax-table table)
1308 "Syntax table used in js2-mode buffers.")
1310 (defvar js2-mode-abbrev-table nil
1311 "Abbrev table in use in `js2-mode' buffers.")
1312 (define-abbrev-table 'js2-mode-abbrev-table ())
1314 (defvar js2-mode-pending-parse-callbacks nil
1315 "List of functions waiting to be notified that parse is finished.")
1317 (defvar js2-mode-last-indented-line -1)
1319 ;;; Localizable error and warning messages
1321 ;; Messages are copied from Rhino's Messages.properties.
1322 ;; Many of the Java-specific messages have been elided.
1323 ;; Add any js2-specific ones at the end, so we can keep
1324 ;; this file synced with changes to Rhino's.
1326 (defvar js2-message-table
1327 (make-hash-table :test 'equal :size 250)
1328 "Contains localized messages for js2-mode.")
1330 ;; TODO(stevey): construct this table at compile-time.
1331 (defmacro js2-msg (key &rest strings)
1332 `(puthash ,key (funcall #'concat ,@strings)
1335 (defun js2-get-msg (msg-key)
1336 "Look up a localized message.
1337 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1338 the correct number of ARGS must be provided."
1339 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1340 (args (if (listp msg-key) (cdr msg-key)))
1341 (msg (gethash key js2-message-table)))
1343 (apply #'format msg args)
1344 key))) ; default to showing the key
1346 (js2-msg "msg.dup.parms"
1347 "Duplicate parameter name '%s'.")
1349 (js2-msg "msg.too.big.jump"
1350 "Program too complex: jump offset too big.")
1352 (js2-msg "msg.too.big.index"
1353 "Program too complex: internal index exceeds 64K limit.")
1355 (js2-msg "msg.while.compiling.fn"
1356 "Encountered code generation error while compiling function '%s': %s")
1358 (js2-msg "msg.while.compiling.script"
1359 "Encountered code generation error while compiling script: %s")
1362 (js2-msg "msg.ctor.not.found"
1363 "Constructor for '%s' not found.")
1365 (js2-msg "msg.not.ctor"
1366 "'%s' is not a constructor.")
1369 (js2-msg "msg.varargs.ctor"
1370 "Method or constructor '%s' must be static "
1371 "with the signature (Context cx, Object[] args, "
1372 "Function ctorObj, boolean inNewExpr) "
1373 "to define a variable arguments constructor.")
1375 (js2-msg "msg.varargs.fun"
1376 "Method '%s' must be static with the signature "
1377 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1378 "to define a variable arguments function.")
1380 (js2-msg "msg.incompat.call"
1381 "Method '%s' called on incompatible object.")
1383 (js2-msg "msg.bad.parms"
1384 "Unsupported parameter type '%s' in method '%s'.")
1386 (js2-msg "msg.bad.method.return"
1387 "Unsupported return type '%s' in method '%s'.")
1389 (js2-msg "msg.bad.ctor.return"
1390 "Construction of objects of type '%s' is not supported.")
1392 (js2-msg "msg.no.overload"
1393 "Method '%s' occurs multiple times in class '%s'.")
1395 (js2-msg "msg.method.not.found"
1396 "Method '%s' not found in '%s'.")
1400 (js2-msg "msg.bad.for.in.lhs"
1401 "Invalid left-hand side of for..in loop.")
1403 (js2-msg "msg.mult.index"
1404 "Only one variable allowed in for..in loop.")
1406 (js2-msg "msg.bad.for.in.destruct"
1407 "Left hand side of for..in loop must be an array of "
1408 "length 2 to accept key/value pair.")
1410 (js2-msg "msg.cant.convert"
1411 "Can't convert to type '%s'.")
1413 (js2-msg "msg.bad.assign.left"
1414 "Invalid assignment left-hand side.")
1416 (js2-msg "msg.bad.decr"
1417 "Invalid decerement operand.")
1419 (js2-msg "msg.bad.incr"
1420 "Invalid increment operand.")
1422 (js2-msg "msg.bad.yield"
1423 "yield must be in a function.")
1425 (js2-msg "msg.yield.parenthesized"
1426 "yield expression must be parenthesized.")
1429 (js2-msg "msg.cant.call.indirect"
1430 "Function '%s' must be called directly, and not by way of a "
1431 "function of another name.")
1433 (js2-msg "msg.eval.nonstring"
1434 "Calling eval() with anything other than a primitive "
1435 "string value will simply return the value. "
1436 "Is this what you intended?")
1438 (js2-msg "msg.eval.nonstring.strict"
1439 "Calling eval() with anything other than a primitive "
1440 "string value is not allowed in strict mode.")
1442 (js2-msg "msg.bad.destruct.op"
1443 "Invalid destructuring assignment operator")
1446 (js2-msg "msg.only.from.new"
1447 "'%s' may only be invoked from a `new' expression.")
1449 (js2-msg "msg.deprec.ctor"
1450 "The '%s' constructor is deprecated.")
1453 (js2-msg "msg.no.function.ref.found"
1454 "no source found to decompile function reference %s")
1456 (js2-msg "msg.arg.isnt.array"
1457 "second argument to Function.prototype.apply must be an array")
1460 (js2-msg "msg.bad.esc.mask"
1461 "invalid string escape mask")
1464 (js2-msg "msg.bad.quant"
1465 "Invalid quantifier %s")
1467 (js2-msg "msg.overlarge.backref"
1468 "Overly large back reference %s")
1470 (js2-msg "msg.overlarge.min"
1471 "Overly large minimum %s")
1473 (js2-msg "msg.overlarge.max"
1474 "Overly large maximum %s")
1476 (js2-msg "msg.zero.quant"
1477 "Zero quantifier %s")
1479 (js2-msg "msg.max.lt.min"
1480 "Maximum %s less than minimum")
1482 (js2-msg "msg.unterm.quant"
1483 "Unterminated quantifier %s")
1485 (js2-msg "msg.unterm.paren"
1486 "Unterminated parenthetical %s")
1488 (js2-msg "msg.unterm.class"
1489 "Unterminated character class %s")
1491 (js2-msg "msg.bad.range"
1492 "Invalid range in character class.")
1494 (js2-msg "msg.trail.backslash"
1495 "Trailing \\ in regular expression.")
1497 (js2-msg "msg.re.unmatched.right.paren"
1498 "unmatched ) in regular expression.")
1500 (js2-msg "msg.no.regexp"
1501 "Regular expressions are not available.")
1503 (js2-msg "msg.bad.backref"
1504 "back-reference exceeds number of capturing parentheses.")
1506 (js2-msg "msg.bad.regexp.compile"
1507 "Only one argument may be specified if the first "
1508 "argument to RegExp.prototype.compile is a RegExp object.")
1511 (js2-msg "msg.got.syntax.errors"
1512 "Compilation produced %s syntax errors.")
1514 (js2-msg "msg.var.redecl"
1515 "TypeError: redeclaration of var %s.")
1517 (js2-msg "msg.const.redecl"
1518 "TypeError: redeclaration of const %s.")
1520 (js2-msg "msg.let.redecl"
1521 "TypeError: redeclaration of variable %s.")
1523 (js2-msg "msg.parm.redecl"
1524 "TypeError: redeclaration of formal parameter %s.")
1526 (js2-msg "msg.fn.redecl"
1527 "TypeError: redeclaration of function %s.")
1529 (js2-msg "msg.let.decl.not.in.block"
1530 "SyntaxError: let declaration not directly within block")
1533 (js2-msg "msg.dup.label"
1536 (js2-msg "msg.undef.label"
1539 (js2-msg "msg.bad.break"
1540 "unlabelled break must be inside loop or switch")
1542 (js2-msg "msg.continue.outside"
1543 "continue must be inside loop")
1545 (js2-msg "msg.continue.nonloop"
1546 "continue can only use labels of iteration statements")
1548 (js2-msg "msg.bad.throw.eol"
1549 "Line terminator is not allowed between the throw "
1550 "keyword and throw expression.")
1552 (js2-msg "msg.no.paren.parms"
1553 "missing ( before function parameters.")
1555 (js2-msg "msg.no.parm"
1556 "missing formal parameter")
1558 (js2-msg "msg.no.paren.after.parms"
1559 "missing ) after formal parameters")
1561 (js2-msg "msg.no.brace.body"
1562 "missing '{' before function body")
1564 (js2-msg "msg.no.brace.after.body"
1565 "missing } after function body")
1567 (js2-msg "msg.no.paren.cond"
1568 "missing ( before condition")
1570 (js2-msg "msg.no.paren.after.cond"
1571 "missing ) after condition")
1573 (js2-msg "msg.no.semi.stmt"
1574 "missing ; before statement")
1576 (js2-msg "msg.missing.semi"
1577 "missing ; after statement")
1579 (js2-msg "msg.no.name.after.dot"
1580 "missing name after . operator")
1582 (js2-msg "msg.no.name.after.coloncolon"
1583 "missing name after :: operator")
1585 (js2-msg "msg.no.name.after.dotdot"
1586 "missing name after .. operator")
1588 (js2-msg "msg.no.name.after.xmlAttr"
1589 "missing name after .@")
1591 (js2-msg "msg.no.bracket.index"
1592 "missing ] in index expression")
1594 (js2-msg "msg.no.paren.switch"
1595 "missing ( before switch expression")
1597 (js2-msg "msg.no.paren.after.switch"
1598 "missing ) after switch expression")
1600 (js2-msg "msg.no.brace.switch"
1601 "missing '{' before switch body")
1603 (js2-msg "msg.bad.switch"
1604 "invalid switch statement")
1606 (js2-msg "msg.no.colon.case"
1607 "missing : after case expression")
1609 (js2-msg "msg.double.switch.default"
1610 "double default label in the switch statement")
1612 (js2-msg "msg.no.while.do"
1613 "missing while after do-loop body")
1615 (js2-msg "msg.no.paren.for"
1616 "missing ( after for")
1618 (js2-msg "msg.no.semi.for"
1619 "missing ; after for-loop initializer")
1621 (js2-msg "msg.no.semi.for.cond"
1622 "missing ; after for-loop condition")
1624 (js2-msg "msg.in.after.for.name"
1625 "missing in after for")
1627 (js2-msg "msg.no.paren.for.ctrl"
1628 "missing ) after for-loop control")
1630 (js2-msg "msg.no.paren.with"
1631 "missing ( before with-statement object")
1633 (js2-msg "msg.no.paren.after.with"
1634 "missing ) after with-statement object")
1636 (js2-msg "msg.no.paren.after.let"
1637 "missing ( after let")
1639 (js2-msg "msg.no.paren.let"
1640 "missing ) after variable list")
1642 (js2-msg "msg.no.curly.let"
1643 "missing } after let statement")
1645 (js2-msg "msg.bad.return"
1648 (js2-msg "msg.no.brace.block"
1649 "missing } in compound statement")
1651 (js2-msg "msg.bad.label"
1654 (js2-msg "msg.bad.var"
1655 "missing variable name")
1657 (js2-msg "msg.bad.var.init"
1658 "invalid variable initialization")
1660 (js2-msg "msg.no.colon.cond"
1661 "missing : in conditional expression")
1663 (js2-msg "msg.no.paren.arg"
1664 "missing ) after argument list")
1666 (js2-msg "msg.no.bracket.arg"
1667 "missing ] after element list")
1669 (js2-msg "msg.bad.prop"
1670 "invalid property id")
1672 (js2-msg "msg.no.colon.prop"
1673 "missing : after property id")
1675 (js2-msg "msg.no.brace.prop"
1676 "missing } after property list")
1678 (js2-msg "msg.no.paren"
1679 "missing ) in parenthetical")
1681 (js2-msg "msg.reserved.id"
1682 "identifier is a reserved word")
1684 (js2-msg "msg.no.paren.catch"
1685 "missing ( before catch-block condition")
1687 (js2-msg "msg.bad.catchcond"
1688 "invalid catch block condition")
1690 (js2-msg "msg.catch.unreachable"
1691 "any catch clauses following an unqualified catch are unreachable")
1693 (js2-msg "msg.no.brace.try"
1694 "missing '{' before try block")
1696 (js2-msg "msg.no.brace.catchblock"
1697 "missing '{' before catch-block body")
1699 (js2-msg "msg.try.no.catchfinally"
1700 "'try' without 'catch' or 'finally'")
1702 (js2-msg "msg.no.return.value"
1703 "function %s does not always return a value")
1705 (js2-msg "msg.anon.no.return.value"
1706 "anonymous function does not always return a value")
1708 (js2-msg "msg.return.inconsistent"
1709 "return statement is inconsistent with previous usage")
1711 (js2-msg "msg.generator.returns"
1712 "TypeError: generator function '%s' returns a value")
1714 (js2-msg "msg.anon.generator.returns"
1715 "TypeError: anonymous generator function returns a value")
1717 (js2-msg "msg.syntax"
1720 (js2-msg "msg.unexpected.eof"
1721 "Unexpected end of file")
1723 (js2-msg "msg.XML.bad.form"
1724 "illegally formed XML syntax")
1726 (js2-msg "msg.XML.not.available"
1727 "XML runtime not available")
1729 (js2-msg "msg.too.deep.parser.recursion"
1730 "Too deep recursion while parsing")
1732 (js2-msg "msg.no.side.effects"
1733 "Code has no side effects")
1735 (js2-msg "msg.extra.trailing.comma"
1736 "Trailing comma is not legal in an ECMA-262 object initializer")
1738 (js2-msg "msg.array.trailing.comma"
1739 "Trailing comma yields different behavior across browsers")
1741 (js2-msg "msg.equal.as.assign"
1742 (concat "Test for equality (==) mistyped as assignment (=)?"
1743 " (parenthesize to suppress warning)"))
1745 (js2-msg "msg.var.hides.arg"
1746 "Variable %s hides argument")
1748 (js2-msg "msg.destruct.assign.no.init"
1749 "Missing = in destructuring declaration")
1752 (js2-msg "msg.no.properties"
1753 "%s has no properties.")
1755 (js2-msg "msg.invalid.iterator"
1756 "Invalid iterator value")
1758 (js2-msg "msg.iterator.primitive"
1759 "__iterator__ returned a primitive value")
1761 (js2-msg "msg.assn.create.strict"
1762 "Assignment to undeclared variable %s")
1764 (js2-msg "msg.ref.undefined.prop"
1765 "Reference to undefined property '%s'")
1767 (js2-msg "msg.prop.not.found"
1768 "Property %s not found.")
1770 (js2-msg "msg.invalid.type"
1771 "Invalid JavaScript value of type %s")
1773 (js2-msg "msg.primitive.expected"
1774 "Primitive type expected (had %s instead)")
1776 (js2-msg "msg.namespace.expected"
1777 "Namespace object expected to left of :: (found %s instead)")
1779 (js2-msg "msg.null.to.object"
1780 "Cannot convert null to an object.")
1782 (js2-msg "msg.undef.to.object"
1783 "Cannot convert undefined to an object.")
1785 (js2-msg "msg.cyclic.value"
1786 "Cyclic %s value not allowed.")
1788 (js2-msg "msg.is.not.defined"
1789 "'%s' is not defined.")
1791 (js2-msg "msg.undef.prop.read"
1792 "Cannot read property '%s' from %s")
1794 (js2-msg "msg.undef.prop.write"
1795 "Cannot set property '%s' of %s to '%s'")
1797 (js2-msg "msg.undef.prop.delete"
1798 "Cannot delete property '%s' of %s")
1800 (js2-msg "msg.undef.method.call"
1801 "Cannot call method '%s' of %s")
1803 (js2-msg "msg.undef.with"
1804 "Cannot apply 'with' to %s")
1806 (js2-msg "msg.isnt.function"
1807 "%s is not a function, it is %s.")
1809 (js2-msg "msg.isnt.function.in"
1810 "Cannot call property %s in object %s. "
1811 "It is not a function, it is '%s'.")
1813 (js2-msg "msg.function.not.found"
1814 "Cannot find function %s.")
1816 (js2-msg "msg.function.not.found.in"
1817 "Cannot find function %s in object %s.")
1819 (js2-msg "msg.isnt.xml.object"
1820 "%s is not an xml object.")
1822 (js2-msg "msg.no.ref.to.get"
1823 "%s is not a reference to read reference value.")
1825 (js2-msg "msg.no.ref.to.set"
1826 "%s is not a reference to set reference value to %s.")
1828 (js2-msg "msg.no.ref.from.function"
1829 "Function %s can not be used as the left-hand "
1830 "side of assignment or as an operand of ++ or -- operator.")
1832 (js2-msg "msg.bad.default.value"
1833 "Object's getDefaultValue() method returned an object.")
1835 (js2-msg "msg.instanceof.not.object"
1836 "Can't use instanceof on a non-object.")
1838 (js2-msg "msg.instanceof.bad.prototype"
1839 "'prototype' property of %s is not an object.")
1841 (js2-msg "msg.bad.radix"
1842 "illegal radix %s.")
1845 (js2-msg "msg.default.value"
1846 "Cannot find default value for object.")
1848 (js2-msg "msg.zero.arg.ctor"
1849 "Cannot load class '%s' which has no zero-parameter constructor.")
1851 (js2-msg "msg.ctor.multiple.parms"
1852 "Can't define constructor or class %s since more than "
1853 "one constructor has multiple parameters.")
1855 (js2-msg "msg.extend.scriptable"
1856 "%s must extend ScriptableObject in order to define property %s.")
1858 (js2-msg "msg.bad.getter.parms"
1859 "In order to define a property, getter %s must have zero "
1860 "parameters or a single ScriptableObject parameter.")
1862 (js2-msg "msg.obj.getter.parms"
1863 "Expected static or delegated getter %s to take "
1864 "a ScriptableObject parameter.")
1866 (js2-msg "msg.getter.static"
1867 "Getter and setter must both be static or neither be static.")
1869 (js2-msg "msg.setter.return"
1870 "Setter must have void return type: %s")
1872 (js2-msg "msg.setter2.parms"
1873 "Two-parameter setter must take a ScriptableObject as "
1874 "its first parameter.")
1876 (js2-msg "msg.setter1.parms"
1877 "Expected single parameter setter for %s")
1879 (js2-msg "msg.setter2.expected"
1880 "Expected static or delegated setter %s to take two parameters.")
1882 (js2-msg "msg.setter.parms"
1883 "Expected either one or two parameters for setter.")
1885 (js2-msg "msg.setter.bad.type"
1886 "Unsupported parameter type '%s' in setter '%s'.")
1888 (js2-msg "msg.add.sealed"
1889 "Cannot add a property to a sealed object: %s.")
1891 (js2-msg "msg.remove.sealed"
1892 "Cannot remove a property from a sealed object: %s.")
1894 (js2-msg "msg.modify.sealed"
1895 "Cannot modify a property of a sealed object: %s.")
1897 (js2-msg "msg.modify.readonly"
1898 "Cannot modify readonly property: %s.")
1901 (js2-msg "msg.missing.exponent"
1904 (js2-msg "msg.caught.nfe"
1905 "number format error")
1907 (js2-msg "msg.unterminated.string.lit"
1908 "unterminated string literal")
1910 (js2-msg "msg.unterminated.comment"
1911 "unterminated comment")
1913 (js2-msg "msg.unterminated.re.lit"
1914 "unterminated regular expression literal")
1916 (js2-msg "msg.invalid.re.flag"
1917 "invalid flag after regular expression")
1919 (js2-msg "msg.no.re.input.for"
1922 (js2-msg "msg.illegal.character"
1923 "illegal character")
1925 (js2-msg "msg.invalid.escape"
1926 "invalid Unicode escape sequence")
1928 (js2-msg "msg.bad.namespace"
1929 "not a valid default namespace statement. "
1930 "Syntax is: default xml namespace = EXPRESSION;")
1932 ;; TokensStream warnings
1933 (js2-msg "msg.bad.octal.literal"
1934 "illegal octal literal digit %s; "
1935 "interpreting it as a decimal digit")
1937 (js2-msg "msg.reserved.keyword"
1938 "illegal usage of future reserved keyword %s; "
1939 "interpreting it as ordinary identifier")
1941 (js2-msg "msg.script.is.not.constructor"
1942 "Script objects are not constructors.")
1945 (js2-msg "msg.arraylength.bad"
1946 "Inappropriate array length.")
1949 (js2-msg "msg.arraylength.too.big"
1950 "Array length %s exceeds supported capacity limit.")
1953 (js2-msg "msg.bad.uri"
1954 "Malformed URI sequence.")
1957 (js2-msg "msg.bad.precision"
1958 "Precision %s out of range.")
1961 (js2-msg "msg.send.newborn"
1962 "Attempt to send value to newborn generator")
1964 (js2-msg "msg.already.exec.gen"
1965 "Already executing generator")
1967 (js2-msg "msg.StopIteration.invalid"
1968 "StopIteration may not be changed to an arbitrary object.")
1971 (js2-msg "msg.yield.closing"
1972 "Yield from closing generator")
1976 (defun js2-delete-if (predicate list)
1977 "Remove all items satisfying PREDICATE in LIST."
1978 (loop for item in list
1979 if (not (funcall predicate item))
1982 (defun js2-position (element list)
1983 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1984 Returns nil if element is not found in the list."
1987 (while (and list (not found))
1988 (if (eq element (car list))
1990 (setq count (1+ count)
1994 (defun js2-find-if (predicate list)
1995 "Find first item satisfying PREDICATE in LIST."
1997 (while (and list (not result))
1998 (if (funcall predicate (car list))
1999 (setq result (car list)))
2000 (setq list (cdr list)))
2003 (defmacro js2-time (form)
2004 "Evaluate FORM, discard result, and return elapsed time in sec"
2006 (let ((beg (make-symbol "--js2-time-beg--"))
2007 (delta (make-symbol "--js2-time-end--")))
2008 `(let ((,beg (current-time))
2011 (/ (truncate (* (- (float-time (current-time))
2016 (defsubst js2-same-line (pos)
2017 "Return t if POS is on the same line as current point."
2018 (and (>= pos (point-at-bol))
2019 (<= pos (point-at-eol))))
2021 (defsubst js2-same-line-2 (p1 p2)
2022 "Return t if p1 is on the same line as p2."
2025 (js2-same-line p2)))
2027 (defun js2-code-bug ()
2028 "Signal an error when we encounter an unexpected code path."
2029 (error "failed assertion"))
2031 (defsubst js2-record-text-property (beg end prop value)
2032 "Record a text property to set when parsing finishes."
2033 (push (list beg end prop value) js2-mode-deferred-properties))
2035 ;; I'd like to associate errors with nodes, but for now the
2036 ;; easiest thing to do is get the context info from the last token.
2037 (defsubst js2-record-parse-error (msg &optional arg pos len)
2038 (push (list (list msg arg)
2039 (or pos js2-token-beg)
2040 (or len (- js2-token-end js2-token-beg)))
2043 (defsubst js2-report-error (msg &optional msg-arg pos len)
2044 "Signal a syntax error or record a parse error."
2045 (if js2-recover-from-parse-errors
2046 (js2-record-parse-error msg msg-arg pos len)
2047 (signal 'js2-syntax-error
2051 (goto-char js2-ts-cursor)
2055 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2056 (if js2-compiler-report-warning-as-error
2057 (js2-report-error msg msg-arg pos len)
2058 (push (list (list msg msg-arg)
2059 (or pos js2-token-beg)
2060 (or len (- js2-token-end js2-token-beg)))
2061 js2-parsed-warnings)))
2063 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2064 (if js2-compiler-strict-mode
2065 (js2-report-warning msg-id msg-arg beg
2066 (and beg end (- end beg)))))
2068 (put 'js2-syntax-error 'error-conditions
2069 '(error syntax-error js2-syntax-error))
2070 (put 'js2-syntax-error 'error-message "Syntax error")
2072 (put 'js2-parse-error 'error-conditions
2073 '(error parse-error js2-parse-error))
2074 (put 'js2-parse-error 'error-message "Parse error")
2076 (defmacro js2-clear-flag (flags flag)
2077 `(setq ,flags (logand ,flags (lognot ,flag))))
2079 (defmacro js2-set-flag (flags flag)
2080 "Logical-or FLAG into FLAGS."
2081 `(setq ,flags (logior ,flags ,flag)))
2083 (defsubst js2-flag-set-p (flags flag)
2084 (/= 0 (logand flags flag)))
2086 (defsubst js2-flag-not-set-p (flags flag)
2087 (zerop (logand flags flag)))
2089 ;; Stolen shamelessly from James Clark's nxml-mode.
2090 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2091 "Evaluate BODY without any text property changes modifying the buffer.
2092 Any text properties changes happen as usual but the changes are not treated as
2093 modifications to the buffer."
2094 (declare (indent 0) (debug t))
2095 (let ((modified (make-symbol "modified")))
2096 `(let ((,modified (buffer-modified-p))
2097 (inhibit-read-only t)
2098 (inhibit-modification-hooks t)
2099 (buffer-undo-list t)
2100 (deactivate-mark nil)
2101 ;; Apparently these avoid file locking problems.
2102 (buffer-file-name nil)
2103 (buffer-file-truename nil))
2107 (restore-buffer-modified-p nil))))))
2109 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2110 "Evaluate BODY with the _ character set to be word-syntax."
2111 (declare (indent 0) (debug t))
2112 (let ((old-syntax (make-symbol "old-syntax")))
2113 `(let ((,old-syntax (string (char-syntax ?_))))
2116 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2118 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2120 (defsubst js2-char-uppercase-p (c)
2121 "Return t if C is an uppercase character.
2122 Handles unicode and latin chars properly."
2123 (/= c (downcase c)))
2125 (defsubst js2-char-lowercase-p (c)
2126 "Return t if C is an uppercase character.
2127 Handles unicode and latin chars properly."
2130 ;;; AST struct and function definitions
2132 ;; flags for ast node property 'member-type (used for e4x operators)
2133 (defvar js2-property-flag #x1 "property access: element is valid name")
2134 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2135 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2137 (defsubst js2-relpos (pos anchor)
2138 "Convert POS to be relative to ANCHOR.
2139 If POS is nil, returns nil."
2140 (and pos (- pos anchor)))
2142 (defsubst js2-make-pad (indent)
2145 (make-string (* indent js2-basic-offset) ? )))
2147 (defsubst js2-visit-ast (node callback)
2148 "Visit every node in ast NODE with visitor CALLBACK.
2150 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2151 called twice: once to visit the node, and again after all the node's
2152 children have been processed. The END-P argument is nil on the first
2153 call and non-nil on the second call. The return value of the callback
2154 affects the traversal: if non-nil, the children of NODE are processed.
2155 If the callback returns nil, or if the node has no children, then the
2156 callback is called immediately with a non-nil END-P argument.
2158 The node traversal is approximately lexical-order, although there
2159 are currently no guarantees around this."
2161 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2163 (when (funcall callback node nil)
2166 ((eq vfunc 'js2-visit-none)
2167 nil) ; don't even bother calling it
2168 ;; Each AST node type has to define a `js2-visitor' function
2169 ;; that takes a node and a callback, and calls `js2-visit-ast'
2170 ;; on each child of the node.
2172 (funcall vfunc node callback))
2174 (error "%s does not define a visitor-traversal function"
2176 ;; call the end-visit
2177 (funcall callback node t))))
2179 (defstruct (js2-node
2180 (:constructor nil)) ; abstract
2181 "Base AST node type."
2182 (type -1) ; token type
2183 (pos -1) ; start position of this AST node in parsed input
2184 (len 1) ; num characters spanned by the node
2185 props ; optional node property list (an alist)
2186 parent) ; link to parent node; null for root
2188 (defsubst js2-node-get-prop (node prop &optional default)
2189 (or (cadr (assoc prop (js2-node-props node))) default))
2191 (defsubst js2-node-set-prop (node prop value)
2192 (setf (js2-node-props node)
2193 (cons (list prop value) (js2-node-props node))))
2195 (defsubst js2-fixup-starts (n nodes)
2196 "Adjust the start positions of NODES to be relative to N.
2197 Any node in the list may be nil, for convenience."
2198 (dolist (node nodes)
2200 (setf (js2-node-pos node) (- (js2-node-pos node)
2201 (js2-node-pos n))))))
2203 (defsubst js2-node-add-children (parent &rest nodes)
2204 "Set parent node of NODES to PARENT, and return PARENT.
2205 Does nothing if we're not recording parent links.
2206 If any given node in NODES is nil, doesn't record that link."
2207 (js2-fixup-starts parent nodes)
2208 (dolist (node nodes)
2210 (setf (js2-node-parent node) parent))))
2212 ;; Non-recursive since it's called a frightening number of times.
2213 (defsubst js2-node-abs-pos (n)
2214 (let ((pos (js2-node-pos n)))
2215 (while (setq n (js2-node-parent n))
2216 (setq pos (+ pos (js2-node-pos n))))
2219 (defsubst js2-node-abs-end (n)
2220 "Return absolute buffer position of end of N."
2221 (+ (js2-node-abs-pos n) (js2-node-len n)))
2223 ;; It's important to make sure block nodes have a lisp list for the
2224 ;; child nodes, to limit printing recursion depth in an AST that
2225 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2226 ;; a sufficiently large vector tree.
2228 (defstruct (js2-block-node
2231 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2236 "A block of statements."
2237 kids) ; a lisp list of the child statement nodes
2239 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2240 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2242 (defsubst js2-visit-block (ast callback)
2243 "Visit the `js2-block-node' children of AST."
2244 (dolist (kid (js2-block-node-kids ast))
2245 (js2-visit-ast kid callback)))
2247 (defun js2-print-block (n i)
2248 (let ((pad (js2-make-pad i)))
2250 (dolist (kid (js2-block-node-kids n))
2251 (js2-print-ast kid (1+ i)))
2254 (defstruct (js2-scope
2255 (:include js2-block-node)
2257 (:constructor make-js2-scope (&key (type js2-BLOCK)
2261 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2262 ;; I don't have one of those handy, so I'll use an alist for now.
2263 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2264 ;; and is much lighter-weight to construct (both CPU and mem).
2265 ;; The keys are interned strings (symbols) for faster lookup.
2266 ;; Should switch to hybrid alist/hashtable eventually.
2267 symbol-table ; an alist of (symbol . js2-symbol)
2268 parent-scope ; a `js2-scope'
2269 top) ; top-level `js2-scope' (script/function)
2271 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2272 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2274 (defun js2-scope-set-parent-scope (scope parent)
2275 (setf (js2-scope-parent-scope scope) parent
2276 (js2-scope-top scope) (if (null parent)
2278 (js2-scope-top parent))))
2280 (defun js2-node-get-enclosing-scope (node)
2281 "Return the innermost `js2-scope' node surrounding NODE.
2282 Returns nil if there is no enclosing scope node."
2283 (let ((parent (js2-node-parent node)))
2284 (while (not (js2-scope-p parent))
2285 (setq parent (js2-node-parent parent)))
2288 (defun js2-get-defining-scope (scope name)
2289 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2290 Returns `js2-scope' in which NAME is defined, or nil if not found."
2291 (let ((sym (if (symbolp name)
2297 (while (and scope continue)
2298 (if (and (setq table (js2-scope-symbol-table scope))
2302 (setq scope (js2-scope-parent-scope scope))))
2305 (defsubst js2-scope-get-symbol (scope name)
2306 "Return symbol table entry for NAME in SCOPE.
2307 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2308 (and (js2-scope-symbol-table scope)
2309 (cdr (assq (if (symbolp name)
2312 (js2-scope-symbol-table scope)))))
2314 (defsubst js2-scope-put-symbol (scope name symbol)
2315 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2316 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2317 (let* ((table (js2-scope-symbol-table scope))
2318 (sym (if (symbolp name) name (intern name)))
2319 (entry (assq sym table)))
2321 (setcdr entry symbol)
2322 (push (cons sym symbol)
2323 (js2-scope-symbol-table scope)))))
2325 (defstruct (js2-symbol
2327 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2328 "A symbol table entry."
2329 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2330 ;; js2-LET, or js2-CONST
2333 ast-node) ; a `js2-node'
2335 (defstruct (js2-error-node
2337 (:constructor nil) ; silence emacs21 byte-compiler
2338 (:constructor make-js2-error-node (&key (type js2-ERROR)
2341 "AST node representing a parse error.")
2343 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2344 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2346 (defstruct (js2-script-node
2347 (:include js2-scope)
2349 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2354 functions ; lisp list of nested functions
2355 regexps ; lisp list of (string . flags)
2356 symbols ; alist (every symbol gets unique index)
2358 var-names ; vector of string names
2359 consts ; bool-vector matching var-decls
2360 (temp-number 0)) ; for generating temp variables
2362 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2363 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2365 (defun js2-print-script (node indent)
2366 (dolist (kid (js2-block-node-kids node))
2367 (js2-print-ast kid indent)))
2369 (defstruct (js2-ast-root
2370 (:include js2-script-node)
2372 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2376 "The root node of a js2 AST."
2377 buffer ; the source buffer from which the code was parsed
2378 comments ; a lisp list of comments, ordered by start position
2379 errors ; a lisp list of errors found during parsing
2380 warnings ; a lisp list of warnings found during parsing
2381 node-count) ; number of nodes in the tree, including the root
2383 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2384 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2386 (defun js2-visit-ast-root (ast callback)
2387 (dolist (kid (js2-ast-root-kids ast))
2388 (js2-visit-ast kid callback))
2389 (dolist (comment (js2-ast-root-comments ast))
2390 (js2-visit-ast comment callback)))
2392 (defstruct (js2-comment-node
2395 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2398 (format js2-ts-comment-type))))
2399 format) ; 'line, 'block, 'jsdoc or 'html
2401 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2402 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2404 (defun js2-print-comment (n i)
2405 ;; We really ought to link end-of-line comments to their nodes.
2406 ;; Or maybe we could add a new comment type, 'endline.
2407 (insert (js2-make-pad i)
2408 (js2-node-string n)))
2410 (defstruct (js2-expr-stmt-node
2413 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2417 "An expression statement."
2420 (defsubst js2-expr-stmt-node-set-has-result (node)
2421 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2422 (setf (js2-node-type node) js2-EXPR_RESULT))
2424 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2425 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2427 (defun js2-visit-expr-stmt-node (n v)
2428 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2430 (defun js2-print-expr-stmt-node (n indent)
2431 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2434 (defstruct (js2-loop-node
2435 (:include js2-scope)
2437 "Abstract supertype of loop nodes."
2438 body ; a `js2-block-node'
2439 lp ; position of left-paren, nil if omitted
2440 rp) ; position of right-paren, nil if omitted
2442 (defstruct (js2-do-node
2443 (:include js2-loop-node)
2445 (:constructor make-js2-do-node (&key (type js2-DO)
2453 "AST node for do-loop."
2454 condition ; while (expression)
2455 while-pos) ; buffer position of 'while' keyword
2457 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2458 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2460 (defun js2-visit-do-node (n v)
2461 (js2-visit-ast (js2-do-node-body n) v)
2462 (js2-visit-ast (js2-do-node-condition n) v))
2464 (defun js2-print-do-node (n i)
2465 (let ((pad (js2-make-pad i)))
2466 (insert pad "do {\n")
2467 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2468 (js2-print-ast kid (1+ i)))
2469 (insert pad "} while (")
2470 (js2-print-ast (js2-do-node-condition n) 0)
2473 (defstruct (js2-while-node
2474 (:include js2-loop-node)
2476 (:constructor make-js2-while-node (&key (type js2-WHILE)
2483 "AST node for while-loop."
2484 condition) ; while-condition
2486 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2487 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2489 (defun js2-visit-while-node (n v)
2490 (js2-visit-ast (js2-while-node-condition n) v)
2491 (js2-visit-ast (js2-while-node-body n) v))
2493 (defun js2-print-while-node (n i)
2494 (let ((pad (js2-make-pad i)))
2495 (insert pad "while (")
2496 (js2-print-ast (js2-while-node-condition n) 0)
2498 (js2-print-body (js2-while-node-body n) (1+ i))
2499 (insert pad "}\n")))
2501 (defstruct (js2-for-node
2502 (:include js2-loop-node)
2504 (:constructor make-js2-for-node (&key (type js2-FOR)
2513 "AST node for a C-style for-loop."
2514 init ; initialization expression
2515 condition ; loop condition
2516 update) ; update clause
2518 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2519 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2521 (defun js2-visit-for-node (n v)
2522 (js2-visit-ast (js2-for-node-init n) v)
2523 (js2-visit-ast (js2-for-node-condition n) v)
2524 (js2-visit-ast (js2-for-node-update n) v)
2525 (js2-visit-ast (js2-for-node-body n) v))
2527 (defun js2-print-for-node (n i)
2528 (let ((pad (js2-make-pad i)))
2529 (insert pad "for (")
2530 (js2-print-ast (js2-for-node-init n) 0)
2532 (js2-print-ast (js2-for-node-condition n) 0)
2534 (js2-print-ast (js2-for-node-update n) 0)
2536 (js2-print-body (js2-for-node-body n) (1+ i))
2537 (insert pad "}\n")))
2539 (defstruct (js2-for-in-node
2540 (:include js2-loop-node)
2542 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2553 "AST node for a for..in loop."
2554 iterator ; [var] foo in ...
2555 object ; object over which we're iterating
2556 in-pos ; buffer position of 'in' keyword
2557 each-pos ; buffer position of 'each' keyword, if foreach-p
2558 foreach-p) ; t if it's a for-each loop
2560 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2561 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2563 (defun js2-visit-for-in-node (n v)
2564 (js2-visit-ast (js2-for-in-node-iterator n) v)
2565 (js2-visit-ast (js2-for-in-node-object n) v)
2566 (js2-visit-ast (js2-for-in-node-body n) v))
2568 (defun js2-print-for-in-node (n i)
2569 (let ((pad (js2-make-pad i))
2570 (foreach (js2-for-in-node-foreach-p n)))
2575 (js2-print-ast (js2-for-in-node-iterator n) 0)
2577 (js2-print-ast (js2-for-in-node-object n) 0)
2579 (js2-print-body (js2-for-in-node-body n) (1+ i))
2580 (insert pad "}\n")))
2582 (defstruct (js2-return-node
2585 (:constructor make-js2-return-node (&key (type js2-RETURN)
2589 "AST node for a return statement."
2590 retval) ; expression to return, or 'undefined
2592 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2593 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2595 (defun js2-visit-return-node (n v)
2596 (js2-visit-ast (js2-return-node-retval n) v))
2598 (defun js2-print-return-node (n i)
2599 (insert (js2-make-pad i) "return")
2600 (when (js2-return-node-retval n)
2602 (js2-print-ast (js2-return-node-retval n) 0))
2605 (defstruct (js2-if-node
2608 (:constructor make-js2-if-node (&key (type js2-IF)
2617 "AST node for an if-statement."
2618 condition ; expression
2619 then-part ; statement or block
2620 else-pos ; optional buffer position of 'else' keyword
2621 else-part ; optional statement or block
2622 lp ; position of left-paren, nil if omitted
2623 rp) ; position of right-paren, nil if omitted
2625 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2626 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2628 (defun js2-visit-if-node (n v)
2629 (js2-visit-ast (js2-if-node-condition n) v)
2630 (js2-visit-ast (js2-if-node-then-part n) v)
2631 (js2-visit-ast (js2-if-node-else-part n) v))
2633 (defun js2-print-if-node (n i)
2634 (let ((pad (js2-make-pad i))
2635 (then-part (js2-if-node-then-part n))
2636 (else-part (js2-if-node-else-part n)))
2638 (js2-print-ast (js2-if-node-condition n) 0)
2640 (js2-print-body then-part (1+ i))
2645 ((js2-if-node-p else-part)
2647 (js2-print-body else-part i))
2649 (insert " else {\n")
2650 (js2-print-body else-part (1+ i))
2651 (insert pad "}\n")))))
2653 (defstruct (js2-try-node
2656 (:constructor make-js2-try-node (&key (type js2-TRY)
2662 "AST node for a try-statement."
2664 catch-clauses ; a lisp list of `js2-catch-node'
2665 finally-block) ; a `js2-finally-node'
2667 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2668 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2670 (defun js2-visit-try-node (n v)
2671 (js2-visit-ast (js2-try-node-try-block n) v)
2672 (dolist (clause (js2-try-node-catch-clauses n))
2673 (js2-visit-ast clause v))
2674 (js2-visit-ast (js2-try-node-finally-block n) v))
2676 (defun js2-print-try-node (n i)
2677 (let ((pad (js2-make-pad i))
2678 (catches (js2-try-node-catch-clauses n))
2679 (finally (js2-try-node-finally-block n)))
2680 (insert pad "try {\n")
2681 (js2-print-body (js2-try-node-try-block n) (1+ i))
2684 (dolist (catch catches)
2685 (js2-print-ast catch i)))
2687 (js2-print-ast finally i)
2690 (defstruct (js2-catch-node
2693 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2702 "AST node for a catch clause."
2703 param ; destructuring form or simple name node
2704 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2705 guard-expr ; catch condition, a `js2-node'
2706 block ; statements, a `js2-block-node'
2707 lp ; buffer position of left-paren, nil if omitted
2708 rp) ; buffer position of right-paren, nil if omitted
2710 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2711 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2713 (defun js2-visit-catch-node (n v)
2714 (js2-visit-ast (js2-catch-node-param n) v)
2715 (when (js2-catch-node-guard-kwd n)
2716 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2717 (js2-visit-ast (js2-catch-node-block n) v))
2719 (defun js2-print-catch-node (n i)
2720 (let ((pad (js2-make-pad i))
2721 (guard-kwd (js2-catch-node-guard-kwd n))
2722 (guard-expr (js2-catch-node-guard-expr n)))
2724 (js2-print-ast (js2-catch-node-param n) 0)
2727 (js2-print-ast guard-expr 0))
2729 (js2-print-body (js2-catch-node-block n) (1+ i))
2732 (defstruct (js2-finally-node
2735 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2739 "AST node for a finally clause."
2740 body) ; a `js2-node', often but not always a block node
2742 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2743 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2745 (defun js2-visit-finally-node (n v)
2746 (js2-visit-ast (js2-finally-node-body n) v))
2748 (defun js2-print-finally-node (n i)
2749 (let ((pad (js2-make-pad i)))
2750 (insert " finally {\n")
2751 (js2-print-body (js2-finally-node-body n) (1+ i))
2752 (insert pad "}\n")))
2754 (defstruct (js2-switch-node
2757 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2764 "AST node for a switch statement."
2765 discriminant ; a `js2-node' (switch expression)
2766 cases ; a lisp list of `js2-case-node'
2767 lp ; position of open-paren for discriminant, nil if omitted
2768 rp) ; position of close-paren for discriminant, nil if omitted
2770 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2771 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2773 (defun js2-visit-switch-node (n v)
2774 (js2-visit-ast (js2-switch-node-discriminant n) v)
2775 (dolist (c (js2-switch-node-cases n))
2776 (js2-visit-ast c v)))
2778 (defun js2-print-switch-node (n i)
2779 (let ((pad (js2-make-pad i))
2780 (cases (js2-switch-node-cases n)))
2781 (insert pad "switch (")
2782 (js2-print-ast (js2-switch-node-discriminant n) 0)
2784 (dolist (case cases)
2785 (js2-print-ast case i))
2786 (insert pad "}\n")))
2788 (defstruct (js2-case-node
2789 (:include js2-block-node)
2791 (:constructor make-js2-case-node (&key (type js2-CASE)
2796 "AST node for a case clause of a switch statement."
2797 expr) ; the case expression (nil for default)
2799 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2800 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2802 (defun js2-visit-case-node (n v)
2803 (js2-visit-ast (js2-case-node-expr n) v)
2804 (js2-visit-block n v))
2806 (defun js2-print-case-node (n i)
2807 (let ((pad (js2-make-pad i))
2808 (expr (js2-case-node-expr n)))
2811 (insert "default:\n")
2813 (js2-print-ast expr 0)
2815 (dolist (kid (js2-case-node-kids n))
2816 (js2-print-ast kid (1+ i)))))
2818 (defstruct (js2-throw-node
2821 (:constructor make-js2-throw-node (&key (type js2-THROW)
2825 "AST node for a throw statement."
2826 expr) ; the expression to throw
2828 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2829 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2831 (defun js2-visit-throw-node (n v)
2832 (js2-visit-ast (js2-throw-node-expr n) v))
2834 (defun js2-print-throw-node (n i)
2835 (insert (js2-make-pad i) "throw ")
2836 (js2-print-ast (js2-throw-node-expr n) 0)
2839 (defstruct (js2-with-node
2842 (:constructor make-js2-with-node (&key (type js2-WITH)
2849 "AST node for a with-statement."
2852 lp ; buffer position of left-paren around object, nil if omitted
2853 rp) ; buffer position of right-paren around object, nil if omitted
2855 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2856 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2858 (defun js2-visit-with-node (n v)
2859 (js2-visit-ast (js2-with-node-object n) v)
2860 (js2-visit-ast (js2-with-node-body n) v))
2862 (defun js2-print-with-node (n i)
2863 (let ((pad (js2-make-pad i)))
2864 (insert pad "with (")
2865 (js2-print-ast (js2-with-node-object n) 0)
2867 (js2-print-body (js2-with-node-body n) (1+ i))
2868 (insert pad "}\n")))
2870 (defstruct (js2-label-node
2873 (:constructor make-js2-label-node (&key (type js2-LABEL)
2877 "AST node for a statement label or case label."
2879 loop) ; for validating and code-generating continue-to-label
2881 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2882 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2884 (defun js2-print-label (n i)
2885 (insert (js2-make-pad i)
2886 (js2-label-node-name n)
2889 (defstruct (js2-labeled-stmt-node
2892 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2893 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2894 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2899 "AST node for a statement with one or more labels.
2900 Multiple labels for a statement are collapsed into the labels field."
2901 labels ; lisp list of `js2-label-node'
2902 stmt) ; the statement these labels are for
2904 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2905 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2907 (defun js2-get-label-by-name (lbl-stmt name)
2908 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2909 Returns nil if no such label is in the list."
2910 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2912 (while (and label-list (not result))
2913 (if (string= (js2-label-node-name (car label-list)) name)
2914 (setq result (car label-list))
2915 (setq label-list (cdr label-list))))
2918 (defun js2-visit-labeled-stmt (n v)
2919 (dolist (label (js2-labeled-stmt-node-labels n))
2920 (js2-visit-ast label v))
2921 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2923 (defun js2-print-labeled-stmt (n i)
2924 (dolist (label (js2-labeled-stmt-node-labels n))
2925 (js2-print-ast label i))
2926 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2928 (defun js2-labeled-stmt-node-contains (node label)
2929 "Return t if NODE contains LABEL in its label set.
2930 NODE is a `js2-labels-node'. LABEL is an identifier."
2931 (loop for nl in (js2-labeled-stmt-node-labels node)
2932 if (string= label (js2-label-node-name nl))
2934 finally return nil))
2936 (defsubst js2-labeled-stmt-node-add-label (node label)
2937 "Add a `js2-label-node' to the label set for this statement."
2938 (setf (js2-labeled-stmt-node-labels node)
2939 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2941 (defstruct (js2-jump-node
2944 "Abstract supertype of break and continue nodes."
2945 label ; `js2-name-node' for location of label identifier, if present
2946 target) ; target js2-labels-node or loop/switch statement
2948 (defun js2-visit-jump-node (n v)
2949 (js2-visit-ast (js2-jump-node-label n) v))
2951 (defstruct (js2-break-node
2952 (:include js2-jump-node)
2954 (:constructor make-js2-break-node (&key (type js2-BREAK)
2959 "AST node for a break statement.
2960 The label field is a `js2-name-node', possibly nil, for the named label
2961 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2962 is the target of the break - a label node or enclosing loop/switch statement.")
2964 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2965 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2967 (defun js2-print-break-node (n i)
2968 (insert (js2-make-pad i) "break")
2969 (when (js2-break-node-label n)
2971 (js2-print-ast (js2-break-node-label n) 0))
2974 (defstruct (js2-continue-node
2975 (:include js2-jump-node)
2977 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2982 "AST node for a continue statement.
2983 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2984 It is nil if continue specifies no label. The target field is the jump target:
2985 a `js2-label-node' or the innermost enclosing loop.")
2987 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2988 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2990 (defun js2-print-continue-node (n i)
2991 (insert (js2-make-pad i) "continue")
2992 (when (js2-continue-node-label n)
2994 (js2-print-ast (js2-continue-node-label n) 0))
2997 (defstruct (js2-function-node
2998 (:include js2-script-node)
3000 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3004 (form 'FUNCTION_STATEMENT)
3010 "AST node for a function declaration.
3011 The `params' field is a lisp list of nodes. Each node is either a simple
3012 `js2-name-node', or if it's a destructuring-assignment parameter, a
3013 `js2-array-node' or `js2-object-node'."
3014 ftype ; FUNCTION, GETTER or SETTER
3015 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3016 name ; function name (a `js2-name-node', or nil if anonymous)
3017 params ; a lisp list of destructuring forms or simple name nodes
3018 body ; a `js2-block-node' or expression node (1.8 only)
3019 lp ; position of arg-list open-paren, or nil if omitted
3020 rp ; position of arg-list close-paren, or nil if omitted
3021 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3022 needs-activation ; t if we need an activation object for this frame
3023 is-generator ; t if this function contains a yield
3024 member-expr) ; nonstandard Ecma extension from Rhino
3026 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3027 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3029 (defun js2-visit-function-node (n v)
3030 (js2-visit-ast (js2-function-node-name n) v)
3031 (dolist (p (js2-function-node-params n))
3032 (js2-visit-ast p v))
3033 (js2-visit-ast (js2-function-node-body n) v))
3035 (defun js2-print-function-node (n i)
3036 (let ((pad (js2-make-pad i))
3037 (getter (js2-node-get-prop n 'GETTER_SETTER))
3038 (name (js2-function-node-name n))
3039 (params (js2-function-node-params n))
3040 (body (js2-function-node-body n))
3041 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3043 (insert pad "function"))
3046 (js2-print-ast name 0))
3048 (loop with len = (length params)
3052 (js2-print-ast param 0)
3058 ;; TODO: fix this to be smarter about indenting, etc.
3059 (js2-print-body body (1+ i))
3064 (defsubst js2-function-name (node)
3065 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3066 (and (js2-function-node-name node)
3067 (js2-name-node-name (js2-function-node-name node))))
3069 ;; Having this be an expression node makes it more flexible.
3070 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3071 ;; that work better if you assume it's an expression. Whenever we have
3072 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3073 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3074 (defstruct (js2-var-decl-node
3077 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3082 "AST node for a variable declaration list (VAR, CONST or LET).
3083 The node bounds differ depending on the declaration type. For VAR or
3084 CONST declarations, the bounds include the var/const keyword. For LET
3085 declarations, the node begins at the position of the first child."
3086 kids ; a lisp list of `js2-var-init-node' structs.
3087 decl-type) ; js2-VAR, js2-CONST or js2-LET
3089 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3090 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3092 (defun js2-visit-var-decl (n v)
3093 (dolist (kid (js2-var-decl-node-kids n))
3094 (js2-visit-ast kid v)))
3096 (defun js2-print-var-decl (n i)
3097 (let ((pad (js2-make-pad i))
3098 (tt (js2-var-decl-node-decl-type n)))
3101 ((= tt js2-VAR) "var ")
3102 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3103 ((= tt js2-CONST) "const ")
3105 (error "malformed var-decl node"))))
3106 (loop with kids = (js2-var-decl-node-kids n)
3107 with len = (length kids)
3111 (js2-print-ast kid 0)
3115 (defstruct (js2-var-init-node
3118 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3123 "AST node for a variable declaration.
3124 The type field will be js2-CONST for a const decl."
3125 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3126 initializer) ; initializer expression, a `js2-node'
3128 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3129 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3131 (defun js2-visit-var-init-node (n v)
3132 (js2-visit-ast (js2-var-init-node-target n) v)
3133 (js2-visit-ast (js2-var-init-node-initializer n) v))
3135 (defun js2-print-var-init-node (n i)
3136 (let ((pad (js2-make-pad i))
3137 (name (js2-var-init-node-target n))
3138 (init (js2-var-init-node-initializer n)))
3140 (js2-print-ast name 0)
3143 (js2-print-ast init 0))))
3145 (defstruct (js2-cond-node
3148 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3156 "AST node for the ternary operator"
3160 q-pos ; buffer position of ?
3161 c-pos) ; buffer position of :
3163 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3164 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3166 (defun js2-visit-cond-node (n v)
3167 (js2-visit-ast (js2-cond-node-test-expr n) v)
3168 (js2-visit-ast (js2-cond-node-true-expr n) v)
3169 (js2-visit-ast (js2-cond-node-false-expr n) v))
3171 (defun js2-print-cond-node (n i)
3172 (let ((pad (js2-make-pad i)))
3174 (js2-print-ast (js2-cond-node-test-expr n) 0)
3176 (js2-print-ast (js2-cond-node-true-expr n) 0)
3178 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3180 (defstruct (js2-infix-node
3183 (:constructor make-js2-infix-node (&key type
3189 "Represents infix expressions.
3190 Includes assignment ops like `|=', and the comma operator.
3191 The type field inherited from `js2-node' holds the operator."
3192 op-pos ; buffer position where operator begins
3193 left ; any `js2-node'
3194 right) ; any `js2-node'
3196 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3197 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3199 (defun js2-visit-infix-node (n v)
3200 (js2-visit-ast (js2-infix-node-left n) v)
3201 (js2-visit-ast (js2-infix-node-right n) v))
3203 (defconst js2-operator-tokens
3204 (let ((table (make-hash-table :test 'eq))
3206 (list (cons js2-IN "in")
3207 (cons js2-TYPEOF "typeof")
3208 (cons js2-INSTANCEOF "instanceof")
3209 (cons js2-DELPROP "delete")
3210 (cons js2-COMMA ",")
3211 (cons js2-COLON ":")
3216 (cons js2-BITOR "|")
3217 (cons js2-BITXOR "^")
3218 (cons js2-BITAND "&")
3227 (cons js2-URSH ">>>")
3228 (cons js2-ADD "+") ; infix plus
3229 (cons js2-SUB "-") ; infix minus
3234 (cons js2-BITNOT "~")
3235 (cons js2-POS "+") ; unary plus
3236 (cons js2-NEG "-") ; unary minus
3237 (cons js2-SHEQ "===") ; shallow equality
3238 (cons js2-SHNE "!==") ; shallow inequality
3239 (cons js2-ASSIGN "=")
3240 (cons js2-ASSIGN_BITOR "|=")
3241 (cons js2-ASSIGN_BITXOR "^=")
3242 (cons js2-ASSIGN_BITAND "&=")
3243 (cons js2-ASSIGN_LSH "<<=")
3244 (cons js2-ASSIGN_RSH ">>=")
3245 (cons js2-ASSIGN_URSH ">>>=")
3246 (cons js2-ASSIGN_ADD "+=")
3247 (cons js2-ASSIGN_SUB "-=")
3248 (cons js2-ASSIGN_MUL "*=")
3249 (cons js2-ASSIGN_DIV "/=")
3250 (cons js2-ASSIGN_MOD "%="))))
3251 (loop for (k . v) in tokens do
3252 (puthash k v table))
3255 (defun js2-print-infix-node (n i)
3256 (let* ((tt (js2-node-type n))
3257 (op (gethash tt js2-operator-tokens)))
3259 (error "unrecognized infix operator %s" (js2-node-type n)))
3260 (insert (js2-make-pad i))
3261 (js2-print-ast (js2-infix-node-left n) 0)
3262 (unless (= tt js2-COMMA)
3266 (js2-print-ast (js2-infix-node-right n) 0)))
3268 (defstruct (js2-assign-node
3269 (:include js2-infix-node)
3271 (:constructor make-js2-assign-node (&key type
3277 "Represents any assignment.
3278 The type field holds the actual assignment operator.")
3280 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3281 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3283 (defstruct (js2-unary-node
3286 (:constructor make-js2-unary-node (&key type ; required
3290 "AST node type for unary operator nodes.
3291 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3292 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3293 property is added if the operator follows the operand."
3294 operand) ; a `js2-node' expression
3296 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3297 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3299 (defun js2-visit-unary-node (n v)
3300 (js2-visit-ast (js2-unary-node-operand n) v))
3302 (defun js2-print-unary-node (n i)
3303 (let* ((tt (js2-node-type n))
3304 (op (gethash tt js2-operator-tokens))
3305 (postfix (js2-node-get-prop n 'postfix)))
3307 (error "unrecognized unary operator %s" tt))
3308 (insert (js2-make-pad i))
3311 (if (or (= tt js2-TYPEOF)
3314 (js2-print-ast (js2-unary-node-operand n) 0)
3318 (defstruct (js2-let-node
3319 (:include js2-scope)
3321 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3328 "AST node for a let expression or a let statement.
3329 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3330 vars ; a `js2-var-decl-node'
3331 body ; a `js2-node' representing the expression or body block
3335 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3336 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3338 (defun js2-visit-let-node (n v)
3339 (js2-visit-ast (js2-let-node-vars n) v)
3340 (js2-visit-ast (js2-let-node-body n) v))
3342 (defun js2-print-let-node (n i)
3343 (insert (js2-make-pad i) "let (")
3344 (js2-print-ast (js2-let-node-vars n) 0)
3346 (js2-print-ast (js2-let-node-body n) i))
3348 (defstruct (js2-keyword-node
3351 (:constructor make-js2-keyword-node (&key type
3353 (len (- js2-ts-cursor pos)))))
3354 "AST node representing a literal keyword such as `null'.
3355 Used for `null', `this', `true', `false' and `debugger'.
3356 The node type is set to js2-NULL, js2-THIS, etc.")
3358 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3359 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3361 (defun js2-print-keyword-node (n i)
3362 (insert (js2-make-pad i)
3363 (let ((tt (js2-node-type n)))
3365 ((= tt js2-THIS) "this")
3366 ((= tt js2-NULL) "null")
3367 ((= tt js2-TRUE) "true")
3368 ((= tt js2-FALSE) "false")
3369 ((= tt js2-DEBUGGER) "debugger")
3370 (t (error "Invalid keyword literal type: %d" tt))))))
3372 (defsubst js2-this-node-p (node)
3373 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3374 (eq (js2-node-type node) js2-THIS))
3376 (defstruct (js2-new-node
3379 (:constructor make-js2-new-node (&key (type js2-NEW)
3387 "AST node for new-expression such as new Foo()."
3388 target ; an identifier or reference
3389 args ; a lisp list of argument nodes
3390 lp ; position of left-paren, nil if omitted
3391 rp ; position of right-paren, nil if omitted
3392 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3394 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3395 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3397 (defun js2-visit-new-node (n v)
3398 (js2-visit-ast (js2-new-node-target n) v)
3399 (dolist (arg (js2-new-node-args n))
3400 (js2-visit-ast arg v))
3401 (js2-visit-ast (js2-new-node-initializer n) v))
3403 (defun js2-print-new-node (n i)
3404 (insert (js2-make-pad i) "new ")
3405 (js2-print-ast (js2-new-node-target n))
3407 (js2-print-list (js2-new-node-args n))
3409 (when (js2-new-node-initializer n)
3411 (js2-print-ast (js2-new-node-initializer n))))
3413 (defstruct (js2-name-node
3416 (:constructor make-js2-name-node (&key (type js2-NAME)
3418 (len (- js2-ts-cursor
3420 (name js2-ts-string))))
3421 "AST node for a JavaScript identifier"
3423 scope) ; a `js2-scope' (optional, used for codegen)
3425 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3426 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3428 (defun js2-print-name-node (n i)
3429 (insert (js2-make-pad i)
3430 (js2-name-node-name n)))
3432 (defsubst js2-name-node-length (node)
3433 "Return identifier length of NODE, a `js2-name-node'.
3434 Returns 0 if NODE is nil or its identifier field is nil."
3436 (length (js2-name-node-name node))
3439 (defstruct (js2-number-node
3442 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3444 (len (- js2-ts-cursor
3446 (value js2-ts-string)
3447 (num-value js2-ts-number))))
3448 "AST node for a number literal."
3449 value ; the original string, e.g. "6.02e23"
3450 num-value) ; the parsed number value
3452 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3453 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3455 (defun js2-print-number-node (n i)
3456 (insert (js2-make-pad i)
3457 (number-to-string (js2-number-node-num-value n))))
3459 (defstruct (js2-regexp-node
3462 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3464 (len (- js2-ts-cursor
3468 "AST node for a regular expression literal."
3469 value ; the regexp string, without // delimiters
3470 flags) ; a string of flags, e.g. `mi'.
3472 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3473 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3475 (defun js2-print-regexp (n i)
3476 (insert (js2-make-pad i)
3478 (js2-regexp-node-value n)
3480 (if (js2-regexp-node-flags n)
3481 (insert (js2-regexp-node-flags n))))
3483 (defstruct (js2-string-node
3486 (:constructor make-js2-string-node (&key (type js2-STRING)
3488 (len (- js2-ts-cursor
3490 (value js2-ts-string))))
3492 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3493 You can tell the quote type by looking at the first character."
3494 value) ; the characters of the string, including the quotes
3496 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3497 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3499 (defun js2-print-string-node (n i)
3500 (insert (js2-make-pad i)
3501 (js2-node-string n)))
3503 (defstruct (js2-array-node
3506 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3510 "AST node for an array literal."
3511 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3513 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3514 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3516 (defun js2-visit-array-node (n v)
3517 (dolist (e (js2-array-node-elems n))
3518 (js2-visit-ast e v)))
3520 (defun js2-print-array-node (n i)
3521 (insert (js2-make-pad i) "[")
3522 (js2-print-list (js2-array-node-elems n))
3525 (defstruct (js2-object-node
3528 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3532 "AST node for an object literal expression.
3533 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3534 the latter represents abbreviation in destructuring expressions."
3537 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3538 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3540 (defun js2-visit-object-node (n v)
3541 (dolist (e (js2-object-node-elems n))
3542 (js2-visit-ast e v)))
3544 (defun js2-print-object-node (n i)
3545 (insert (js2-make-pad i) "{")
3546 (js2-print-list (js2-object-node-elems n))
3549 (defstruct (js2-object-prop-node
3550 (:include js2-infix-node)
3552 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3558 "AST node for an object literal prop:value entry.
3559 The `left' field is the property: a name node, string node or number node.
3560 The `right' field is a `js2-node' representing the initializer value.")
3562 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3563 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3565 (defun js2-print-object-prop-node (n i)
3566 (insert (js2-make-pad i))
3567 (js2-print-ast (js2-object-prop-node-left n) 0)
3569 (js2-print-ast (js2-object-prop-node-right n) 0))
3571 (defstruct (js2-getter-setter-node
3572 (:include js2-infix-node)
3574 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3579 "AST node for a getter/setter property in an object literal.
3580 The `left' field is the `js2-name-node' naming the getter/setter prop.
3581 The `right' field is always an anonymous `js2-function-node' with a node
3582 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3584 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3585 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3587 (defun js2-print-getter-setter (n i)
3588 (let ((pad (js2-make-pad i))
3589 (left (js2-getter-setter-node-left n))
3590 (right (js2-getter-setter-node-right n)))
3592 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3593 (js2-print-ast left 0)
3594 (js2-print-ast right 0)))
3596 (defstruct (js2-prop-get-node
3597 (:include js2-infix-node)
3599 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3604 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3606 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3607 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3609 (defun js2-visit-prop-get-node (n v)
3610 (js2-visit-ast (js2-prop-get-node-left n) v)
3611 (js2-visit-ast (js2-prop-get-node-right n) v))
3613 (defun js2-print-prop-get-node (n i)
3614 (insert (js2-make-pad i))
3615 (js2-print-ast (js2-prop-get-node-left n) 0)
3617 (js2-print-ast (js2-prop-get-node-right n) 0))
3619 (defstruct (js2-elem-get-node
3622 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3629 "AST node for an array index expression such as foo[bar]."
3630 target ; a `js2-node' - the expression preceding the "."
3631 element ; a `js2-node' - the expression in brackets
3632 lb ; position of left-bracket, nil if omitted
3633 rb) ; position of right-bracket, nil if omitted
3635 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3636 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3638 (defun js2-visit-elem-get-node (n v)
3639 (js2-visit-ast (js2-elem-get-node-target n) v)
3640 (js2-visit-ast (js2-elem-get-node-element n) v))
3642 (defun js2-print-elem-get-node (n i)
3643 (insert (js2-make-pad i))
3644 (js2-print-ast (js2-elem-get-node-target n) 0)
3646 (js2-print-ast (js2-elem-get-node-element n) 0)
3649 (defstruct (js2-call-node
3652 (:constructor make-js2-call-node (&key (type js2-CALL)
3659 "AST node for a JavaScript function call."
3660 target ; a `js2-node' evaluating to the function to call
3661 args ; a lisp list of `js2-node' arguments
3662 lp ; position of open-paren, or nil if missing
3663 rp) ; position of close-paren, or nil if missing
3665 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3666 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3668 (defun js2-visit-call-node (n v)
3669 (js2-visit-ast (js2-call-node-target n) v)
3670 (dolist (arg (js2-call-node-args n))
3671 (js2-visit-ast arg v)))
3673 (defun js2-print-call-node (n i)
3674 (insert (js2-make-pad i))
3675 (js2-print-ast (js2-call-node-target n) 0)
3677 (js2-print-list (js2-call-node-args n))
3680 (defstruct (js2-yield-node
3683 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3687 "AST node for yield statement or expression."
3688 value) ; optional: value to be yielded
3690 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3691 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3693 (defun js2-visit-yield-node (n v)
3694 (js2-visit-ast (js2-yield-node-value n) v))
3696 (defun js2-print-yield-node (n i)
3697 (insert (js2-make-pad i))
3699 (when (js2-yield-node-value n)
3701 (js2-print-ast (js2-yield-node-value n) 0)))
3703 (defstruct (js2-paren-node
3706 (:constructor make-js2-paren-node (&key (type js2-LP)
3710 "AST node for a parenthesized expression.
3711 In particular, used when the parens are syntactically optional,
3712 as opposed to required parens such as those enclosing an if-conditional."
3715 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3716 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3718 (defun js2-visit-paren-node (n v)
3719 (js2-visit-ast (js2-paren-node-expr n) v))
3721 (defun js2-print-paren-node (n i)
3722 (insert (js2-make-pad i))
3724 (js2-print-ast (js2-paren-node-expr n) 0)
3727 (defstruct (js2-array-comp-node
3728 (:include js2-scope)
3730 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3739 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3740 result ; result expression (just after left-bracket)
3741 loops ; a lisp list of `js2-array-comp-loop-node'
3742 filter ; guard/filter expression
3743 if-pos ; buffer pos of 'if' keyword, if present, else nil
3744 lp ; buffer position of if-guard left-paren, or nil if not present
3745 rp) ; buffer position of if-guard right-paren, or nil if not present
3747 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3748 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3750 (defun js2-visit-array-comp-node (n v)
3751 (js2-visit-ast (js2-array-comp-node-result n) v)
3752 (dolist (l (js2-array-comp-node-loops n))
3753 (js2-visit-ast l v))
3754 (js2-visit-ast (js2-array-comp-node-filter n) v))
3756 (defun js2-print-array-comp-node (n i)
3757 (let ((pad (js2-make-pad i))
3758 (result (js2-array-comp-node-result n))
3759 (loops (js2-array-comp-node-loops n))
3760 (filter (js2-array-comp-node-filter n)))
3762 (js2-print-ast result 0)
3765 (js2-print-ast l 0))
3768 (js2-print-ast filter 0))
3771 (defstruct (js2-array-comp-loop-node
3772 (:include js2-for-in-node)
3774 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3784 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3786 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3787 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3789 (defun js2-visit-array-comp-loop (n v)
3790 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3791 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3793 (defun js2-print-array-comp-loop (n i)
3795 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3797 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3800 (defstruct (js2-empty-expr-node
3803 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3806 "AST node for an empty expression.")
3808 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3809 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3811 (defstruct (js2-xml-node
3812 (:include js2-block-node)
3814 (:constructor make-js2-xml-node (&key (type js2-XML)
3818 "AST node for initial parse of E4X literals.
3819 The kids field is a list of XML fragments, each a `js2-string-node' or
3820 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3822 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3823 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3825 (defun js2-print-xml-node (n i)
3826 (dolist (kid (js2-xml-node-kids n))
3827 (js2-print-ast kid i)))
3829 (defstruct (js2-xml-js-expr-node
3830 (:include js2-xml-node)
3832 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3836 "AST node for an embedded JavaScript {expression} in an E4X literal.
3837 The start and end fields correspond to the curly-braces."
3838 expr) ; a `js2-expr-node' of some sort
3840 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3841 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3843 (defun js2-visit-xml-js-expr (n v)
3844 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3846 (defun js2-print-xml-js-expr (n i)
3847 (insert (js2-make-pad i))
3849 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3852 (defstruct (js2-xml-dot-query-node
3853 (:include js2-infix-node)
3855 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3862 "AST node for an E4X foo.(bar) filter expression.
3863 Note that the left-paren is automatically the character immediately
3864 following the dot (.) in the operator. No whitespace is permitted
3865 between the dot and the lp by the scanner."
3868 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3869 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3871 (defun js2-print-xml-dot-query (n i)
3872 (insert (js2-make-pad i))
3873 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3875 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3878 (defstruct (js2-xml-ref-node
3880 (:constructor nil)) ; abstract
3881 "Base type for E4X XML attribute-access or property-get expressions.
3882 Such expressions can take a variety of forms. The general syntax has
3885 - (optional) an @ (specifying an attribute access)
3886 - (optional) a namespace (a `js2-name-node') and double-colon
3887 - (required) either a `js2-name-node' or a bracketed [expression]
3889 The property-name expressions (examples: ns::name, @name) are
3890 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3891 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3893 This node type (or more specifically, its subclasses) will sometimes
3894 be the right-hand child of a `js2-prop-get-node' or a
3895 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3896 The `js2-xml-ref-node' may also be a standalone primary expression with
3897 no explicit target, which is valid in certain expression contexts such as
3899 company..employee.(@id < 100)
3901 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3902 expression whose parent is a `js2-xml-dot-query-node'."
3907 (defsubst js2-xml-ref-node-attr-access-p (node)
3908 "Return non-nil if this expression began with an @-token."
3909 (and (numberp (js2-xml-ref-node-at-pos node))
3910 (plusp (js2-xml-ref-node-at-pos node))))
3912 (defstruct (js2-xml-prop-ref-node
3913 (:include js2-xml-ref-node)
3915 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3922 "AST node for an E4X XML [expr] property-ref expression.
3923 The JavaScript syntax is an optional @, an optional ns::, and a name.
3925 [ '@' ] [ name '::' ] name
3927 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3928 @ns::*, @*::attr, @*::*, and @*.
3930 The node starts at the @ token, if present. Otherwise it starts at the
3931 namespace name. The node bounds extend through the closing right-bracket,
3932 or if it is missing due to a syntax error, through the end of the index
3936 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3937 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3939 (defun js2-visit-xml-prop-ref-node (n v)
3940 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3941 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3943 (defun js2-print-xml-prop-ref-node (n i)
3944 (insert (js2-make-pad i))
3945 (if (js2-xml-ref-node-attr-access-p n)
3947 (when (js2-xml-prop-ref-node-namespace n)
3948 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3950 (if (js2-xml-prop-ref-node-propname n)
3951 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3953 (defstruct (js2-xml-elem-ref-node
3954 (:include js2-xml-ref-node)
3956 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3965 "AST node for an E4X XML [expr] member-ref expression.
3968 [ '@' ] [ name '::' ] '[' expr ']'
3970 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3972 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3973 is not a legal E4X XML element-ref expression, since it's already used
3974 for standard JavaScript element-get array indexing. Hence, a
3975 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3976 non-nil namespace node, or both.
3978 The node starts at the @ token, if present. Otherwise it starts
3979 at the namespace name. The node bounds extend through the closing
3980 right-bracket, or if it is missing due to a syntax error, through the
3981 end of the index expression."
3982 expr ; the bracketed index expression
3986 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3987 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3989 (defun js2-visit-xml-elem-ref-node (n v)
3990 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3991 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3993 (defun js2-print-xml-elem-ref-node (n i)
3994 (insert (js2-make-pad i))
3995 (if (js2-xml-ref-node-attr-access-p n)
3997 (when (js2-xml-elem-ref-node-namespace n)
3998 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4001 (if (js2-xml-elem-ref-node-expr n)
4002 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4005 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4007 (defstruct (js2-xml-start-tag-node
4008 (:include js2-xml-node)
4010 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4017 "AST node for an XML start-tag. Not currently used.
4018 The `kids' field is a lisp list of child content nodes."
4019 name ; a `js2-xml-name-node'
4020 attrs ; a lisp list of `js2-xml-attr-node'
4021 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4023 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4024 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4026 (defun js2-visit-xml-start-tag (n v)
4027 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4028 (dolist (attr (js2-xml-start-tag-node-attrs n))
4029 (js2-visit-ast attr v))
4030 (js2-visit-block n v))
4032 (defun js2-print-xml-start-tag (n i)
4033 (insert (js2-make-pad i) "<")
4034 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4035 (when (js2-xml-start-tag-node-attrs n)
4037 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4040 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4041 ;; and add the end-tag to the kids list of the parent as well.
4042 (defstruct (js2-xml-end-tag-node
4043 (:include js2-xml-node)
4045 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4049 "AST node for an XML end-tag. Not currently used."
4050 name) ; a `js2-xml-name-node'
4052 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4053 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4055 (defun js2-visit-xml-end-tag (n v)
4056 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4058 (defun js2-print-xml-end-tag (n i)
4059 (insert (js2-make-pad i))
4061 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4064 (defstruct (js2-xml-name-node
4065 (:include js2-xml-node)
4067 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4072 "AST node for an E4X XML name. Not currently used.
4073 Any XML name can be qualified with a namespace, hence the namespace field.
4074 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4075 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4076 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4077 namespace) ; a `js2-string-node'
4079 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4080 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4082 (defun js2-visit-xml-name-node (n v)
4083 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4085 (defun js2-print-xml-name-node (n i)
4086 (insert (js2-make-pad i))
4087 (when (js2-xml-name-node-namespace n)
4088 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4090 (dolist (kid (js2-xml-name-node-kids n))
4091 (js2-print-ast kid 0)))
4093 (defstruct (js2-xml-pi-node
4094 (:include js2-xml-node)
4096 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4101 "AST node for an E4X XML processing instruction. Not currently used."
4102 name ; a `js2-xml-name-node'
4103 attrs) ; a list of `js2-xml-attr-node'
4105 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4106 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4108 (defun js2-visit-xml-pi-node (n v)
4109 (js2-visit-ast (js2-xml-pi-node-name n) v)
4110 (dolist (attr (js2-xml-pi-node-attrs n))
4111 (js2-visit-ast attr v)))
4113 (defun js2-print-xml-pi-node (n i)
4114 (insert (js2-make-pad i) "<?")
4115 (js2-print-ast (js2-xml-pi-node-name n))
4116 (when (js2-xml-pi-node-attrs n)
4118 (js2-print-list (js2-xml-pi-node-attrs n)))
4121 (defstruct (js2-xml-cdata-node
4122 (:include js2-xml-node)
4124 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4128 "AST node for a CDATA escape section. Not currently used."
4129 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4131 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4132 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4134 (defun js2-visit-xml-cdata-node (n v)
4135 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4137 (defun js2-print-xml-cdata-node (n i)
4138 (insert (js2-make-pad i))
4139 (js2-print-ast (js2-xml-cdata-node-content n)))
4141 (defstruct (js2-xml-attr-node
4142 (:include js2-xml-node)
4144 (:constructor make-js2-attr-node (&key (type js2-XML)
4151 "AST node representing a foo='bar' XML attribute value. Not yet used."
4152 name ; a `js2-xml-name-node'
4153 value ; a `js2-xml-name-node'
4154 eq-pos ; buffer position of "=" sign
4155 quote-type) ; 'single or 'double
4157 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4158 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4160 (defun js2-visit-xml-attr-node (n v)
4161 (js2-visit-ast (js2-xml-attr-node-name n) v)
4162 (js2-visit-ast (js2-xml-attr-node-value n) v))
4164 (defun js2-print-xml-attr-node (n i)
4165 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4168 (insert (js2-make-pad i))
4169 (js2-print-ast (js2-xml-attr-node-name n) 0)
4171 (js2-print-ast (js2-xml-attr-node-value n) 0)
4174 (defstruct (js2-xml-text-node
4175 (:include js2-xml-node)
4177 (:constructor make-js2-text-node (&key (type js2-XML)
4181 "AST node for an E4X XML text node. Not currently used."
4182 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4184 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4185 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4187 (defun js2-visit-xml-text-node (n v)
4188 (js2-visit-ast (js2-xml-text-node-content n) v))
4190 (defun js2-print-xml-text-node (n i)
4191 (insert (js2-make-pad i))
4192 (dolist (kid (js2-xml-text-node-content n))
4193 (js2-print-ast kid)))
4195 (defstruct (js2-xml-comment-node
4196 (:include js2-xml-node)
4198 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4201 "AST node for E4X XML comment. Not currently used.")
4203 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4204 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4206 (defun js2-print-xml-comment (n i)
4207 (insert (js2-make-pad i)
4208 (js2-node-string n)))
4212 (defsubst js2-node-line (n)
4213 "Fetch the source line number at the start of node N.
4214 This is O(n) in the length of the source buffer; use prudently."
4215 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4217 (defsubst js2-block-node-kid (n i)
4218 "Return child I of node N, or nil if there aren't that many."
4219 (nth i (js2-block-node-kids n)))
4221 (defsubst js2-block-node-first (n)
4222 "Return first child of block node N, or nil if there is none."
4223 (first (js2-block-node-kids n)))
4225 (defun js2-node-root (n)
4226 "Return the root of the AST containing N.
4227 If N has no parent pointer, returns N."
4228 (let ((parent (js2-node-parent n)))
4230 (js2-node-root parent)
4233 (defun js2-node-position-in-parent (node &optional parent)
4234 "Return the position of NODE in parent's block-kids list.
4235 PARENT can be supplied if known. Positioned returned is zero-indexed.
4236 Returns 0 if NODE is not a child of a block statement, or if NODE
4237 is not a statement node."
4238 (let ((p (or parent (js2-node-parent node)))
4240 (if (not (js2-block-node-p p))
4242 (or (js2-position node (js2-block-node-kids p))
4245 (defsubst js2-node-short-name (n)
4246 "Return the short name of node N as a string, e.g. `js2-if-node'."
4247 (substring (symbol-name (aref n 0))
4248 (length "cl-struct-")))
4250 (defsubst js2-node-child-list (node)
4251 "Return the child list for NODE, a lisp list of nodes.
4252 Works for block nodes, array nodes, obj literals, funarg lists,
4253 var decls and try nodes (for catch clauses). Note that you should call
4254 `js2-block-node-kids' on the function body for the body statements.
4255 Returns nil for zero-length child lists or unsupported nodes."
4257 ((js2-function-node-p node)
4258 (js2-function-node-params node))
4259 ((js2-block-node-p node)
4260 (js2-block-node-kids node))
4261 ((js2-try-node-p node)
4262 (js2-try-node-catch-clauses node))
4263 ((js2-array-node-p node)
4264 (js2-array-node-elems node))
4265 ((js2-object-node-p node)
4266 (js2-object-node-elems node))
4267 ((js2-call-node-p node)
4268 (js2-call-node-args node))
4269 ((js2-new-node-p node)
4270 (js2-new-node-args node))
4271 ((js2-var-decl-node-p node)
4272 (js2-var-decl-node-kids node))
4276 (defsubst js2-node-set-child-list (node kids)
4277 "Set the child list for NODE to KIDS."
4279 ((js2-function-node-p node)
4280 (setf (js2-function-node-params node) kids))
4281 ((js2-block-node-p node)
4282 (setf (js2-block-node-kids node) kids))
4283 ((js2-try-node-p node)
4284 (setf (js2-try-node-catch-clauses node) kids))
4285 ((js2-array-node-p node)
4286 (setf (js2-array-node-elems node) kids))
4287 ((js2-object-node-p node)
4288 (setf (js2-object-node-elems node) kids))
4289 ((js2-call-node-p node)
4290 (setf (js2-call-node-args node) kids))
4291 ((js2-new-node-p node)
4292 (setf (js2-new-node-args node) kids))
4293 ((js2-var-decl-node-p node)
4294 (setf (js2-var-decl-node-kids node) kids))
4296 (error "Unsupported node type: %s" (js2-node-short-name node))))
4299 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4300 (defconst js2-paren-expr-nodes
4301 '(cl-struct-js2-array-comp-loop-node
4302 cl-struct-js2-array-comp-node
4303 cl-struct-js2-call-node
4304 cl-struct-js2-catch-node
4305 cl-struct-js2-do-node
4306 cl-struct-js2-elem-get-node
4307 cl-struct-js2-for-in-node
4308 cl-struct-js2-for-node
4309 cl-struct-js2-function-node
4310 cl-struct-js2-if-node
4311 cl-struct-js2-let-node
4312 cl-struct-js2-new-node
4313 cl-struct-js2-paren-node
4314 cl-struct-js2-switch-node
4315 cl-struct-js2-while-node
4316 cl-struct-js2-with-node
4317 cl-struct-js2-xml-dot-query-node)
4318 "Node types that can have a parenthesized child expression.
4319 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4321 (defsubst js2-paren-expr-node-p (node)
4322 "Return t for nodes that typically have a parenthesized child expression.
4323 Useful for computing the indentation anchors for arg-lists and conditions.
4324 Note that it may return a false positive, for instance when NODE is
4325 a `js2-new-node' and there are no arguments or parentheses."
4326 (memq (aref node 0) js2-paren-expr-nodes))
4328 ;; Fake polymorphism... yech.
4329 (defsubst js2-node-lp (node)
4330 "Return relative left-paren position for NODE, if applicable.
4331 For `js2-elem-get-node' structs, returns left-bracket position.
4332 Note that the position may be nil in the case of a parse error."
4334 ((js2-elem-get-node-p node)
4335 (js2-elem-get-node-lb node))
4336 ((js2-loop-node-p node)
4337 (js2-loop-node-lp node))
4338 ((js2-function-node-p node)
4339 (js2-function-node-lp node))
4340 ((js2-if-node-p node)
4341 (js2-if-node-lp node))
4342 ((js2-new-node-p node)
4343 (js2-new-node-lp node))
4344 ((js2-call-node-p node)
4345 (js2-call-node-lp node))
4346 ((js2-paren-node-p node)
4347 (js2-node-pos node))
4348 ((js2-switch-node-p node)
4349 (js2-switch-node-lp node))
4350 ((js2-catch-node-p node)
4351 (js2-catch-node-lp node))
4352 ((js2-let-node-p node)
4353 (js2-let-node-lp node))
4354 ((js2-array-comp-node-p node)
4355 (js2-array-comp-node-lp node))
4356 ((js2-with-node-p node)
4357 (js2-with-node-lp node))
4358 ((js2-xml-dot-query-node-p node)
4359 (1+ (js2-infix-node-op-pos node)))
4361 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4363 ;; Fake polymorphism... blech.
4364 (defsubst js2-node-rp (node)
4365 "Return relative right-paren position for NODE, if applicable.
4366 For `js2-elem-get-node' structs, returns right-bracket position.
4367 Note that the position may be nil in the case of a parse error."
4369 ((js2-elem-get-node-p node)
4370 (js2-elem-get-node-lb node))
4371 ((js2-loop-node-p node)
4372 (js2-loop-node-rp node))
4373 ((js2-function-node-p node)
4374 (js2-function-node-rp node))
4375 ((js2-if-node-p node)
4376 (js2-if-node-rp node))
4377 ((js2-new-node-p node)
4378 (js2-new-node-rp node))
4379 ((js2-call-node-p node)
4380 (js2-call-node-rp node))
4381 ((js2-paren-node-p node)
4382 (+ (js2-node-pos node) (js2-node-len node)))
4383 ((js2-switch-node-p node)
4384 (js2-switch-node-rp node))
4385 ((js2-catch-node-p node)
4386 (js2-catch-node-rp node))
4387 ((js2-let-node-p node)
4388 (js2-let-node-rp node))
4389 ((js2-array-comp-node-p node)
4390 (js2-array-comp-node-rp node))
4391 ((js2-with-node-p node)
4392 (js2-with-node-rp node))
4393 ((js2-xml-dot-query-node-p node)
4394 (1+ (js2-xml-dot-query-node-rp node)))
4396 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4398 (defsubst js2-node-first-child (node)
4399 "Returns the first element of `js2-node-child-list' for NODE."
4400 (car (js2-node-child-list node)))
4402 (defsubst js2-node-last-child (node)
4403 "Returns the last element of `js2-node-last-child' for NODE."
4404 (car (last (js2-node-child-list node))))
4406 (defun js2-node-prev-sibling (node)
4407 "Return the previous statement in parent.
4408 Works for parents supported by `js2-node-child-list'.
4409 Returns nil if NODE is not in the parent, or PARENT is
4410 not a supported node, or if NODE is the first child."
4411 (let* ((p (js2-node-parent node))
4412 (kids (js2-node-child-list p))
4415 (not (eq node (cadr kids))))
4416 (setq kids (cdr kids)
4420 (defun js2-node-next-sibling (node)
4421 "Return the next statement in parent block.
4422 Returns nil if NODE is not in the block, or PARENT is not
4423 a block node, or if NODE is the last statement."
4424 (let* ((p (js2-node-parent node))
4425 (kids (js2-node-child-list p)))
4427 (not (eq node (car kids))))
4428 (setq kids (cdr kids)))
4431 (defun js2-node-find-child-before (pos parent &optional after)
4432 "Find the last child that starts before POS in parent.
4433 If AFTER is non-nil, returns first child starting after POS.
4434 POS is an absolute buffer position. PARENT is any node
4435 supported by `js2-node-child-list'.
4436 Returns nil if no applicable child is found."
4437 (let ((kids (if (js2-function-node-p parent)
4438 (js2-block-node-kids (js2-function-node-body parent))
4439 (js2-node-child-list parent)))
4440 (beg (if (js2-function-node-p parent)
4441 (js2-node-abs-pos (js2-function-node-body parent))
4442 (js2-node-abs-pos parent)))
4447 (setq fn (if after '> '<))
4448 (while (and kids continue)
4449 (setq kid (car kids))
4450 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4452 continue (if after nil t))
4453 (setq continue (if after t nil)))
4454 (setq kids (cdr kids)))
4457 (defun js2-node-find-child-after (pos parent)
4458 "Find first child that starts after POS in parent.
4459 POS is an absolute buffer position. PARENT is any node
4460 supported by `js2-node-child-list'.
4461 Returns nil if no applicable child is found."
4462 (js2-node-find-child-before pos parent 'after))
4464 (defun js2-node-replace-child (pos parent new-node)
4465 "Replace node at index POS in PARENT with NEW-NODE.
4466 Only works for parents supported by `js2-node-child-list'."
4467 (let ((kids (js2-node-child-list parent))
4470 (setq kids (cdr kids)
4472 (setcar kids new-node)
4473 (js2-node-add-children parent new-node)))
4475 (defun js2-node-buffer (n)
4476 "Return the buffer associated with AST N.
4477 Returns nil if the buffer is not set as a property on the root
4478 node, or if parent links were not recorded during parsing."
4479 (let ((root (js2-node-root n)))
4481 (js2-ast-root-p root)
4482 (js2-ast-root-buffer root))))
4484 (defsubst js2-block-node-push (n kid)
4485 "Push js2-node KID onto the end of js2-block-node N's child list.
4486 KID is always added to the -end- of the kids list.
4487 Function also calls `js2-node-add-children' to add the parent link."
4488 (let ((kids (js2-node-child-list n)))
4490 (setcdr kids (nconc (cdr kids) (list kid)))
4491 (js2-node-set-child-list n (list kid)))
4492 (js2-node-add-children n kid)))
4494 (defun js2-node-string (node)
4495 (let ((buf (js2-node-buffer node))
4498 (error "No buffer available for node %s" node))
4501 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4502 (+ pos (js2-node-len node))))))
4504 ;; Container for storing the node we're looking for in a traversal.
4505 (js2-deflocal js2-discovered-node nil)
4507 ;; Keep track of absolute node position during traversals.
4508 (js2-deflocal js2-visitor-offset nil)
4510 (js2-deflocal js2-node-search-point nil)
4512 (when js2-mode-dev-mode-p
4513 (defun js2-find-node-at-point ()
4515 (let ((node (js2-node-at-point)))
4516 (message "%s" (or node "No node found at point"))))
4517 (defun js2-node-name-at-point ()
4519 (let ((node (js2-node-at-point)))
4520 (message "%s" (if node
4521 (js2-node-short-name node)
4522 "No node found at point.")))))
4524 (defun js2-node-at-point (&optional pos skip-comments)
4525 "Return AST node at POS, a buffer position, defaulting to current point.
4526 The `js2-mode-ast' variable must be set to the current parse tree.
4527 Signals an error if the AST (`js2-mode-ast') is nil.
4528 Always returns a node - if it can't find one, it returns the root.
4529 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4530 (let ((ast js2-mode-ast)
4533 (error "No JavaScript AST available"))
4534 ;; Look through comments first, since they may be inside nodes that
4535 ;; would otherwise report a match.
4536 (setq pos (or pos (point))
4537 result (if (> pos (js2-node-abs-end ast))
4539 (if (not skip-comments)
4540 (js2-comment-at-point pos))))
4542 (setq js2-discovered-node nil
4543 js2-visitor-offset 0
4544 js2-node-search-point pos)
4546 (catch 'js2-visit-done
4547 (js2-visit-ast ast #'js2-node-at-point-visitor))
4548 (setq js2-visitor-offset nil
4549 js2-node-search-point nil))
4550 (setq result js2-discovered-node))
4551 ;; may have found a comment beyond end of last child node,
4552 ;; since visiting the ast-root looks at the comment-list last.
4553 (if (and skip-comments
4554 (js2-comment-node-p result))
4556 (or result js2-mode-ast)))
4558 (defun js2-node-at-point-visitor (node end-p)
4559 (let ((rel-pos (js2-node-pos node))
4562 (point js2-node-search-point))
4565 ;; this evaluates to a non-nil return value, even if it's zero
4566 (decf js2-visitor-offset rel-pos))
4567 ;; we already looked for comments before visiting, and don't want them now
4568 ((js2-comment-node-p node)
4571 (setq abs-pos (incf js2-visitor-offset rel-pos)
4572 ;; we only want to use the node if the point is before
4573 ;; the last character position in the node, so we decrement
4574 ;; the absolute end by 1.
4575 abs-end (+ abs-pos (js2-node-len node) -1))
4577 ;; If this node starts after search-point, stop the search.
4579 (throw 'js2-visit-done nil))
4580 ;; If this node ends before the search-point, don't check kids.
4584 ;; Otherwise point is within this node, possibly in a child.
4585 (setq js2-discovered-node node)
4586 t)))))) ; keep processing kids to look for more specific match
4588 (defsubst js2-block-comment-p (node)
4589 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4590 (and (js2-comment-node-p node)
4591 (memq (js2-comment-node-format node) '(jsdoc block))))
4593 ;; TODO: put the comments in a vector and binary-search them instead
4594 (defun js2-comment-at-point (&optional pos)
4595 "Look through scanned comment nodes for one containing POS.
4596 POS is a buffer position that defaults to current point.
4597 Function returns nil if POS was not in any comment node."
4598 (let ((ast js2-mode-ast)
4599 (x (or pos (point)))
4603 (error "No JavaScript AST available"))
4605 ;; Comments are stored in lexical order.
4606 (dolist (comment (js2-ast-root-comments ast) nil)
4607 (setq beg (js2-node-abs-pos comment)
4608 end (+ beg (js2-node-len comment)))
4611 (throw 'done comment))))))
4613 (defun js2-mode-find-parent-fn (node)
4614 "Find function enclosing NODE.
4615 Returns nil if NODE is not inside a function."
4616 (setq node (js2-node-parent node))
4617 (while (and node (not (js2-function-node-p node)))
4618 (setq node (js2-node-parent node)))
4619 (and (js2-function-node-p node) node))
4621 (defun js2-mode-find-enclosing-fn (node)
4622 "Find function or root enclosing NODE."
4623 (if (js2-ast-root-p node)
4625 (setq node (js2-node-parent node))
4626 (while (not (or (js2-ast-root-p node)
4627 (js2-function-node-p node)))
4628 (setq node (js2-node-parent node)))
4631 (defun js2-mode-find-enclosing-node (beg end)
4632 "Find script or function fully enclosing BEG and END."
4633 (let ((node (js2-node-at-point beg))
4637 (if (or (js2-ast-root-p node)
4638 (and (js2-function-node-p node)
4639 (<= (setq pos (js2-node-abs-pos node)) beg)
4640 (>= (+ pos (js2-node-len node)) end)))
4642 (setq node (js2-node-parent node))))
4645 (defun js2-node-parent-script-or-fn (node)
4646 "Find script or function immediately enclosing NODE.
4647 If NODE is the ast-root, returns nil."
4648 (if (js2-ast-root-p node)
4650 (setq node (js2-node-parent node))
4651 (while (and node (not (or (js2-function-node-p node)
4652 (js2-script-node-p node))))
4653 (setq node (js2-node-parent node)))
4656 (defsubst js2-nested-function-p (node)
4657 "Return t if NODE is a nested function, or is inside a nested function."
4658 (unless (js2-ast-root-p node)
4659 (js2-function-node-p (if (js2-function-node-p node)
4660 (js2-node-parent-script-or-fn node)
4661 (js2-node-parent-script-or-fn
4662 (js2-node-parent-script-or-fn node))))))
4664 (defsubst js2-function-param-node-p (node)
4665 "Return non-nil if NODE is a param node of a `js2-function-node'."
4666 (let ((parent (js2-node-parent node)))
4668 (js2-function-node-p parent)
4669 (memq node (js2-function-node-params parent)))))
4671 (defsubst js2-mode-shift-kids (kids start offset)
4673 (if (> (js2-node-pos kid) start)
4674 (incf (js2-node-pos kid) offset))))
4676 (defsubst js2-mode-shift-children (parent start offset)
4677 "Update start-positions of all children of PARENT beyond START."
4678 (let ((root (js2-node-root parent)))
4679 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4680 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4682 (defsubst js2-node-is-descendant (node ancestor)
4683 "Return t if NODE is a descendant of ANCESTOR."
4685 (not (eq node ancestor)))
4686 (setq node (js2-node-parent node)))
4689 ;;; visitor infrastructure
4691 (defun js2-visit-none (node callback)
4692 "Visitor for AST node that have no node children."
4695 (defun js2-print-none (node indent)
4696 "Visitor for AST node with no printed representation.")
4698 (defun js2-print-body (node indent)
4699 "Print a statement, or a block without braces."
4700 (if (js2-block-node-p node)
4701 (dolist (kid (js2-block-node-kids node))
4702 (js2-print-ast kid indent))
4703 (js2-print-ast node indent)))
4705 (defun js2-print-list (args &optional delimiter)
4706 (loop with len = (length args)
4710 (js2-print-ast arg 0)
4712 (insert (or delimiter ", ")))))
4714 (defun js2-print-tree (ast)
4715 "Prints an AST to the current buffer.
4716 Makes `js2-ast-parent-nodes' available to the printer functions."
4717 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4718 (js2-print-ast ast)))
4720 (defun js2-print-ast (node &optional indent)
4721 "Helper function for printing AST nodes.
4722 Requires `js2-ast-parent-nodes' to be non-nil.
4723 You should use `js2-print-tree' instead of this function."
4724 (let ((printer (get (aref node 0) 'js2-printer))
4726 (pos (js2-node-abs-pos node)))
4727 ;; TODO: wedge comments in here somewhere
4729 (funcall printer node i))))
4731 (defconst js2-side-effecting-tokens
4732 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4733 (dolist (tt (list js2-ASSIGN
4802 (if js2-instanceof-has-side-effects
4803 (aset tokens js2-INSTANCEOF t))
4806 (defun js2-node-has-side-effects (node)
4807 "Return t if NODE has side effects."
4808 (when node ; makes it easier to handle malformed expressions
4809 (let ((tt (js2-node-type node)))
4811 ;; This doubtless needs some work, since EXPR_VOID is used
4812 ;; in several ways in Rhino, and I may not have caught them all.
4813 ;; I'll wait for people to notice incorrect warnings.
4814 ((and (= tt js2-EXPR_VOID)
4815 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4816 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4818 (js2-node-has-side-effects (js2-infix-node-right node)))
4821 (or (js2-node-has-side-effects (js2-infix-node-right node))
4822 (js2-node-has-side-effects (js2-infix-node-left node))))
4824 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4825 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4826 ((js2-paren-node-p node)
4827 (js2-node-has-side-effects (js2-paren-node-expr node)))
4828 ((= tt js2-ERROR) ; avoid cascaded error messages
4831 (aref js2-side-effecting-tokens tt))))))
4833 (defun js2-member-expr-leftmost-name (node)
4834 "For an expr such as foo.bar.baz, return leftmost node foo.
4835 NODE is any `js2-node' object. If it represents a member expression,
4836 which is any sequence of property gets, element-gets, function calls,
4837 or xml descendants/filter operators, then we look at the lexically
4838 leftmost (first) node in the chain. If it is a name-node we return it.
4839 Note that NODE can be a raw name-node and it will be returned as well.
4840 If NODE is not a name-node or member expression, or if it is a member
4841 expression whose leftmost target is not a name node, returns nil."
4844 (while (and continue (not result))
4846 ((js2-name-node-p node)
4848 ((js2-prop-get-node-p node)
4849 (setq node (js2-prop-get-node-left node)))
4850 ;; TODO: handle call-nodes, xml-nodes, others?
4852 (setq continue nil))))
4855 (defconst js2-stmt-node-types
4859 js2-DEFAULT ; e4x "default xml namespace" statement
4871 "Node types that only appear in statement contexts.
4872 The list does not include nodes that always appear as the child
4873 of another specific statement type, such as switch-cases,
4874 catch and finally blocks, and else-clauses. The list also excludes
4875 nodes like yield, let and var, which may appear in either expression
4876 or statement context, and in the latter context always have a
4877 `js2-expr-stmt-node' parent. Finally, the list does not include
4878 functions or scripts, which are treated separately from statements
4879 by the JavaScript parser and runtime.")
4881 (defun js2-stmt-node-p (node)
4882 "Heuristic for figuring out if NODE is a statement.
4883 Some node types can appear in either an expression context or a
4884 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4885 For these node types in a statement context, the parent will be a
4886 `js2-expr-stmt-node'.
4887 Functions aren't included in the check."
4888 (memq (js2-node-type node) js2-stmt-node-types))
4890 (defsubst js2-mode-find-first-stmt (node)
4891 "Search upward starting from NODE looking for a statement.
4892 For purposes of this function, a `js2-function-node' counts."
4893 (while (not (or (js2-stmt-node-p node)
4894 (js2-function-node-p node)))
4895 (setq node (js2-node-parent node)))
4898 (defun js2-node-parent-stmt (node)
4899 "Return the node's first ancestor that is a statement.
4900 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4901 appearing in a statement context will have a parent that is a
4902 `js2-expr-stmt-node' that will be returned by this function."
4903 (let ((parent (js2-node-parent node)))
4904 (if (or (null parent)
4905 (js2-stmt-node-p parent)
4906 (and (js2-function-node-p parent)
4907 (not (eq (js2-function-node-form parent)
4908 'FUNCTION_EXPRESSION))))
4910 (js2-node-parent-stmt parent))))
4912 ;; In the Mozilla Rhino sources, Roshan James writes:
4913 ;; Does consistent-return analysis on the function body when strict mode is
4916 ;; function (x) { return (x+1) }
4920 ;; function (x) { if (x < 0) return (x+1); }
4922 ;; is not because the function can potentially return a value when the
4923 ;; condition is satisfied and if not, the function does not explicitly
4926 ;; This extends to checking mismatches such as "return" and "return <value>"
4927 ;; used in the same function. Warnings are not emitted if inconsistent
4928 ;; returns exist in code that can be statically shown to be unreachable.
4930 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4932 ;; emits no warning. However if the loop had a break statement, then a
4933 ;; warning would be emitted.
4935 ;; The consistency analysis looks at control structures such as loops, ifs,
4936 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4937 ;; warns the user about an inconsistent set of termination possibilities.
4939 ;; These flags enumerate the possible ways a statement/function can
4940 ;; terminate. These flags are used by endCheck() and by the Parser to
4941 ;; detect inconsistent return usage.
4943 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4944 ;; able to execute (example: throw, continue)
4946 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4947 ;; next one. Statement such as return dont. A compound statement may have
4948 ;; some branch that drops off control to the next statement.
4950 ;; END_RETURNS indicates that the statement can return with no value.
4951 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4953 ;; A compound statement such as
4957 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4959 (defconst js2-END_UNREACHED 0)
4960 (defconst js2-END_DROPS_OFF 1)
4961 (defconst js2-END_RETURNS 2)
4962 (defconst js2-END_RETURNS_VALUE 4)
4963 (defconst js2-END_YIELDS 8)
4965 (defun js2-has-consistent-return-usage (node)
4966 "Check that every return usage in a function body is consistent.
4967 Returns t if the function satisfies strict mode requirement."
4968 (let ((n (js2-end-check node)))
4969 ;; either it doesn't return a value in any branch...
4970 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4971 ;; or it returns a value (or is unreached) at every branch
4972 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4976 (defun js2-end-check-if (node)
4977 "Returns in the then and else blocks must be consistent with each other.
4978 If there is no else block, then the return statement can fall through.
4979 Returns logical OR of END_* flags"
4980 (let ((th (js2-if-node-then-part node))
4981 (el (js2-if-node-else-part node)))
4984 (logior (js2-end-check th) (if el
4986 js2-END_DROPS_OFF)))))
4988 (defun js2-end-check-switch (node)
4989 "Consistency of return statements is checked between the case statements.
4990 If there is no default, then the switch can fall through. If there is a
4991 default, we check to see if all code paths in the default return or if
4992 there is a code path that can fall through.
4993 Returns logical OR of END_* flags."
4994 (let ((rv js2-END_UNREACHED)
4996 ;; examine the cases
4998 (dolist (c (js2-switch-node-cases node))
4999 (if (js2-case-node-expr c)
5000 (js2-set-flag rv (js2-end-check-block c))
5001 (setq default-case c)
5002 (throw 'break nil))))
5003 ;; we don't care how the cases drop into each other
5004 (js2-clear-flag rv js2-END_DROPS_OFF)
5005 ;; examine the default
5006 (js2-set-flag rv (if default-case
5007 (js2-end-check default-case)
5011 (defun js2-end-check-try (node)
5012 "If the block has a finally, return consistency is checked in the
5013 finally block. If all code paths in the finally return, then the
5014 returns in the try-catch blocks don't matter. If there is a code path
5015 that does not return or if there is no finally block, the returns
5016 of the try and catch blocks are checked for mismatch.
5017 Returns logical OR of END_* flags."
5018 (let ((finally (js2-try-node-finally-block node))
5020 ;; check the finally if it exists
5021 (setq rv (if finally
5022 (js2-end-check (js2-finally-node-body finally))
5024 ;; If the finally block always returns, then none of the returns
5025 ;; in the try or catch blocks matter.
5026 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5027 (js2-clear-flag rv js2-END_DROPS_OFF)
5028 ;; examine the try block
5029 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5030 ;; check each catch block
5031 (dolist (cb (js2-try-node-catch-clauses node))
5032 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5035 (defun js2-end-check-loop (node)
5036 "Return statement in the loop body must be consistent. The default
5037 assumption for any kind of a loop is that it will eventually terminate.
5038 The only exception is a loop with a constant true condition. Code that
5039 follows such a loop is examined only if one can statically determine
5040 that there is a break out of the loop.
5042 for(... ; ... ; ...) {}
5047 Returns logical OR of END_* flags."
5048 (let ((rv (js2-end-check (js2-loop-node-body node)))
5050 ((js2-while-node-p node)
5051 (js2-while-node-condition node))
5052 ((js2-do-node-p node)
5053 (js2-do-node-condition node))
5054 ((js2-for-node-p node)
5055 (js2-for-node-condition node)))))
5057 ;; check to see if the loop condition is always true
5059 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5060 (js2-clear-flag rv js2-END_DROPS_OFF))
5062 ;; look for effect of breaks
5063 (js2-set-flag rv (js2-node-get-prop node
5068 (defun js2-end-check-block (node)
5069 "A general block of code is examined statement by statement.
5070 If any statement (even a compound one) returns in all branches, then
5071 subsequent statements are not examined.
5072 Returns logical OR of END_* flags."
5073 (let* ((rv js2-END_DROPS_OFF)
5074 (kids (js2-block-node-kids node))
5076 ;; Check each statment. If the statement can continue onto the next
5077 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5078 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5079 (js2-clear-flag rv js2-END_DROPS_OFF)
5080 (js2-set-flag rv (js2-end-check n))
5081 (setq kids (cdr kids)
5085 (defun js2-end-check-label (node)
5086 "A labeled statement implies that there may be a break to the label.
5087 The function processes the labeled statement and then checks the
5088 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5090 Returns logical OR of END_* flags."
5091 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5092 (logior rv (js2-node-get-prop node
5094 js2-END_UNREACHED))))
5096 (defun js2-end-check-break (node)
5097 "When a break is encountered annotate the statement being broken
5098 out of by setting its CONTROL_BLOCK_PROP property.
5099 Returns logical OR of END_* flags."
5100 (and (js2-break-node-target node)
5101 (js2-node-set-prop (js2-break-node-target node)
5106 (defun js2-end-check (node)
5107 "Examine the body of a function, doing a basic reachability analysis.
5108 Returns a combination of flags END_* flags that indicate
5109 how the function execution can terminate. These constitute only the
5110 pessimistic set of termination conditions. It is possible that at
5111 runtime certain code paths will never be actually taken. Hence this
5112 analysis will flag errors in cases where there may not be errors.
5113 Returns logical OR of END_* flags"
5116 ((js2-break-node-p node)
5117 (js2-end-check-break node))
5118 ((js2-expr-stmt-node-p node)
5119 (if (setq kid (js2-expr-stmt-node-expr node))
5122 ((or (js2-continue-node-p node)
5123 (js2-throw-node-p node))
5125 ((js2-return-node-p node)
5126 (if (setq kid (js2-return-node-retval node))
5127 js2-END_RETURNS_VALUE
5129 ((js2-loop-node-p node)
5130 (js2-end-check-loop node))
5131 ((js2-switch-node-p node)
5132 (js2-end-check-switch node))
5133 ((js2-labeled-stmt-node-p node)
5134 (js2-end-check-label node))
5135 ((js2-if-node-p node)
5136 (js2-end-check-if node))
5137 ((js2-try-node-p node)
5138 (js2-end-check-try node))
5139 ((js2-block-node-p node)
5140 (if (null (js2-block-node-kids node))
5142 (js2-end-check-block node)))
5143 ((js2-yield-node-p node)
5146 js2-END_DROPS_OFF))))
5148 (defun js2-always-defined-boolean-p (node)
5149 "Check if NODE always evaluates to true or false in boolean context.
5150 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5152 (let ((tt (js2-node-type node))
5155 ((or (= tt js2-FALSE) (= tt js2-NULL))
5160 (setq num (js2-number-node-num-value node))
5161 (if (and (not (eq num 0.0e+NaN))
5168 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5169 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5171 (defvar js2-tokens nil
5172 "List of all defined token names.") ; initialized in `js2-token-names'
5174 (defconst js2-token-names
5175 (let* ((names (make-vector js2-num-tokens -1))
5176 (case-fold-search nil) ; only match js2-UPPER_CASE
5177 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5178 (loop for sym in syms
5181 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5183 (aset names (symbol-value sym) ; code, e.g. 152
5184 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5185 (push sym js2-tokens)))
5187 "Vector mapping int values to token string names, sans `js2-' prefix.")
5189 (defun js2-token-name (tok)
5190 "Return a string name for TOK, a token symbol or code.
5191 Signals an error if it's not a recognized token."
5194 (setq code (symbol-value tok)))
5197 (if (and (numberp code)
5199 (< code js2-num-tokens))
5200 (aref js2-token-names code)
5201 (error "Invalid token: %s" code)))))
5203 (defsubst js2-token-sym (tok)
5204 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5205 (intern (js2-token-name tok)))
5207 (defconst js2-token-codes
5208 (let ((table (make-hash-table :test 'eq :size 256)))
5209 (loop for name across js2-token-names
5210 for sym = (intern (concat "js2-" name))
5212 (puthash sym (symbol-value sym) table))
5213 ;; clean up a few that are "wrong" in Rhino's token codes
5214 (puthash 'js2-DELETE js2-DELPROP table)
5216 "Hashtable mapping token symbols to their bytecodes.")
5218 (defsubst js2-token-code (sym)
5219 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5220 (or (gethash sym js2-token-codes)
5221 (error "Invalid token symbol: %s " sym))) ; signal code bug
5223 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5224 (setq js2-token-end js2-ts-cursor)
5225 (js2-report-error msg nil
5226 (or beg js2-token-beg)
5227 (or len (- js2-token-end js2-token-beg)))
5229 (throw 'return js2-ERROR)))
5231 (defsubst js2-get-string-from-buffer ()
5232 "Reverse the char accumulator and return it as a string."
5233 (setq js2-token-end js2-ts-cursor)
5234 (if js2-ts-string-buffer
5235 (apply #'string (nreverse js2-ts-string-buffer))
5238 ;; TODO: could potentially avoid a lot of consing by allocating a
5239 ;; char buffer the way Rhino does.
5240 (defsubst js2-add-to-string (c)
5241 (push c js2-ts-string-buffer))
5243 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5244 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5245 ;; any other character: when it's not part of the current token, we
5246 ;; unget it, allowing it to be read again by the following call.
5247 (defsubst js2-unget-char ()
5248 (decf js2-ts-cursor))
5250 ;; Rhino distinguishes \r and \n line endings. We don't need to
5251 ;; because we only scan from Emacs buffers, which always use \n.
5252 (defsubst js2-get-char ()
5253 "Read and return the next character from the input buffer.
5254 Increments `js2-ts-lineno' if the return value is a newline char.
5255 Updates `js2-ts-cursor' to the point after the returned char.
5256 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5257 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5259 ;; check for end of buffer
5260 (if (>= js2-ts-cursor (point-max))
5261 (setq js2-ts-hit-eof t
5262 js2-ts-cursor (1+ js2-ts-cursor)
5263 c js2-EOF_CHAR) ; return value
5264 ;; otherwise read next char
5265 (setq c (char-before (incf js2-ts-cursor)))
5266 ;; if we read a newline, update counters
5268 (setq js2-ts-line-start js2-ts-cursor
5269 js2-ts-lineno (1+ js2-ts-lineno)))
5270 ;; TODO: skip over format characters
5273 (defsubst js2-read-unicode-escape ()
5274 "Read a \\uNNNN sequence from the input.
5275 Assumes the ?\ and ?u have already been read.
5276 Returns the unicode character, or nil if it wasn't a valid character.
5277 Doesn't change the values of any scanner variables."
5278 ;; I really wish I knew a better way to do this, but I can't
5279 ;; find the Emacs function that takes a 16-bit int and converts
5280 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5281 ;; Have to first check that it's 4 hex characters or it may stop
5284 (let ((s (buffer-substring-no-properties js2-ts-cursor
5285 (+ 4 js2-ts-cursor))))
5286 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5287 (read (concat "?\\u" s))))))
5289 (defsubst js2-match-char (test)
5290 "Consume and return next character if it matches TEST, a character.
5291 Returns nil and consumes nothing if TEST is not the next character."
5292 (let ((c (js2-get-char)))
5298 (defsubst js2-peek-char ()
5303 (defsubst js2-java-identifier-start-p (c)
5306 (js2-char-uppercase-p c)
5307 (js2-char-lowercase-p c)))
5309 (defsubst js2-java-identifier-part-p (c)
5310 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5311 ;; TODO: make me Unicode-friendly. See comments above.
5314 (js2-char-uppercase-p c)
5315 (js2-char-lowercase-p c)
5316 (and (>= c ?0) (<= c ?9))))
5318 (defsubst js2-alpha-p (c)
5319 (cond ((and (<= ?A c) (<= c ?Z)) t)
5320 ((and (<= ?a c) (<= c ?z)) t)
5323 (defsubst js2-digit-p (c)
5324 (and (<= ?0 c) (<= c ?9)))
5326 (defsubst js2-js-space-p (c)
5328 (memq c '(#x20 #x9 #xB #xC #xD))
5331 ;; TODO: change this nil to check for Unicode space character
5334 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5336 (defsubst js2-skip-line ()
5337 "Skip to end of line"
5339 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5341 (setq js2-token-end js2-ts-cursor)))
5343 (defun js2-init-scanner (&optional buf line)
5344 "Create token stream for BUF starting on LINE.
5345 BUF defaults to current-buffer and line defaults to 1.
5347 A buffer can only have one scanner active at a time, which yields
5348 dramatically simpler code than using a defstruct. If you need to
5349 have simultaneous scanners in a buffer, copy the regions to scan
5354 (setq js2-ts-dirty-line nil
5355 js2-ts-regexp-flags nil
5360 js2-ts-lineno (or line 1)
5361 js2-ts-line-end-char -1
5362 js2-ts-cursor (point-min)
5363 js2-ts-is-xml-attribute nil
5364 js2-ts-xml-is-tag-content nil
5365 js2-ts-xml-open-tags-count 0
5366 js2-ts-string-buffer nil)))
5368 ;; This function uses the cached op, string and number fields in
5369 ;; TokenStream; if getToken has been called since the passed token
5370 ;; was scanned, the op or string printed may be incorrect.
5371 (defun js2-token-to-string (token)
5372 ;; Not sure where this function is used in Rhino. Not tested.
5373 (if (not js2-debug-print-trees)
5375 (let ((name (js2-token-name token)))
5377 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5378 (concat name " `" js2-ts-string "'"))
5379 ((eq token js2-NUMBER)
5380 (format "NUMBER %g" js2-ts-number))
5384 (defconst js2-keywords
5386 case catch const continue
5387 debugger default delete do
5389 false finally for function
5390 if in instanceof import
5395 this throw true try typeof
5400 ;; Token names aren't exactly the same as the keywords, unfortunately.
5401 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5402 (defconst js2-kwd-tokens
5403 (let ((table (make-vector js2-num-tokens nil))
5406 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5407 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5409 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5410 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5415 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5420 (aset table i 'font-lock-keyword-face))
5421 (aset table js2-STRING 'font-lock-string-face)
5422 (aset table js2-REGEXP 'font-lock-string-face)
5423 (aset table js2-COMMENT 'font-lock-comment-face)
5424 (aset table js2-THIS 'font-lock-builtin-face)
5425 (aset table js2-VOID 'font-lock-constant-face)
5426 (aset table js2-NULL 'font-lock-constant-face)
5427 (aset table js2-TRUE 'font-lock-constant-face)
5428 (aset table js2-FALSE 'font-lock-constant-face)
5430 "Vector whose values are non-nil for tokens that are keywords.
5431 The values are default faces to use for highlighting the keywords.")
5433 (defconst js2-reserved-words
5441 implements import int interface
5444 package private protected public
5445 short static super synchronized
5449 (defconst js2-keyword-names
5450 (let ((table (make-hash-table :test 'equal)))
5451 (loop for k in js2-keywords
5453 (symbol-name k) ; instanceof
5454 (intern (concat "js2-"
5455 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5458 "JavaScript keywords by name, mapped to their symbols.")
5460 (defconst js2-reserved-word-names
5461 (let ((table (make-hash-table :test 'equal)))
5462 (loop for k in js2-reserved-words
5464 (puthash (symbol-name k) 'js2-RESERVED table))
5466 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5468 (defsubst js2-collect-string (buf)
5469 "Convert BUF, a list of chars, to a string.
5470 Reverses BUF before converting."
5474 ((null buf) ; for emacs21 compat
5478 (apply #'string (nreverse buf))
5481 (defun js2-string-to-keyword (s)
5482 "Return token for S, a string, if S is a keyword or reserved word.
5483 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5484 (or (gethash s js2-keyword-names)
5485 (gethash s js2-reserved-word-names)))
5487 (defsubst js2-ts-set-char-token-bounds ()
5488 "Used when next token is one character."
5489 (setq js2-token-beg (1- js2-ts-cursor)
5490 js2-token-end js2-ts-cursor))
5492 (defsubst js2-ts-return (token)
5493 "Return an N-character TOKEN from `js2-get-token'.
5494 Updates `js2-token-end' accordingly."
5495 (setq js2-token-end js2-ts-cursor)
5496 (throw 'return token))
5498 (defsubst js2-x-digit-to-int (c accumulator)
5499 "Build up a hex number.
5500 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5501 corresponding number. Otherwise return -1."
5504 ;; Use 0..9 < A..Z < a..z
5509 (throw 'check nil)))
5513 (throw 'check nil)))
5517 (throw 'check nil))))
5519 (logior c (lsh accumulator 4))))
5521 (defun js2-get-token ()
5522 "Return next JavaScript token, an int such as js2-RETURN."
5526 is-unicode-escape-start
5540 ;; Eat whitespace, possibly sensitive to newlines.
5543 (setq c (js2-get-char))
5545 ((eq c js2-EOF_CHAR)
5546 (js2-ts-set-char-token-bounds)
5547 (throw 'return js2-EOF))
5549 (js2-ts-set-char-token-bounds)
5550 (setq js2-ts-dirty-line nil)
5551 (throw 'return js2-EOL))
5552 ((not (js2-js-space-p c))
5553 (if (/= c ?-) ; in case end of HTML comment
5554 (setq js2-ts-dirty-line t))
5555 (setq continue nil))))
5556 ;; Assume the token will be 1 char - fixed up below.
5557 (js2-ts-set-char-token-bounds)
5559 (throw 'return js2-XMLATTR))
5560 ;; identifier/keyword/instanceof?
5561 ;; watch out for starting with a <backslash>
5564 (setq c (js2-get-char))
5566 (setq identifier-start t
5567 is-unicode-escape-start t
5568 js2-ts-string-buffer nil)
5569 (setq identifier-start nil)
5573 (when (setq identifier-start (js2-java-identifier-start-p c))
5574 (setq js2-ts-string-buffer nil)
5575 (js2-add-to-string c))))
5576 (when identifier-start
5577 (setq contains-escape is-unicode-escape-start)
5580 (if is-unicode-escape-start
5581 ;; strictly speaking we should probably push-back
5582 ;; all the bad characters if the <backslash>uXXXX
5583 ;; sequence is malformed. But since there isn't a
5584 ;; correct context(is there?) for a bad Unicode
5585 ;; escape sequence in an identifier, we can report
5590 (setq c (js2-get-char)
5591 escape-val (js2-x-digit-to-int c escape-val))
5592 ;; Next check takes care of c < 0 and bad escape
5593 (if (minusp escape-val)
5594 (throw 'break nil)))
5595 (if (minusp escape-val)
5596 (js2-report-scan-error "msg.invalid.escape" t))
5597 (js2-add-to-string escape-val)
5598 (setq is-unicode-escape-start nil))
5599 (setq c (js2-get-char))
5602 (setq c (js2-get-char))
5604 (setq is-unicode-escape-start t
5606 (js2-report-scan-error "msg.illegal.character" t)))
5608 (if (or (eq c js2-EOF_CHAR)
5609 (not (js2-java-identifier-part-p c)))
5611 (js2-add-to-string c))))))
5613 (setq str (js2-get-string-from-buffer))
5614 (unless contains-escape
5615 ;; OPT we shouldn't have to make a string (object!) to
5616 ;; check if it's a keyword.
5617 ;; Return the corresponding token if it's a keyword
5618 (when (setq result (js2-string-to-keyword str))
5619 (if (and (< js2-language-version 170)
5620 (memq result '(js2-LET js2-YIELD)))
5621 ;; LET and YIELD are tokens only in 1.7 and later
5622 (setq result 'js2-NAME))
5623 (if (not (eq result 'js2-RESERVED))
5624 (throw 'return (js2-token-code result)))
5625 (js2-report-warning "msg.reserved.keyword" str)))
5626 ;; If we want to intern these as Rhino does, just use (intern str)
5627 (setq js2-ts-string str)
5628 (throw 'return js2-NAME)) ; end identifier/kwd check
5630 (when (or (js2-digit-p c)
5631 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5632 (setq js2-ts-string-buffer nil
5635 (setq c (js2-get-char))
5637 ((or (eq c ?x) (eq c ?X))
5639 (setq c (js2-get-char)))
5643 (js2-add-to-string ?0))))
5645 (while (<= 0 (js2-x-digit-to-int c 0))
5646 (js2-add-to-string c)
5647 (setq c (js2-get-char)))
5648 (while (and (<= ?0 c) (<= c ?9))
5649 ;; We permit 08 and 09 as decimal numbers, which
5650 ;; makes our behavior a superset of the ECMA
5651 ;; numeric grammar. We might not always be so
5652 ;; permissive, so we warn about it.
5653 (when (and (eq base 8) (>= c ?8))
5654 (js2-report-warning "msg.bad.octal.literal"
5655 (if (eq c ?8) "8" "9"))
5657 (js2-add-to-string c)
5658 (setq c (js2-get-char))))
5660 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5661 (setq is-integer nil)
5664 (js2-add-to-string c)
5665 (setq c (js2-get-char))
5666 while (js2-digit-p c)))
5667 (when (memq c '(?e ?E))
5668 (js2-add-to-string c)
5669 (setq c (js2-get-char))
5670 (when (memq c '(?+ ?-))
5671 (js2-add-to-string c)
5672 (setq c (js2-get-char)))
5673 (unless (js2-digit-p c)
5674 (js2-report-scan-error "msg.missing.exponent" t))
5676 (js2-add-to-string c)
5677 (setq c (js2-get-char))
5678 while (js2-digit-p c))))
5680 (setq js2-ts-string (js2-get-string-from-buffer)
5682 (if (and (eq base 10) (not is-integer))
5683 (string-to-number js2-ts-string)
5684 ;; TODO: call runtime number-parser. Some of it is in
5685 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5686 (string-to-number js2-ts-string)))
5687 (throw 'return js2-NUMBER))
5689 (when (memq c '(?\" ?\'))
5690 ;; We attempt to accumulate a string the fast way, by
5691 ;; building it directly out of the reader. But if there
5692 ;; are any escaped characters in the string, we revert to
5693 ;; building it out of a string buffer.
5695 js2-ts-string-buffer nil
5698 (while (/= c quote-char)
5700 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5702 (setq js2-token-end js2-ts-cursor)
5703 (js2-report-error "msg.unterminated.string.lit")
5704 (throw 'return js2-STRING))
5706 ;; We've hit an escaped character
5707 (setq c (js2-get-char))
5716 (setq c1 (js2-read-unicode-escape))
5717 (if js2-parse-ide-mode
5720 ;; just copy the string in IDE-mode
5721 (js2-add-to-string ?\\)
5722 (js2-add-to-string ?u)
5724 (js2-add-to-string (js2-get-char)))
5725 (setq c (js2-get-char))) ; added at end of loop
5726 ;; flag it as an invalid escape
5727 (js2-report-warning "msg.invalid.escape"
5728 nil (- js2-ts-cursor 2) 6))
5729 ;; Get 4 hex digits; if the u escape is not
5730 ;; followed by 4 hex digits, use 'u' + the
5731 ;; literal character sequence that follows.
5732 (js2-add-to-string ?u)
5735 (setq c (js2-get-char)
5736 escape-val (js2-x-digit-to-int c escape-val))
5737 (if (minusp escape-val)
5738 (throw 'continue nil))
5739 (js2-add-to-string c))
5740 ;; prepare for replace of stored 'u' sequence by escape value
5741 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5744 ;; Get 2 hex digits, defaulting to 'x'+literal
5745 ;; sequence, as above.
5746 (setq c (js2-get-char)
5747 escape-val (js2-x-digit-to-int c 0))
5748 (if (minusp escape-val)
5750 (js2-add-to-string ?x)
5751 (throw 'continue nil))
5754 escape-val (js2-x-digit-to-int c escape-val))
5755 (if (minusp escape-val)
5757 (js2-add-to-string ?x)
5758 (js2-add-to-string c1)
5759 (throw 'continue nil))
5761 (setq c escape-val))))
5763 ;; Remove line terminator after escape to follow
5764 ;; SpiderMonkey and C/C++
5765 (setq c (js2-get-char))
5766 (throw 'continue nil))
5768 (when (and (<= ?0 c) (< c ?8))
5771 (when (and (<= ?0 c) (< c ?8))
5772 (setq val (- (+ (* 8 val) c) ?0)
5774 (when (and (<= ?0 c)
5777 ;; c is 3rd char of octal sequence only
5778 ;; if the resulting val <= 0377
5779 (setq val (- (+ (* 8 val) c) ?0)
5783 (js2-add-to-string c)
5784 (setq c (js2-get-char)))))
5785 (setq js2-ts-string (js2-get-string-from-buffer))
5786 (throw 'return js2-STRING))
5789 (throw 'return js2-SEMI))
5791 (throw 'return js2-LB))
5793 (throw 'return js2-RB))
5795 (throw 'return js2-LC))
5797 (throw 'return js2-RC))
5799 (throw 'return js2-LP))
5801 (throw 'return js2-RP))
5803 (throw 'return js2-COMMA))
5805 (throw 'return js2-HOOK))
5807 (if (js2-match-char ?:)
5808 (js2-ts-return js2-COLONCOLON)
5809 (throw 'return js2-COLON)))
5811 (if (js2-match-char ?.)
5812 (js2-ts-return js2-DOTDOT)
5813 (if (js2-match-char ?\()
5814 (js2-ts-return js2-DOTQUERY)
5815 (throw 'return js2-DOT))))
5817 (if (js2-match-char ?|)
5818 (throw 'return js2-OR)
5819 (if (js2-match-char ?=)
5820 (js2-ts-return js2-ASSIGN_BITOR)
5821 (throw 'return js2-BITOR))))
5823 (if (js2-match-char ?=)
5824 (js2-ts-return js2-ASSIGN_BITOR)
5825 (throw 'return js2-BITXOR)))
5827 (if (js2-match-char ?&)
5828 (throw 'return js2-AND)
5829 (if (js2-match-char ?=)
5830 (js2-ts-return js2-ASSIGN_BITAND)
5831 (throw 'return js2-BITAND))))
5833 (if (js2-match-char ?=)
5834 (if (js2-match-char ?=)
5835 (js2-ts-return js2-SHEQ)
5836 (throw 'return js2-EQ))
5837 (throw 'return js2-ASSIGN)))
5839 (if (js2-match-char ?=)
5840 (if (js2-match-char ?=)
5841 (js2-ts-return js2-SHNE)
5842 (js2-ts-return js2-NE))
5843 (throw 'return js2-NOT)))
5845 ;; NB:treat HTML begin-comment as comment-till-eol
5846 (when (js2-match-char ?!)
5847 (when (js2-match-char ?-)
5848 (when (js2-match-char ?-)
5850 (setq js2-ts-comment-type 'html)
5851 (throw 'return js2-COMMENT)))
5853 (if (js2-match-char ?<)
5854 (if (js2-match-char ?=)
5855 (js2-ts-return js2-ASSIGN_LSH)
5856 (js2-ts-return js2-LSH))
5857 (if (js2-match-char ?=)
5858 (js2-ts-return js2-LE)
5859 (throw 'return js2-LT))))
5861 (if (js2-match-char ?>)
5862 (if (js2-match-char ?>)
5863 (if (js2-match-char ?=)
5864 (js2-ts-return js2-ASSIGN_URSH)
5865 (js2-ts-return js2-URSH))
5866 (if (js2-match-char ?=)
5867 (js2-ts-return js2-ASSIGN_RSH)
5868 (js2-ts-return js2-RSH)))
5869 (if (js2-match-char ?=)
5870 (js2-ts-return js2-GE)
5871 (throw 'return js2-GT))))
5873 (if (js2-match-char ?=)
5874 (js2-ts-return js2-ASSIGN_MUL)
5875 (throw 'return js2-MUL)))
5877 ;; is it a // comment?
5878 (when (js2-match-char ?/)
5879 (setq js2-token-beg (- js2-ts-cursor 2))
5881 (setq js2-ts-comment-type 'line)
5882 ;; include newline so highlighting goes to end of window
5883 (incf js2-token-end)
5884 (throw 'return js2-COMMENT))
5885 ;; is it a /* comment?
5886 (when (js2-match-char ?*)
5887 (setq look-for-slash nil
5888 js2-token-beg (- js2-ts-cursor 2)
5890 (if (js2-match-char ?*)
5892 (setq look-for-slash t)
5896 (setq c (js2-get-char))
5898 ((eq c js2-EOF_CHAR)
5899 (setq js2-token-end (1- js2-ts-cursor))
5900 (js2-report-error "msg.unterminated.comment")
5901 (throw 'return js2-COMMENT))
5903 (setq look-for-slash t))
5906 (js2-ts-return js2-COMMENT)))
5908 (setq look-for-slash nil
5909 js2-token-end js2-ts-cursor)))))
5910 (if (js2-match-char ?=)
5911 (js2-ts-return js2-ASSIGN_DIV)
5912 (throw 'return js2-DIV)))
5914 (when js2-skip-preprocessor-directives
5916 (setq js2-ts-comment-type 'preprocessor
5917 js2-token-end js2-ts-cursor)
5918 (throw 'return js2-COMMENT))
5919 (throw 'return js2-ERROR))
5921 (if (js2-match-char ?=)
5922 (js2-ts-return js2-ASSIGN_MOD)
5923 (throw 'return js2-MOD)))
5925 (throw 'return js2-BITNOT))
5927 (if (js2-match-char ?=)
5928 (js2-ts-return js2-ASSIGN_ADD)
5929 (if (js2-match-char ?+)
5930 (js2-ts-return js2-INC)
5931 (throw 'return js2-ADD))))
5934 ((js2-match-char ?=)
5935 (setq c js2-ASSIGN_SUB))
5936 ((js2-match-char ?-)
5937 (unless js2-ts-dirty-line
5938 ;; treat HTML end-comment after possible whitespace
5939 ;; after line start as comment-until-eol
5940 (when (js2-match-char ?>)
5942 (setq js2-ts-comment-type 'html)
5943 (throw 'return js2-COMMENT)))
5947 (setq js2-ts-dirty-line t)
5950 (js2-report-scan-error "msg.illegal.character")))))))
5952 (defun js2-read-regexp (start-token)
5953 "Called by parser when it gets / or /= in literal context."
5956 in-class ; inside a '[' .. ']' character-class
5959 (setq js2-token-beg js2-ts-cursor
5960 js2-ts-string-buffer nil
5961 js2-ts-regexp-flags nil)
5962 (if (eq start-token js2-ASSIGN_DIV)
5964 (js2-add-to-string ?=)
5965 (if (not (eq start-token js2-DIV))
5966 (error "failed assertion")))
5967 (while (and (not err)
5968 (or (/= (setq c (js2-get-char)) ?/)
5973 (setq js2-token-end (1- js2-ts-cursor)
5975 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5976 (js2-report-error "msg.unterminated.re.lit"))
5979 (js2-add-to-string c)
5980 (setq c (js2-get-char)))
5984 (setq in-class nil)))
5985 (js2-add-to-string c))))
5989 ((js2-match-char ?g)
5991 ((js2-match-char ?i)
5993 ((js2-match-char ?m)
5996 (setq continue nil))))
5997 (if (js2-alpha-p (js2-peek-char))
5998 (js2-report-scan-error "msg.invalid.re.flag" t
6000 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6001 js2-ts-regexp-flags (js2-collect-string flags)
6002 js2-token-end js2-ts-cursor)
6003 ;; tell `parse-partial-sexp' to ignore this range of chars
6004 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6006 (defun js2-get-first-xml-token ()
6007 (setq js2-ts-xml-open-tags-count 0
6008 js2-ts-is-xml-attribute nil
6009 js2-ts-xml-is-tag-content nil)
6011 (js2-get-next-xml-token))
6013 (defsubst js2-xml-discard-string ()
6014 "Throw away the string in progress and flag an XML parse error."
6015 (setq js2-ts-string-buffer nil
6017 (js2-report-scan-error "msg.XML.bad.form" t))
6019 (defun js2-get-next-xml-token ()
6020 (setq js2-ts-string-buffer nil ; for recording the XML
6021 js2-token-beg js2-ts-cursor)
6026 (setq c (js2-get-char))
6029 (throw 'return js2-ERROR))
6030 (js2-ts-xml-is-tag-content
6033 (js2-add-to-string c)
6034 (setq js2-ts-xml-is-tag-content nil
6035 js2-ts-is-xml-attribute nil))
6037 (js2-add-to-string c)
6038 (when (eq ?> (js2-peek-char))
6039 (setq c (js2-get-char))
6040 (js2-add-to-string c)
6041 (setq js2-ts-xml-is-tag-content nil)
6042 (decf js2-ts-xml-open-tags-count)))
6045 (setq js2-ts-string (js2-get-string-from-buffer))
6046 (throw 'return js2-XML))
6048 (js2-add-to-string c)
6049 (unless (js2-read-quoted-string c)
6050 (throw 'return js2-ERROR)))
6052 (js2-add-to-string c)
6053 (setq js2-ts-is-xml-attribute t))
6055 (js2-add-to-string c))
6057 (js2-add-to-string c)
6058 (setq js2-ts-is-xml-attribute nil)))
6059 (when (and (not js2-ts-xml-is-tag-content)
6060 (zerop js2-ts-xml-open-tags-count))
6061 (setq js2-ts-string (js2-get-string-from-buffer))
6062 (throw 'return js2-XMLEND)))
6064 ;; else not tag content
6067 (js2-add-to-string c)
6068 (setq c (js2-peek-char))
6071 (setq c (js2-get-char)) ;; skip !
6072 (js2-add-to-string c)
6073 (setq c (js2-peek-char))
6076 (setq c (js2-get-char)) ;; skip -
6077 (js2-add-to-string c)
6080 (js2-add-to-string c)
6081 (unless (js2-read-xml-comment)
6082 (throw 'return js2-ERROR)))
6083 (js2-xml-discard-string)
6084 (throw 'return js2-ERROR)))
6086 (setq c (js2-get-char)) ;; skip [
6087 (js2-add-to-string c)
6088 (if (and (= (js2-get-char) ?C)
6089 (= (js2-get-char) ?D)
6090 (= (js2-get-char) ?A)
6091 (= (js2-get-char) ?T)
6092 (= (js2-get-char) ?A)
6093 (= (js2-get-char) ?\[))
6095 (js2-add-to-string ?C)
6096 (js2-add-to-string ?D)
6097 (js2-add-to-string ?A)
6098 (js2-add-to-string ?T)
6099 (js2-add-to-string ?A)
6100 (js2-add-to-string ?\[)
6101 (unless (js2-read-cdata)
6102 (throw 'return js2-ERROR)))
6103 (js2-xml-discard-string)
6104 (throw 'return js2-ERROR)))
6106 (unless (js2-read-entity)
6107 (throw 'return js2-ERROR))))
6108 ;; allow bare CDATA section
6109 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6110 (when (zerop js2-ts-xml-open-tags-count)
6111 (throw 'return js2-XMLEND)))
6113 (setq c (js2-get-char)) ;; skip ?
6114 (js2-add-to-string c)
6115 (unless (js2-read-PI)
6116 (throw 'return js2-ERROR)))
6119 (setq c (js2-get-char)) ;; skip /
6120 (js2-add-to-string c)
6121 (when (zerop js2-ts-xml-open-tags-count)
6122 (js2-xml-discard-string)
6123 (throw 'return js2-ERROR))
6124 (setq js2-ts-xml-is-tag-content t)
6125 (decf js2-ts-xml-open-tags-count))
6128 (setq js2-ts-xml-is-tag-content t)
6129 (incf js2-ts-xml-open-tags-count))))
6132 (setq js2-ts-string (js2-get-string-from-buffer))
6133 (throw 'return js2-XML))
6135 (js2-add-to-string c))))))))
6136 (setq js2-token-end js2-ts-cursor)
6139 (defun js2-read-quoted-string (quote)
6142 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6143 (js2-add-to-string c)
6146 (js2-xml-discard-string) ;; throw away string in progress
6149 (defun js2-read-xml-comment ()
6150 (let ((c (js2-get-char)))
6152 (while (/= c js2-EOF_CHAR)
6154 (js2-add-to-string c)
6155 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6156 (setq c (js2-get-char))
6157 (js2-add-to-string c)
6158 (if (eq (js2-peek-char) ?>)
6160 (setq c (js2-get-char)) ;; skip >
6161 (js2-add-to-string c)
6163 (throw 'continue nil)))
6164 (setq c (js2-get-char))))
6165 (js2-xml-discard-string)
6168 (defun js2-read-cdata ()
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-entity ()
6191 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6192 (js2-add-to-string c)
6198 (if (zerop decl-tags)
6199 (throw 'return t)))))
6200 (js2-xml-discard-string)
6203 (defun js2-read-PI ()
6204 "Scan an XML processing instruction."
6207 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6208 (js2-add-to-string c)
6209 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6210 (setq c (js2-get-char)) ;; Skip >
6211 (js2-add-to-string c)
6213 (js2-xml-discard-string)
6216 (defun js2-scanner-get-line ()
6217 "Return the text of the current scan line."
6218 (buffer-substring (point-at-bol) (point-at-eol)))
6222 (defsubst js2-set-face (beg end face &optional record)
6223 "Fontify a region. If RECORD is non-nil, record for later."
6224 (when (plusp js2-highlight-level)
6225 (setq beg (min (point-max) beg)
6226 beg (max (point-min) beg)
6227 end (min (point-max) end)
6228 end (max (point-min) end))
6230 (push (list beg end face) js2-mode-fontifications)
6231 (put-text-property beg end 'face face))))
6233 (defsubst js2-set-kid-face (pos kid len face)
6234 "Set-face on a child node.
6235 POS is absolute buffer position of parent.
6236 KID is the child node.
6237 LEN is the length to fontify.
6238 FACE is the face to fontify with."
6239 (js2-set-face (+ pos (js2-node-pos kid))
6240 (+ pos (js2-node-pos kid) (js2-node-len kid))
6243 (defsubst js2-fontify-kwd (start length)
6244 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6246 (defsubst js2-clear-face (beg end)
6247 (remove-text-properties beg end '(face nil
6252 (defconst js2-ecma-global-props
6255 '("Infinity" "NaN" "undefined" "arguments") t)
6257 "Value properties of the Ecma-262 Global Object.
6258 Shown at or above `js2-highlight-level' 2.")
6260 ;; might want to add the name "arguments" to this list?
6261 (defconst js2-ecma-object-props
6264 '("prototype" "__proto__" "__parent__") t)
6266 "Value properties of the Ecma-262 Object constructor.
6267 Shown at or above `js2-highlight-level' 2.")
6269 (defconst js2-ecma-global-funcs
6273 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6274 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6276 "Function properties of the Ecma-262 Global object.
6277 Shown at or above `js2-highlight-level' 2.")
6279 (defconst js2-ecma-number-props
6281 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6283 "POSITIVE_INFINITY") t)
6285 "Properties of the Ecma-262 Number constructor.
6286 Shown at or above `js2-highlight-level' 2.")
6288 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6289 "Properties of the Ecma-262 Date constructor.
6290 Shown at or above `js2-highlight-level' 2.")
6292 (defconst js2-ecma-math-props
6295 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6298 "Properties of the Ecma-262 Math object.
6299 Shown at or above `js2-highlight-level' 2.")
6301 (defconst js2-ecma-math-funcs
6304 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6305 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6307 "Function properties of the Ecma-262 Math object.
6308 Shown at or above `js2-highlight-level' 2.")
6310 (defconst js2-ecma-function-props
6314 '(;; properties of the Object prototype object
6315 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6316 "toLocaleString" "toString" "valueOf"
6317 ;; properties of the Function prototype object
6319 ;; properties of the Array prototype object
6320 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6322 ;; properties of the String prototype object
6323 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6324 "localeCompare" "match" "replace" "search" "split" "substring"
6325 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6327 ;; properties of the Number prototype object
6328 "toExponential" "toFixed" "toPrecision"
6329 ;; properties of the Date prototype object
6330 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6331 "getMinutes" "getMonth" "getSeconds" "getTime"
6332 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6333 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6334 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6335 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6336 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6337 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6338 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6339 "toTimeString" "toUTCString"
6340 ;; properties of the RegExp prototype object
6342 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6343 "toSource" "__defineGetter__" "__defineSetter__"
6344 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6345 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6348 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6349 Shown at or above `js2-highlight-level' 3.")
6351 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6352 (let ((target-name (and target
6353 (js2-name-node-p target)
6354 (js2-name-node-name target)))
6355 (prop-name (if prop (js2-name-node-name prop)))
6356 (level1 (>= js2-highlight-level 1))
6357 (level2 (>= js2-highlight-level 2))
6358 (level3 (>= js2-highlight-level 3))
6366 ((and level3 (string-match js2-ecma-function-props prop-name))
6367 (setq face 'font-lock-builtin-face))
6368 ((and target-name prop)
6370 ((string= target-name "Date")
6371 (if (string-match js2-ecma-date-props prop-name)
6372 (setq face 'font-lock-builtin-face)))
6373 ((string= target-name "Math")
6374 (if (string-match js2-ecma-math-funcs prop-name)
6375 (setq face 'font-lock-builtin-face)))))))
6377 (if (string-match js2-ecma-global-funcs prop-name)
6378 (setq face 'font-lock-builtin-face))))
6382 ((string= target-name "Number")
6383 (if (string-match js2-ecma-number-props prop-name)
6384 (setq face 'font-lock-constant-face)))
6385 ((string= target-name "Math")
6386 (if (string-match js2-ecma-math-props prop-name)
6387 (setq face 'font-lock-constant-face)))))
6389 (if (string-match js2-ecma-object-props prop-name)
6390 (setq face 'font-lock-constant-face)))))
6392 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6393 (js2-node-pos prop))) ; relative
6394 (+ pos (js2-node-len prop))
6397 (defun js2-parse-highlight-member-expr-node (node)
6398 "Perform syntax highlighting of EcmaScript built-in properties.
6399 The variable `js2-highlight-level' governs this highighting."
6400 (let (face target prop name pos end parent call-p callee)
6402 ;; case 1: simple name, e.g. foo
6403 ((js2-name-node-p node)
6404 (setq name (js2-name-node-name node))
6405 ;; possible for name to be nil in rare cases - saw it when
6406 ;; running js2-mode on an elisp buffer. Might as well try to
6407 ;; make it so js2-mode never barfs.
6409 (setq face (if (string-match js2-ecma-global-props name)
6410 'font-lock-constant-face))
6412 (setq pos (js2-node-pos node)
6413 end (+ pos (js2-node-len node)))
6414 (js2-set-face pos end face))))
6415 ;; case 2: property access or function call
6416 ((or (js2-prop-get-node-p node)
6417 ;; highlight function call if expr is a prop-get node
6418 ;; or a plain name (i.e. unqualified function call)
6419 (and (setq call-p (js2-call-node-p node))
6420 (setq callee (js2-call-node-target node)) ; separate setq!
6421 (or (js2-prop-get-node-p callee)
6422 (js2-name-node-p callee))))
6424 node (if call-p callee node))
6425 (if (and call-p (js2-name-node-p callee))
6427 (setq target (js2-prop-get-node-left node)
6428 prop (js2-prop-get-node-right node)))
6430 ((js2-name-node-p target)
6431 (if (js2-name-node-p prop)
6432 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6433 (js2-parse-highlight-prop-get parent target prop call-p)
6434 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6435 (js2-parse-highlight-prop-get parent target nil call-p)))
6436 ((js2-name-node-p prop)
6437 ;; case 2c: complex target, simple name, e.g. x[y].bar
6438 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6440 (defun js2-parse-highlight-member-expr-fn-name (expr)
6441 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6442 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6443 We currently only handle the case where the last component is a prop-get
6444 of a simple name. Called before EXPR has a parent node."
6446 (name (and (js2-prop-get-node-p expr)
6447 (js2-prop-get-node-right expr))))
6448 (when (js2-name-node-p name)
6449 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6450 (js2-node-pos name)))
6451 (+ pos (js2-node-len name))
6452 'font-lock-function-name-face
6455 ;; source: http://jsdoc.sourceforge.net/
6456 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6457 ;; allows type specifications, and needs work before entering the wild.
6459 (defconst js2-jsdoc-param-tag-regexp
6460 (concat "^\\s-*\\*+\\s-*\\(@"
6461 "\\(?:param\\|argument\\)"
6463 "\\s-*\\({[^}]+}\\)?" ; optional type
6464 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6466 "Matches jsdoc tags with optional type and optional param name.")
6468 (defconst js2-jsdoc-typed-tag-regexp
6469 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6483 "\\)\\)\\s-*\\({[^}]+}\\)?")
6484 "Matches jsdoc tags with optional type.")
6486 (defconst js2-jsdoc-arg-tag-regexp
6487 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6510 "\\)\\)\\s-+\\([^ \t]+\\)")
6511 "Matches jsdoc tags with a single argument.")
6513 (defconst js2-jsdoc-empty-tag-regexp
6514 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6554 "Matches empty jsdoc tags.")
6556 (defconst js2-jsdoc-link-tag-regexp
6557 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6558 "Matches a jsdoc link or code tag.")
6560 (defconst js2-jsdoc-see-tag-regexp
6561 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6562 "Matches a jsdoc @see tag.")
6564 (defconst js2-jsdoc-html-tag-regexp
6565 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6566 "Matches a simple (no attributes) html start- or end-tag.")
6568 (defsubst js2-jsdoc-highlight-helper ()
6569 (js2-set-face (match-beginning 1)
6571 'js2-jsdoc-tag-face)
6572 (if (match-beginning 2)
6574 (goto-char (match-beginning 2))
6575 (= (char-after) ?{))
6576 (js2-set-face (1+ (match-beginning 2))
6578 'js2-jsdoc-type-face)
6579 (js2-set-face (match-beginning 2)
6581 'js2-jsdoc-value-face)))
6582 (if (match-beginning 3)
6583 (js2-set-face (match-beginning 3)
6585 'js2-jsdoc-value-face)))
6587 (defun js2-highlight-jsdoc (ast)
6588 "Highlight doc comment tags."
6589 (let ((comments (js2-ast-root-comments ast))
6592 (dolist (node comments)
6593 (when (eq (js2-comment-node-format node) 'jsdoc)
6594 (setq beg (js2-node-abs-pos node)
6595 end (+ beg (js2-node-len node)))
6597 (narrow-to-region beg end)
6598 (dolist (re (list js2-jsdoc-param-tag-regexp
6599 js2-jsdoc-typed-tag-regexp
6600 js2-jsdoc-arg-tag-regexp
6601 js2-jsdoc-link-tag-regexp
6602 js2-jsdoc-see-tag-regexp
6603 js2-jsdoc-empty-tag-regexp))
6605 (while (re-search-forward re nil t)
6606 (js2-jsdoc-highlight-helper)))
6607 ;; simple highlighting for html tags
6609 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6610 (js2-set-face (match-beginning 1)
6612 'js2-jsdoc-html-tag-delimiter-face)
6613 (js2-set-face (match-beginning 2)
6615 'js2-jsdoc-html-tag-name-face)
6616 (js2-set-face (match-beginning 3)
6618 'js2-jsdoc-html-tag-delimiter-face))))))))
6620 (defun js2-highlight-assign-targets (node left right)
6621 "Highlight function properties and external variables."
6622 (let (leftpos end name)
6623 ;; highlight vars and props assigned function values
6624 (when (js2-function-node-p right)
6626 ;; var foo = function() {...}
6627 ((js2-name-node-p left)
6629 ;; foo.bar.baz = function() {...}
6630 ((and (js2-prop-get-node-p left)
6631 (js2-name-node-p (js2-prop-get-node-right left)))
6632 (setq name (js2-prop-get-node-right left))))
6634 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6635 (+ leftpos (js2-node-len name))
6636 'font-lock-function-name-face
6639 (defun js2-record-name-node (node)
6640 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6641 later. NODE must be a name node."
6643 (push (list node js2-current-scope
6644 (setq leftpos (js2-node-abs-pos node))
6645 (setq end (+ leftpos (js2-node-len node))))
6646 js2-recorded-identifiers)))
6648 (defun js2-highlight-undeclared-vars ()
6649 "After entire parse is finished, look for undeclared variable references.
6650 We have to wait until entire buffer is parsed, since JavaScript permits var
6651 decls to occur after they're used.
6653 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6654 it is considered declared."
6656 (dolist (entry js2-recorded-identifiers)
6657 (destructuring-bind (name-node scope pos end) entry
6658 (setq name (js2-name-node-name name-node))
6659 (unless (or (member name js2-global-externs)
6660 (member name js2-default-externs)
6661 (member name js2-additional-externs)
6662 (js2-get-defining-scope scope name))
6663 (js2-set-face pos end 'js2-external-variable-face 'record)
6664 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6665 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6666 (setq js2-recorded-identifiers nil)))
6670 ;; We currently only support imenu, but eventually should support speedbar and
6671 ;; possibly other browsing mechanisms.
6673 ;; The basic strategy is to identify function assignment targets of the form
6674 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6675 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6676 ;; for imenu after parsing is finished.
6678 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6679 ;; JavaScript, and the general problem is undecidable. However, several forms
6680 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6683 ;; function foo() -- function declaration
6684 ;; foo = function() -- function expression assigned to variable
6685 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6686 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6687 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6688 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6689 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6690 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6691 ;; function foo() {function bar() {...}} -- nested function
6692 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6694 ;; This list boils down to a few forms that can be combined recursively.
6695 ;; Top-level named function declarations include both the left-hand (name)
6696 ;; and the right-hand (function value) expressions needed to produce an imenu
6697 ;; entry. The other "right-hand" forms we need to look for are:
6698 ;; - functions declared as props/getters/setters in object literals
6699 ;; - nested named function declarations
6700 ;; The "left-hand" expressions that functions can be assigned to include:
6701 ;; - local/global variables
6702 ;; - nested property-get expressions like a.b.c.d
6703 ;; - element gets like foo[10] or foo['bar'] where the index
6704 ;; expression can be trivially converted to a property name. They
6705 ;; effectively then become property gets.
6707 ;; All the different definition types are canonicalized into the form
6708 ;; foo.bar.baz = position-of-function-keyword
6710 ;; We need to build a trie-like structure for imenu. As an example,
6711 ;; consider the following JavaScript code:
6713 ;; a = function() {...} // function at position 5
6714 ;; b = function() {...} // function at position 25
6715 ;; foo = function() {...} // function at position 100
6716 ;; foo.bar = function() {...} // function at position 200
6717 ;; foo.bar.baz = function() {...} // function at position 300
6718 ;; foo.bar.zab = function() {...} // function at position 400
6720 ;; During parsing we accumulate an entry for each definition in
6721 ;; the variable `js2-imenu-recorder', like so:
6727 ;; (foo bar baz 300)
6728 ;; (foo bar zab 400))
6730 ;; After parsing these entries are merged into this alist-trie:
6734 ;; (foo (<definition> . 3)
6735 ;; (bar (<definition> . 6)
6739 ;; Note the wacky need for a <definition> name. The token can be anything
6740 ;; that isn't a valid JavaScript identifier, because you might make foo
6741 ;; a function and then start setting properties on it that are also functions.
6743 (defsubst js2-prop-node-name (node)
6744 "Return the name of a node that may be a property-get/property-name.
6745 If NODE is not a valid name-node, string-node or integral number-node,
6746 returns nil. Otherwise returns the string name/value of the node."
6748 ((js2-name-node-p node)
6749 (js2-name-node-name node))
6750 ((js2-string-node-p node)
6751 (js2-string-node-value node))
6752 ((and (js2-number-node-p node)
6753 (string-match "^[0-9]+$" (js2-number-node-value node)))
6754 (js2-number-node-value node))
6755 ((js2-this-node-p node)
6758 (defsubst js2-node-qname-component (node)
6759 "Test function: return the name of this node, if it contributes to a qname.
6760 Returns nil if the node doesn't contribute."
6762 (or (js2-prop-node-name node)
6763 (if (and (js2-function-node-p node)
6764 (js2-function-node-name node))
6765 (js2-name-node-name (js2-function-node-name node))))))
6767 (defsubst js2-record-function-qname (fn-node qname)
6768 "Associate FN-NODE with its QNAME for later lookup.
6769 This is used in postprocessing the chain list. When we find a chain
6770 whose first element is a js2-THIS keyword node, we look up the parent
6771 function and see (using this map) whether it is the tail of a chain.
6772 If so, we replace the this-node with a copy of the parent's qname."
6773 (unless js2-imenu-function-map
6774 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6775 (puthash fn-node qname js2-imenu-function-map))
6777 (defun js2-record-imenu-functions (node &optional var)
6778 "Record function definitions for imenu.
6779 NODE is a function node or an object literal.
6780 VAR, if non-nil, is the expression that NODE is being assigned to."
6781 (when js2-parse-ide-mode
6782 (let ((fun-p (js2-function-node-p node))
6783 qname left fname-node pos)
6785 ;; non-anonymous function declaration?
6788 (setq fname-node (js2-function-node-name node)))
6789 (push (setq qname (list fname-node (js2-node-pos node)))
6791 (js2-record-function-qname node qname))
6792 ;; for remaining forms, compute left-side tree branch first
6793 ((and var (setq qname (js2-compute-nested-prop-get var)))
6795 ;; foo.bar.baz = function
6797 (push (nconc qname (list (js2-node-pos node)))
6799 (js2-record-function-qname node qname))
6800 ;; foo.bar.baz = object-literal
6801 ;; look for nested functions: {a: {b: function() {...} }}
6802 ((js2-object-node-p node)
6803 ;; Node position here is still absolute, since the parser
6804 ;; passes the assignment target and value expressions
6805 ;; to us before they are added as children of the assignment node.
6806 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6808 (defun js2-compute-nested-prop-get (node)
6809 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6810 component nodes as a list. Otherwise return nil. Element-gets are treated
6811 as property-gets if the index expression is a string, or a positive integer."
6812 (let (left right head)
6814 ((or (js2-name-node-p node)
6815 (js2-this-node-p node))
6817 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6818 ((js2-prop-get-node-p node) ; foo.bar
6819 (setq left (js2-prop-get-node-left node)
6820 right (js2-prop-get-node-right node))
6821 (if (setq head (js2-compute-nested-prop-get left))
6822 (nconc head (list right))))
6823 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6824 (setq left (js2-elem-get-node-target node)
6825 right (js2-elem-get-node-element node))
6826 (if (or (js2-string-node-p right) ; ['bar']
6827 (and (js2-number-node-p right) ; [10]
6828 (string-match "^[0-9]+$"
6829 (js2-number-node-value right))))
6830 (if (setq head (js2-compute-nested-prop-get left))
6831 (nconc head (list right))))))))
6833 (defun js2-record-object-literal (node qname pos)
6834 "Recursively process an object literal looking for functions.
6835 NODE is an object literal that is the right-hand child of an assignment
6836 expression. QNAME is a list of nodes representing the assignment target,
6837 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6838 POS is the absolute position of the node.
6839 We do a depth-first traversal of NODE. Any functions we find are prefixed
6840 with QNAME plus the property name of the function and appended to the
6841 variable `js2-imenu-recorder'."
6843 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6844 (let ((left (js2-infix-node-left e))
6845 ;; Element positions are relative to the parent position.
6846 (pos (+ pos (js2-node-pos e))))
6848 ;; foo: function() {...}
6849 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6850 (when (js2-prop-node-name left)
6851 ;; As a policy decision, we record the position of the property,
6852 ;; not the position of the `function' keyword, since the property
6853 ;; is effectively the name of the function.
6854 (push (append qname (list left pos))
6856 (js2-record-function-qname right qname)))
6857 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6858 ((js2-object-node-p right)
6859 (js2-record-object-literal right
6860 (append qname (list (js2-infix-node-left e)))
6861 (+ pos (js2-node-pos right)))))))))
6863 (defsubst js2-node-top-level-decl-p (node)
6864 "Return t if NODE's name is defined in the top-level scope.
6865 Also returns t if NODE's name is not defined in any scope, since it implies
6866 that it's an external variable, which must also be in the top-level scope."
6867 (let* ((name (js2-prop-node-name node))
6868 (this-scope (js2-node-get-enclosing-scope node))
6871 ((js2-this-node-p node)
6875 ((setq defining-scope (js2-get-defining-scope this-scope name))
6876 (js2-ast-root-p defining-scope))
6879 (defsubst js2-wrapper-function-p (node)
6880 "Returns t if NODE is a function expression that's immediately invoked.
6881 NODE must be `js2-function-node'."
6882 (let ((parent (js2-node-parent node)))
6884 ;; function(){...}();
6885 (js2-call-node-p parent)
6886 (and (js2-paren-node-p parent)
6887 ;; (function(){...})();
6888 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6889 ;; (function(){...}).call(this);
6890 (and (js2-prop-get-node-p parent)
6891 (member (js2-name-node-name (js2-prop-get-node-right parent))
6893 (js2-call-node-p (js2-node-parent parent))))))))
6895 (defun js2-browse-postprocess-chains (chains)
6896 "Modify function-declaration name chains after parsing finishes.
6897 Some of the information is only available after the parse tree is complete.
6898 For instance, following a 'this' reference requires a parent function node."
6899 (let ((js2-imenu-fn-type-map (make-hash-table :test 'eq))
6900 result head fn fn-type parent-chain p elem parent)
6901 (dolist (chain chains)
6902 ;; examine the head of each node to get its defining scope
6903 (setq head (car chain))
6904 ;; if top-level/external, keep as-is
6905 (if (js2-node-top-level-decl-p head)
6908 ;; starts with this-reference
6909 ((js2-this-node-p head)
6910 (setq fn (js2-node-parent-script-or-fn head)
6911 chain (cdr chain))) ; discard this-node
6912 ;; nested named function
6913 ((js2-function-node-p (setq parent (js2-node-parent head)))
6914 (setq fn (js2-node-parent-script-or-fn parent)))
6915 ;; variable assigned a function expression
6916 (t (setq fn (js2-node-parent-script-or-fn head))))
6918 (setq fn-type (gethash fn js2-imenu-fn-type-map))
6921 (cond ((js2-nested-function-p fn) 'skip)
6923 (gethash fn js2-imenu-function-map))
6925 ((js2-wrapper-function-p fn) 'anon)
6927 (puthash fn fn-type js2-imenu-fn-type-map))
6929 ('anon (push chain result)) ; anonymous top-level wrapper
6930 ('named ; top-level named function
6931 ;; prefix parent fn qname, which is
6932 ;; parent-chain sans last elem, to this chain.
6933 (push (append (butlast parent-chain) chain) result))))))
6934 ;; finally replace each node in each chain with its name.
6935 (dolist (chain result)
6938 (if (js2-node-p (setq elem (car p)))
6939 (setcar p (js2-node-qname-component elem)))
6943 ;; Merge name chains into a trie-like tree structure of nested lists.
6944 ;; To simplify construction of the trie, we first build it out using the rule
6945 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6946 ;; [key, num-or-list]. The second element can be a number; if so, this key
6947 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6948 ;; associated with the key at this level.) Otherwise the second element is
6949 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6950 ;; a simple recursive formulation.
6952 ;; js2-mode is building the data structure for imenu. The imenu documentation
6953 ;; claims that it's the structure above, but in practice it wants the children
6954 ;; at the same list level as the key for that level, which is how I've drawn
6955 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6956 ;; list wrapper around the children at each level.
6958 ;; A completed nested imenu-alist entry looks like this:
6960 ;; ("<definition>" . 7)
6965 ;; In particular, the documentation for `imenu--index-alist' says that
6966 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6967 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6969 (defsubst js2-treeify (lst)
6970 "Convert (a b c d) to (a ((b ((c d)))))"
6971 (if (null (cddr lst)) ; list length <= 2
6973 (list (car lst) (list (js2-treeify (cdr lst))))))
6975 (defun js2-build-alist-trie (chains trie)
6976 "Merge declaration name chains into a trie-like alist structure for imenu.
6977 CHAINS is the qname chain list produced during parsing. TRIE is a
6978 list of elements built up so far."
6979 (let (head tail pos branch kids)
6980 (dolist (chain chains)
6981 (setq head (car chain)
6983 pos (if (numberp (car tail)) (car tail))
6984 branch (js2-find-if (lambda (n)
6985 (string= (car n) head))
6987 kids (second branch))
6989 ;; case 1: this key isn't in the trie yet
6992 (setcdr (last trie) (list (js2-treeify chain)))
6993 (setq trie (list (js2-treeify chain)))))
6994 ;; case 2: key is present with a single number entry: replace w/ list
6995 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6996 ;; ("<definition>" 20)))
6998 (setcar (cdr branch)
6999 (list (list "<definition-1>" kids)
7001 (list "<definition-2>" pos)
7002 (js2-treeify tail)))))
7003 ;; case 3: key is there (with kids), and we're a number entry
7007 (list (format "<definition-%d>"
7008 (1+ (loop for kid in kids
7009 count (eq ?< (aref (car kid) 0)))))
7011 ;; case 4: key is there with kids, need to merge in our chain
7013 (js2-build-alist-trie (list tail) kids))))
7016 (defun js2-flatten-trie (trie)
7017 "Convert TRIE to imenu-format.
7018 Recurses through nodes, and for each one whose second element is a list,
7019 appends the list's flattened elements to the current element. Also
7020 changes the tails into conses. For instance, this pre-flattened trie
7032 Note that the root of the trie has no key, just a list of chains.
7033 This is also true for the value of any key with multiple children,
7034 e.g. key 'c' in the example above."
7037 (mapcar #'js2-flatten-trie trie))
7039 (if (numberp (second trie))
7040 (cons (car trie) (second trie))
7041 ;; else pop list and append its kids
7042 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7044 (defun js2-build-imenu-index ()
7045 "Turn `js2-imenu-recorder' into an imenu data structure."
7046 (unless (eq js2-imenu-recorder 'empty)
7047 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7048 (result (js2-build-alist-trie chains nil)))
7049 (js2-flatten-trie result))))
7051 (defun js2-test-print-chains (chains)
7052 "Print a list of qname chains.
7053 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7054 i.e. one or more nodes, and an integer position as the list tail."
7055 (mapconcat (lambda (chain)
7057 (mapconcat (lambda (elem)
7058 (if (js2-node-p elem)
7059 (or (js2-node-qname-component elem)
7061 (number-to-string elem)))
7070 (defconst js2-version "1.8.0"
7071 "Version of JavaScript supported, plus minor js2 version.")
7073 (defmacro js2-record-face (face)
7074 "Record a style run of FACE for the current token."
7075 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7077 (defsubst js2-node-end (n)
7078 "Computes the absolute end of node N.
7079 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7080 is only true until the node is added to its parent; i.e., while parsing."
7084 (defsubst js2-record-comment ()
7085 "Record a comment in `js2-scanned-comments'."
7086 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7087 :format js2-ts-comment-type)
7088 js2-scanned-comments)
7089 (when js2-parse-ide-mode
7090 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7092 'font-lock-comment-face))
7093 (when (memq js2-ts-comment-type '(html preprocessor))
7094 ;; Tell cc-engine the bounds of the comment.
7095 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7097 ;; This function is called depressingly often, so it should be fast.
7098 ;; Most of the time it's looking at the same token it peeked before.
7099 (defsubst js2-peek-token ()
7100 "Returns the next token without consuming it.
7101 If previous token was consumed, calls scanner to get new token.
7102 If previous token was -not- consumed, returns it (idempotent).
7104 This function will not return a newline (js2-EOL) - instead, it
7105 gobbles newlines until it finds a non-newline token, and flags
7106 that token as appearing just after a newline.
7108 This function will also not return a js2-COMMENT. Instead, it
7109 records comments found in `js2-scanned-comments'. If the token
7110 returned by this function immediately follows a jsdoc comment,
7111 the token is flagged as such.
7113 Note that this function always returned the un-flagged token!
7114 The flags, if any, are saved in `js2-current-flagged-token'."
7115 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7116 js2-current-token ; most common case - return already-peeked token
7117 (let ((tt (js2-get-token)) ; call scanner
7120 ;; process comments and whitespace
7121 (while (or (= tt js2-EOL)
7126 (if js2-record-comments
7127 (js2-record-comment)))
7128 (setq tt (js2-get-token))) ; call scanner
7129 (setq js2-current-token tt
7130 js2-current-flagged-token (if saw-eol
7131 (logior tt js2-ti-after-eol)
7133 ;; perform lexical fontification as soon as token is scanned
7134 (when js2-parse-ide-mode
7137 (js2-record-face 'js2-error-face))
7138 ((setq face (aref js2-kwd-tokens tt))
7139 (js2-record-face face))
7140 ((and (= tt js2-NAME)
7141 (equal js2-ts-string "undefined"))
7142 (js2-record-face 'font-lock-constant-face))))
7143 tt))) ; return unflagged token
7145 (defsubst js2-peek-flagged-token ()
7146 "Returns the current token along with any flags set for it."
7148 js2-current-flagged-token)
7150 (defsubst js2-consume-token ()
7151 (setq js2-current-flagged-token js2-EOF))
7153 (defsubst js2-next-token ()
7156 (js2-consume-token)))
7158 (defsubst js2-next-flagged-token ()
7160 (prog1 js2-current-flagged-token
7161 (js2-consume-token)))
7163 (defsubst js2-match-token (match)
7164 "Consume and return t if next token matches MATCH, a bytecode.
7165 Returns nil and consumes nothing if MATCH is not the next token."
7166 (if (/= (js2-peek-token) match)
7171 (defsubst js2-valid-prop-name-token (tt)
7173 (and js2-allow-keywords-as-property-names
7175 (aref js2-kwd-tokens tt))))
7177 (defsubst js2-match-prop-name ()
7178 "Consume token and return t if next token is a valid property name.
7179 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7180 is non-nil and it's a keyword token."
7181 (if (js2-valid-prop-name-token (js2-peek-token))
7187 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7188 (if (js2-match-prop-name)
7190 (js2-report-error msg-id nil pos len)
7193 (defsubst js2-peek-token-or-eol ()
7194 "Return js2-EOL if the current token immediately follows a newline.
7195 Else returns the current token. Used in situations where we don't
7196 consider certain token types valid if they are preceded by a newline.
7197 One example is the postfix ++ or -- operator, which has to be on the
7198 same line as its operand."
7199 (let ((tt (js2-peek-token)))
7200 ;; Check for last peeked token flags
7201 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7205 (defsubst js2-set-check-for-label ()
7206 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7207 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7209 (defsubst js2-must-match (token msg-id &optional pos len)
7210 "Match next token to token code TOKEN, or record a syntax error.
7211 MSG-ID is the error message to report if the match fails.
7212 Returns t on match, nil if no match."
7213 (if (js2-match-token token)
7215 (js2-report-error msg-id nil pos len)
7218 (defsubst js2-inside-function ()
7219 (plusp js2-nesting-of-function))
7221 (defsubst js2-set-requires-activation ()
7222 (if (js2-function-node-p js2-current-script-or-fn)
7223 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7225 (defsubst js2-check-activation-name (name token)
7226 (when (js2-inside-function)
7227 ;; skip language-version 1.2 check from Rhino
7228 (if (or (string= "arguments" name)
7229 (and js2-compiler-activation-names ; only used in codegen
7230 (gethash name js2-compiler-activation-names)))
7231 (js2-set-requires-activation))))
7233 (defsubst js2-set-is-generator ()
7234 (if (js2-function-node-p js2-current-script-or-fn)
7235 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7237 (defsubst js2-must-have-xml ()
7238 (unless js2-compiler-xml-available
7239 (js2-report-error "msg.XML.not.available")))
7241 (defsubst js2-push-scope (scope)
7242 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7243 (assert (js2-scope-p scope))
7244 (assert (null (js2-scope-parent-scope scope)))
7245 (assert (not (eq js2-current-scope scope)))
7246 (setf (js2-scope-parent-scope scope) js2-current-scope
7247 js2-current-scope scope))
7249 (defsubst js2-pop-scope ()
7250 (setq js2-current-scope
7251 (js2-scope-parent-scope js2-current-scope)))
7253 (defsubst js2-enter-loop (loop-node)
7254 (push loop-node js2-loop-set)
7255 (push loop-node js2-loop-and-switch-set)
7256 (js2-push-scope loop-node)
7257 ;; Tell the current labeled statement (if any) its statement,
7258 ;; and set the jump target of the first label to the loop.
7259 ;; These are used in `js2-parse-continue' to verify that the
7260 ;; continue target is an actual labeled loop. (And for codegen.)
7261 (when js2-labeled-stmt
7262 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7263 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7264 js2-labeled-stmt))) loop-node)))
7266 (defsubst js2-exit-loop ()
7268 (pop js2-loop-and-switch-set)
7271 (defsubst js2-enter-switch (switch-node)
7272 (push switch-node js2-loop-and-switch-set))
7274 (defsubst js2-exit-switch ()
7275 (pop js2-loop-and-switch-set))
7277 (defun js2-parse (&optional buf cb)
7278 "Tells the js2 parser to parse a region of JavaScript.
7280 BUF is a buffer or buffer name containing the code to parse.
7281 Call `narrow-to-region' first to parse only part of the buffer.
7283 The returned AST root node is given some additional properties:
7284 `node-count' - total number of nodes in the AST
7285 `buffer' - BUF. The buffer it refers to may change or be killed,
7286 so the value is not necessarily reliable.
7288 An optional callback CB can be specified to report parsing
7289 progress. If `(functionp CB)' returns t, it will be called with
7290 the current line number once before parsing begins, then again
7291 each time the lexer reaches a new line number.
7293 CB can also be a list of the form `(symbol cb ...)' to specify
7294 multiple callbacks with different criteria. Each symbol is a
7295 criterion keyword, and the following element is the callback to
7298 :line - called whenever the line number changes
7299 :token - called for each new token consumed
7301 The list of criteria could be extended to include entering or
7302 leaving a statement, an expression, or a function definition."
7303 (if (and cb (not (functionp cb)))
7304 (error "criteria callbacks not yet implemented"))
7305 (let ((inhibit-point-motion-hooks t)
7306 (js2-compiler-xml-available (>= js2-language-version 160))
7307 ;; This is a recursive-descent parser, so give it a big stack.
7308 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7309 (max-specpdl-size (max max-specpdl-size 3000))
7310 (case-fold-search nil)
7312 (or buf (setq buf (current-buffer)))
7313 (message nil) ; clear any error message from previous parse
7316 (setq js2-scanned-comments nil
7317 js2-parsed-errors nil
7318 js2-parsed-warnings nil
7319 js2-imenu-recorder nil
7320 js2-imenu-function-map nil
7323 (setq ast (js2-with-unmodifying-text-property-changes
7325 (unless js2-ts-hit-eof
7326 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7327 (setf (js2-ast-root-errors ast) js2-parsed-errors
7328 (js2-ast-root-warnings ast) js2-parsed-warnings)
7329 ;; if we didn't find any declarations, put a dummy in this list so we
7330 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7331 (unless js2-imenu-recorder
7332 (setq js2-imenu-recorder 'empty))
7333 (run-hooks 'js2-parse-finished-hook)
7336 ;; Corresponds to Rhino's Parser.parse() method.
7337 (defun js2-do-parse ()
7338 "Parse current buffer starting from current point.
7339 Scanner should be initialized."
7340 (let ((pos js2-ts-cursor)
7341 (end js2-ts-cursor) ; in case file is empty
7343 ;; initialize buffer-local parsing vars
7344 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7345 js2-current-script-or-fn root
7346 js2-current-scope root
7347 js2-current-flagged-token js2-EOF
7348 js2-nesting-of-function 0
7349 js2-labeled-stmt nil
7350 js2-recorded-identifiers nil) ; for js2-highlight
7351 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7352 (if (= tt js2-FUNCTION)
7355 (setq n (js2-parse-function (if js2-called-by-compile-function
7356 'FUNCTION_EXPRESSION
7357 'FUNCTION_STATEMENT))))
7358 ;; not a function - parse a statement
7359 (setq n (js2-parse-statement)))
7360 ;; add function or statement to script
7361 (setq end (js2-node-end n))
7362 (js2-block-node-push root n))
7363 ;; add comments to root in lexical order
7364 (when js2-scanned-comments
7365 ;; if we find a comment beyond end of normal kids, use its end
7366 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7367 (dolist (comment js2-scanned-comments)
7368 (push comment (js2-ast-root-comments root))
7369 (js2-node-add-children root comment)))
7370 (setf (js2-node-len root) (- end pos))
7371 ;; Give extensions a chance to muck with things before highlighting starts.
7372 (let ((js2-additional-externs js2-additional-externs))
7373 (dolist (callback js2-post-parse-callbacks)
7375 (js2-highlight-undeclared-vars))
7378 (defun js2-function-parser ()
7380 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7382 (defun js2-parse-function-closure-body (fn-node)
7383 "Parse a JavaScript 1.8 function closure body."
7384 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7386 (js2-report-error "msg.no.brace.body" nil
7387 (js2-node-pos fn-node)
7388 (- js2-ts-cursor (js2-node-pos fn-node)))
7389 (js2-node-add-children fn-node
7390 (setf (js2-function-node-body fn-node)
7391 (js2-parse-expr t))))))
7393 (defun js2-parse-function-body (fn-node)
7394 (js2-must-match js2-LC "msg.no.brace.body"
7395 (js2-node-pos fn-node)
7396 (- js2-ts-cursor (js2-node-pos fn-node)))
7397 (let ((pos js2-token-beg) ; LC position
7398 (pn (make-js2-block-node)) ; starts at LC position
7401 (incf js2-nesting-of-function)
7403 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7406 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7407 (js2-parse-statement)
7409 (js2-parse-function 'FUNCTION_STATEMENT))))
7410 (decf js2-nesting-of-function))
7411 (setq end js2-token-end) ; assume no curly and leave at current token
7412 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7413 (setq end js2-token-end))
7414 (setf (js2-node-pos pn) pos
7415 (js2-node-len pn) (- end pos))
7416 (setf (js2-function-node-body fn-node) pn)
7417 (js2-node-add-children fn-node pn)
7420 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7421 "Declare and fontify destructuring parameters inside NODE.
7422 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7424 ((js2-name-node-p node)
7426 (js2-define-symbol decl-type (js2-name-node-name node)
7427 node ignore-not-in-block)
7429 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7430 (+ leftpos (js2-node-len node))
7432 ((js2-object-node-p node)
7433 (dolist (elem (js2-object-node-elems node))
7434 (js2-define-destruct-symbols
7435 (if (js2-object-prop-node-p elem)
7436 (js2-object-prop-node-right elem)
7437 ;; abbreviated destructuring {a, b}
7439 decl-type face ignore-not-in-block)))
7440 ((js2-array-node-p node)
7441 (dolist (elem (js2-array-node-elems node))
7443 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7444 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7445 (js2-node-len node)))))
7447 (defun js2-parse-function-params (fn-node pos)
7448 (if (js2-match-token js2-RP)
7449 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7450 (let (params len param)
7451 (loop for tt = (js2-peek-token)
7454 ;; destructuring param
7455 ((or (= tt js2-LB) (= tt js2-LC))
7456 (setq param (js2-parse-primary-expr-lhs))
7457 (js2-define-destruct-symbols param
7459 'js2-function-param-face)
7460 (push param params))
7463 (js2-must-match js2-NAME "msg.no.parm")
7464 (js2-record-face 'js2-function-param-face)
7465 (setq param (js2-create-name-node))
7466 (js2-define-symbol js2-LP js2-ts-string param)
7467 (push param params)))
7469 (js2-match-token js2-COMMA))
7470 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7471 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7473 (js2-node-add-children fn-node p)
7474 (push p (js2-function-node-params fn-node))))))
7476 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7477 "Possibly show inconsistent-return warning.
7478 Last token scanned is the close-curly for the function body."
7479 (when (and js2-mode-show-strict-warnings
7480 js2-strict-inconsistent-return-warning
7481 (not (js2-has-consistent-return-usage
7482 (js2-function-node-body fn-node))))
7483 ;; Have it extend from close-curly to bol or beginning of block.
7484 (let ((pos (save-excursion
7485 (goto-char js2-token-end)
7486 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7488 (end js2-token-end))
7489 (if (plusp (js2-name-node-length name))
7490 (js2-add-strict-warning "msg.no.return.value"
7491 (js2-name-node-name name) pos end)
7492 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7494 (defun js2-parse-function (function-type)
7495 "Function parser. FUNCTION-TYPE is a symbol."
7496 (let ((pos js2-token-beg) ; start of 'function' keyword
7502 (synthetic-type function-type)
7504 ;; parse function name, expression, or non-name (anonymous)
7506 ;; function foo(...)
7507 ((js2-match-token js2-NAME)
7508 (setq name (js2-create-name-node t)
7509 name-beg js2-token-beg
7510 name-end js2-token-end)
7511 (unless (js2-match-token js2-LP)
7512 (when js2-allow-member-expr-as-function-name
7513 ;; function foo.bar(...)
7514 (setq member-expr-node name
7516 member-expr-node (js2-parse-member-expr-tail
7517 nil member-expr-node)))
7518 (js2-must-match js2-LP "msg.no.paren.parms")))
7519 ((js2-match-token js2-LP)
7520 nil) ; anonymous function: leave name as null
7522 ;; function random-member-expr(...)
7523 (when js2-allow-member-expr-as-function-name
7524 ;; Note that memberExpr can not start with '(' like
7525 ;; in function (1+2).toString(), because 'function (' already
7526 ;; processed as anonymous function
7527 (setq member-expr-node (js2-parse-member-expr)))
7528 (js2-must-match js2-LP "msg.no.paren.parms")))
7529 (if (= js2-current-token js2-LP) ; eventually matched LP?
7530 (setq lp js2-token-beg))
7531 (if member-expr-node
7533 (setq synthetic-type 'FUNCTION_EXPRESSION)
7534 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7536 (js2-set-face name-beg name-end
7537 'font-lock-function-name-face 'record)))
7538 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7539 (plusp (js2-name-node-length name)))
7540 ;; Function statements define a symbol in the enclosing scope
7541 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7542 (setf fn-node (make-js2-function-node :pos pos
7545 :lp (if lp (- lp pos))))
7546 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7547 ;; 1. Nested functions are not affected by the dynamic scope flag
7548 ;; as dynamic scope is already a parent of their scope.
7549 ;; 2. Functions defined under the with statement also immune to
7550 ;; this setup, in which case dynamic scope is ignored in favor
7551 ;; of the with object.
7552 (setf (js2-function-node-ignore-dynamic fn-node) t))
7553 ;; dynamically bind all the per-function variables
7554 (let ((js2-current-script-or-fn fn-node)
7555 (js2-current-scope fn-node)
7556 (js2-nesting-of-with 0)
7560 js2-loop-and-switch-set)
7561 (js2-parse-function-params fn-node pos)
7562 (if (and (>= js2-language-version 180)
7563 (/= (js2-peek-token) js2-LC))
7564 (js2-parse-function-closure-body fn-node)
7565 (js2-parse-function-body fn-node))
7567 (js2-node-add-children fn-node name))
7568 (js2-check-inconsistent-return-warning fn-node name)
7569 ;; Function expressions define a name only in the body of the
7570 ;; function, and only if not hidden by a parameter name
7572 (eq synthetic-type 'FUNCTION_EXPRESSION)
7573 (null (js2-scope-get-symbol js2-current-scope
7574 (js2-name-node-name name))))
7575 (js2-define-symbol js2-FUNCTION
7576 (js2-name-node-name name)
7579 (not (eq function-type 'FUNCTION_EXPRESSION)))
7580 (js2-record-imenu-functions fn-node)))
7581 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7582 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7583 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7584 ;; We wait until after parsing the function to set its parent scope,
7585 ;; since `js2-define-symbol' needs the defining-scope check to stop
7586 ;; at the function boundary when checking for redeclarations.
7587 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7590 (defun js2-parse-statements (&optional parent)
7591 "Parse a statement list. Last token consumed must be js2-LC.
7593 PARENT can be a `js2-block-node', in which case the statements are
7594 appended to PARENT. Otherwise a new `js2-block-node' is created
7597 This function does not match the closing js2-RC: the caller
7598 matches the RC so it can provide a suitable error message if not
7599 matched. This means it's up to the caller to set the length of
7600 the node to include the closing RC. The node start pos is set to
7601 the absolute buffer start position, and the caller should fix it
7602 up to be relative to the parent node. All children of this block
7603 node are given relative start positions and correct lengths."
7604 (let ((pn (or parent (make-js2-block-node)))
7606 (setf (js2-node-pos pn) js2-token-beg)
7607 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7609 (js2-block-node-push pn (js2-parse-statement)))
7612 (defun js2-parse-statement ()
7613 (let (tt pn beg end)
7614 ;; coarse-grained user-interrupt check - needs work
7615 (and js2-parse-interruptable-p
7616 (zerop (% (incf js2-parse-stmt-count)
7617 js2-statements-per-pause))
7619 (throw 'interrupted t))
7620 (setq pn (js2-statement-helper))
7621 ;; no-side-effects warning check
7622 (unless (js2-node-has-side-effects pn)
7623 (setq end (js2-node-end pn))
7626 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7627 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7630 ;; These correspond to the switch cases in Parser.statementHelper
7631 (defconst js2-parsers
7632 (let ((parsers (make-vector js2-num-tokens
7633 #'js2-parse-expr-stmt)))
7634 (aset parsers js2-BREAK #'js2-parse-break)
7635 (aset parsers js2-CONST #'js2-parse-const-var)
7636 (aset parsers js2-CONTINUE #'js2-parse-continue)
7637 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7638 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7639 (aset parsers js2-DO #'js2-parse-do)
7640 (aset parsers js2-FOR #'js2-parse-for)
7641 (aset parsers js2-FUNCTION #'js2-function-parser)
7642 (aset parsers js2-IF #'js2-parse-if)
7643 (aset parsers js2-LC #'js2-parse-block)
7644 (aset parsers js2-LET #'js2-parse-let-stmt)
7645 (aset parsers js2-NAME #'js2-parse-name-or-label)
7646 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7647 (aset parsers js2-SEMI #'js2-parse-semi)
7648 (aset parsers js2-SWITCH #'js2-parse-switch)
7649 (aset parsers js2-THROW #'js2-parse-throw)
7650 (aset parsers js2-TRY #'js2-parse-try)
7651 (aset parsers js2-VAR #'js2-parse-const-var)
7652 (aset parsers js2-WHILE #'js2-parse-while)
7653 (aset parsers js2-WITH #'js2-parse-with)
7654 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7656 "A vector mapping token types to parser functions.")
7658 (defsubst js2-parse-warn-missing-semi (beg end)
7659 (and js2-mode-show-strict-warnings
7660 js2-strict-missing-semi-warning
7661 (js2-add-strict-warning
7662 "msg.missing.semi" nil
7663 ;; back up to beginning of statement or line
7664 (max beg (save-excursion
7669 (defconst js2-no-semi-insertion
7681 "List of tokens that don't do automatic semicolon insertion.")
7683 (defconst js2-autoinsert-semi-and-warn
7684 (list js2-ERROR js2-EOF js2-RC))
7686 (defun js2-statement-helper ()
7687 (let* ((tt (js2-peek-token))
7690 (parser (if (= tt js2-ERROR)
7692 (aref js2-parsers tt)))
7695 ;; If the statement is set, then it's been told its label by now.
7696 (and js2-labeled-stmt
7697 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7698 (setq js2-labeled-stmt nil))
7699 (setq pn (funcall parser))
7700 ;; Don't do auto semi insertion for certain statement types.
7701 (unless (or (memq first-tt js2-no-semi-insertion)
7702 (js2-labeled-stmt-node-p pn))
7703 (js2-auto-insert-semicolon pn))
7706 (defun js2-auto-insert-semicolon (pn)
7707 (let* ((tt-flagged (js2-peek-flagged-token))
7708 (tt (logand tt-flagged js2-clear-ti-mask))
7709 (pos (js2-node-pos pn)))
7712 ;; Consume ';' as a part of expression
7714 ;; extend the node bounds to include the semicolon.
7715 (setf (js2-node-len pn) (- js2-token-end pos)))
7716 ((memq tt js2-autoinsert-semi-and-warn)
7718 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7720 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7721 ;; Report error if no EOL or autoinsert ';' otherwise
7722 (js2-report-error "msg.no.semi.stmt")
7723 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7725 (defun js2-parse-condition ()
7726 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7727 The parens are discarded and the expression node is returned.
7728 The `pos' field of the return value is set to an absolute position
7729 that must be fixed up by the caller.
7730 Return value is a list (EXPR LP RP), with absolute paren positions."
7732 (if (js2-must-match js2-LP "msg.no.paren.cond")
7733 (setq lp js2-token-beg))
7734 (setq pn (js2-parse-expr))
7735 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7736 (setq rp js2-token-beg))
7737 ;; Report strict warning on code like "if (a = 7) ..."
7738 (if (and js2-strict-cond-assign-warning
7739 (js2-assign-node-p pn))
7740 (js2-add-strict-warning "msg.equal.as.assign" nil
7742 (+ (js2-node-pos pn)
7743 (js2-node-len pn))))
7746 (defun js2-parse-if ()
7747 "Parser for if-statement. Last matched token must be js2-IF."
7748 (let ((pos js2-token-beg)
7756 (setq cond (js2-parse-condition)
7757 if-true (js2-parse-statement)
7758 if-false (if (js2-match-token js2-ELSE)
7760 (setq else-pos (- js2-token-beg pos))
7761 (js2-parse-statement)))
7762 end (js2-node-end (or if-false if-true))
7763 pn (make-js2-if-node :pos pos
7765 :condition (car cond)
7769 :lp (js2-relpos (second cond) pos)
7770 :rp (js2-relpos (third cond) pos)))
7771 (js2-node-add-children pn (car cond) if-true if-false)
7774 (defun js2-parse-switch ()
7775 "Parser for if-statement. Last matched token must be js2-SWITCH."
7776 (let ((pos js2-token-beg)
7789 (if (js2-must-match js2-LP "msg.no.paren.switch")
7790 (setq lp js2-token-beg))
7791 (setq discriminant (js2-parse-expr)
7792 pn (make-js2-switch-node :discriminant discriminant
7794 :lp (js2-relpos lp pos)))
7795 (js2-node-add-children pn discriminant)
7796 (js2-enter-switch pn)
7799 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7800 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7801 (js2-must-match js2-LC "msg.no.brace.switch")
7804 (setq tt (js2-next-token)
7805 case-pos js2-token-beg)
7808 (setf (js2-node-len pn) (- js2-token-end pos))
7809 (throw 'break nil)) ; done
7811 (setq case-expr (js2-parse-expr))
7812 (js2-must-match js2-COLON "msg.no.colon.case"))
7815 (js2-report-error "msg.double.switch.default"))
7818 (js2-must-match js2-COLON "msg.no.colon.case"))
7820 (js2-report-error "msg.bad.switch")
7821 (throw 'break nil)))
7822 (setq case-node (make-js2-case-node :pos case-pos
7823 :len (- js2-token-end case-pos)
7825 (js2-node-add-children case-node case-expr)
7826 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7830 (setf stmt (js2-parse-statement)
7831 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7832 (js2-block-node-push case-node stmt))
7833 (push case-node cases)))
7834 ;; add cases last, as pushing reverses the order to be correct
7836 (js2-node-add-children pn kid)
7837 (push kid (js2-switch-node-cases pn)))
7839 (js2-exit-switch))))
7841 (defun js2-parse-while ()
7842 "Parser for while-statement. Last matched token must be js2-WHILE."
7843 (let ((pos js2-token-beg)
7844 (pn (make-js2-while-node))
7851 (setf cond (js2-parse-condition)
7852 (js2-while-node-condition pn) (car cond)
7853 body (js2-parse-statement)
7854 (js2-while-node-body pn) body
7855 (js2-node-len pn) (- (js2-node-end body) pos)
7856 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7857 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7858 (js2-node-add-children pn body (car cond)))
7862 (defun js2-parse-do ()
7863 "Parser for do-statement. Last matched token must be js2-DO."
7864 (let ((pos js2-token-beg)
7865 (pn (make-js2-do-node))
7873 (setq body (js2-parse-statement))
7874 (js2-must-match js2-WHILE "msg.no.while.do")
7875 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7876 cond (js2-parse-condition)
7877 (js2-do-node-condition pn) (car cond)
7878 (js2-do-node-body pn) body
7880 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7881 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7882 (js2-node-add-children pn (car cond) body))
7884 ;; Always auto-insert semicolon to follow SpiderMonkey:
7885 ;; It is required by ECMAScript but is ignored by the rest of
7886 ;; world; see bug 238945
7887 (if (js2-match-token js2-SEMI)
7888 (setq end js2-ts-cursor))
7889 (setf (js2-node-len pn) (- end pos))
7892 (defun js2-parse-for ()
7893 "Parser for for-statement. Last matched token must be js2-FOR.
7894 Parses for, for-in, and for each-in statements."
7895 (let ((for-pos js2-token-beg)
7902 init ; Node init is also foo in 'foo in object'
7903 cond ; Node cond is also object in 'foo in object'
7904 incr ; 3rd section of for-loop initializer
7910 ;; See if this is a for each () instead of just a for ()
7911 (when (js2-match-token js2-NAME)
7912 (if (string= "each" js2-ts-string)
7915 each-pos (- js2-token-beg for-pos)) ; relative
7916 (js2-record-face 'font-lock-keyword-face))
7917 (js2-report-error "msg.no.paren.for")))
7918 (if (js2-must-match js2-LP "msg.no.paren.for")
7919 (setq lp (- js2-token-beg for-pos)))
7920 (setq tt (js2-peek-token))
7921 ;; 'for' makes local scope
7922 (js2-push-scope (make-js2-scope))
7924 ;; parse init clause
7925 (let ((js2-in-for-init t)) ; set as dynamic variable
7928 (setq init (make-js2-empty-expr-node)))
7929 ((or (= tt js2-VAR) (= tt js2-LET))
7931 (setq init (js2-parse-variables tt js2-token-beg)))
7933 (setq init (js2-parse-expr)))))
7934 (if (js2-match-token js2-IN)
7936 in-pos (- js2-token-beg for-pos)
7937 ;; scope of iteration target object is not the scope we've created above.
7938 ;; stash current scope temporary.
7939 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7940 (js2-parse-expr))) ; object over which we're iterating
7941 ;; else ordinary for loop - parse cond and incr
7942 (js2-must-match js2-SEMI "msg.no.semi.for")
7943 (setq cond (if (= (js2-peek-token) js2-SEMI)
7944 (make-js2-empty-expr-node) ; no loop condition
7946 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7947 (setq tmp-pos js2-token-end
7948 incr (if (= (js2-peek-token) js2-RP)
7949 (make-js2-empty-expr-node :pos tmp-pos)
7951 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7952 (setq rp (- js2-token-beg for-pos)))
7954 (setq pn (make-js2-for-node :init init
7959 ;; cond could be null if 'in obj' got eaten by the init node.
7960 (if (js2-infix-node-p init)
7961 ;; it was (foo in bar) instead of (var foo in bar)
7962 (setq cond (js2-infix-node-right init)
7963 init (js2-infix-node-left init))
7964 (if (and (js2-var-decl-node-p init)
7965 (> (length (js2-var-decl-node-kids init)) 1))
7966 (js2-report-error "msg.mult.index")))
7967 (setq pn (make-js2-for-in-node :iterator init
7970 :foreach-p is-for-each
7977 ;; We have to parse the body -after- creating the loop node,
7978 ;; so that the loop node appears in the js2-loop-set, allowing
7979 ;; break/continue statements to find the enclosing loop.
7980 (setf body (js2-parse-statement)
7981 (js2-loop-node-body pn) body
7982 (js2-node-pos pn) for-pos
7983 (js2-node-len pn) (- (js2-node-end body) for-pos))
7984 (js2-node-add-children pn init cond incr body))
7990 (defun js2-parse-try ()
7991 "Parser for try-statement. Last matched token must be js2-TRY."
7992 (let ((try-pos js2-token-beg)
8010 (if (/= (js2-peek-token) js2-LC)
8011 (js2-report-error "msg.no.brace.try"))
8012 (setq try-block (js2-parse-statement)
8013 try-end (js2-node-end try-block)
8014 peek (js2-peek-token))
8017 (while (js2-match-token js2-CATCH)
8018 (setq catch-pos js2-token-beg
8023 (if saw-default-catch
8024 (js2-report-error "msg.catch.unreachable"))
8025 (if (js2-must-match js2-LP "msg.no.paren.catch")
8026 (setq lp (- js2-token-beg catch-pos)))
8027 (js2-push-scope (make-js2-scope))
8028 (let ((tt (js2-peek-token)))
8030 ;; destructuring pattern
8031 ;; catch ({ message, file }) { ... }
8032 ((or (= tt js2-LB) (= tt js2-LC))
8034 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8038 (js2-must-match js2-NAME "msg.bad.catchcond")
8039 (setq param (js2-create-name-node))
8040 (js2-define-symbol js2-LET js2-ts-string param))))
8042 (if (js2-match-token js2-IF)
8043 (setq guard-kwd (- js2-token-beg catch-pos)
8044 catch-cond (js2-parse-expr))
8045 (setq saw-default-catch t))
8046 (if (js2-must-match js2-RP "msg.bad.catchcond")
8047 (setq rp (- js2-token-beg catch-pos)))
8048 (js2-must-match js2-LC "msg.no.brace.catchblock")
8049 (setq block (js2-parse-statements)
8050 try-end (js2-node-end block)
8051 catch-node (make-js2-catch-node :pos catch-pos
8053 :guard-expr catch-cond
8054 :guard-kwd guard-kwd
8059 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8060 (setq try-end js2-token-beg))
8061 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8062 (js2-node-len catch-node) (- try-end catch-pos))
8063 (js2-node-add-children catch-node param catch-cond block)
8064 (push catch-node catch-blocks)))
8065 ((/= peek js2-FINALLY)
8066 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8067 (js2-node-pos try-block)
8068 (- (setq try-end (js2-node-end try-block))
8069 (js2-node-pos try-block)))))
8070 (when (js2-match-token js2-FINALLY)
8071 (setq finally-pos js2-token-beg
8072 block (js2-parse-statement)
8073 try-end (js2-node-end block)
8074 finally-block (make-js2-finally-node :pos finally-pos
8075 :len (- try-end finally-pos)
8077 (js2-node-add-children finally-block block))
8078 (setq pn (make-js2-try-node :pos try-pos
8079 :len (- try-end try-pos)
8080 :try-block try-block
8081 :finally-block finally-block))
8082 (js2-node-add-children pn try-block finally-block)
8083 ;; push them onto the try-node, which reverses and corrects their order
8084 (dolist (cb catch-blocks)
8085 (js2-node-add-children pn cb)
8086 (push cb (js2-try-node-catch-clauses pn)))
8089 (defun js2-parse-throw ()
8090 "Parser for throw-statement. Last matched token must be js2-THROW."
8091 (let ((pos js2-token-beg)
8095 (if (= (js2-peek-token-or-eol) js2-EOL)
8096 ;; ECMAScript does not allow new lines before throw expression,
8098 (js2-report-error "msg.bad.throw.eol"))
8099 (setq expr (js2-parse-expr)
8100 pn (make-js2-throw-node :pos pos
8101 :len (- (js2-node-end expr) pos)
8103 (js2-node-add-children pn expr)
8106 (defsubst js2-match-jump-label-name (label-name)
8107 "If break/continue specified a label, return that label's labeled stmt.
8108 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8109 does not match an existing label, reports an error and returns nil."
8110 (let ((bundle (cdr (assoc label-name js2-label-set))))
8112 (js2-report-error "msg.undef.label"))
8115 (defun js2-parse-break ()
8116 "Parser for break-statement. Last matched token must be js2-BREAK."
8117 (let ((pos js2-token-beg)
8119 break-target ; statement to break from
8120 break-label ; in "break foo", name-node representing the foo
8121 labels ; matching labeled statement to break to
8123 (js2-consume-token) ; `break'
8124 (when (eq (js2-peek-token-or-eol) js2-NAME)
8126 (setq break-label (js2-create-name-node)
8127 end (js2-node-end break-label)
8128 ;; matchJumpLabelName only matches if there is one
8129 labels (js2-match-jump-label-name js2-ts-string)
8130 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8131 (unless (or break-target break-label)
8132 ;; no break target specified - try for innermost enclosing loop/switch
8133 (if (null js2-loop-and-switch-set)
8135 (js2-report-error "msg.bad.break" nil pos (length "break")))
8136 (setq break-target (car js2-loop-and-switch-set))))
8137 (setq pn (make-js2-break-node :pos pos
8140 :target break-target))
8141 (js2-node-add-children pn break-label) ; but not break-target
8144 (defun js2-parse-continue ()
8145 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8146 (let ((pos js2-token-beg)
8148 label ; optional user-specified label, a `js2-name-node'
8149 labels ; current matching labeled stmt, if any
8150 target ; the `js2-loop-node' target of this continue stmt
8152 (js2-consume-token) ; `continue'
8153 (when (= (js2-peek-token-or-eol) js2-NAME)
8155 (setq label (js2-create-name-node)
8156 end (js2-node-end label)
8157 ;; matchJumpLabelName only matches if there is one
8158 labels (js2-match-jump-label-name js2-ts-string)))
8160 ((null labels) ; no current label to go to
8161 (if (null js2-loop-set) ; no loop to continue to
8162 (js2-report-error "msg.continue.outside" nil pos
8163 (length "continue"))
8164 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8166 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8167 (setq target (js2-labeled-stmt-node-stmt labels))
8168 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8169 (setq pn (make-js2-continue-node :pos pos
8173 (js2-node-add-children pn label) ; but not target - it's not our child
8176 (defun js2-parse-with ()
8177 "Parser for with-statement. Last matched token must be js2-WITH."
8179 (let ((pos js2-token-beg)
8181 (if (js2-must-match js2-LP "msg.no.paren.with")
8182 (setq lp js2-token-beg))
8183 (setq obj (js2-parse-expr))
8184 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8185 (setq rp js2-token-beg))
8186 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8187 (setq body (js2-parse-statement)))
8188 (setq pn (make-js2-with-node :pos pos
8189 :len (- (js2-node-end body) pos)
8192 :lp (js2-relpos lp pos)
8193 :rp (js2-relpos rp pos)))
8194 (js2-node-add-children pn obj body)
8197 (defun js2-parse-const-var ()
8198 "Parser for var- or const-statement.
8199 Last matched token must be js2-CONST or js2-VAR."
8200 (let ((tt (js2-peek-token))
8205 (setq expr (js2-parse-variables tt js2-token-beg)
8206 pn (make-js2-expr-stmt-node :pos pos
8207 :len (- (js2-node-end expr) pos)
8209 (js2-node-add-children pn expr)
8212 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8213 (let ((pn (make-js2-expr-stmt-node :pos pos
8214 :len (js2-node-len expr)
8215 :type (if (js2-inside-function)
8220 (js2-node-add-children pn expr))
8223 (defun js2-parse-let-stmt ()
8224 "Parser for let-statement. Last matched token must be js2-LET."
8226 (let ((pos js2-token-beg)
8229 (if (= (js2-peek-token) js2-LP)
8230 ;; let expression in statement context
8231 (setq expr (js2-parse-let pos 'statement)
8232 pn (js2-wrap-with-expr-stmt pos expr t))
8233 ;; else we're looking at a statement like let x=6, y=7;
8234 (setf expr (js2-parse-variables js2-LET pos)
8235 pn (js2-wrap-with-expr-stmt pos expr t)
8236 (js2-node-type pn) js2-EXPR_RESULT))
8239 (defun js2-parse-ret-yield ()
8240 (js2-parse-return-or-yield (js2-peek-token) nil))
8242 (defconst js2-parse-return-stmt-enders
8243 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8245 (defsubst js2-now-all-set (before after mask)
8246 "Return whether or not the bits in the mask have changed to all set.
8247 BEFORE is bits before change, AFTER is bits after change, and MASK is
8248 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8250 (and (/= (logand before mask) mask)
8251 (= (logand after mask) mask)))
8253 (defun js2-parse-return-or-yield (tt expr-context)
8254 (let ((pos js2-token-beg)
8256 (before js2-end-flags)
8257 (inside-function (js2-inside-function))
8261 (unless inside-function
8262 (js2-report-error (if (eq tt js2-RETURN)
8266 ;; This is ugly, but we don't want to require a semicolon.
8267 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8268 (setq e (js2-parse-expr)
8269 end (js2-node-end e)))
8272 (js2-set-flag js2-end-flags (if (null e)
8274 js2-end-returns-value))
8275 (setq ret (make-js2-return-node :pos pos
8278 (js2-node-add-children ret e)
8279 ;; See if we need a strict mode warning.
8280 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8281 ;; more thorough and accurate than this before/after flag check.
8282 ;; E.g. if there's a finally-block that always returns, we shouldn't
8283 ;; show a warning generated by inconsistent returns in the catch blocks.
8284 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8285 ;; so we know which returns/yields to highlight, and we should get rid of
8286 ;; all the checking in `js2-parse-return-or-yield'.
8287 (if (and js2-strict-inconsistent-return-warning
8288 (js2-now-all-set before js2-end-flags
8289 (logior js2-end-returns js2-end-returns-value)))
8290 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8292 (unless (js2-inside-function)
8293 (js2-report-error "msg.bad.yield"))
8294 (js2-set-flag js2-end-flags js2-end-yields)
8295 (setq ret (make-js2-yield-node :pos pos
8298 (js2-node-add-children ret e)
8299 (unless expr-context
8301 ret (js2-wrap-with-expr-stmt pos e t))
8302 (js2-set-requires-activation)
8303 (js2-set-is-generator))))
8304 ;; see if we are mixing yields and value returns.
8305 (when (and inside-function
8306 (js2-now-all-set before js2-end-flags
8307 (logior js2-end-yields js2-end-returns-value)))
8308 (setq name (js2-function-name js2-current-script-or-fn))
8309 (if (zerop (length name))
8310 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8311 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8314 (defun js2-parse-debugger ()
8316 (make-js2-keyword-node :type js2-DEBUGGER))
8318 (defun js2-parse-block ()
8319 "Parser for a curly-delimited statement block.
8320 Last token matched must be js2-LC."
8321 (let ((pos js2-token-beg)
8322 (pn (make-js2-scope)))
8327 (js2-parse-statements pn)
8328 (js2-must-match js2-RC "msg.no.brace.block")
8329 (setf (js2-node-len pn) (- js2-token-end pos)))
8333 ;; for js2-ERROR too, to have a node for error recovery to work on
8334 (defun js2-parse-semi ()
8335 "Parse a statement or handle an error.
8336 Last matched token is js-SEMI or js-ERROR."
8337 (let ((tt (js2-peek-token)) pos len)
8339 (if (eq tt js2-SEMI)
8340 (make-js2-empty-expr-node :len 1)
8341 (setq pos js2-token-beg
8342 len (- js2-token-beg pos))
8343 (js2-report-error "msg.syntax" nil pos len)
8344 (make-js2-error-node :pos pos :len len))))
8346 (defun js2-parse-default-xml-namespace ()
8347 "Parse a `default xml namespace = <expr>' e4x statement."
8348 (let ((pos js2-token-beg)
8349 end len expr unary es)
8352 (js2-set-requires-activation)
8353 (setq len (- js2-ts-cursor pos))
8354 (unless (and (js2-match-token js2-NAME)
8355 (string= js2-ts-string "xml"))
8356 (js2-report-error "msg.bad.namespace" nil pos len))
8357 (unless (and (js2-match-token js2-NAME)
8358 (string= js2-ts-string "namespace"))
8359 (js2-report-error "msg.bad.namespace" nil pos len))
8360 (unless (js2-match-token js2-ASSIGN)
8361 (js2-report-error "msg.bad.namespace" nil pos len))
8362 (setq expr (js2-parse-expr)
8363 end (js2-node-end expr)
8364 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8368 (js2-node-add-children unary expr)
8369 (make-js2-expr-stmt-node :pos pos
8373 (defun js2-record-label (label bundle)
8374 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8376 (let ((name (js2-label-node-name label))
8379 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8380 ;; flag both labels if possible when used in editing mode
8381 (if (and js2-parse-ide-mode
8382 (setq dup (js2-get-label-by-name labeled-stmt name)))
8383 (js2-report-error "msg.dup.label" nil
8384 (js2-node-abs-pos dup) (js2-node-len dup)))
8385 (js2-report-error "msg.dup.label" nil
8386 (js2-node-pos label) (js2-node-len label)))
8387 (js2-labeled-stmt-node-add-label bundle label)
8388 (js2-node-add-children bundle label)
8389 ;; Add one reference to the bundle per label in `js2-label-set'
8390 (push (cons name bundle) js2-label-set)))
8392 (defun js2-parse-name-or-label ()
8393 "Parser for identifier or label. Last token matched must be js2-NAME.
8394 Called when we found a name in a statement context. If it's a label, we gather
8395 up any following labels and the next non-label statement into a
8396 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8397 expression and return it wrapped in a `js2-expr-stmt-node'."
8398 (let ((pos js2-token-beg)
8405 ;; set check for label and call down to `js2-parse-primary-expr'
8406 (js2-set-check-for-label)
8407 (setq expr (js2-parse-expr))
8408 (if (/= (js2-node-type expr) js2-LABEL)
8409 ;; Parsed non-label expression - wrap with expression stmt.
8410 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8411 ;; else parsed a label
8412 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8413 (js2-record-label expr bundle)
8414 ;; look for more labels
8415 (while (and continue (= (js2-peek-token) js2-NAME))
8416 (js2-set-check-for-label)
8417 (setq expr (js2-parse-expr))
8418 (if (/= (js2-node-type expr) js2-LABEL)
8420 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8422 (js2-auto-insert-semicolon stmt))
8423 (js2-record-label expr bundle)))
8424 ;; no more labels; now parse the labeled statement
8427 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8428 (setq stmt (js2-statement-helper))))
8429 ;; remove the labels for this statement from the global set
8430 (dolist (label (js2-labeled-stmt-node-labels bundle))
8431 (setq js2-label-set (remove label js2-label-set))))
8432 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8433 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8434 (js2-node-add-children bundle stmt)
8437 (defun js2-parse-expr-stmt ()
8438 "Default parser in statement context, if no recognized statement found."
8439 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8441 (defun js2-parse-variables (decl-type pos)
8442 "Parse a comma-separated list of variable declarations.
8443 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8445 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8446 For 'var' or 'const', the keyword should be the token last scanned.
8448 POS is the position where the node should start. It's sometimes the
8449 var/const/let keyword, and other times the beginning of the first token
8450 in the first variable declaration.
8452 Returns the parsed `js2-var-decl-node' expression node."
8453 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8465 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8466 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8467 ;; var {a, b} = baz;
8469 (setq destructuring nil
8472 kid-pos js2-token-beg
8475 (if (or (= tt js2-LB) (= tt js2-LC))
8476 ;; Destructuring assignment, e.g., var [a, b] = ...
8477 (setq destructuring (js2-parse-primary-expr-lhs)
8478 end (js2-node-end destructuring))
8479 ;; Simple variable name
8480 (when (js2-must-match js2-NAME "msg.bad.var")
8481 (setq name (js2-create-name-node)
8485 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8486 (when (js2-match-token js2-ASSIGN)
8487 (setq init (js2-parse-assign-expr)
8488 end (js2-node-end init))
8489 (if (and js2-parse-ide-mode
8490 (or (js2-object-node-p init)
8491 (js2-function-node-p init)))
8492 (js2-record-imenu-functions init name)))
8494 (js2-set-face nbeg nend (if (js2-function-node-p init)
8495 'font-lock-function-name-face
8496 'font-lock-variable-name-face)
8498 (setq vi (make-js2-var-init-node :pos kid-pos
8499 :len (- end kid-pos)
8503 (if (and (null init) (not js2-in-for-init))
8504 (js2-report-error "msg.destruct.assign.no.init"))
8505 (js2-define-destruct-symbols destructuring
8507 'font-lock-variable-name-face)
8508 (setf (js2-var-init-node-target vi) destructuring))
8509 (setf (js2-var-init-node-target vi) name))
8510 (setf (js2-var-init-node-initializer vi) init)
8511 (js2-node-add-children vi name destructuring init)
8512 (js2-block-node-push result vi)
8513 (unless (js2-match-token js2-COMMA)
8514 (setq continue nil)))
8515 (setf (js2-node-len result) (- end pos))
8518 (defun js2-parse-let (pos &optional stmt-p)
8519 "Parse a let expression or statement.
8520 A let-expression is of the form `let (vars) expr'.
8521 A let-statment is of the form `let (vars) {statements}'.
8522 The third form of let is a variable declaration list, handled
8523 by `js2-parse-variables'."
8524 (let ((pn (make-js2-let-node :pos pos))
8526 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8527 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8531 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8532 (if (js2-must-match js2-RP "msg.no.paren.let")
8533 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8534 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8538 (setf beg js2-token-beg ; position stmt at LC
8539 body (js2-parse-statements))
8540 (js2-must-match js2-RC "msg.no.curly.let")
8541 (setf (js2-node-len body) (- js2-token-end beg)
8542 (js2-node-len pn) (- js2-token-end pos)
8543 (js2-let-node-body pn) body
8544 (js2-node-type pn) js2-LET))
8546 (setf body (js2-parse-expr)
8547 (js2-node-len pn) (- (js2-node-end body) pos)
8548 (js2-let-node-body pn) body))
8549 (js2-node-add-children pn vars body))
8553 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8554 (js2-scope-put-symbol (or scope js2-current-scope)
8556 (make-js2-symbol decl-type name node)))
8558 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8559 "Define a symbol in the current scope.
8560 If NODE is non-nil, it is the AST node associated with the symbol."
8561 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8562 (symbol (if defining-scope
8563 (js2-scope-get-symbol defining-scope name)))
8564 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8566 ((and symbol ; already defined
8567 (or (= sdt js2-CONST) ; old version is const
8568 (= decl-type js2-CONST) ; new version is const
8569 ;; two let-bound vars in this block have same name
8570 (and (= sdt js2-LET)
8571 (eq defining-scope js2-current-scope))))
8574 ((= sdt js2-CONST) "msg.const.redecl")
8575 ((= sdt js2-LET) "msg.let.redecl")
8576 ((= sdt js2-VAR) "msg.var.redecl")
8577 ((= sdt js2-FUNCTION) "msg.function.redecl")
8578 (t "msg.parm.redecl"))
8580 ((= decl-type js2-LET)
8581 (if (and (not ignore-not-in-block)
8582 (or (= (js2-node-type js2-current-scope) js2-IF)
8583 (js2-loop-node-p js2-current-scope)))
8584 (js2-report-error "msg.let.decl.not.in.block")
8585 (js2-define-new-symbol decl-type name node)))
8586 ((or (= decl-type js2-VAR)
8587 (= decl-type js2-CONST)
8588 (= decl-type js2-FUNCTION))
8590 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8591 (js2-add-strict-warning "msg.var.redecl" name)
8592 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8593 (js2-add-strict-warning "msg.var.hides.arg" name)))
8594 (js2-define-new-symbol decl-type name node
8595 js2-current-script-or-fn)))
8596 ((= decl-type js2-LP)
8598 ;; must be duplicate parameter. Second parameter hides the
8599 ;; first, so go ahead and add the second pararameter
8600 (js2-report-warning "msg.dup.parms" name))
8601 (js2-define-new-symbol decl-type name node))
8602 (t (js2-code-bug)))))
8604 (defun js2-parse-expr (&optional oneshot)
8605 (let* ((pn (js2-parse-assign-expr))
8606 (pos (js2-node-pos pn))
8610 (while (and (not oneshot)
8611 (js2-match-token js2-COMMA))
8612 (setq op-pos (- js2-token-beg pos)) ; relative
8613 (if (= (js2-peek-token) js2-YIELD)
8614 (js2-report-error "msg.yield.parenthesized"))
8615 (setq right (js2-parse-assign-expr)
8617 pn (make-js2-infix-node :type js2-COMMA
8619 :len (- js2-ts-cursor pos)
8623 (js2-node-add-children pn left right))
8626 (defun js2-parse-assign-expr ()
8627 (let ((tt (js2-peek-token))
8633 (if (= tt js2-YIELD)
8634 (js2-parse-return-or-yield tt t)
8635 ;; not yield - parse assignment expression
8636 (setq pn (js2-parse-cond-expr)
8637 tt (js2-peek-token))
8638 (when (and (<= js2-first-assign tt)
8639 (<= tt js2-last-assign))
8640 ;; tt express assignment (=, |=, ^=, ..., %=)
8642 (setq op-pos (- js2-token-beg pos) ; relative
8644 right (js2-parse-assign-expr)
8645 pn (make-js2-assign-node :type tt
8647 :len (- (js2-node-end right) pos)
8651 (when js2-parse-ide-mode
8652 (js2-highlight-assign-targets pn left right)
8653 (if (or (js2-function-node-p right)
8654 (js2-object-node-p right))
8655 (js2-record-imenu-functions right left)))
8656 ;; do this last so ide checks above can use absolute positions
8657 (js2-node-add-children pn left right))
8660 (defun js2-parse-cond-expr ()
8661 (let ((pos js2-token-beg)
8662 (pn (js2-parse-or-expr))
8668 (when (js2-match-token js2-HOOK)
8669 (setq q-pos (- js2-token-beg pos)
8670 if-true (js2-parse-assign-expr))
8671 (js2-must-match js2-COLON "msg.no.colon.cond")
8672 (setq c-pos (- js2-token-beg pos)
8673 if-false (js2-parse-assign-expr)
8675 pn (make-js2-cond-node :pos pos
8676 :len (- (js2-node-end if-false) pos)
8677 :test-expr test-expr
8679 :false-expr if-false
8682 (js2-node-add-children pn test-expr if-true if-false))
8685 (defun js2-make-binary (type left parser)
8686 "Helper for constructing a binary-operator AST node.
8687 LEFT is the left-side-expression, already parsed, and the
8688 binary operator should have just been matched.
8689 PARSER is a function to call to parse the right operand,
8690 or a `js2-node' struct if it has already been parsed."
8691 (let* ((pos (js2-node-pos left))
8692 (op-pos (- js2-token-beg pos))
8693 (right (if (js2-node-p parser)
8696 (pn (make-js2-infix-node :type type
8698 :len (- (js2-node-end right) pos)
8702 (js2-node-add-children pn left right)
8705 (defun js2-parse-or-expr ()
8706 (let ((pn (js2-parse-and-expr)))
8707 (when (js2-match-token js2-OR)
8708 (setq pn (js2-make-binary js2-OR
8710 'js2-parse-or-expr)))
8713 (defun js2-parse-and-expr ()
8714 (let ((pn (js2-parse-bit-or-expr)))
8715 (when (js2-match-token js2-AND)
8716 (setq pn (js2-make-binary js2-AND
8718 'js2-parse-and-expr)))
8721 (defun js2-parse-bit-or-expr ()
8722 (let ((pn (js2-parse-bit-xor-expr)))
8723 (while (js2-match-token js2-BITOR)
8724 (setq pn (js2-make-binary js2-BITOR
8726 'js2-parse-bit-xor-expr)))
8729 (defun js2-parse-bit-xor-expr ()
8730 (let ((pn (js2-parse-bit-and-expr)))
8731 (while (js2-match-token js2-BITXOR)
8732 (setq pn (js2-make-binary js2-BITXOR
8734 'js2-parse-bit-and-expr)))
8737 (defun js2-parse-bit-and-expr ()
8738 (let ((pn (js2-parse-eq-expr)))
8739 (while (js2-match-token js2-BITAND)
8740 (setq pn (js2-make-binary js2-BITAND
8742 'js2-parse-eq-expr)))
8745 (defconst js2-parse-eq-ops
8746 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8748 (defun js2-parse-eq-expr ()
8749 (let ((pn (js2-parse-rel-expr))
8751 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8753 (setq pn (js2-make-binary tt
8755 'js2-parse-rel-expr)))
8758 (defconst js2-parse-rel-ops
8759 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8761 (defun js2-parse-rel-expr ()
8762 (let ((pn (js2-parse-shift-expr))
8766 (setq tt (js2-peek-token))
8768 ((and js2-in-for-init (= tt js2-IN))
8769 (setq continue nil))
8770 ((memq tt js2-parse-rel-ops)
8772 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8774 (setq continue nil))))
8777 (defconst js2-parse-shift-ops
8778 (list js2-LSH js2-URSH js2-RSH))
8780 (defun js2-parse-shift-expr ()
8781 (let ((pn (js2-parse-add-expr))
8785 (setq tt (js2-peek-token))
8786 (if (memq tt js2-parse-shift-ops)
8789 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8790 (setq continue nil)))
8793 (defun js2-parse-add-expr ()
8794 (let ((pn (js2-parse-mul-expr))
8798 (setq tt (js2-peek-token))
8799 (if (or (= tt js2-ADD) (= tt js2-SUB))
8802 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8803 (setq continue nil)))
8806 (defconst js2-parse-mul-ops
8807 (list js2-MUL js2-DIV js2-MOD))
8809 (defun js2-parse-mul-expr ()
8810 (let ((pn (js2-parse-unary-expr))
8814 (setq tt (js2-peek-token))
8815 (if (memq tt js2-parse-mul-ops)
8818 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8819 (setq continue nil)))
8822 (defsubst js2-make-unary (type parser &rest args)
8823 "Make a unary node of type TYPE.
8824 PARSER is either a node (for postfix operators) or a function to call
8825 to parse the operand (for prefix operators)."
8826 (let* ((pos js2-token-beg)
8827 (postfix (js2-node-p parser))
8830 (apply parser args)))
8833 (if postfix ; e.g. i++
8834 (setq pos (js2-node-pos expr)
8836 (setq end (js2-node-end expr)))
8837 (setq pn (make-js2-unary-node :type type
8841 (js2-node-add-children pn expr)
8844 (defconst js2-incrementable-node-types
8845 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8846 "Node types that can be the operand of a ++ or -- operator.")
8848 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8849 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8850 js2-incrementable-node-types)
8851 (js2-report-error (if (= tt js2-INC)
8854 nil beg (- end beg))))
8856 (defun js2-parse-unary-expr ()
8857 (let ((tt (js2-peek-token))
8860 ((or (= tt js2-VOID)
8865 (js2-make-unary tt 'js2-parse-unary-expr))
8868 ;; Convert to special POS token in decompiler and parse tree
8869 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8872 ;; Convert to special NEG token in decompiler and parse tree
8873 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8878 (setq beg js2-token-beg
8880 expr (js2-make-unary tt 'js2-parse-member-expr t))
8881 (js2-check-bad-inc-dec tt beg end expr)))
8884 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8887 (make-js2-error-node)) ; try to continue
8889 js2-compiler-xml-available)
8890 ;; XML stream encountered in expression.
8892 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8894 (setq pn (js2-parse-member-expr t)
8895 ;; Don't look across a newline boundary for a postfix incop.
8896 tt (js2-peek-token-or-eol))
8897 (when (or (= tt js2-INC) (= tt js2-DEC))
8900 pn (js2-make-unary tt expr))
8901 (js2-node-set-prop pn 'postfix t)
8902 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8905 (defun js2-parse-xml-initializer ()
8906 "Parse an E4X XML initializer.
8907 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8908 Then I'll postprocess the result, depending on whether we're in IDE
8909 mode or codegen mode, and generate the appropriate rewritten AST.
8910 IDE mode uses a rich AST that models the XML structure. Codegen mode
8911 just concatenates everything and makes a new XML or XMLList out of it."
8912 (let ((tt (js2-get-first-xml-token))
8920 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8921 (js2-report-error "msg.syntax"))
8922 (setq pn-xml (make-js2-xml-node))
8925 (setq first-token nil)
8926 (setq tt (js2-get-next-xml-token)))
8928 ;; js2-XML means we found a {expr} in the XML stream.
8929 ;; The js2-ts-string is the XML up to the left-curly.
8931 (push (make-js2-string-node :pos js2-token-beg
8932 :len (- js2-ts-cursor js2-token-beg))
8934 (js2-must-match js2-LC "msg.syntax")
8935 (setq expr-pos js2-ts-cursor
8936 expr (if (eq (js2-peek-token) js2-RC)
8937 (make-js2-empty-expr-node :pos expr-pos)
8939 (js2-must-match js2-RC "msg.syntax")
8940 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8941 :len (js2-node-len expr)
8943 (js2-node-add-children pn expr)
8945 ;; a js2-XMLEND token means we hit the final close-tag.
8947 (push (make-js2-string-node :pos js2-token-beg
8948 :len (- js2-ts-cursor js2-token-beg))
8950 (dolist (kid (nreverse kids))
8951 (js2-block-node-push pn-xml kid))
8952 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8953 (js2-node-pos pn-xml))
8956 (js2-report-error "msg.syntax")
8957 (setq continue nil))))
8961 (defun js2-parse-argument-list ()
8962 "Parse an argument list and return it as a lisp list of nodes.
8963 Returns the list in reverse order. Consumes the right-paren token."
8965 (unless (js2-match-token js2-RP)
8967 (if (= (js2-peek-token) js2-YIELD)
8968 (js2-report-error "msg.yield.parenthesized"))
8969 (push (js2-parse-assign-expr) result)
8971 (js2-match-token js2-COMMA))
8972 (js2-must-match js2-RP "msg.no.paren.arg")
8975 (defun js2-parse-member-expr (&optional allow-call-syntax)
8976 (let ((tt (js2-peek-token))
8986 (setq pn (js2-parse-primary-expr))
8987 ;; parse a 'new' expression
8989 (setq pos js2-token-beg
8991 target (js2-parse-member-expr)
8992 end (js2-node-end target)
8993 pn (make-js2-new-node :pos pos
8996 (js2-node-add-children pn target)
8997 (when (js2-match-token js2-LP)
8998 ;; Add the arguments to pn, if any are supplied.
8999 (setf beg pos ; start of "new" keyword
9001 args (nreverse (js2-parse-argument-list))
9002 (js2-new-node-args pn) args
9004 (js2-new-node-lp pn) (- pos beg)
9005 (js2-new-node-rp pn) (- end 1 beg))
9006 (apply #'js2-node-add-children pn args))
9007 (when (and js2-allow-rhino-new-expr-initializer
9008 (js2-match-token js2-LC))
9009 (setf init (js2-parse-object-literal)
9010 end (js2-node-end init)
9011 (js2-new-node-initializer pn) init)
9012 (js2-node-add-children pn init))
9013 (setf (js2-node-len pn) (- end beg))) ; end outer if
9014 (js2-parse-member-expr-tail allow-call-syntax pn)))
9016 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9017 "Parse a chain of property/array accesses or function calls.
9018 Includes parsing for E4X operators like `..' and `.@'.
9019 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9020 Returns an expression tree that includes PN, the parent node."
9021 (let ((beg (js2-node-pos pn))
9025 (setq tt (js2-peek-token))
9027 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9028 (setq pn (js2-parse-property-access tt pn)))
9029 ((= tt js2-DOTQUERY)
9030 (setq pn (js2-parse-dot-query pn)))
9032 (setq pn (js2-parse-element-get pn)))
9034 (if allow-call-syntax
9035 (setq pn (js2-parse-function-call pn))
9036 (setq continue nil)))
9038 (setq continue nil))))
9039 (if (>= js2-highlight-level 2)
9040 (js2-parse-highlight-member-expr-node pn))
9043 (defun js2-parse-dot-query (pn)
9044 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9045 Last token parsed must be `js2-DOTQUERY'."
9046 (let ((pos (js2-node-pos pn))
9052 (js2-set-requires-activation)
9053 (setq op-pos js2-token-beg
9054 expr (js2-parse-expr)
9055 end (js2-node-end expr)
9056 pn (make-js2-xml-dot-query-node :left pn
9060 (js2-node-add-children pn
9061 (js2-xml-dot-query-node-left pn)
9062 (js2-xml-dot-query-node-right pn))
9063 (if (js2-must-match js2-RP "msg.no.paren")
9064 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9066 (setf (js2-node-len pn) (- end pos))
9069 (defun js2-parse-element-get (pn)
9070 "Parse an element-get expression, e.g. foo[bar].
9071 Last token parsed must be `js2-RB'."
9072 (let ((lb js2-token-beg)
9073 (pos (js2-node-pos pn))
9077 (setq expr (js2-parse-expr))
9078 (if (js2-must-match js2-RB "msg.no.bracket.index")
9079 (setq rb js2-token-beg))
9080 (setq pn (make-js2-elem-get-node :target pn
9083 :lb (js2-relpos lb pos)
9084 :rb (js2-relpos rb pos)
9085 :len (- js2-token-end pos)))
9086 (js2-node-add-children pn
9087 (js2-elem-get-node-target pn)
9088 (js2-elem-get-node-element pn))
9091 (defun js2-parse-function-call (pn)
9093 (pos (js2-node-pos pn)))
9095 (setq pn (make-js2-call-node :pos pos
9097 :lp (- js2-token-beg pos)))
9098 (js2-node-add-children pn (js2-call-node-target pn))
9099 ;; Add the arguments to pn, if any are supplied.
9100 (setf args (nreverse (js2-parse-argument-list))
9101 (js2-call-node-rp pn) (- js2-token-beg pos)
9102 (js2-call-node-args pn) args)
9103 (apply #'js2-node-add-children pn args)
9104 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9107 (defun js2-parse-property-access (tt pn)
9108 "Parse a property access, XML descendants access, or XML attr access."
9109 (let ((member-type-flags 0)
9110 (dot-pos js2-token-beg)
9111 (dot-len (if (= tt js2-DOTDOT) 2 1))
9113 ref ; right side of . or .. operator
9116 (when (= tt js2-DOTDOT)
9118 (setq member-type-flags js2-descendants-flag))
9119 (if (not js2-compiler-xml-available)
9121 (js2-must-match-prop-name "msg.no.name.after.dot")
9122 (setq name (js2-create-name-node t js2-GETPROP)
9123 result (make-js2-prop-get-node :left pn
9126 :len (- js2-token-end
9128 (js2-node-add-children result pn name)
9130 ;; otherwise look for XML operators
9131 (setf result (if (= tt js2-DOT)
9132 (make-js2-prop-get-node)
9133 (make-js2-infix-node :type js2-DOTDOT))
9134 (js2-node-pos result) (js2-node-pos pn)
9135 (js2-infix-node-op-pos result) dot-pos
9136 (js2-infix-node-left result) pn ; do this after setting position
9137 tt (js2-next-token))
9139 ;; needed for generator.throw()
9141 (js2-save-name-token-data js2-token-beg "throw")
9142 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9143 ;; handles: name, ns::name, ns::*, ns::[expr]
9144 ((js2-valid-prop-name-token tt)
9145 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9146 ;; handles: *, *::name, *::*, *::[expr]
9148 (js2-save-name-token-data js2-token-beg "*")
9149 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9150 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9152 (setq result (js2-parse-attribute-access)))
9154 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9156 (setf (js2-node-len result) (- (js2-node-end ref)
9157 (js2-node-pos result))
9158 (js2-infix-node-right result) ref))
9159 (if (js2-infix-node-p result)
9160 (js2-node-add-children result
9161 (js2-infix-node-left result)
9162 (js2-infix-node-right result)))
9165 (defun js2-parse-attribute-access ()
9166 "Parse an E4X XML attribute expression.
9167 This includes expressions of the forms:
9169 @attr @ns::attr @ns::*
9171 @[expr] @*::[expr] @ns::[expr]
9173 Called if we peeked an '@' token."
9174 (let ((tt (js2-next-token))
9175 (at-pos js2-token-beg))
9177 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9178 ((js2-valid-prop-name-token tt)
9179 (js2-parse-property-name at-pos js2-ts-string 0))
9180 ;; handles: @*, @*::name, @*::*, @*::[expr]
9182 (js2-save-name-token-data js2-token-beg "*")
9183 (js2-parse-property-name js2-token-beg "*" 0))
9186 (js2-parse-xml-elem-ref at-pos))
9188 (js2-report-error "msg.no.name.after.xmlAttr")
9189 ;; Avoid cascaded errors that happen if we make an error node here.
9190 (js2-save-name-token-data js2-token-beg "")
9191 (js2-parse-property-name js2-token-beg "" 0)))))
9193 (defun js2-parse-property-name (at-pos s member-type-flags)
9194 "Check if :: follows name in which case it becomes qualified name.
9196 AT-POS is a natural number if we just read an '@' token, else nil.
9197 S is the name or string that was matched: an identifier, 'throw' or '*'.
9198 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9200 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9201 operator, or the name is followed by ::. For a plain name, returns a
9202 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9203 (let ((pos (or at-pos js2-token-beg))
9205 (name (js2-create-name-node t js2-current-token))
9211 (when (js2-match-token js2-COLONCOLON)
9213 colon-pos js2-token-beg
9214 tt (js2-next-token))
9216 ;; handles name::name
9217 ((js2-valid-prop-name-token tt)
9218 (setq name (js2-create-name-node)))
9221 (js2-save-name-token-data js2-token-beg "*")
9222 (setq name (js2-create-name-node)))
9223 ;; handles name::[expr]
9225 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9227 (js2-report-error "msg.no.name.after.coloncolon"))))
9228 (if (and (null ns) (zerop member-type-flags))
9232 (make-js2-xml-prop-ref-node :pos pos
9233 :len (- (js2-node-end name) pos)
9235 :colon-pos colon-pos
9237 (js2-node-add-children pn name))))))
9239 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9240 "Parse the [expr] portion of an xml element reference.
9241 For instance, @[expr], @*::[expr], or ns::[expr]."
9242 (let* ((lb js2-token-beg)
9243 (pos (or at-pos lb))
9245 (expr (js2-parse-expr))
9246 (end (js2-node-end expr))
9248 (if (js2-must-match js2-RB "msg.no.bracket.index")
9249 (setq rb js2-token-beg
9253 (make-js2-xml-elem-ref-node :pos pos
9255 :namespace namespace
9256 :colon-pos colon-pos
9259 :lb (js2-relpos lb pos)
9260 :rb (js2-relpos rb pos)))
9261 (js2-node-add-children pn namespace expr))))
9263 (defsubst js2-parse-primary-expr-lhs ()
9264 (let ((js2-is-in-lhs t))
9265 (js2-parse-primary-expr)))
9267 (defun js2-parse-primary-expr ()
9268 "Parses a literal (leaf) expression of some sort.
9269 Includes complex literals such as functions, object-literals,
9270 array-literals, array comprehensions and regular expressions."
9271 (let ((tt-flagged (js2-next-flagged-token))
9272 pn ; parent node (usually return value)
9274 px-pos ; paren-expr pos
9276 flags ; regexp flags
9278 (setq tt js2-current-token)
9280 ((= tt js2-FUNCTION)
9281 (js2-parse-function 'FUNCTION_EXPRESSION))
9283 (js2-parse-array-literal))
9285 (js2-parse-object-literal))
9287 (js2-parse-let js2-token-beg))
9289 (setq px-pos js2-token-beg
9290 expr (js2-parse-expr))
9291 (js2-must-match js2-RP "msg.no.paren")
9292 (setq pn (make-js2-paren-node :pos px-pos
9294 :len (- js2-token-end px-pos)))
9295 (js2-node-add-children pn (js2-paren-node-expr pn))
9299 (js2-parse-attribute-access))
9301 (js2-parse-name tt-flagged tt))
9303 (make-js2-number-node))
9306 (make-js2-string-node)
9307 (js2-record-face 'font-lock-string-face)))
9308 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9309 ;; Got / or /= which in this context means a regexp literal
9310 (setq px-pos js2-token-beg)
9311 (js2-read-regexp tt)
9312 (setq flags js2-ts-regexp-flags
9313 js2-ts-regexp-flags nil)
9315 (make-js2-regexp-node :pos px-pos
9316 :len (- js2-ts-cursor px-pos)
9317 :value js2-ts-string
9319 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9320 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9321 ((or (= tt js2-NULL)
9325 (make-js2-keyword-node :type tt))
9326 ((= tt js2-RESERVED)
9327 (js2-report-error "msg.reserved.id")
9328 (make-js2-name-node))
9330 ;; the scanner or one of its subroutines reported the error.
9331 (make-js2-error-node))
9333 (setq px-pos (point-at-bol)
9334 len (- js2-ts-cursor px-pos))
9335 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9336 (make-js2-error-node :pos px-pos :len len))
9338 (js2-report-error "msg.syntax")
9339 (make-js2-error-node)))))
9341 (defun js2-parse-name (tt-flagged tt)
9342 (let ((name js2-ts-string)
9343 (name-pos js2-token-beg)
9345 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9346 (= (js2-peek-token) js2-COLON))
9348 ;; Do not consume colon, it is used as unwind indicator
9349 ;; to return to statementHelper.
9350 (make-js2-label-node :pos name-pos
9351 :len (- js2-token-end name-pos)
9353 (js2-set-face name-pos
9355 'font-lock-variable-name-face 'record))
9356 ;; Otherwise not a label, just a name. Unfortunately peeking
9357 ;; the next token to check for a colon has biffed js2-token-beg
9358 ;; and js2-token-end. We store the name's bounds in buffer vars
9359 ;; and `js2-create-name-node' uses them.
9360 (js2-save-name-token-data name-pos name)
9361 (setq node (if js2-compiler-xml-available
9362 (js2-parse-property-name nil name 0)
9363 (js2-create-name-node 'check-activation)))
9364 (if js2-highlight-external-variables
9365 (js2-record-name-node node))
9368 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9369 (js2-add-strict-warning
9371 ;; back up from comma to beginning of line or array/objlit
9373 (js2-node-pos (car elems))
9376 (goto-char comma-pos)
9377 (back-to-indentation)
9381 (defun js2-parse-array-literal ()
9382 (let ((pos js2-token-beg)
9384 (after-lb-or-comma t)
9390 (unless js2-is-in-lhs
9391 (js2-push-scope (make-js2-scope))) ; for array comp
9393 (setq tt (js2-peek-token))
9398 (setq after-comma js2-token-end)
9399 (if (not after-lb-or-comma)
9400 (setq after-lb-or-comma t)
9404 (= tt js2-EOF)) ; prevent infinite loop
9406 (js2-report-error "msg.no.bracket.arg" nil pos)
9407 (js2-consume-token))
9410 pn (make-js2-array-node :pos pos
9411 :len (- js2-ts-cursor pos)
9412 :elems (nreverse elems)))
9413 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9415 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9416 pos elems after-comma)))
9417 ;; destructuring binding
9419 (push (if (or (= tt js2-LC)
9422 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9423 (js2-parse-primary-expr-lhs)
9426 (js2-report-error "msg.bad.var")
9427 (make-js2-error-node))
9429 (setq after-lb-or-comma nil
9432 ((and (>= js2-language-version 170)
9433 (= tt js2-FOR) ; check for array comprehension
9434 (not after-lb-or-comma) ; "for" can't follow a comma
9435 elems ; must have at least 1 element
9436 (not (cdr elems))) ; but no 2nd element
9438 pn (js2-parse-array-comprehension (car elems) pos)))
9442 (unless after-lb-or-comma
9443 (js2-report-error "msg.no.bracket.arg"))
9444 (push (js2-parse-assign-expr) elems)
9445 (setq after-lb-or-comma nil
9447 (unless js2-is-in-lhs
9451 (defun js2-parse-array-comprehension (expr pos)
9452 "Parse a JavaScript 1.7 Array Comprehension.
9453 EXPR is the first expression after the opening left-bracket.
9454 POS is the beginning of the LB token preceding EXPR.
9455 We should have just parsed the 'for' keyword before calling this function."
9463 (while (= (js2-peek-token) js2-FOR)
9464 (let ((prev (car loops))) ; rearrange scope chain
9465 (push (setq loop (js2-parse-array-comp-loop)) loops)
9466 (if prev ; each loop is parent scope to the next one
9467 (setf (js2-scope-parent-scope loop) prev)
9468 ; first loop takes expr scope's parent
9469 (setf (js2-scope-parent-scope (setq first loop))
9470 (js2-scope-parent-scope js2-current-scope)))))
9471 ;; set expr scope's parent to the last loop
9472 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9473 (when (= (js2-peek-token) js2-IF)
9475 (setq if-pos (- js2-token-beg pos) ; relative
9476 filter (js2-parse-condition)))
9477 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9478 (setq result (make-js2-array-comp-node :pos pos
9479 :len (- js2-ts-cursor pos)
9481 :loops (nreverse loops)
9482 :filter (car filter)
9483 :lp (js2-relpos (second filter) pos)
9484 :rp (js2-relpos (third filter) pos)
9486 (apply #'js2-node-add-children result expr (car filter)
9487 (js2-array-comp-node-loops result))
9488 (setq js2-current-scope first) ; pop to the first loop
9491 (defun js2-parse-array-comp-loop ()
9492 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9493 Last token peeked should be the initial FOR."
9494 (let ((pos js2-token-beg)
9495 (pn (make-js2-array-comp-loop-node))
9504 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9508 (when (js2-match-token js2-NAME)
9509 (if (string= js2-ts-string "each")
9512 each-pos (- js2-token-beg pos)) ; relative
9513 (js2-record-face 'font-lock-keyword-face))
9514 (js2-report-error "msg.no.paren.for")))
9515 (if (js2-must-match js2-LP "msg.no.paren.for")
9516 (setq lp (- js2-token-beg pos)))
9517 (setq tt (js2-peek-token))
9521 ;; handle destructuring assignment
9522 (setq iter (js2-parse-primary-expr-lhs))
9523 (js2-define-destruct-symbols iter js2-LET
9524 'font-lock-variable-name-face t))
9525 ((js2-valid-prop-name-token tt)
9527 (setq iter (js2-create-name-node)))
9529 (js2-report-error "msg.bad.var")))
9530 ;; Define as a let since we want the scope of the variable to
9531 ;; be restricted to the array comprehension
9532 (if (js2-name-node-p iter)
9533 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9534 (if (js2-must-match js2-IN "msg.in.after.for.name")
9535 (setq in-pos (- js2-token-beg pos)))
9536 (setq obj (js2-parse-expr))
9537 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9538 (setq rp (- js2-token-beg pos)))
9539 (setf (js2-node-pos pn) pos
9540 (js2-node-len pn) (- js2-ts-cursor pos)
9541 (js2-array-comp-loop-node-iterator pn) iter
9542 (js2-array-comp-loop-node-object pn) obj
9543 (js2-array-comp-loop-node-in-pos pn) in-pos
9544 (js2-array-comp-loop-node-each-pos pn) each-pos
9545 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9546 (js2-array-comp-loop-node-lp pn) lp
9547 (js2-array-comp-loop-node-rp pn) rp)
9548 (js2-node-add-children pn iter obj))
9552 (defun js2-parse-object-literal ()
9553 (let ((pos js2-token-beg)
9560 (setq tt (js2-peek-token))
9562 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9563 ((or (js2-valid-prop-name-token tt)
9565 (setq after-comma nil
9566 result (js2-parse-named-prop tt))
9567 (if (and (null result)
9568 (not js2-recover-from-parse-errors))
9570 (push result elems)))
9571 ;; {12: x} or {10.7: x}
9574 (setq after-comma nil)
9575 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9580 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9581 pos elems after-comma)))
9583 (js2-report-error "msg.bad.prop")
9584 (unless js2-recover-from-parse-errors
9585 (setq continue nil)))) ; end switch
9586 (if (js2-match-token js2-COMMA)
9587 (setq after-comma js2-token-end)
9588 (setq continue nil))) ; end loop
9589 (js2-must-match js2-RC "msg.no.brace.prop")
9590 (setq result (make-js2-object-node :pos pos
9591 :len (- js2-ts-cursor pos)
9592 :elems (nreverse elems)))
9593 (apply #'js2-node-add-children result (js2-object-node-elems result))
9596 (defun js2-parse-named-prop (tt)
9597 "Parse a name, string, or getter/setter object property.
9598 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9600 (let ((string-prop (and (= tt js2-STRING)
9601 (make-js2-string-node)))
9603 (ppos js2-token-beg)
9604 (pend js2-token-end)
9605 (name (js2-create-name-node))
9606 (prop js2-ts-string))
9608 ;; getter/setter prop
9609 ((and (= tt js2-NAME)
9610 (= (js2-peek-token) js2-NAME)
9611 (or (string= prop "get")
9612 (string= prop "set")))
9614 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9615 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9616 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9617 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9618 ;; abbreviated destructuring bind e.g., {a, b} = c;
9619 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9620 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9621 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9622 ;; assignment but it's difficult because it requires looking ahead of expression.
9625 (let ((ctk (js2-peek-token)))
9626 (or (= ctk js2-COMMA)
9628 (js2-valid-prop-name-token ctk))))
9633 (setq expr (js2-parse-plain-property (or string-prop name)))
9634 (js2-set-face ppos pend
9635 (if (js2-function-node-p
9636 (js2-object-prop-node-right expr))
9637 'font-lock-function-name-face
9638 'font-lock-variable-name-face)
9641 (defun js2-parse-plain-property (prop)
9642 "Parse a non-getter/setter property in an object literal.
9643 PROP is the node representing the property: a number, name or string."
9644 (js2-must-match js2-COLON "msg.no.colon.prop")
9645 (let* ((pos (js2-node-pos prop))
9646 (colon (- js2-token-beg pos))
9647 (expr (js2-parse-assign-expr))
9648 (result (make-js2-object-prop-node
9650 ;; don't include last consumed token in length
9651 :len (- (+ (js2-node-pos expr)
9652 (js2-node-len expr))
9657 (js2-node-add-children result prop expr)
9660 (defun js2-parse-getter-setter-prop (pos prop get-p)
9661 "Parse getter or setter property in an object literal.
9662 JavaScript syntax is:
9664 { get foo() {...}, set foo(x) {...} }
9666 and expression closure style is also supported
9668 { get foo() x, set foo(x) _x = x }
9670 POS is the start position of the `get' or `set' keyword.
9671 PROP is the `js2-name-node' representing the property name.
9672 GET-P is non-nil if the keyword was `get'."
9673 (let ((type (if get-p js2-GET js2-SET))
9676 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9677 ;; it has to be an anonymous function, as we already parsed the name
9678 (if (/= (js2-node-type fn) js2-FUNCTION)
9679 (js2-report-error "msg.bad.prop")
9680 (if (plusp (length (js2-function-name fn)))
9681 (js2-report-error "msg.bad.prop")))
9682 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9683 (setq end (js2-node-end fn)
9684 result (make-js2-getter-setter-node :type type
9689 (js2-node-add-children result prop fn)
9692 (defun js2-create-name-node (&optional check-activation-p token)
9693 "Create a name node using the token info from last scanned name.
9694 In some cases we need to either synthesize a name node, or we lost
9695 the name token information by peeking. If the TOKEN parameter is
9696 not `js2-NAME', then we use the token info saved in instance vars."
9697 (let ((beg js2-token-beg)
9700 (when (/= js2-current-token js2-NAME)
9701 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9702 s js2-prev-name-token-string
9703 js2-prev-name-token-start nil
9704 js2-prev-name-token-string nil))
9705 (setq name (make-js2-name-node :pos beg
9708 (if check-activation-p
9709 (js2-check-activation-name s (or token js2-NAME)))
9712 ;;; Indentation support
9714 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9715 ;; Karl cleverly deduces that the desired indentation level is often a
9716 ;; function of paren/bracket/brace nesting depth, which can be determined
9717 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9718 ;; then does some equally clever checks to see if we're in the context of a
9719 ;; substatement of a possibly braceless statement keyword such as if, while,
9720 ;; or finally. This approach yields pretty good results.
9722 ;; The indenter is often "wrong", however, and needs to be overridden.
9723 ;; The right long-term solution is probably to emulate (or integrate
9724 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9725 ;; parse tree from `js2-parse' is present, which is not true at the
9726 ;; moment the user is typing, computing indentation is still thousands
9727 ;; of lines of code to handle every possible syntactic edge case.
9729 ;; In the meantime, the compromise solution is that we offer a "bounce
9730 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9731 ;; current line indent among various likely guess points. This approach
9732 ;; is far from perfect, but should at least make it slightly easier to
9733 ;; move the line towards its desired indentation when manually
9734 ;; overriding Karl's heuristic nesting guesser.
9736 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9737 ;; extensions such as `let' and Array comprehensions. Major kudos to
9738 ;; Karl for coming up with the initial approach, which packs a lot of
9739 ;; punch for so little code.
9741 (defconst js-possibly-braceless-keywords-re
9742 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9743 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9744 "try" "while" "with" "let")))
9745 "Regular expression matching keywords that are optionally
9746 followed by an opening brace.")
9748 (defconst js-indent-operator-re
9749 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9750 (regexp-opt '("in" "instanceof") 'words))
9751 "Regular expression matching operators that affect indentation
9752 of continued expressions.")
9754 (defconst js-declaration-keyword-re
9755 (regexp-opt '("var" "let" "const") 'words)
9756 "Regular expression matching variable declaration keywords.")
9758 ;; This function has horrible results if you're typing an array
9759 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9760 ;; in conjunction with electric-indent, so just disabling it.
9761 (defsubst js2-code-at-bol-p ()
9762 "Return t if the first character on line is non-whitespace."
9765 (defun js2-insert-and-indent (key)
9766 "Run command bound to key and indent current line. Runs the command
9767 bound to KEY in the global keymap and indents the current line."
9768 (interactive (list (this-command-keys)))
9769 (let ((cmd (lookup-key (current-global-map) key)))
9771 (call-interactively cmd)))
9772 ;; don't do the electric keys inside comments or strings,
9773 ;; and don't do bounce-indent with them.
9774 (let ((parse-state (syntax-ppss (point)))
9775 (js2-bounce-indent-p (js2-code-at-bol-p)))
9776 (unless (or (nth 3 parse-state)
9777 (nth 4 parse-state))
9778 (indent-according-to-mode))))
9780 (defun js-re-search-forward-inner (regexp &optional bound count)
9781 "Auxiliary function for `js-re-search-forward'."
9782 (let (parse saved-point)
9784 (re-search-forward regexp bound)
9785 (setq parse (if saved-point
9786 (parse-partial-sexp saved-point (point))
9787 (syntax-ppss (point))))
9788 (cond ((nth 3 parse)
9790 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9791 (save-excursion (end-of-line) (point)) t))
9795 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9796 (re-search-forward "\\*/"))
9798 (setq count (1- count))))
9799 (setq saved-point (point))))
9802 (defun js-re-search-forward (regexp &optional bound noerror count)
9803 "Search forward but ignore strings and comments. Invokes
9804 `re-search-forward' but treats the buffer as if strings and
9805 comments have been removed."
9806 (let ((saved-point (point))
9809 '(js-re-search-forward-inner regexp bound 1))
9811 '(js-re-search-backward-inner regexp bound (- count)))
9813 '(js-re-search-forward-inner regexp bound count)))))
9817 (goto-char saved-point)
9819 (error (error-message-string err)))))))
9821 (defun js-re-search-backward-inner (regexp &optional bound count)
9822 "Auxiliary function for `js-re-search-backward'."
9823 (let (parse saved-point)
9825 (re-search-backward regexp bound)
9826 (setq parse (if saved-point
9827 (parse-partial-sexp saved-point (point))
9828 (syntax-ppss (point))))
9829 (cond ((nth 3 parse)
9831 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9832 (save-excursion (beginning-of-line) (point)) t))
9834 (goto-char (nth 8 parse)))
9836 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9837 (re-search-backward "/\\*"))
9839 (setq count (1- count))))))
9842 (defun js-re-search-backward (regexp &optional bound noerror count)
9843 "Search backward but ignore strings and comments. Invokes
9844 `re-search-backward' but treats the buffer as if strings and
9845 comments have been removed."
9846 (let ((saved-point (point))
9849 '(js-re-search-backward-inner regexp bound 1))
9851 '(js-re-search-forward-inner regexp bound (- count)))
9853 '(js-re-search-backward-inner regexp bound count)))))
9857 (goto-char saved-point)
9859 (error (error-message-string err)))))))
9861 (defun js-looking-at-operator-p ()
9862 "Return non-nil if text after point is an operator (that is not
9865 (and (looking-at js-indent-operator-re)
9866 (or (not (looking-at ":"))
9868 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9869 (looking-at "?")))))))
9871 (defun js-continued-expression-p ()
9872 "Returns non-nil if the current line continues an expression."
9874 (back-to-indentation)
9875 (or (js-looking-at-operator-p)
9877 (and (js-re-search-backward "\n" nil t)
9879 (skip-chars-backward " \t")
9881 (and (js-looking-at-operator-p)
9882 (and (progn (backward-char)
9883 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9885 (defun js-end-of-do-while-loop-p ()
9886 "Returns non-nil if word after point is `while' of a do-while
9887 statement, else returns nil. A braceless do-while statement
9888 spanning several lines requires that the start of the loop is
9889 indented to the same column as the current line."
9893 (when (looking-at "\\s-*\\<while\\>")
9895 (skip-chars-backward "[ \t\n]*}")
9896 (looking-at "[ \t\n]*}"))
9898 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9899 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9900 (or (looking-at "\\<do\\>")
9901 (let ((saved-indent (current-indentation)))
9902 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9903 (/= (current-indentation) saved-indent)))
9904 (and (looking-at "[ \t]*\\<do\\>")
9905 (not (js-re-search-forward
9906 "\\<while\\>" (point-at-eol) t))
9907 (= (current-indentation) saved-indent)))))))))
9909 (defun js-multiline-decl-indentation ()
9910 "Returns the proper indentation of the current line if it belongs
9911 to a multiline declaration statement. All assignments are lined up vertically:
9917 (let (forward-sexp-function ; use lisp version
9920 (back-to-indentation)
9921 (when (looking-at (concat js2-mode-identifier-re "[ \t]*=[^=]"))
9922 (while (not (save-excursion
9924 (skip-chars-backward "-+~! \t")
9925 (or at-opening-bracket
9926 ;; explicit semicolon
9927 (save-excursion (js2-backward-sws)
9928 (= (char-before) ?\;))
9929 ;; implicit semicolon
9931 (progn (js2-backward-sws)
9932 (/= (char-before) ?,))
9933 (progn (skip-chars-backward "[[:punct:]]")
9934 (not (looking-at js-indent-operator-re)))))))
9937 (scan-error (setq at-opening-bracket t))))
9938 (when (looking-at js-declaration-keyword-re)
9939 (- (1+ (match-end 0)) (point-at-bol)))))))
9941 (defun js-ctrl-statement-indentation ()
9942 "Returns the proper indentation of the current line if it
9943 starts the body of a control statement without braces, else
9945 (let (forward-sexp-function) ; temporarily unbind it
9947 (back-to-indentation)
9948 (when (and (not (js2-same-line (point-min)))
9949 (not (looking-at "{"))
9950 (js-re-search-backward "[[:graph:]]" nil t)
9951 (not (looking-at "[{([]"))
9954 (when (= (char-before) ?\))
9955 ;; scan-sexps sometimes throws an error
9956 (ignore-errors (backward-sexp))
9957 (skip-chars-backward " \t" (point-at-bol)))
9959 (back-to-indentation)
9960 (and (looking-at js-possibly-braceless-keywords-re)
9961 (= (match-end 0) pt)
9962 (not (js-end-of-do-while-loop-p))))))
9963 (+ (current-indentation) js2-basic-offset)))))
9965 (defun js2-indent-in-array-comp (parse-status)
9966 "Return non-nil if we think we're in an array comprehension.
9967 In particular, return the buffer position of the first `for' kwd."
9968 (let ((end (point)))
9969 (when (nth 1 parse-status)
9971 (goto-char (nth 1 parse-status))
9972 (when (looking-at "\\[")
9975 (if (looking-at "[[{]")
9976 (let (forward-sexp-function) ; use lisp version
9977 (forward-sexp) ; skip destructuring form
9979 (if (and (/= (char-after) ?,) ; regular array
9981 (match-beginning 0)))
9982 ;; to skip arbitrary expressions we need the parser,
9983 ;; so we'll just guess at it.
9984 (if (re-search-forward "[^,]* \\(for\\) " end t)
9985 (match-beginning 1))))))))
9987 (defun js2-array-comp-indentation (parse-status for-kwd)
9988 (if (js2-same-line for-kwd)
9989 ;; first continuation line
9991 (goto-char (nth 1 parse-status))
9993 (skip-chars-forward " \t")
9999 (defun js-proper-indentation (parse-status)
10000 "Return the proper indentation for the current line."
10002 (back-to-indentation)
10003 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10004 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10005 (continued-expr-p (js-continued-expression-p))
10006 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10007 (js-multiline-decl-indentation)))
10008 (bracket (nth 1 parse-status))
10011 ;; indent array comprehension continuation lines specially
10013 (not (js2-same-line bracket))
10014 (setq beg (js2-indent-in-array-comp parse-status))
10015 (>= (point) (save-excursion
10017 (point-at-bol)))) ; at or after first loop?
10018 (js2-array-comp-indentation parse-status beg))
10022 (declaration-indent)
10025 (goto-char bracket)
10027 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10028 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10029 (when (save-excursion (skip-chars-backward " \t)")
10033 (not js2-consistent-level-indent-inner-bracket-p))
10034 (progn (goto-char (1+ (nth 1 p)))
10035 (skip-chars-forward " \t"))
10036 (back-to-indentation))
10037 (cond (same-indent-p
10040 (+ (current-column) (* 2 js2-basic-offset)))
10042 (+ (current-column) js2-basic-offset)))))
10044 (unless same-indent-p
10046 (skip-chars-forward " \t"))
10047 (current-column))))
10049 (continued-expr-p js2-basic-offset)
10053 (defun js2-lineup-comment (parse-status)
10054 "Indent a multi-line block comment continuation line."
10055 (let* ((beg (nth 8 parse-status))
10056 (first-line (js2-same-line beg))
10057 (offset (save-excursion
10059 (if (looking-at "/\\*")
10060 (+ 1 (current-column))
10063 (indent-line-to offset))))
10065 (defun js2-backward-sws ()
10066 "Move backward through whitespace and comments."
10068 (while (forward-comment -1)))
10070 (defun js2-forward-sws ()
10071 "Move forward through whitespace and comments."
10073 (while (forward-comment 1)))
10075 (defsubst js2-current-indent (&optional pos)
10076 "Return column of indentation on current line.
10077 If POS is non-nil, go to that point and return indentation for that line."
10081 (back-to-indentation)
10084 (defsubst js2-arglist-close ()
10085 "Return non-nil if we're on a line beginning with a close-paren/brace."
10088 (goto-char (point-at-bol))
10090 (looking-at "[])}]"))))
10092 (defsubst js2-indent-looks-like-label-p ()
10093 (goto-char (point-at-bol))
10095 (looking-at (concat js2-mode-identifier-re ":")))
10097 (defun js2-indent-in-objlit-p (parse-status)
10098 "Return non-nil if this looks like an object-literal entry."
10099 (let ((start (nth 1 parse-status)))
10103 (and (zerop (forward-line -1))
10104 (not (< (point) start)) ; crossed a {} boundary
10105 (js2-indent-looks-like-label-p)))
10107 (js2-indent-looks-like-label-p)))))
10109 ;; if prev line looks like foobar({ then we're passing an object
10110 ;; literal to a function call, and people pretty much always want to
10111 ;; de-dent back to the previous line, so move the 'basic-offset'
10112 ;; position to the front.
10113 (defsubst js2-indent-objlit-arg-p (parse-status)
10115 (back-to-indentation)
10117 (and (eq (1- (point)) (nth 1 parse-status))
10118 (eq (char-before) ?{)
10121 (skip-chars-backward " \t")
10122 (eq (char-before) ?\()))))
10124 (defsubst js2-indent-case-block-p ()
10126 (back-to-indentation)
10128 (goto-char (point-at-bol))
10129 (skip-chars-forward " \t")
10131 (looking-at "case\\s-.+:"))))
10133 (defsubst js2-syntax-bol ()
10134 "Return the point at the first non-whitespace char on the line.
10135 Returns `point-at-bol' if the line is empty."
10137 (beginning-of-line)
10138 (skip-chars-forward " \t")
10141 (defun js2-bounce-indent (normal-col parse-status backwards)
10142 "Cycle among alternate computed indentation positions.
10143 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10144 of the buffer to the current point. NORMAL-COL is the indentation
10145 column computed by the heuristic guesser based on current paren,
10146 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10148 (let ((cur-indent (js2-current-indent))
10149 (old-buffer-undo-list buffer-undo-list)
10150 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10151 (current-line (save-excursion
10152 (forward-line 0) ; move to bol
10153 (1+ (count-lines (point-min) (point)))))
10163 ;; temporarily don't record undo info, if user requested this
10164 (if js2-mode-indent-inhibit-undo
10165 (setq buffer-undo-list t))
10168 ;; first likely point: indent from beginning of previous code line
10169 (push (setq basic-offset
10171 (back-to-indentation)
10173 (back-to-indentation)
10174 (setq prev-line-col (current-column)))
10178 ;; (first + epsilon) likely point: indent 2x from beginning of
10179 ;; previous code line. Some companies like this approach. Ahem.
10180 ;; Seriously, though -- 4-space indent for expression continuation
10181 ;; lines isn't a bad idea. We should eventually implement it
10183 (push (setq basic-offset
10185 (back-to-indentation)
10187 (back-to-indentation)
10188 (setq prev-line-col (current-column)))
10189 (* 2 js2-basic-offset)))
10192 ;; second likely point: indent from assign-expr RHS. This
10193 ;; is just a crude guess based on finding " = " on the previous
10194 ;; line containing actual code.
10195 (setq pos (save-excursion
10198 (goto-char (point-at-bol))
10199 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10201 (goto-char (match-end 1))
10202 (skip-chars-forward " \t\r\n")
10203 (current-column)))))
10205 (incf pos js2-basic-offset)
10206 (push pos positions))
10208 ;; third likely point: same indent as previous line of code.
10209 ;; Make it the first likely point if we're not on an
10210 ;; arglist-close line and previous line ends in a comma, or
10211 ;; both this line and prev line look like object-literal
10213 (setq pos (save-excursion
10214 (goto-char (point-at-bol))
10216 (back-to-indentation)
10219 ;; while we're here, look for trailing comma
10220 (if (save-excursion
10221 (goto-char (point-at-eol))
10223 (eq (char-before) ?,))
10224 (setq arglist-cont (1- (point)))))))
10226 (if (and (or arglist-cont
10227 (js2-indent-in-objlit-p parse-status))
10228 (not (js2-arglist-close)))
10229 (setq same-indent pos))
10230 (push pos positions))
10232 ;; fourth likely point: first preceding code with less indentation
10233 ;; than the immediately preceding code line.
10234 (setq pos (save-excursion
10235 (back-to-indentation)
10237 (back-to-indentation)
10238 (setq anchor (current-column))
10239 (while (and (zerop (forward-line -1))
10241 (back-to-indentation)
10244 (setq pos (current-column))))
10245 (push pos positions)
10247 ;; nesting-heuristic position, main by default
10248 (push (setq main-pos normal-col) positions)
10250 ;; delete duplicates and sort positions list
10251 (setq positions (sort (delete-dups positions) '<))
10253 ;; comma-list continuation lines: prev line indent takes precedence
10255 (setq main-pos same-indent))
10257 ;; common special cases where we want to indent in from previous line
10258 (if (or (js2-indent-case-block-p)
10259 (js2-indent-objlit-arg-p parse-status))
10260 (setq main-pos basic-offset))
10262 ;; if bouncing backwards, reverse positions list
10264 (setq positions (reverse positions)))
10266 ;; record whether we're already sitting on one of the alternatives
10267 (setq pos (member cur-indent positions))
10270 ;; case 0: we're one one of the alternatives and this is the
10271 ;; first time they've pressed TAB on this line (best-guess).
10272 ((and js2-mode-indent-ignore-first-tab
10274 ;; first time pressing TAB on this line?
10275 (not (eq js2-mode-last-indented-line current-line)))
10277 (setq computed-pos nil))
10278 ;; case 1: only one computed position => use it
10279 ((null (cdr positions))
10280 (setq computed-pos 0))
10281 ;; case 2: not on any of the computed spots => use main spot
10283 (setq computed-pos (js2-position main-pos positions)))
10284 ;; case 3: on last position: cycle to first position
10286 (setq computed-pos 0))
10287 ;; case 4: on intermediate position: cycle to next position
10289 (setq computed-pos (js2-position (second pos) positions))))
10291 ;; see if any hooks want to indent; otherwise we do it
10292 (loop with result = nil
10293 for hook in js2-indent-hook
10294 while (null result)
10296 (setq result (funcall hook positions computed-pos))
10298 (unless (or result (null computed-pos))
10299 (indent-line-to (nth computed-pos positions)))))
10302 (if js2-mode-indent-inhibit-undo
10303 (setq buffer-undo-list old-buffer-undo-list))
10304 ;; see commentary for `js2-mode-last-indented-line'
10305 (setq js2-mode-last-indented-line current-line))))
10307 (defun js2-indent-bounce-backwards ()
10308 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10309 cycles between the computed indentation positions in reverse order."
10311 (js2-indent-line t))
10313 (defsubst js2-1-line-comment-continuation-p ()
10314 "Return t if we're in a 1-line comment continuation.
10315 If so, we don't ever want to use bounce-indent."
10320 (looking-at "\\s-*//"))
10324 (when (looking-at "\\s-*$")
10327 (looking-at "\\s-*//"))))))
10329 (defun js2-indent-line (&optional bounce-backwards)
10330 "Indent the current line as JavaScript source text."
10337 ;; don't whine about errors/warnings when we're indenting.
10338 ;; This has to be set before calling parse-partial-sexp below.
10339 (inhibit-point-motion-hooks t))
10340 (setq parse-status (save-excursion
10341 (syntax-ppss (point-at-bol)))
10342 offset (- (point) (save-excursion
10343 (back-to-indentation)
10344 (setq current-indent (current-column))
10346 (js2-with-underscore-as-word-syntax
10347 (if (nth 4 parse-status)
10348 (js2-lineup-comment parse-status)
10349 (setq indent-col (js-proper-indentation parse-status))
10350 ;; see comments below about js2-mode-last-indented-line
10353 ;; bounce-indenting is disabled during electric-key indent.
10354 ;; It doesn't work well on first line of buffer.
10355 ((and js2-bounce-indent-p
10356 (not (js2-same-line (point-min)))
10357 (not (js2-1-line-comment-continuation-p)))
10358 (js2-bounce-indent indent-col parse-status bounce-backwards)
10360 ;; just indent to the guesser's likely spot
10361 ((/= current-indent indent-col)
10362 (indent-line-to indent-col)
10364 (when (and moved (plusp offset))
10365 (forward-char offset)))))))
10367 (defun js2-indent-region (start end)
10368 "Indent the region, but don't use bounce indenting."
10369 (let ((js2-bounce-indent-p nil)
10370 (indent-region-function nil)
10371 (after-change-functions (delq 'js2-mode-edit
10372 after-change-functions)))
10373 (indent-region start end nil) ; nil for byte-compiler
10374 (js2-mode-edit start end (- end start))))
10376 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10380 "Major mode for editing JavaScript code."
10382 (kill-all-local-variables)
10383 (set-syntax-table js2-mode-syntax-table)
10384 (use-local-map js2-mode-map)
10385 (make-local-variable 'comment-start)
10386 (make-local-variable 'comment-end)
10387 (make-local-variable 'comment-start-skip)
10388 (setq major-mode 'js2-mode
10389 mode-name "JavaScript-IDE"
10390 comment-start "//" ; used by comment-region; don't change it
10392 (setq local-abbrev-table js2-mode-abbrev-table)
10393 (set (make-local-variable 'max-lisp-eval-depth)
10394 (max max-lisp-eval-depth 3000))
10395 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10396 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10398 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10399 ;; on most platforms other than the one I originally wrote it on. So it's
10400 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10401 ;; with our binding of the RET key inside comments: short lines stay short.
10402 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10404 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10405 (set (make-local-variable 'next-error-function) #'js2-next-error)
10406 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10407 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10408 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10409 ;; for characters inside regexp literals.
10410 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10411 ;; this is necessary to make `show-paren-function' work properly
10412 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10413 ;; needed for M-x rgrep, among other things
10414 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10416 ;; some variables needed by cc-engine for paragraph-fill, etc.
10417 (setq c-buffer-is-cc-mode t
10418 c-comment-prefix-regexp js2-comment-prefix-regexp
10419 c-comment-start-regexp "/[*/]\\|\\s|"
10420 c-paragraph-start js2-paragraph-start
10421 c-paragraph-separate "$"
10422 comment-start-skip js2-comment-start-skip
10423 c-syntactic-ws-start js2-syntactic-ws-start
10424 c-syntactic-ws-end js2-syntactic-ws-end
10425 c-syntactic-eol js2-syntactic-eol)
10427 (setq js2-default-externs
10428 (append js2-ecma-262-externs
10429 (if js2-include-browser-externs
10430 js2-browser-externs)
10431 (if js2-include-gears-externs
10433 (if js2-include-rhino-externs
10434 js2-rhino-externs)))
10436 ;; We do our own syntax highlighting based on the parse tree.
10437 ;; However, we want minor modes that add keywords to highlight properly
10438 ;; (examples: doxymacs, column-marker). We do this by not letting
10439 ;; font-lock unfontify anything, and telling it to fontify after we
10440 ;; re-parse and re-highlight the buffer. (We currently don't do any
10441 ;; work with regions other than the whole buffer.)
10442 (dolist (var '(font-lock-unfontify-buffer-function
10443 font-lock-unfontify-region-function))
10444 (set (make-local-variable var) (lambda (&rest args) t)))
10446 ;; Don't let font-lock do syntactic (string/comment) fontification.
10447 (set (make-local-variable #'font-lock-syntactic-face-function)
10448 (lambda (state) nil))
10450 ;; Experiment: make reparse-delay longer for longer files.
10451 (if (plusp js2-dynamic-idle-timer-adjust)
10452 (setq js2-idle-timer-delay
10453 (* js2-idle-timer-delay
10454 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10456 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10457 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10458 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10459 (imenu-add-to-menubar (concat "IM-" mode-name))
10460 (when js2-mirror-mode
10461 (js2-enter-mirror-mode))
10462 (add-to-invisibility-spec '(js2-outline . t))
10463 (set (make-local-variable 'line-move-ignore-invisible) t)
10464 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10465 (setq js2-mode-functions-hidden nil
10466 js2-mode-comments-hidden nil
10467 js2-mode-buffer-dirty-p t
10468 js2-mode-parsing nil)
10471 (if (fboundp 'run-mode-hooks)
10472 (run-mode-hooks 'js2-mode-hook)
10473 (run-hooks 'js2-mode-hook)))
10475 (defun js2-mode-exit ()
10476 "Exit `js2-mode' and clean up."
10478 (when js2-mode-node-overlay
10479 (delete-overlay js2-mode-node-overlay)
10480 (setq js2-mode-node-overlay nil))
10481 (js2-remove-overlays)
10482 (setq js2-mode-ast nil)
10483 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10484 (remove-from-invisibility-spec '(js2-outline . t))
10485 (js2-mode-show-all)
10486 (js2-with-unmodifying-text-property-changes
10487 (js2-clear-face (point-min) (point-max))))
10489 (defun js2-before-save ()
10490 "Clean up whitespace before saving file.
10491 You can disable this by customizing `js2-cleanup-whitespace'."
10492 (when js2-cleanup-whitespace
10493 (let ((col (current-column)))
10494 (delete-trailing-whitespace)
10495 ;; don't change trailing whitespace on current line
10496 (unless (eq (current-column) col)
10497 (indent-to col)))))
10499 (defsubst js2-mode-reset-timer ()
10500 "Cancel any existing parse timer and schedule a new one."
10501 (if js2-mode-parse-timer
10502 (cancel-timer js2-mode-parse-timer))
10503 (setq js2-mode-parsing nil)
10504 (setq js2-mode-parse-timer
10505 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10507 (defun js2-mode-edit (beg end len)
10508 "Schedule a new parse after buffer is edited.
10509 Buffer edit spans from BEG to END and is of length LEN.
10510 Also clears the `js2-magic' bit on autoinserted parens/brackets
10511 if the edit occurred on a line different from the magic paren."
10512 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10513 (line (if magic-pos (line-number-at-pos magic-pos))))
10515 (or (/= (line-number-at-pos beg) line)
10517 (/= (line-number-at-pos end) line)))
10518 (js2-mode-mundanify-parens)))
10519 (setq js2-mode-buffer-dirty-p t)
10520 (js2-mode-hide-overlay)
10521 (js2-mode-reset-timer))
10523 (defun js2-mode-run-font-lock ()
10524 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10525 This is intended to allow modes that install their own font-lock keywords
10526 to work with js2-mode. In practice it never seems to work for long.
10527 Hopefully the Emacs maintainers can help figure out a way to make it work."
10528 (when (and (boundp 'font-lock-keywords)
10530 (boundp 'font-lock-mode)
10532 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10533 ;; play nicely with js2-mode. They go out of their way to fail to
10534 ;; provide any option for saying "look, fontify the farging buffer
10535 ;; with just the keywords already". Argh.
10536 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10537 (let (font-lock-verbose)
10538 (font-lock-fontify-buffer))))
10540 (defun js2-reparse (&optional force)
10541 "Re-parse current buffer after user finishes some data entry.
10542 If we get any user input while parsing, including cursor motion,
10543 we discard the parse and reschedule it. If FORCE is nil, then the
10544 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10547 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10548 (unless js2-mode-parsing
10549 (setq js2-mode-parsing t)
10551 (when (or js2-mode-buffer-dirty-p force)
10552 (js2-remove-overlays)
10553 (js2-with-unmodifying-text-property-changes
10554 (setq js2-mode-buffer-dirty-p nil
10555 js2-mode-fontifications nil
10556 js2-mode-deferred-properties nil)
10557 (if js2-mode-verbose-parse-p
10558 (message "parsing..."))
10561 (setq interrupted-p
10562 (catch 'interrupted
10563 (setq js2-mode-ast (js2-parse))
10564 ;; if parsing is interrupted, comments and regex
10565 ;; literals stay ignored by `parse-partial-sexp'
10566 (remove-text-properties (point-min) (point-max)
10568 (js2-mode-apply-deferred-properties)
10569 (js2-mode-remove-suppressed-warnings)
10570 (js2-mode-show-warnings)
10571 (js2-mode-show-errors)
10572 (js2-mode-run-font-lock) ; note: doesn't work
10573 (js2-mode-highlight-magic-parens)
10574 (if (>= js2-highlight-level 1)
10575 (js2-highlight-jsdoc js2-mode-ast))
10579 ;; unfinished parse => try again
10580 (setq js2-mode-buffer-dirty-p t)
10581 (js2-mode-reset-timer))
10582 (if js2-mode-verbose-parse-p
10583 (message "Parse time: %s" time)))))
10584 (setq js2-mode-parsing nil)
10585 (unless interrupted-p
10586 (setq js2-mode-parse-timer nil))))))
10588 (defun js2-mode-show-node ()
10589 "Debugging aid: highlight selected AST node on mouse click."
10591 (let ((node (js2-node-at-point))
10594 (when js2-mode-show-overlay
10596 (message "No node found at location %s" (point))
10597 (setq beg (js2-node-abs-pos node)
10598 end (+ beg (js2-node-len node)))
10599 (if js2-mode-node-overlay
10600 (move-overlay js2-mode-node-overlay beg end)
10601 (setq js2-mode-node-overlay (make-overlay beg end))
10602 (overlay-put js2-mode-node-overlay 'face 'highlight))
10603 (js2-with-unmodifying-text-property-changes
10604 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10605 (message "%s, parent: %s"
10606 (js2-node-short-name node)
10607 (if (js2-node-parent node)
10608 (js2-node-short-name (js2-node-parent node))
10611 (defun js2-mode-hide-overlay (&optional p1 p2)
10612 "Remove the debugging overlay when the point moves.
10613 P1 and P2 are the old and new values of point, respectively."
10614 (when js2-mode-node-overlay
10615 (let ((beg (overlay-start js2-mode-node-overlay))
10616 (end (overlay-end js2-mode-node-overlay)))
10617 ;; Sometimes we're called spuriously.
10621 (js2-with-unmodifying-text-property-changes
10622 (remove-text-properties beg end '(point-left nil)))
10623 (delete-overlay js2-mode-node-overlay)
10624 (setq js2-mode-node-overlay nil)))))
10626 (defun js2-mode-reset ()
10627 "Debugging helper: reset everything."
10632 (defsubst js2-mode-show-warn-or-err (e face)
10633 "Highlight a warning or error E with FACE.
10634 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10635 (let* ((key (first e))
10637 (end (+ beg (third e)))
10638 ;; Don't inadvertently go out of bounds.
10639 (beg (max (point-min) (min beg (point-max))))
10640 (end (max (point-min) (min end (point-max))))
10641 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10642 (ovl (make-overlay beg end)))
10643 (overlay-put ovl 'face face)
10644 (overlay-put ovl 'js2-error t)
10645 (put-text-property beg end 'help-echo (js2-get-msg key))
10646 (put-text-property beg end 'point-entered #'js2-echo-error)))
10648 (defun js2-remove-overlays ()
10649 "Remove overlays from buffer that have a `js2-error' property."
10650 (let ((beg (point-min))
10653 (dolist (o (overlays-in beg end))
10654 (when (overlay-get o 'js2-error)
10655 (delete-overlay o))))))
10657 (defun js2-error-at-point (&optional pos)
10658 "Return non-nil if there's an error overlay at POS.
10659 Defaults to point."
10660 (loop with pos = (or pos (point))
10661 for o in (overlays-at pos)
10662 thereis (overlay-get o 'js2-error)))
10664 (defun js2-mode-apply-deferred-properties ()
10665 "Apply fontifications and other text properties recorded during parsing."
10666 (when (plusp js2-highlight-level)
10667 ;; We defer clearing faces as long as possible to eliminate flashing.
10668 (js2-clear-face (point-min) (point-max))
10669 ;; Have to reverse the recorded fontifications list so that errors
10670 ;; and warnings overwrite the normal fontifications.
10671 (dolist (f (nreverse js2-mode-fontifications))
10672 (put-text-property (first f) (second f) 'face (third f)))
10673 (setq js2-mode-fontifications nil))
10674 (dolist (p js2-mode-deferred-properties)
10675 (apply #'put-text-property p))
10676 (setq js2-mode-deferred-properties nil))
10678 (defun js2-mode-show-errors ()
10679 "Highlight syntax errors."
10680 (when js2-mode-show-parse-errors
10681 (dolist (e (js2-ast-root-errors js2-mode-ast))
10682 (js2-mode-show-warn-or-err e 'js2-error-face))))
10684 (defun js2-mode-remove-suppressed-warnings ()
10685 "Take suppressed warnings out of the AST warnings list.
10686 This ensures that the counts and `next-error' are correct."
10687 (setf (js2-ast-root-warnings js2-mode-ast)
10690 (let ((key (caar e)))
10692 (and (not js2-strict-trailing-comma-warning)
10693 (string-match "trailing\\.comma" key))
10694 (and (not js2-strict-cond-assign-warning)
10695 (string= key "msg.equal.as.assign"))
10696 (and js2-missing-semi-one-line-override
10697 (string= key "msg.missing.semi")
10698 (let* ((beg (second e))
10699 (node (js2-node-at-point beg))
10700 (fn (js2-mode-find-parent-fn node))
10701 (body (and fn (js2-function-node-body fn)))
10702 (lc (and body (js2-node-abs-pos body)))
10703 (rc (and lc (+ lc (js2-node-len body)))))
10708 (and (js2-same-line lc)
10709 (js2-same-line rc))))))))))
10710 (js2-ast-root-warnings js2-mode-ast))))
10712 (defun js2-mode-show-warnings ()
10713 "Highlight strict-mode warnings."
10714 (when js2-mode-show-strict-warnings
10715 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10716 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10718 (defun js2-echo-error (old-point new-point)
10719 "Called by point-motion hooks."
10720 (let ((msg (get-text-property new-point 'help-echo)))
10724 (defalias #'js2-echo-help #'js2-echo-error)
10726 (defun js2-enter-key ()
10727 "Handle user pressing the Enter key."
10729 (let ((parse-status (save-excursion
10730 (syntax-ppss (point)))))
10732 ;; check if we're inside a string
10733 ((nth 3 parse-status)
10734 (js2-mode-split-string parse-status))
10735 ;; check if inside a block comment
10736 ((nth 4 parse-status)
10737 (js2-mode-extend-comment))
10739 ;; should probably figure out what the mode-map says we should do
10740 (if js2-indent-on-enter-key
10741 (let ((js2-bounce-indent-p nil))
10742 (js2-indent-line)))
10744 (if js2-enter-indents-newline
10745 (let ((js2-bounce-indent-p nil))
10746 (js2-indent-line)))))))
10748 (defun js2-mode-split-string (parse-status)
10749 "Turn a newline in mid-string into a string concatenation.
10750 PARSE-STATUS is as documented in `parse-partial-sexp'."
10751 (let* ((col (current-column))
10752 (quote-char (nth 3 parse-status))
10753 (quote-string (string quote-char))
10754 (string-beg (nth 8 parse-status))
10755 (indent (save-match-data
10758 (back-to-indentation)
10759 (if (looking-at "\\+")
10762 (goto-char string-beg)
10763 (if (looking-back "\\+\\s-+")
10764 (goto-char (match-beginning 0)))
10765 (current-column))))))
10766 (insert quote-char "\n")
10768 (insert "+ " quote-string)
10770 (insert quote-string)
10771 (backward-char 1))))
10773 (defun js2-mode-extend-comment ()
10774 "When inside a comment block, add comment prefix."
10775 (let (star single col first-line needs-close)
10777 (back-to-indentation)
10779 ((looking-at "\\*[^/]")
10781 col (current-column)))
10782 ((looking-at "/\\*")
10785 col (1+ (current-column))))
10788 col (current-column)))))
10789 ;; Heuristic for whether we need to close the comment:
10790 ;; if we've got a parse error here, assume it's an unterminated
10794 (eq (get-text-property (1- (point)) 'point-entered)
10796 ;; The heuristic above doesn't work well when we're
10797 ;; creating a comment and there's another one downstream,
10798 ;; as our parser thinks this one ends at the end of the
10799 ;; next one. (You can have a /* inside a js block comment.)
10800 ;; So just close it if the next non-ws char isn't a *.
10804 (skip-chars-forward " \t\r\n")
10805 (not (eq (char-after) ?*))))))
10811 (if (and first-line needs-close)
10817 (when (save-excursion
10818 (and (zerop (forward-line 1))
10819 (looking-at "\\s-*//")))
10821 (insert "// "))))))
10823 (defun js2-beginning-of-line ()
10824 "Toggles point between bol and first non-whitespace char in line.
10825 Also moves past comment delimiters when inside comments."
10830 (back-to-indentation))
10832 (skip-chars-forward "/ \t"))
10833 ((and (eq (char-after) ?*)
10834 (setq node (js2-comment-at-point))
10835 (memq (js2-comment-node-format node) '(jsdoc block))
10837 (skip-chars-backward " \t")
10839 (skip-chars-forward "\* \t"))
10841 (goto-char (point-at-bol))))))
10843 (defun js2-end-of-line ()
10844 "Toggles point between eol and last non-whitespace char in line."
10847 (skip-chars-backward " \t")
10848 (goto-char (point-at-eol))))
10850 (defun js2-enter-mirror-mode()
10851 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10854 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10855 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10856 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10857 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10858 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10859 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10860 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10861 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10863 (defun js2-leave-mirror-mode()
10864 "Turns off mirror mode."
10866 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10867 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10869 (defsubst js2-mode-inside-string ()
10870 "Return non-nil if inside a string.
10871 Actually returns the quote character that begins the string."
10872 (let ((parse-state (save-excursion
10873 (syntax-ppss (point)))))
10874 (nth 3 parse-state)))
10876 (defsubst js2-mode-inside-comment-or-string ()
10877 "Return non-nil if inside a comment or string."
10879 (let ((comment-start
10881 (goto-char (point-at-bol))
10882 (if (re-search-forward "//" (point-at-eol) t)
10883 (match-beginning 0)))))
10885 (<= comment-start (point))))
10886 (let ((parse-state (save-excursion
10887 (syntax-ppss (point)))))
10888 (or (nth 3 parse-state)
10889 (nth 4 parse-state)))))
10891 (defsubst js2-make-magic-delimiter (delim &optional pos)
10892 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10893 Sets value of `js2-magic' text property to line number at POS."
10895 'js2-magic (line-number-at-pos pos)
10896 'face 'js2-magic-paren-face))
10898 (defun js2-mode-match-delimiter (open close)
10899 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10900 The rule we use, which as far as we can tell is how Eclipse works,
10901 is that we insert the match if we're not in a comment or string,
10902 and the next non-whitespace character is either punctuation or
10903 occurs on another line."
10905 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10906 (not (js2-mode-inside-comment-or-string)))
10908 (insert (js2-make-magic-delimiter close)))
10909 (when js2-auto-indent-p
10910 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10911 (js2-indent-line)))))
10913 (defun js2-mode-match-bracket ()
10914 "Insert matching bracket."
10916 (js2-mode-match-delimiter "[" "]"))
10918 (defun js2-mode-match-paren ()
10919 "Insert matching paren unless already inserted."
10921 (js2-mode-match-delimiter "(" ")"))
10923 (defun js2-mode-match-curly (arg)
10924 "Insert matching curly-brace.
10925 With prefix arg, no formatting or indentation will occur -- the close-brace
10926 is simply inserted directly at the point."
10930 (current-prefix-arg
10931 (js2-mode-match-delimiter "{" "}"))
10932 ((and js2-auto-insert-catch-block
10933 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10935 (match-beginning 1))))
10936 (js2-insert-catch-skel try-pos))
10938 ;; Otherwise try to do something smarter.
10940 (unless (or (not (looking-at "\\s-*$"))
10942 (skip-chars-forward " \t\r\n")
10943 (and (looking-at "}")
10944 (js2-error-at-point)))
10945 (js2-mode-inside-comment-or-string))
10947 ;; absolutely mystifying bug: when inserting the next "\n",
10948 ;; the buffer-undo-list is given two new entries: the inserted range,
10949 ;; and the incorrect position of the point. It's recorded incorrectly
10950 ;; as being before the opening "{", not after it. But it's recorded
10951 ;; as the correct value if you're debugging `js2-mode-match-curly'
10952 ;; in edebug. I have no idea why it's doing this, but incrementing
10953 ;; the inserted position fixes the problem, so that the undo takes us
10954 ;; back to just after the user-inserted "{".
10957 (incf (cadr buffer-undo-list)))
10961 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10962 (js2-indent-line))))))))
10964 (defun js2-insert-catch-skel (try-pos)
10965 "Complete a try/catch block after inserting a { following a try keyword.
10966 Rationale is that a try always needs a catch or a finally, and the catch is
10967 the more likely of the two.
10969 TRY-POS is the buffer position of the try keyword. The open-curly should
10970 already have been inserted."
10972 (let ((try-col (save-excursion
10973 (goto-char try-pos)
10974 (current-column))))
10977 (js2-indent-line) ;; indent the blank line where cursor will end up
10980 (indent-to try-col)
10981 (insert "} catch (x) {\n\n")
10982 (indent-to try-col)
10985 (defun js2-mode-highlight-magic-parens ()
10986 "Re-highlight magic parens after parsing nukes the 'face prop."
10987 (let ((beg (point-min))
10989 (while (setq beg (next-single-property-change beg 'js2-magic))
10990 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10991 (if (get-text-property beg 'js2-magic)
10992 (js2-with-unmodifying-text-property-changes
10993 (put-text-property beg (or end (1+ beg))
10994 'face 'js2-magic-paren-face))))))
10996 (defun js2-mode-mundanify-parens ()
10997 "Clear all magic parens and brackets."
10998 (let ((beg (point-min))
11000 (while (setq beg (next-single-property-change beg 'js2-magic))
11001 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11002 (remove-text-properties beg (or end (1+ beg))
11003 '(js2-magic face)))))
11005 (defsubst js2-match-quote (quote-string)
11006 (let ((start-quote (js2-mode-inside-string)))
11008 ;; inside a comment - don't do quote-matching, since we can't
11009 ;; reliably figure out if we're in a string inside the comment
11010 ((js2-comment-at-point)
11011 (insert quote-string))
11013 ;; not in string => insert matched quotes
11014 (insert quote-string)
11015 ;; exception: if we're just before a word, don't double it.
11016 (unless (looking-at "[^ \t\r\n]")
11018 (insert quote-string))))
11019 ((looking-at quote-string)
11020 (if (looking-back "[^\\]\\\\")
11021 (insert quote-string)
11023 ((and js2-mode-escape-quotes
11026 (re-search-forward quote-string (point-at-eol) t))))
11027 ;; inside terminated string, escape quote (unless already escaped)
11028 (insert (if (looking-back "[^\\]\\\\")
11030 (concat "\\" quote-string))))
11032 (insert quote-string))))) ; else terminate the string
11034 (defun js2-mode-match-single-quote ()
11035 "Insert matching single-quote."
11037 (let ((parse-status (syntax-ppss (point))))
11038 ;; don't match inside comments, since apostrophe is more common
11039 (if (nth 4 parse-status)
11041 (js2-match-quote "'"))))
11043 (defun js2-mode-match-double-quote ()
11044 "Insert matching double-quote."
11046 (js2-match-quote "\""))
11048 ;; Eclipse works as follows:
11049 ;; * type an open-paren and it auto-inserts close-paren
11050 ;; - auto-inserted paren gets a green bracket
11051 ;; - green bracket means typing close-paren there will skip it
11052 ;; * if you insert any text on a different line, it turns off
11053 (defun js2-mode-magic-close-paren ()
11054 "Skip over close-paren rather than inserting, where appropriate."
11056 (let* ((here (point))
11057 (parse-status (syntax-ppss here))
11058 (open-pos (nth 1 parse-status))
11059 (close last-input-event)
11068 (if (and (eq (char-after) close)
11069 (eq open (char-after open-pos))
11070 (js2-same-line open-pos)
11071 (get-text-property here 'js2-magic))
11073 (remove-text-properties here (1+ here) '(js2-magic face))
11075 (insert-char close 1))
11076 (blink-matching-open)))
11078 (defun js2-mode-wait-for-parse (callback)
11079 "Invoke CALLBACK when parsing is finished.
11080 If parsing is already finished, calls CALLBACK immediately."
11081 (if (not js2-mode-buffer-dirty-p)
11083 (push callback js2-mode-pending-parse-callbacks)
11084 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11086 (defun js2-mode-parse-finished ()
11087 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11088 ;; We can't let errors propagate up, since it prevents the
11089 ;; `js2-parse' method from completing normally and returning
11090 ;; the ast, which makes things mysteriously not work right.
11092 (dolist (cb js2-mode-pending-parse-callbacks)
11093 (condition-case err
11095 (error (message "%s" err))))
11096 (setq js2-mode-pending-parse-callbacks nil)))
11098 (defun js2-mode-flag-region (from to flag)
11099 "Hide or show text from FROM to TO, according to FLAG.
11100 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11101 Returns the created overlay if FLAG is non-nil."
11102 (remove-overlays from to 'invisible 'js2-outline)
11104 (let ((o (make-overlay from to)))
11105 (overlay-put o 'invisible 'js2-outline)
11106 (overlay-put o 'isearch-open-invisible
11107 'js2-isearch-open-invisible)
11110 ;; Function to be set as an outline-isearch-open-invisible' property
11111 ;; to the overlay that makes the outline invisible (see
11112 ;; `js2-mode-flag-region').
11113 (defun js2-isearch-open-invisible (overlay)
11114 ;; We rely on the fact that isearch places point on the matched text.
11115 (js2-mode-show-element))
11117 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11118 "Return cons cell of bounds of folding overlay at POS.
11119 Returns nil if not found."
11120 (let ((overlays (overlays-at (or pos (point))))
11122 (while (and overlays
11124 (if (overlay-get (car overlays) 'invisible)
11125 (setq o (car overlays))
11126 (setq overlays (cdr overlays))))
11128 (cons (overlay-start o) (overlay-end o)))))
11130 (defun js2-mode-function-at-point (&optional pos)
11131 "Return the innermost function node enclosing current point.
11132 Returns nil if point is not in a function."
11133 (let ((node (js2-node-at-point pos)))
11134 (while (and node (not (js2-function-node-p node)))
11135 (setq node (js2-node-parent node)))
11136 (if (js2-function-node-p node)
11139 (defun js2-mode-toggle-element ()
11140 "Hide or show the foldable element at the point."
11142 (let (comment fn pos)
11146 ;; /* ... */ comment?
11147 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11148 (if (js2-mode-invisible-overlay-bounds
11149 (setq pos (+ 3 (js2-node-abs-pos comment))))
11152 (js2-mode-show-element))
11153 (js2-mode-hide-element)))
11156 (back-to-indentation)
11157 (looking-at js2-mode-//-comment-re))
11158 (js2-mode-toggle-//-comment))
11160 ((setq fn (js2-mode-function-at-point))
11161 (setq pos (and (js2-function-node-body fn)
11162 (js2-node-abs-pos (js2-function-node-body fn))))
11163 (goto-char (1+ pos))
11164 (if (js2-mode-invisible-overlay-bounds)
11165 (js2-mode-show-element)
11166 (js2-mode-hide-element)))
11168 (message "Nothing at point to hide or show")))))))
11170 (defun js2-mode-hide-element ()
11171 "Fold/hide contents of a block, showing ellipses.
11172 Show the hidden text with \\[js2-mode-show-element]."
11174 (if js2-mode-buffer-dirty-p
11175 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11176 (let (node body beg end)
11178 ((js2-mode-invisible-overlay-bounds)
11179 (message "already hidden"))
11181 (setq node (js2-node-at-point))
11183 ((js2-block-comment-p node)
11184 (js2-mode-hide-comment node))
11186 (while (and node (not (js2-function-node-p node)))
11187 (setq node (js2-node-parent node)))
11189 (setq body (js2-function-node-body node)))
11191 (setq beg (js2-node-abs-pos body)
11192 end (+ beg (js2-node-len body)))
11193 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11194 (message "No collapsable element found at point"))))))))
11196 (defun js2-mode-show-element ()
11197 "Show the hidden element at current point."
11199 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11201 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11202 (message "Nothing to un-hide"))))
11204 (defun js2-mode-show-all ()
11205 "Show all of the text in the buffer."
11207 (js2-mode-flag-region (point-min) (point-max) nil))
11209 (defun js2-mode-toggle-hide-functions ()
11211 (if js2-mode-functions-hidden
11212 (js2-mode-show-functions)
11213 (js2-mode-hide-functions)))
11215 (defun js2-mode-hide-functions ()
11216 "Hides all non-nested function bodies in the buffer.
11217 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11218 to open an individual entry."
11220 (if js2-mode-buffer-dirty-p
11221 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11222 (if (null js2-mode-ast)
11223 (message "Oops - parsing failed")
11224 (setq js2-mode-functions-hidden t)
11225 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11227 (defun js2-mode-function-hider (n endp)
11229 (let ((tt (js2-node-type n))
11232 ((and (= tt js2-FUNCTION)
11233 (setq body (js2-function-node-body n)))
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 nil) ; don't process children of function
11239 t))))) ; keep processing other AST nodes
11241 (defun js2-mode-show-functions ()
11242 "Un-hide any folded function bodies in the buffer."
11244 (setq js2-mode-functions-hidden nil)
11246 (goto-char (point-min))
11247 (while (/= (goto-char (next-overlay-change (point)))
11249 (dolist (o (overlays-at (point)))
11250 (when (and (overlay-get o 'invisible)
11251 (not (overlay-get o 'comment)))
11252 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11254 (defun js2-mode-hide-comment (n)
11255 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11258 (beg (+ (js2-node-abs-pos n) head))
11259 (end (- (+ beg (js2-node-len n)) head 2))
11260 (o (js2-mode-flag-region beg end 'hide)))
11261 (overlay-put o 'comment t)))
11263 (defun js2-mode-toggle-hide-comments ()
11264 "Folds all block comments in the buffer.
11265 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11266 to open an individual entry."
11268 (if js2-mode-comments-hidden
11269 (js2-mode-show-comments)
11270 (js2-mode-hide-comments)))
11272 (defun js2-mode-hide-comments ()
11274 (if js2-mode-buffer-dirty-p
11275 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11276 (if (null js2-mode-ast)
11277 (message "Oops - parsing failed")
11278 (setq js2-mode-comments-hidden t)
11279 (dolist (n (js2-ast-root-comments js2-mode-ast))
11280 (let ((format (js2-comment-node-format n)))
11281 (when (js2-block-comment-p n)
11282 (js2-mode-hide-comment n))))
11283 (js2-mode-hide-//-comments)))
11285 (defsubst js2-mode-extend-//-comment (direction)
11286 "Find start or end of a block of similar //-comment lines.
11287 DIRECTION is -1 to look back, 1 to look forward.
11288 INDENT is the indentation level to match.
11289 Returns the end-of-line position of the furthest adjacent
11290 //-comment line with the same indentation as the current line.
11291 If there is no such matching line, returns current end of line."
11292 (let ((pos (point-at-eol))
11293 (indent (current-indentation)))
11296 (while (and (zerop (forward-line direction))
11297 (looking-at js2-mode-//-comment-re)
11298 (eq indent (length (match-string 1))))
11299 (setq pos (point-at-eol)))
11302 (defun js2-mode-hide-//-comments ()
11303 "Fold adjacent 1-line comments, showing only snippet of first one."
11307 (goto-char (point-min))
11308 (while (re-search-forward js2-mode-//-comment-re nil t)
11310 end (js2-mode-extend-//-comment 1))
11311 (unless (eq beg end)
11312 (overlay-put (js2-mode-flag-region beg end 'hide)
11315 (forward-char 1))))))
11317 (defun js2-mode-toggle-//-comment ()
11318 "Fold or un-fold any multi-line //-comment at point.
11319 Caller should have determined that this line starts with a //-comment."
11320 (let* ((beg (point-at-eol))
11324 (if (js2-mode-invisible-overlay-bounds)
11325 (js2-mode-show-element)
11326 ;; else hide the comment
11327 (setq beg (js2-mode-extend-//-comment -1)
11328 end (js2-mode-extend-//-comment 1))
11329 (unless (eq beg end)
11330 (overlay-put (js2-mode-flag-region beg end 'hide)
11333 (defun js2-mode-show-comments ()
11334 "Un-hide any hidden comments, leaving other hidden elements alone."
11336 (setq js2-mode-comments-hidden nil)
11338 (goto-char (point-min))
11339 (while (/= (goto-char (next-overlay-change (point)))
11341 (dolist (o (overlays-at (point)))
11342 (when (overlay-get o 'comment)
11343 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11345 (defun js2-mode-display-warnings-and-errors ()
11346 "Turn on display of warnings and errors."
11348 (setq js2-mode-show-parse-errors t
11349 js2-mode-show-strict-warnings t)
11350 (js2-reparse 'force))
11352 (defun js2-mode-hide-warnings-and-errors ()
11353 "Turn off display of warnings and errors."
11355 (setq js2-mode-show-parse-errors nil
11356 js2-mode-show-strict-warnings nil)
11357 (js2-reparse 'force))
11359 (defun js2-mode-toggle-warnings-and-errors ()
11360 "Toggle the display of warnings and errors.
11361 Some users don't like having warnings/errors reported while they type."
11363 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11364 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11365 (if (interactive-p)
11366 (message "warnings and errors %s"
11367 (if js2-mode-show-parse-errors
11370 (js2-reparse 'force))
11372 (defun js2-mode-customize ()
11374 (customize-group 'js2-mode))
11376 (defun js2-mode-forward-sexp (&optional arg)
11377 "Move forward across one statement or balanced expression.
11378 With ARG, do it that many times. Negative arg -N means
11379 move backward across N balanced expressions."
11381 (setq arg (or arg 1))
11382 (if js2-mode-buffer-dirty-p
11383 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11384 (let (node end (start (point)))
11387 ;; could probably make this better for some cases:
11388 ;; - if in statement block (e.g. function body), go to parent
11389 ;; - infix exprs like (foo in bar) - maybe go to beginning
11390 ;; of infix expr if in the right-side expression?
11391 ((and arg (minusp arg))
11392 (dotimes (i (- arg))
11394 (forward-char -1) ; enter the node we backed up to
11395 (setq node (js2-node-at-point (point) t))
11396 (goto-char (if node
11397 (js2-node-abs-pos node)
11404 (setq node (js2-node-at-point (point) t)
11405 end (if node (+ (js2-node-abs-pos node)
11406 (js2-node-len node))))
11407 (goto-char (or end (point-max))))))))
11409 (defun js2-next-error (&optional arg reset)
11410 "Move to next parse error.
11411 Typically invoked via \\[next-error].
11412 ARG is the number of errors, forward or backward, to move.
11413 RESET means start over from the beginning."
11415 (if (or (null js2-mode-ast)
11416 (and (null (js2-ast-root-errors js2-mode-ast))
11417 (null (js2-ast-root-warnings js2-mode-ast))))
11418 (message "No errors")
11420 (goto-char (point-min)))
11421 (let* ((errs (copy-sequence
11422 (append (js2-ast-root-errors js2-mode-ast)
11423 (js2-ast-root-warnings js2-mode-ast))))
11427 (backward (minusp count))
11428 (sorter (if backward '> '<))
11429 (stopper (if backward '< '>))
11430 (count (abs count))
11433 ;; sort by start position
11434 (setq errs (sort errs (lambda (e1 e2)
11435 (funcall sorter (second e1) (second e2))))
11437 ;; find nth error with pos > start
11438 (while (and errs continue)
11439 (when (funcall stopper (cadar errs) start)
11440 (setq err (car errs))
11441 (if (zerop (decf count))
11442 (setq continue nil)))
11443 (setq errs (cdr errs)))
11445 (goto-char (second err))
11446 ;; wrap around to first error
11447 (goto-char (second (car all-errs)))
11448 ;; if we were already on it, echo msg again
11449 (if (= (point) start)
11450 (js2-echo-error (point) (point)))))))
11452 (defun js2-down-mouse-3 ()
11453 "Make right-click move the point to the click location.
11454 This makes right-click context menu operations a bit more intuitive.
11455 The point will not move if the region is active, however, to avoid
11456 destroying the region selection."
11458 (when (and js2-move-point-on-right-click
11460 (let ((e last-input-event))
11462 (goto-char (cadadr e))))))
11464 (defun js2-mode-create-imenu-index ()
11465 "Return an alist for `imenu--index-alist'."
11466 ;; This is built up in `js2-parse-record-imenu' during parsing.
11468 ;; if we have an ast but no recorder, they're requesting a rescan
11469 (unless js2-imenu-recorder
11470 (js2-reparse 'force))
11472 (js2-build-imenu-index)
11473 (setq js2-imenu-recorder nil
11474 js2-imenu-function-map nil))))
11476 (defun js2-mode-find-tag ()
11477 "Replacement for `find-tag-default'.
11478 `find-tag-default' returns a ridiculous answer inside comments."
11480 (js2-with-underscore-as-word-syntax
11482 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11483 (looking-back "[A-Za-z0-9_$]"))
11484 (setq beg (progn (forward-word -1) (point))
11485 end (progn (forward-word 1) (point)))
11486 (setq beg (progn (forward-word 1) (point))
11487 end (progn (forward-word -1) (point))))
11488 (replace-regexp-in-string
11490 (buffer-substring-no-properties beg end))))))
11492 (defun js2-mode-forward-sibling ()
11493 "Move to the end of the sibling following point in parent.
11494 Returns non-nil if successful, or nil if there was no following sibling."
11495 (let* ((node (js2-node-at-point))
11496 (parent (js2-mode-find-enclosing-fn node))
11498 (when (setq sib (js2-node-find-child-after (point) parent))
11499 (goto-char (+ (js2-node-abs-pos sib)
11500 (js2-node-len sib))))))
11502 (defun js2-mode-backward-sibling ()
11503 "Move to the beginning of the sibling node preceding point in parent.
11504 Parent is defined as the enclosing script or function."
11505 (let* ((node (js2-node-at-point))
11506 (parent (js2-mode-find-enclosing-fn node))
11508 (when (setq sib (js2-node-find-child-before (point) parent))
11509 (goto-char (js2-node-abs-pos sib)))))
11511 (defun js2-beginning-of-defun ()
11512 "Go to line on which current function starts, and return non-nil.
11513 If we're not in a function, go to beginning of previous script-level element."
11515 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11518 ((and (js2-function-node-p parent)
11519 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11522 (js2-mode-backward-sibling)))))
11524 (defun js2-end-of-defun ()
11525 "Go to the char after the last position of the current function.
11526 If we're not in a function, skips over the next script-level element."
11528 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11529 (if (not (js2-function-node-p parent))
11530 ;; punt: skip over next script-level element beyond point
11531 (js2-mode-forward-sibling)
11532 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11533 (js2-node-len parent)))))))
11535 (defun js2-mark-defun (&optional allow-extend)
11536 "Put mark at end of this function, point at beginning.
11537 The function marked is the one that contains point.
11539 Interactively, if this command is repeated,
11540 or (in Transient Mark mode) if the mark is active,
11541 it marks the next defun after the ones already marked."
11544 (when (and allow-extend
11545 (or (and (eq last-command this-command) (mark t))
11546 (and transient-mark-mode mark-active)))
11547 (let ((sib (save-excursion
11549 (if (js2-mode-forward-sibling)
11556 ;; no more siblings - try extending to enclosing node
11557 (goto-char (mark t)))))
11558 (when (not extended)
11559 (let ((node (js2-node-at-point (point) t)) ; skip comments
11560 ast fn stmt parent beg end)
11561 (when (js2-ast-root-p node)
11563 node (or (js2-node-find-child-after (point) node)
11564 (js2-node-find-child-before (point) node))))
11565 ;; only mark whole buffer if we can't find any children
11568 (if (js2-function-node-p node)
11570 (setq fn (js2-mode-find-enclosing-fn node)
11571 stmt (if (or (null fn)
11572 (js2-ast-root-p fn))
11573 (js2-mode-find-first-stmt node))
11574 parent (or stmt fn)))
11575 (setq beg (js2-node-abs-pos parent)
11576 end (+ beg (js2-node-len parent)))
11579 (exchange-point-and-mark)))))
11581 (defun js2-narrow-to-defun ()
11582 "Narrow to the function enclosing point."
11584 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11585 (fn (if (js2-script-node-p node)
11587 (js2-mode-find-enclosing-fn node)))
11588 (beg (js2-node-abs-pos fn)))
11589 (unless (js2-ast-root-p fn)
11590 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11592 (provide 'js2-mode)
11594 ;;; js2-mode.el ends here