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-always-indent-assigned-expr-in-decls-p nil
244 "If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
245 always additionally indent function expression or array/object literal
246 assigned in a declaration, even when only one var is declared."
250 (defcustom js2-indent-on-enter-key nil
251 "Non-nil to have Enter/Return key indent the line.
252 This is unusual for Emacs modes but common in IDEs like Eclipse."
256 (defcustom js2-enter-indents-newline nil
257 "Non-nil to have Enter/Return key indent the newly-inserted line.
258 This is unusual for Emacs modes but common in IDEs like Eclipse."
262 (defcustom js2-rebind-eol-bol-keys t
263 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
264 If non-nil, bounce between bol/eol and first/last non-whitespace char."
268 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
269 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
270 Each value in the list is passed to `define-key'."
274 (defcustom js2-idle-timer-delay 0.2
275 "Delay in secs before re-parsing after user makes changes.
276 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
279 (make-variable-buffer-local 'js2-idle-timer-delay)
281 (defcustom js2-dynamic-idle-timer-adjust 0
282 "Positive to adjust `js2-idle-timer-delay' based on file size.
283 The idea is that for short files, parsing is faster so we can be
284 more responsive to user edits without interfering with editing.
285 The buffer length in characters (typically bytes) is divided by
286 this value and used to multiply `js2-idle-timer-delay' for the
287 buffer. For example, a 21k file and 10k adjust yields 21k/10k
288 == 2, so js2-idle-timer-delay is multiplied by 2.
289 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
290 `js2-idle-timer-delay' is not dependent on the file size."
294 (defcustom js2-mode-escape-quotes t
295 "Non-nil to disable automatic quote-escaping inside strings."
299 (defcustom js2-mode-squeeze-spaces t
300 "Non-nil to normalize whitespace when filling in comments.
301 Multiple runs of spaces are converted to a single space."
305 (defcustom js2-mode-show-parse-errors t
306 "True to highlight parse errors."
310 (defcustom js2-mode-show-strict-warnings t
311 "Non-nil to emit Ecma strict-mode warnings.
312 Some of the warnings can be individually disabled by other flags,
313 even if this flag is non-nil."
317 (defcustom js2-strict-trailing-comma-warning t
318 "Non-nil to warn about trailing commas in array literals.
319 Ecma-262 forbids them, but many browsers permit them. IE is the
320 big exception, and can produce bugs if you have trailing commas."
324 (defcustom js2-strict-missing-semi-warning t
325 "Non-nil to warn about semicolon auto-insertion after statement.
326 Technically this is legal per Ecma-262, but some style guides disallow
331 (defcustom js2-missing-semi-one-line-override nil
332 "Non-nil to permit missing semicolons in one-line functions.
333 In one-liner functions such as `function identity(x) {return x}'
334 people often omit the semicolon for a cleaner look. If you are
335 such a person, you can suppress the missing-semicolon warning
336 by setting this variable to t."
340 (defcustom js2-strict-inconsistent-return-warning t
341 "Non-nil to warn about mixing returns with value-returns.
342 It's perfectly legal to have a `return' and a `return foo' in the
343 same function, but it's often an indicator of a bug, and it also
344 interferes with type inference (in systems that support it.)"
348 (defcustom js2-strict-cond-assign-warning t
349 "Non-nil to warn about expressions like if (a = b).
350 This often should have been '==' instead of '='. If the warning
351 is enabled, you can suppress it on a per-expression basis by
352 parenthesizing the expression, e.g. if ((a = b)) ..."
356 (defcustom js2-strict-cond-assign-warning t
357 "Non-nil to warn about expressions like if (a = b).
358 This often should have been '==' instead of '='. If the warning
359 is enabled, you can suppress it on a per-expression basis by
360 parenthesizing the expression, e.g. if ((a = b)) ..."
364 (defcustom js2-strict-var-redeclaration-warning t
365 "Non-nil to warn about redeclaring variables in a script or function."
369 (defcustom js2-strict-var-hides-function-arg-warning t
370 "Non-nil to warn about a var decl hiding a function argument."
374 (defcustom js2-skip-preprocessor-directives nil
375 "Non-nil to treat lines beginning with # as comments.
376 Useful for viewing Mozilla JavaScript source code."
380 (defcustom js2-language-version 180
381 "Configures what JavaScript language version to recognize.
382 Currently versions 150, 160, 170 and 180 are supported, corresponding
383 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
384 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
385 and 1.8 adds function closures."
389 (defcustom js2-allow-keywords-as-property-names t
390 "If non-nil, you can use JavaScript keywords as object property names.
393 var foo = {int: 5, while: 6, continue: 7};
396 Ecma-262 forbids this syntax, but many browsers support it."
400 (defcustom js2-instanceof-has-side-effects nil
401 "If non-nil, treats the instanceof operator as having side effects.
402 This is useful for xulrunner apps."
406 (defcustom js2-cleanup-whitespace nil
407 "Non-nil to invoke `delete-trailing-whitespace' before saves."
411 (defcustom js2-move-point-on-right-click t
412 "Non-nil to move insertion point when you right-click.
413 This makes right-click context menu behavior a bit more intuitive,
414 since menu operations generally apply to the point. The exception
415 is if there is a region selection, in which case the point does -not-
416 move, so cut/copy/paste etc. can work properly.
418 Note that IntelliJ moves the point, and Eclipse leaves it alone,
419 so this behavior is customizable."
423 (defcustom js2-allow-rhino-new-expr-initializer t
424 "Non-nil to support a Rhino's experimental syntactic construct.
426 Rhino supports the ability to follow a `new' expression with an object
427 literal, which is used to set additional properties on the new object
428 after calling its constructor. Syntax:
430 new <expr> [ ( arglist ) ] [initializer]
432 Hence, this expression:
434 new Object {a: 1, b: 2}
436 results in an Object with properties a=1 and b=2. This syntax is
437 apparently not configurable in Rhino - it's currently always enabled,
438 as of Rhino version 1.7R2."
442 (defcustom js2-allow-member-expr-as-function-name nil
443 "Non-nil to support experimental Rhino syntax for function names.
445 Rhino supports an experimental syntax configured via the Rhino Context
446 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
448 function <member-expr> ( [ arg-list ] ) { <body> }
450 Where member-expr is a non-parenthesized 'member expression', which
451 is anything at the grammar level of a new-expression or lower, meaning
452 any expression that does not involve infix or unary operators.
454 When <member-expr> is not a simple identifier, then it is syntactic
455 sugar for assigning the anonymous function to the <member-expr>. Hence,
458 function a.b().c[2] (x, y) { ... }
462 a.b().c[2] = function(x, y) {...}
464 which doesn't seem particularly useful, but Rhino permits it."
468 (defvar js2-mode-version 20101228
469 "Release number for `js2-mode'.")
473 (defmacro js2-deflocal (name value &optional comment)
474 "Define a buffer-local variable NAME with VALUE and COMMENT."
476 (defvar ,name ,value ,comment)
477 (make-variable-buffer-local ',name)))
479 ;; We record the start and end position of each token.
480 (js2-deflocal js2-token-beg 1)
481 (js2-deflocal js2-token-end -1)
483 (defvar js2-EOF_CHAR -1
484 "Represents end of stream. Distinct from js2-EOF token type.")
486 ;; I originally used symbols to represent tokens, but Rhino uses
487 ;; ints and then sets various flag bits in them, so ints it is.
488 ;; The upshot is that we need a `js2-' prefix in front of each name.
489 (defvar js2-ERROR -1)
492 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
493 (defvar js2-LEAVEWITH 3)
494 (defvar js2-RETURN 4)
498 (defvar js2-SETNAME 8)
500 (defvar js2-BITXOR 10)
501 (defvar js2-BITAND 11)
511 (defvar js2-ADD 21) ; infix plus
512 (defvar js2-SUB 22) ; infix minus
517 (defvar js2-BITNOT 27)
518 (defvar js2-POS 28) ; unary plus
519 (defvar js2-NEG 29) ; unary minus
521 (defvar js2-DELPROP 31)
522 (defvar js2-TYPEOF 32)
523 (defvar js2-GETPROP 33)
524 (defvar js2-GETPROPNOWARN 34)
525 (defvar js2-SETPROP 35)
526 (defvar js2-GETELEM 36)
527 (defvar js2-SETELEM 37)
529 (defvar js2-NAME 39) ; an identifier
530 (defvar js2-NUMBER 40)
531 (defvar js2-STRING 41)
534 (defvar js2-FALSE 44)
536 (defvar js2-SHEQ 46) ; shallow equality (===)
537 (defvar js2-SHNE 47) ; shallow inequality (!==)
538 (defvar js2-REGEXP 48)
539 (defvar js2-BINDNAME 49)
540 (defvar js2-THROW 50)
541 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
543 (defvar js2-INSTANCEOF 53)
544 (defvar js2-LOCAL_LOAD 54)
545 (defvar js2-GETVAR 55)
546 (defvar js2-SETVAR 56)
547 (defvar js2-CATCH_SCOPE 57)
548 (defvar js2-ENUM_INIT_KEYS 58)
549 (defvar js2-ENUM_INIT_VALUES 59)
550 (defvar js2-ENUM_INIT_ARRAY 60)
551 (defvar js2-ENUM_NEXT 61)
552 (defvar js2-ENUM_ID 62)
553 (defvar js2-THISFN 63)
554 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
555 (defvar js2-ARRAYLIT 65) ; array literal
556 (defvar js2-OBJECTLIT 66) ; object literal
557 (defvar js2-GET_REF 67) ; *reference
558 (defvar js2-SET_REF 68) ; *reference = something
559 (defvar js2-DEL_REF 69) ; delete reference
560 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
561 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
562 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
565 (defvar js2-DEFAULTNAMESPACE 73)
566 (defvar js2-ESCXMLATTR 74)
567 (defvar js2-ESCXMLTEXT 75)
568 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
569 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
570 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
571 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
573 (defvar js2-first-bytecode js2-ENTERWITH)
574 (defvar js2-last-bytecode js2-REF_NS_NAME)
577 (defvar js2-SEMI 81) ; semicolon
578 (defvar js2-LB 82) ; left and right brackets
580 (defvar js2-LC 84) ; left and right curly-braces
582 (defvar js2-LP 86) ; left and right parens
584 (defvar js2-COMMA 88) ; comma operator
586 (defvar js2-ASSIGN 89) ; simple assignment (=)
587 (defvar js2-ASSIGN_BITOR 90) ; |=
588 (defvar js2-ASSIGN_BITXOR 91) ; ^=
589 (defvar js2-ASSIGN_BITAND 92) ; &=
590 (defvar js2-ASSIGN_LSH 93) ; <<=
591 (defvar js2-ASSIGN_RSH 94) ; >>=
592 (defvar js2-ASSIGN_URSH 95) ; >>>=
593 (defvar js2-ASSIGN_ADD 96) ; +=
594 (defvar js2-ASSIGN_SUB 97) ; -=
595 (defvar js2-ASSIGN_MUL 98) ; *=
596 (defvar js2-ASSIGN_DIV 99) ; /=
597 (defvar js2-ASSIGN_MOD 100) ; %=
599 (defvar js2-first-assign js2-ASSIGN)
600 (defvar js2-last-assign js2-ASSIGN_MOD)
602 (defvar js2-HOOK 101) ; conditional (?:)
603 (defvar js2-COLON 102)
604 (defvar js2-OR 103) ; logical or (||)
605 (defvar js2-AND 104) ; logical and (&&)
606 (defvar js2-INC 105) ; increment/decrement (++ --)
608 (defvar js2-DOT 107) ; member operator (.)
609 (defvar js2-FUNCTION 108) ; function keyword
610 (defvar js2-EXPORT 109) ; export keyword
611 (defvar js2-IMPORT 110) ; import keyword
612 (defvar js2-IF 111) ; if keyword
613 (defvar js2-ELSE 112) ; else keyword
614 (defvar js2-SWITCH 113) ; switch keyword
615 (defvar js2-CASE 114) ; case keyword
616 (defvar js2-DEFAULT 115) ; default keyword
617 (defvar js2-WHILE 116) ; while keyword
618 (defvar js2-DO 117) ; do keyword
619 (defvar js2-FOR 118) ; for keyword
620 (defvar js2-BREAK 119) ; break keyword
621 (defvar js2-CONTINUE 120) ; continue keyword
622 (defvar js2-VAR 121) ; var keyword
623 (defvar js2-WITH 122) ; with keyword
624 (defvar js2-CATCH 123) ; catch keyword
625 (defvar js2-FINALLY 124) ; finally keyword
626 (defvar js2-VOID 125) ; void keyword
627 (defvar js2-RESERVED 126) ; reserved keywords
629 (defvar js2-EMPTY 127)
631 ;; Types used for the parse tree - never returned by scanner.
633 (defvar js2-BLOCK 128) ; statement block
634 (defvar js2-LABEL 129) ; label
635 (defvar js2-TARGET 130)
636 (defvar js2-LOOP 131)
637 (defvar js2-EXPR_VOID 132) ; expression statement in functions
638 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
640 (defvar js2-SCRIPT 135) ; top-level node for entire script
641 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
642 (defvar js2-USE_STACK 137)
643 (defvar js2-SETPROP_OP 138) ; x.y op= something
644 (defvar js2-SETELEM_OP 139) ; x[y] op= something
645 (defvar js2-LOCAL_BLOCK 140)
646 (defvar js2-SET_REF_OP 141) ; *reference op= something
649 (defvar js2-DOTDOT 142) ; member operator (..)
650 (defvar js2-COLONCOLON 143) ; namespace::name
651 (defvar js2-XML 144) ; XML type
652 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
653 (defvar js2-XMLATTR 146) ; @
654 (defvar js2-XMLEND 147)
656 ;; Optimizer-only tokens
657 (defvar js2-TO_OBJECT 148)
658 (defvar js2-TO_DOUBLE 149)
660 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
661 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
662 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
663 (defvar js2-CONST 153)
664 (defvar js2-SETCONST 154)
665 (defvar js2-SETCONSTVAR 155)
666 (defvar js2-ARRAYCOMP 156)
667 (defvar js2-LETEXPR 157)
668 (defvar js2-WITHEXPR 158)
669 (defvar js2-DEBUGGER 159)
671 (defvar js2-COMMENT 160)
672 (defvar js2-ENUM 161) ; for "enum" reserved word
674 (defconst js2-num-tokens (1+ js2-ENUM))
676 (defconst js2-debug-print-trees nil)
678 ;; Rhino accepts any string or stream as input. Emacs character
679 ;; processing works best in buffers, so we'll assume the input is a
680 ;; buffer. JavaScript strings can be copied into temp buffers before
683 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
684 ;; They're the Emacs equivalent of instance variables, more or less.
686 (js2-deflocal js2-ts-dirty-line nil
687 "Token stream buffer-local variable.
688 Indicates stuff other than whitespace since start of line.")
690 (js2-deflocal js2-ts-regexp-flags nil
691 "Token stream buffer-local variable.")
693 (js2-deflocal js2-ts-string ""
694 "Token stream buffer-local variable.
695 Last string scanned.")
697 (js2-deflocal js2-ts-number nil
698 "Token stream buffer-local variable.
699 Last literal number scanned.")
701 (js2-deflocal js2-ts-hit-eof nil
702 "Token stream buffer-local variable.")
704 (js2-deflocal js2-ts-line-start 0
705 "Token stream buffer-local variable.")
707 (js2-deflocal js2-ts-lineno 1
708 "Token stream buffer-local variable.")
710 (js2-deflocal js2-ts-line-end-char -1
711 "Token stream buffer-local variable.")
713 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
714 "Token stream buffer-local variable.
715 Current scan position.")
717 (js2-deflocal js2-ts-is-xml-attribute nil
718 "Token stream buffer-local variable.")
720 (js2-deflocal js2-ts-xml-is-tag-content nil
721 "Token stream buffer-local variable.")
723 (js2-deflocal js2-ts-xml-open-tags-count 0
724 "Token stream buffer-local variable.")
726 (js2-deflocal js2-ts-string-buffer nil
727 "Token stream buffer-local variable.
728 List of chars built up while scanning various tokens.")
730 (js2-deflocal js2-ts-comment-type nil
731 "Token stream buffer-local variable.")
735 (js2-deflocal js2-parsed-errors nil
736 "List of errors produced during scanning/parsing.")
738 (js2-deflocal js2-parsed-warnings nil
739 "List of warnings produced during scanning/parsing.")
741 (js2-deflocal js2-recover-from-parse-errors t
742 "Non-nil to continue parsing after a syntax error.
744 In recovery mode, the AST will be built in full, and any error
745 nodes will be flagged with appropriate error information. If
746 this flag is nil, a syntax error will result in an error being
749 The variable is automatically buffer-local, because different
750 modes that use the parser will need different settings.")
752 (js2-deflocal js2-parse-hook nil
753 "List of callbacks for receiving parsing progress.")
755 (defvar js2-parse-finished-hook nil
756 "List of callbacks to notify when parsing finishes.
757 Not called if parsing was interrupted.")
759 (js2-deflocal js2-is-eval-code nil
760 "True if we're evaluating code in a string.
761 If non-nil, the tokenizer will record the token text, and the AST nodes
762 will record their source text. Off by default for IDE modes, since the
763 text is available in the buffer.")
765 (defvar js2-parse-ide-mode t
766 "Non-nil if the parser is being used for `js2-mode'.
767 If non-nil, the parser will set text properties for fontification
768 and the syntax table. The value should be nil when using the
769 parser as a frontend to an interpreter or byte compiler.")
771 ;;; Parser instance variables (buffer-local vars for js2-parse)
773 (defconst js2-clear-ti-mask #xFFFF
774 "Mask to clear token information bits.")
776 (defconst js2-ti-after-eol (lsh 1 16)
777 "Flag: first token of the source line.")
779 (defconst js2-ti-check-label (lsh 1 17)
780 "Flag: indicates to check for label.")
782 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
784 (js2-deflocal js2-compiler-generate-debug-info t)
785 (js2-deflocal js2-compiler-use-dynamic-scope nil)
786 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
787 (js2-deflocal js2-compiler-xml-available t)
788 (js2-deflocal js2-compiler-optimization-level 0)
789 (js2-deflocal js2-compiler-generating-source t)
790 (js2-deflocal js2-compiler-strict-mode nil)
791 (js2-deflocal js2-compiler-report-warning-as-error nil)
792 (js2-deflocal js2-compiler-generate-observer-count nil)
793 (js2-deflocal js2-compiler-activation-names nil)
797 ;; There's a compileFunction method in Context.java - may need it.
798 (js2-deflocal js2-called-by-compile-function nil
799 "True if `js2-parse' was called by `js2-compile-function'.
800 Will only be used when we finish implementing the interpreter.")
802 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
804 (js2-deflocal js2-current-flagged-token js2-EOF)
805 (js2-deflocal js2-current-token js2-EOF)
807 ;; SKIP: node factory - we're going to just call functions directly,
808 ;; and eventually go to a unified AST format.
810 (js2-deflocal js2-nesting-of-function 0)
812 (js2-deflocal js2-recorded-identifiers nil
813 "Tracks identifiers found during parsing.")
815 (defmacro js2-in-lhs (body)
816 `(let ((js2-is-in-lhs t))
819 (defmacro js2-in-rhs (body)
820 `(let ((js2-is-in-lhs nil))
823 (js2-deflocal js2-is-in-lhs nil
824 "True while parsing lhs statement")
826 (defcustom js2-global-externs nil
827 "A list of any extern names you'd like to consider always declared.
828 This list is global and is used by all js2-mode files.
829 You can create buffer-local externs list using `js2-additional-externs'.
831 There is also a buffer-local variable `js2-default-externs',
832 which is initialized by default to include the Ecma-262 externs
833 and the standard browser externs. The three lists are all
834 checked during highlighting."
838 (js2-deflocal js2-default-externs nil
839 "Default external declarations.
841 These are currently only used for highlighting undeclared variables,
842 which only worries about top-level (unqualified) references.
843 As js2-mode's processing improves, we will flesh out this list.
845 The initial value is set to `js2-ecma-262-externs', unless you
846 have set `js2-include-browser-externs', in which case the browser
847 externs are also included.
849 See `js2-additional-externs' for more information.")
851 (defcustom js2-include-browser-externs t
852 "Non-nil to include browser externs in the master externs list.
853 If you work on JavaScript files that are not intended for browsers,
854 such as Mozilla Rhino server-side JavaScript, set this to nil.
855 You can always include them on a per-file basis by calling
856 `js2-add-browser-externs' from a function on `js2-mode-hook'.
858 See `js2-additional-externs' for more information about externs."
862 (defcustom js2-include-rhino-externs t
863 "Non-nil to include Mozilla Rhino externs in the master externs list.
864 See `js2-additional-externs' for more information about externs."
868 (defcustom js2-include-gears-externs t
869 "Non-nil to include Google Gears externs in the master externs list.
870 See `js2-additional-externs' for more information about externs."
874 (js2-deflocal js2-additional-externs nil
875 "A buffer-local list of additional external declarations.
876 It is used to decide whether variables are considered undeclared
877 for purposes of highlighting.
879 Each entry is a lisp string. The string should be the fully qualified
880 name of an external entity. All externs should be added to this list,
881 so that as js2-mode's processing improves it can take advantage of them.
883 You may want to declare your externs in three ways.
884 First, you can add externs that are valid for all your JavaScript files.
885 You should probably do this by adding them to `js2-global-externs', which
886 is a global list used for all js2-mode files.
888 Next, you can add a function to `js2-mode-hook' that adds additional
889 externs appropriate for the specific file, perhaps based on its path.
890 These should go in `js2-additional-externs', which is buffer-local.
892 Finally, you can add a function to `js2-post-parse-callbacks',
893 which is called after parsing completes, and `root' is bound to
894 the root of the parse tree. At this stage you can set up an AST
895 node visitor using `js2-visit-ast' and examine the parse tree
896 for specific import patterns that may imply the existence of
897 other externs, possibly tied to your build system. These should also
898 be added to `js2-additional-externs'.
900 Your post-parse callback may of course also use the simpler and
901 faster (but perhaps less robust) approach of simply scanning the
902 buffer text for your imports, using regular expressions.")
905 ;; SKIP: encoded-source
907 ;;; The following variables are per-function and should be saved/restored
908 ;;; during function parsing...
910 (js2-deflocal js2-current-script-or-fn nil)
911 (js2-deflocal js2-current-scope nil)
912 (js2-deflocal js2-nesting-of-with 0)
913 (js2-deflocal js2-label-set nil
914 "An alist mapping label names to nodes.")
916 (js2-deflocal js2-loop-set nil)
917 (js2-deflocal js2-loop-and-switch-set nil)
918 (js2-deflocal js2-has-return-value nil)
919 (js2-deflocal js2-end-flags 0)
921 ;;; ...end of per function variables
923 ;; Without 2-token lookahead, labels are a problem.
924 ;; These vars store the token info of the last matched name,
925 ;; iff it wasn't the last matched token. Only valid in some contexts.
926 (defvar js2-prev-name-token-start nil)
927 (defvar js2-prev-name-token-string nil)
929 (defsubst js2-save-name-token-data (pos name)
930 (setq js2-prev-name-token-start pos
931 js2-prev-name-token-string name))
933 ;; These flags enumerate the possible ways a statement/function can
934 ;; terminate. These flags are used by endCheck() and by the Parser to
935 ;; detect inconsistent return usage.
937 ;; END_UNREACHED is reserved for code paths that are assumed to always be
938 ;; able to execute (example: throw, continue)
940 ;; END_DROPS_OFF indicates if the statement can transfer control to the
941 ;; next one. Statement such as return dont. A compound statement may have
942 ;; some branch that drops off control to the next statement.
944 ;; END_RETURNS indicates that the statement can return (without arguments)
945 ;; END_RETURNS_VALUE indicates that the statement can return a value.
947 ;; A compound statement such as
951 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
953 (defconst js2-end-unreached #x0)
954 (defconst js2-end-drops-off #x1)
955 (defconst js2-end-returns #x2)
956 (defconst js2-end-returns-value #x4)
957 (defconst js2-end-yields #x8)
959 ;; Rhino awkwardly passes a statementLabel parameter to the
960 ;; statementHelper() function, the main statement parser, which
961 ;; is then used by quite a few of the sub-parsers. We just make
962 ;; it a buffer-local variable and make sure it's cleaned up properly.
963 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
965 ;; Similarly, Rhino passes an inForInit boolean through about half
966 ;; the expression parsers. We use a dynamically-scoped variable,
967 ;; which makes it easier to funcall the parsers individually without
968 ;; worrying about whether they take the parameter or not.
969 (js2-deflocal js2-in-for-init nil)
970 (js2-deflocal js2-temp-name-counter 0)
971 (js2-deflocal js2-parse-stmt-count 0)
973 (defsubst js2-get-next-temp-name ()
974 (format "$%d" (incf js2-temp-name-counter)))
976 (defvar js2-parse-interruptable-p t
977 "Set this to nil to force parse to continue until finished.
978 This will mostly be useful for interpreters.")
980 (defvar js2-statements-per-pause 50
981 "Pause after this many statements to check for user input.
982 If user input is pending, stop the parse and discard the tree.
983 This makes for a smoother user experience for large files.
984 You may have to wait a second or two before the highlighting
985 and error-reporting appear, but you can always type ahead if
986 you wish. This appears to be more or less how Eclipse, IntelliJ
987 and other editors work.")
989 (js2-deflocal js2-record-comments t
990 "Instructs the scanner to record comments in `js2-scanned-comments'.")
992 (js2-deflocal js2-scanned-comments nil
993 "List of all comments from the current parse.")
995 (defcustom js2-mode-indent-inhibit-undo nil
996 "Non-nil to disable collection of Undo information when indenting lines.
997 Some users have requested this behavior. It's nil by default because
998 other Emacs modes don't work this way."
1002 (defcustom js2-mode-indent-ignore-first-tab nil
1003 "If non-nil, ignore first TAB keypress if we look indented properly.
1004 It's fairly common for users to navigate to an already-indented line
1005 and press TAB for reassurance that it's been indented. For this class
1006 of users, we want the first TAB press on a line to be ignored if the
1007 line is already indented to one of the precomputed alternatives.
1009 This behavior is only partly implemented. If you TAB-indent a line,
1010 navigate to another line, and then navigate back, it fails to clear
1011 the last-indented variable, so it thinks you've already hit TAB once,
1012 and performs the indent. A full solution would involve getting on the
1013 point-motion hooks for the entire buffer. If we come across another
1014 use cases that requires watching point motion, I'll consider doing it.
1016 If you set this variable to nil, then the TAB key will always change
1017 the indentation of the current line, if more than one alternative
1018 indentation spot exists."
1022 (defvar js2-indent-hook nil
1023 "A hook for user-defined indentation rules.
1025 Functions on this hook should expect two arguments: (LIST INDEX)
1026 The LIST argument is the list of computed indentation points for
1027 the current line. INDEX is the list index of the indentation point
1028 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1029 indent function is not going to change the current line indentation.
1031 If a hook function on this list returns a non-nil value, then
1032 `js2-bounce-indent' assumes the hook function has performed its own
1033 indentation, and will do nothing. If all hook functions on the list
1034 return nil, then `js2-bounce-indent' will use its computed indentation
1035 and reindent the line.
1037 When hook functions on this hook list are called, the variable
1038 `js2-mode-ast' may or may not be set, depending on whether the
1039 parse tree is available. If the variable is nil, you can pass a
1040 callback to `js2-mode-wait-for-parse', and your callback will be
1041 called after the new parse tree is built. This can take some time
1044 (defface js2-warning-face
1045 `((((class color) (background light))
1046 (:underline "orange"))
1047 (((class color) (background dark))
1048 (:underline "orange"))
1050 "Face for JavaScript warnings."
1053 (defface js2-error-face
1054 `((((class color) (background light))
1055 (:foreground "red"))
1056 (((class color) (background dark))
1057 (:foreground "red"))
1058 (t (:foreground "red")))
1059 "Face for JavaScript errors."
1062 (defface js2-jsdoc-tag-face
1063 '((t :foreground "SlateGray"))
1064 "Face used to highlight @whatever tags in jsdoc comments."
1067 (defface js2-jsdoc-type-face
1068 '((t :foreground "SteelBlue"))
1069 "Face used to highlight {FooBar} types in jsdoc comments."
1072 (defface js2-jsdoc-value-face
1073 '((t :foreground "PeachPuff3"))
1074 "Face used to highlight tag values in jsdoc comments."
1077 (defface js2-function-param-face
1078 '((t :foreground "SeaGreen"))
1079 "Face used to highlight function parameters in javascript."
1082 (defface js2-instance-member-face
1083 '((t :foreground "DarkOrchid"))
1084 "Face used to highlight instance variables in javascript.
1085 Not currently used."
1088 (defface js2-private-member-face
1089 '((t :foreground "PeachPuff3"))
1090 "Face used to highlight calls to private methods in javascript.
1091 Not currently used."
1094 (defface js2-private-function-call-face
1095 '((t :foreground "goldenrod"))
1096 "Face used to highlight calls to private functions in javascript.
1097 Not currently used."
1100 (defface js2-jsdoc-html-tag-name-face
1102 '((((class color) (min-colors 88) (background light))
1103 (:foreground "rosybrown"))
1104 (((class color) (min-colors 8) (background dark))
1105 (:foreground "yellow"))
1106 (((class color) (min-colors 8) (background light))
1107 (:foreground "magenta")))
1108 '((((type tty pc) (class color) (background light))
1109 (:foreground "magenta"))
1110 (((type tty pc) (class color) (background dark))
1111 (:foreground "yellow"))
1112 (t (:foreground "RosyBrown"))))
1113 "Face used to highlight jsdoc html tag names"
1116 (defface js2-jsdoc-html-tag-delimiter-face
1118 '((((class color) (min-colors 88) (background light))
1119 (:foreground "dark khaki"))
1120 (((class color) (min-colors 8) (background dark))
1121 (:foreground "green"))
1122 (((class color) (min-colors 8) (background light))
1123 (:foreground "green")))
1124 '((((type tty pc) (class color) (background light))
1125 (:foreground "green"))
1126 (((type tty pc) (class color) (background dark))
1127 (:foreground "green"))
1128 (t (:foreground "dark khaki"))))
1129 "Face used to highlight brackets in jsdoc html tags."
1132 (defface js2-magic-paren-face
1134 "Face used to color parens that will be auto-overwritten."
1137 (defcustom js2-post-parse-callbacks nil
1138 "A list of callback functions invoked after parsing finishes.
1139 Currently, the main use for this function is to add synthetic
1140 declarations to `js2-recorded-identifiers', which see."
1144 (defface js2-external-variable-face
1145 '((t :foreground "orange"))
1146 "Face used to highlight undeclared variable identifiers.
1147 An undeclared variable is any variable not declared with var or let
1148 in the current scope or any lexically enclosing scope. If you use
1149 such a variable, then you are either expecting it to originate from
1150 another file, or you've got a potential bug."
1153 (defcustom js2-highlight-external-variables t
1154 "Non-nil to highlight undeclared variable identifiers."
1158 (defcustom js2-auto-insert-catch-block t
1159 "Non-nil to insert matching catch block on open-curly after `try'."
1163 (defvar js2-mode-map
1164 (let ((map (make-sparse-keymap))
1166 (define-key map [mouse-1] #'js2-mode-show-node)
1167 (define-key map (kbd "C-m") #'js2-enter-key)
1168 (when js2-rebind-eol-bol-keys
1169 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1170 (define-key map (kbd "C-e") #'js2-end-of-line))
1171 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1172 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1173 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1174 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1175 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1176 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1177 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1178 (define-key map (kbd "C-c C-`") #'js2-next-error)
1179 ;; also define user's preference for next-error, if available
1180 (if (setq keys (where-is-internal #'next-error))
1181 (define-key map (car keys) #'js2-next-error))
1182 (define-key map (or (car (where-is-internal #'mark-defun))
1185 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1187 #'js2-narrow-to-defun)
1188 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1189 (when js2-auto-indent-p
1191 (define-key map key #'js2-insert-and-indent))
1193 (when js2-bounce-indent-p
1194 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1196 (define-key map [menu-bar javascript]
1197 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1199 (define-key map [menu-bar javascript customize-js2-mode]
1200 '(menu-item "Customize js2-mode" js2-mode-customize
1201 :help "Customize the behavior of this mode"))
1203 (define-key map [menu-bar javascript js2-force-refresh]
1204 '(menu-item "Force buffer refresh" js2-mode-reset
1205 :help "Re-parse the buffer from scratch"))
1207 (define-key map [menu-bar javascript separator-2]
1210 (define-key map [menu-bar javascript next-error]
1211 '(menu-item "Next warning or error" js2-next-error
1212 :enabled (and js2-mode-ast
1213 (or (js2-ast-root-errors js2-mode-ast)
1214 (js2-ast-root-warnings js2-mode-ast)))
1215 :help "Move to next warning or error"))
1217 (define-key map [menu-bar javascript display-errors]
1218 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1219 :visible (not js2-mode-show-parse-errors)
1220 :help "Turn on display of warnings and errors"))
1222 (define-key map [menu-bar javascript hide-errors]
1223 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1224 :visible js2-mode-show-parse-errors
1225 :help "Turn off display of warnings and errors"))
1227 (define-key map [menu-bar javascript separator-1]
1230 (define-key map [menu-bar javascript js2-toggle-function]
1231 '(menu-item "Show/collapse element" js2-mode-toggle-element
1232 :help "Hide or show function body or comment"))
1234 (define-key map [menu-bar javascript show-comments]
1235 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1236 :visible js2-mode-comments-hidden
1237 :help "Expand all hidden block comments"))
1239 (define-key map [menu-bar javascript hide-comments]
1240 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1241 :visible (not js2-mode-comments-hidden)
1242 :help "Show block comments as /*...*/"))
1244 (define-key map [menu-bar javascript show-all-functions]
1245 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1246 :visible js2-mode-functions-hidden
1247 :help "Expand all hidden function bodies"))
1249 (define-key map [menu-bar javascript hide-all-functions]
1250 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1251 :visible (not js2-mode-functions-hidden)
1252 :help "Show {...} for all top-level function bodies"))
1255 "Keymap used in `js2-mode' buffers.")
1257 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1259 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1260 "Matches a //-comment line. Must be first non-whitespace on line.
1261 First match-group is the leading whitespace.")
1263 (defvar js2-mode-hook nil)
1265 (js2-deflocal js2-mode-ast nil "Private variable.")
1266 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1267 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1268 (js2-deflocal js2-mode-parsing nil "Private variable.")
1269 (js2-deflocal js2-mode-node-overlay nil)
1271 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1272 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1274 (js2-deflocal js2-mode-fontifications nil "Private variable")
1275 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1276 (js2-deflocal js2-imenu-recorder nil "Private variable")
1277 (js2-deflocal js2-imenu-function-map nil "Private variable")
1279 (defvar js2-paragraph-start
1280 "\\(@[a-zA-Z]+\\>\\|$\\)")
1282 ;; Note that we also set a 'c-in-sws text property in html comments,
1283 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1284 (defvar js2-syntactic-ws-start
1285 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1287 (defvar js2-syntactic-ws-end
1288 "\\s \\|[\n\r/]\\|\\s!")
1290 (defvar js2-syntactic-eol
1291 (concat "\\s *\\(/\\*[^*\n\r]*"
1292 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1294 "\\(//\\|/\\*[^*\n\r]*"
1295 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1297 "Copied from `java-mode'. Needed for some cc-engine functions.")
1299 (defvar js2-comment-prefix-regexp
1302 (defvar js2-comment-start-skip
1303 "\\(//+\\|/\\*+\\)\\s *")
1305 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1306 "Non-nil to emit status messages during parsing.")
1308 (defvar js2-mode-functions-hidden nil "private variable")
1309 (defvar js2-mode-comments-hidden nil "private variable")
1311 (defvar js2-mode-syntax-table
1312 (let ((table (make-syntax-table)))
1313 (c-populate-syntax-table table)
1315 "Syntax table used in js2-mode buffers.")
1317 (defvar js2-mode-abbrev-table nil
1318 "Abbrev table in use in `js2-mode' buffers.")
1319 (define-abbrev-table 'js2-mode-abbrev-table ())
1321 (defvar js2-mode-pending-parse-callbacks nil
1322 "List of functions waiting to be notified that parse is finished.")
1324 (defvar js2-mode-last-indented-line -1)
1326 ;;; Localizable error and warning messages
1328 ;; Messages are copied from Rhino's Messages.properties.
1329 ;; Many of the Java-specific messages have been elided.
1330 ;; Add any js2-specific ones at the end, so we can keep
1331 ;; this file synced with changes to Rhino's.
1333 (defvar js2-message-table
1334 (make-hash-table :test 'equal :size 250)
1335 "Contains localized messages for js2-mode.")
1337 ;; TODO(stevey): construct this table at compile-time.
1338 (defmacro js2-msg (key &rest strings)
1339 `(puthash ,key (funcall #'concat ,@strings)
1342 (defun js2-get-msg (msg-key)
1343 "Look up a localized message.
1344 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1345 the correct number of ARGS must be provided."
1346 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1347 (args (if (listp msg-key) (cdr msg-key)))
1348 (msg (gethash key js2-message-table)))
1350 (apply #'format msg args)
1351 key))) ; default to showing the key
1353 (js2-msg "msg.dup.parms"
1354 "Duplicate parameter name '%s'.")
1356 (js2-msg "msg.too.big.jump"
1357 "Program too complex: jump offset too big.")
1359 (js2-msg "msg.too.big.index"
1360 "Program too complex: internal index exceeds 64K limit.")
1362 (js2-msg "msg.while.compiling.fn"
1363 "Encountered code generation error while compiling function '%s': %s")
1365 (js2-msg "msg.while.compiling.script"
1366 "Encountered code generation error while compiling script: %s")
1369 (js2-msg "msg.ctor.not.found"
1370 "Constructor for '%s' not found.")
1372 (js2-msg "msg.not.ctor"
1373 "'%s' is not a constructor.")
1376 (js2-msg "msg.varargs.ctor"
1377 "Method or constructor '%s' must be static "
1378 "with the signature (Context cx, Object[] args, "
1379 "Function ctorObj, boolean inNewExpr) "
1380 "to define a variable arguments constructor.")
1382 (js2-msg "msg.varargs.fun"
1383 "Method '%s' must be static with the signature "
1384 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1385 "to define a variable arguments function.")
1387 (js2-msg "msg.incompat.call"
1388 "Method '%s' called on incompatible object.")
1390 (js2-msg "msg.bad.parms"
1391 "Unsupported parameter type '%s' in method '%s'.")
1393 (js2-msg "msg.bad.method.return"
1394 "Unsupported return type '%s' in method '%s'.")
1396 (js2-msg "msg.bad.ctor.return"
1397 "Construction of objects of type '%s' is not supported.")
1399 (js2-msg "msg.no.overload"
1400 "Method '%s' occurs multiple times in class '%s'.")
1402 (js2-msg "msg.method.not.found"
1403 "Method '%s' not found in '%s'.")
1407 (js2-msg "msg.bad.for.in.lhs"
1408 "Invalid left-hand side of for..in loop.")
1410 (js2-msg "msg.mult.index"
1411 "Only one variable allowed in for..in loop.")
1413 (js2-msg "msg.bad.for.in.destruct"
1414 "Left hand side of for..in loop must be an array of "
1415 "length 2 to accept key/value pair.")
1417 (js2-msg "msg.cant.convert"
1418 "Can't convert to type '%s'.")
1420 (js2-msg "msg.bad.assign.left"
1421 "Invalid assignment left-hand side.")
1423 (js2-msg "msg.bad.decr"
1424 "Invalid decerement operand.")
1426 (js2-msg "msg.bad.incr"
1427 "Invalid increment operand.")
1429 (js2-msg "msg.bad.yield"
1430 "yield must be in a function.")
1432 (js2-msg "msg.yield.parenthesized"
1433 "yield expression must be parenthesized.")
1436 (js2-msg "msg.cant.call.indirect"
1437 "Function '%s' must be called directly, and not by way of a "
1438 "function of another name.")
1440 (js2-msg "msg.eval.nonstring"
1441 "Calling eval() with anything other than a primitive "
1442 "string value will simply return the value. "
1443 "Is this what you intended?")
1445 (js2-msg "msg.eval.nonstring.strict"
1446 "Calling eval() with anything other than a primitive "
1447 "string value is not allowed in strict mode.")
1449 (js2-msg "msg.bad.destruct.op"
1450 "Invalid destructuring assignment operator")
1453 (js2-msg "msg.only.from.new"
1454 "'%s' may only be invoked from a `new' expression.")
1456 (js2-msg "msg.deprec.ctor"
1457 "The '%s' constructor is deprecated.")
1460 (js2-msg "msg.no.function.ref.found"
1461 "no source found to decompile function reference %s")
1463 (js2-msg "msg.arg.isnt.array"
1464 "second argument to Function.prototype.apply must be an array")
1467 (js2-msg "msg.bad.esc.mask"
1468 "invalid string escape mask")
1471 (js2-msg "msg.bad.quant"
1472 "Invalid quantifier %s")
1474 (js2-msg "msg.overlarge.backref"
1475 "Overly large back reference %s")
1477 (js2-msg "msg.overlarge.min"
1478 "Overly large minimum %s")
1480 (js2-msg "msg.overlarge.max"
1481 "Overly large maximum %s")
1483 (js2-msg "msg.zero.quant"
1484 "Zero quantifier %s")
1486 (js2-msg "msg.max.lt.min"
1487 "Maximum %s less than minimum")
1489 (js2-msg "msg.unterm.quant"
1490 "Unterminated quantifier %s")
1492 (js2-msg "msg.unterm.paren"
1493 "Unterminated parenthetical %s")
1495 (js2-msg "msg.unterm.class"
1496 "Unterminated character class %s")
1498 (js2-msg "msg.bad.range"
1499 "Invalid range in character class.")
1501 (js2-msg "msg.trail.backslash"
1502 "Trailing \\ in regular expression.")
1504 (js2-msg "msg.re.unmatched.right.paren"
1505 "unmatched ) in regular expression.")
1507 (js2-msg "msg.no.regexp"
1508 "Regular expressions are not available.")
1510 (js2-msg "msg.bad.backref"
1511 "back-reference exceeds number of capturing parentheses.")
1513 (js2-msg "msg.bad.regexp.compile"
1514 "Only one argument may be specified if the first "
1515 "argument to RegExp.prototype.compile is a RegExp object.")
1518 (js2-msg "msg.got.syntax.errors"
1519 "Compilation produced %s syntax errors.")
1521 (js2-msg "msg.var.redecl"
1522 "TypeError: redeclaration of var %s.")
1524 (js2-msg "msg.const.redecl"
1525 "TypeError: redeclaration of const %s.")
1527 (js2-msg "msg.let.redecl"
1528 "TypeError: redeclaration of variable %s.")
1530 (js2-msg "msg.parm.redecl"
1531 "TypeError: redeclaration of formal parameter %s.")
1533 (js2-msg "msg.fn.redecl"
1534 "TypeError: redeclaration of function %s.")
1536 (js2-msg "msg.let.decl.not.in.block"
1537 "SyntaxError: let declaration not directly within block")
1540 (js2-msg "msg.dup.label"
1543 (js2-msg "msg.undef.label"
1546 (js2-msg "msg.bad.break"
1547 "unlabelled break must be inside loop or switch")
1549 (js2-msg "msg.continue.outside"
1550 "continue must be inside loop")
1552 (js2-msg "msg.continue.nonloop"
1553 "continue can only use labels of iteration statements")
1555 (js2-msg "msg.bad.throw.eol"
1556 "Line terminator is not allowed between the throw "
1557 "keyword and throw expression.")
1559 (js2-msg "msg.no.paren.parms"
1560 "missing ( before function parameters.")
1562 (js2-msg "msg.no.parm"
1563 "missing formal parameter")
1565 (js2-msg "msg.no.paren.after.parms"
1566 "missing ) after formal parameters")
1568 (js2-msg "msg.no.brace.body"
1569 "missing '{' before function body")
1571 (js2-msg "msg.no.brace.after.body"
1572 "missing } after function body")
1574 (js2-msg "msg.no.paren.cond"
1575 "missing ( before condition")
1577 (js2-msg "msg.no.paren.after.cond"
1578 "missing ) after condition")
1580 (js2-msg "msg.no.semi.stmt"
1581 "missing ; before statement")
1583 (js2-msg "msg.missing.semi"
1584 "missing ; after statement")
1586 (js2-msg "msg.no.name.after.dot"
1587 "missing name after . operator")
1589 (js2-msg "msg.no.name.after.coloncolon"
1590 "missing name after :: operator")
1592 (js2-msg "msg.no.name.after.dotdot"
1593 "missing name after .. operator")
1595 (js2-msg "msg.no.name.after.xmlAttr"
1596 "missing name after .@")
1598 (js2-msg "msg.no.bracket.index"
1599 "missing ] in index expression")
1601 (js2-msg "msg.no.paren.switch"
1602 "missing ( before switch expression")
1604 (js2-msg "msg.no.paren.after.switch"
1605 "missing ) after switch expression")
1607 (js2-msg "msg.no.brace.switch"
1608 "missing '{' before switch body")
1610 (js2-msg "msg.bad.switch"
1611 "invalid switch statement")
1613 (js2-msg "msg.no.colon.case"
1614 "missing : after case expression")
1616 (js2-msg "msg.double.switch.default"
1617 "double default label in the switch statement")
1619 (js2-msg "msg.no.while.do"
1620 "missing while after do-loop body")
1622 (js2-msg "msg.no.paren.for"
1623 "missing ( after for")
1625 (js2-msg "msg.no.semi.for"
1626 "missing ; after for-loop initializer")
1628 (js2-msg "msg.no.semi.for.cond"
1629 "missing ; after for-loop condition")
1631 (js2-msg "msg.in.after.for.name"
1632 "missing in after for")
1634 (js2-msg "msg.no.paren.for.ctrl"
1635 "missing ) after for-loop control")
1637 (js2-msg "msg.no.paren.with"
1638 "missing ( before with-statement object")
1640 (js2-msg "msg.no.paren.after.with"
1641 "missing ) after with-statement object")
1643 (js2-msg "msg.no.paren.after.let"
1644 "missing ( after let")
1646 (js2-msg "msg.no.paren.let"
1647 "missing ) after variable list")
1649 (js2-msg "msg.no.curly.let"
1650 "missing } after let statement")
1652 (js2-msg "msg.bad.return"
1655 (js2-msg "msg.no.brace.block"
1656 "missing } in compound statement")
1658 (js2-msg "msg.bad.label"
1661 (js2-msg "msg.bad.var"
1662 "missing variable name")
1664 (js2-msg "msg.bad.var.init"
1665 "invalid variable initialization")
1667 (js2-msg "msg.no.colon.cond"
1668 "missing : in conditional expression")
1670 (js2-msg "msg.no.paren.arg"
1671 "missing ) after argument list")
1673 (js2-msg "msg.no.bracket.arg"
1674 "missing ] after element list")
1676 (js2-msg "msg.bad.prop"
1677 "invalid property id")
1679 (js2-msg "msg.no.colon.prop"
1680 "missing : after property id")
1682 (js2-msg "msg.no.brace.prop"
1683 "missing } after property list")
1685 (js2-msg "msg.no.paren"
1686 "missing ) in parenthetical")
1688 (js2-msg "msg.reserved.id"
1689 "identifier is a reserved word")
1691 (js2-msg "msg.no.paren.catch"
1692 "missing ( before catch-block condition")
1694 (js2-msg "msg.bad.catchcond"
1695 "invalid catch block condition")
1697 (js2-msg "msg.catch.unreachable"
1698 "any catch clauses following an unqualified catch are unreachable")
1700 (js2-msg "msg.no.brace.try"
1701 "missing '{' before try block")
1703 (js2-msg "msg.no.brace.catchblock"
1704 "missing '{' before catch-block body")
1706 (js2-msg "msg.try.no.catchfinally"
1707 "'try' without 'catch' or 'finally'")
1709 (js2-msg "msg.no.return.value"
1710 "function %s does not always return a value")
1712 (js2-msg "msg.anon.no.return.value"
1713 "anonymous function does not always return a value")
1715 (js2-msg "msg.return.inconsistent"
1716 "return statement is inconsistent with previous usage")
1718 (js2-msg "msg.generator.returns"
1719 "TypeError: generator function '%s' returns a value")
1721 (js2-msg "msg.anon.generator.returns"
1722 "TypeError: anonymous generator function returns a value")
1724 (js2-msg "msg.syntax"
1727 (js2-msg "msg.unexpected.eof"
1728 "Unexpected end of file")
1730 (js2-msg "msg.XML.bad.form"
1731 "illegally formed XML syntax")
1733 (js2-msg "msg.XML.not.available"
1734 "XML runtime not available")
1736 (js2-msg "msg.too.deep.parser.recursion"
1737 "Too deep recursion while parsing")
1739 (js2-msg "msg.no.side.effects"
1740 "Code has no side effects")
1742 (js2-msg "msg.extra.trailing.comma"
1743 "Trailing comma is not legal in an ECMA-262 object initializer")
1745 (js2-msg "msg.array.trailing.comma"
1746 "Trailing comma yields different behavior across browsers")
1748 (js2-msg "msg.equal.as.assign"
1749 (concat "Test for equality (==) mistyped as assignment (=)?"
1750 " (parenthesize to suppress warning)"))
1752 (js2-msg "msg.var.hides.arg"
1753 "Variable %s hides argument")
1755 (js2-msg "msg.destruct.assign.no.init"
1756 "Missing = in destructuring declaration")
1759 (js2-msg "msg.no.properties"
1760 "%s has no properties.")
1762 (js2-msg "msg.invalid.iterator"
1763 "Invalid iterator value")
1765 (js2-msg "msg.iterator.primitive"
1766 "__iterator__ returned a primitive value")
1768 (js2-msg "msg.assn.create.strict"
1769 "Assignment to undeclared variable %s")
1771 (js2-msg "msg.ref.undefined.prop"
1772 "Reference to undefined property '%s'")
1774 (js2-msg "msg.prop.not.found"
1775 "Property %s not found.")
1777 (js2-msg "msg.invalid.type"
1778 "Invalid JavaScript value of type %s")
1780 (js2-msg "msg.primitive.expected"
1781 "Primitive type expected (had %s instead)")
1783 (js2-msg "msg.namespace.expected"
1784 "Namespace object expected to left of :: (found %s instead)")
1786 (js2-msg "msg.null.to.object"
1787 "Cannot convert null to an object.")
1789 (js2-msg "msg.undef.to.object"
1790 "Cannot convert undefined to an object.")
1792 (js2-msg "msg.cyclic.value"
1793 "Cyclic %s value not allowed.")
1795 (js2-msg "msg.is.not.defined"
1796 "'%s' is not defined.")
1798 (js2-msg "msg.undef.prop.read"
1799 "Cannot read property '%s' from %s")
1801 (js2-msg "msg.undef.prop.write"
1802 "Cannot set property '%s' of %s to '%s'")
1804 (js2-msg "msg.undef.prop.delete"
1805 "Cannot delete property '%s' of %s")
1807 (js2-msg "msg.undef.method.call"
1808 "Cannot call method '%s' of %s")
1810 (js2-msg "msg.undef.with"
1811 "Cannot apply 'with' to %s")
1813 (js2-msg "msg.isnt.function"
1814 "%s is not a function, it is %s.")
1816 (js2-msg "msg.isnt.function.in"
1817 "Cannot call property %s in object %s. "
1818 "It is not a function, it is '%s'.")
1820 (js2-msg "msg.function.not.found"
1821 "Cannot find function %s.")
1823 (js2-msg "msg.function.not.found.in"
1824 "Cannot find function %s in object %s.")
1826 (js2-msg "msg.isnt.xml.object"
1827 "%s is not an xml object.")
1829 (js2-msg "msg.no.ref.to.get"
1830 "%s is not a reference to read reference value.")
1832 (js2-msg "msg.no.ref.to.set"
1833 "%s is not a reference to set reference value to %s.")
1835 (js2-msg "msg.no.ref.from.function"
1836 "Function %s can not be used as the left-hand "
1837 "side of assignment or as an operand of ++ or -- operator.")
1839 (js2-msg "msg.bad.default.value"
1840 "Object's getDefaultValue() method returned an object.")
1842 (js2-msg "msg.instanceof.not.object"
1843 "Can't use instanceof on a non-object.")
1845 (js2-msg "msg.instanceof.bad.prototype"
1846 "'prototype' property of %s is not an object.")
1848 (js2-msg "msg.bad.radix"
1849 "illegal radix %s.")
1852 (js2-msg "msg.default.value"
1853 "Cannot find default value for object.")
1855 (js2-msg "msg.zero.arg.ctor"
1856 "Cannot load class '%s' which has no zero-parameter constructor.")
1858 (js2-msg "msg.ctor.multiple.parms"
1859 "Can't define constructor or class %s since more than "
1860 "one constructor has multiple parameters.")
1862 (js2-msg "msg.extend.scriptable"
1863 "%s must extend ScriptableObject in order to define property %s.")
1865 (js2-msg "msg.bad.getter.parms"
1866 "In order to define a property, getter %s must have zero "
1867 "parameters or a single ScriptableObject parameter.")
1869 (js2-msg "msg.obj.getter.parms"
1870 "Expected static or delegated getter %s to take "
1871 "a ScriptableObject parameter.")
1873 (js2-msg "msg.getter.static"
1874 "Getter and setter must both be static or neither be static.")
1876 (js2-msg "msg.setter.return"
1877 "Setter must have void return type: %s")
1879 (js2-msg "msg.setter2.parms"
1880 "Two-parameter setter must take a ScriptableObject as "
1881 "its first parameter.")
1883 (js2-msg "msg.setter1.parms"
1884 "Expected single parameter setter for %s")
1886 (js2-msg "msg.setter2.expected"
1887 "Expected static or delegated setter %s to take two parameters.")
1889 (js2-msg "msg.setter.parms"
1890 "Expected either one or two parameters for setter.")
1892 (js2-msg "msg.setter.bad.type"
1893 "Unsupported parameter type '%s' in setter '%s'.")
1895 (js2-msg "msg.add.sealed"
1896 "Cannot add a property to a sealed object: %s.")
1898 (js2-msg "msg.remove.sealed"
1899 "Cannot remove a property from a sealed object: %s.")
1901 (js2-msg "msg.modify.sealed"
1902 "Cannot modify a property of a sealed object: %s.")
1904 (js2-msg "msg.modify.readonly"
1905 "Cannot modify readonly property: %s.")
1908 (js2-msg "msg.missing.exponent"
1911 (js2-msg "msg.caught.nfe"
1912 "number format error")
1914 (js2-msg "msg.unterminated.string.lit"
1915 "unterminated string literal")
1917 (js2-msg "msg.unterminated.comment"
1918 "unterminated comment")
1920 (js2-msg "msg.unterminated.re.lit"
1921 "unterminated regular expression literal")
1923 (js2-msg "msg.invalid.re.flag"
1924 "invalid flag after regular expression")
1926 (js2-msg "msg.no.re.input.for"
1929 (js2-msg "msg.illegal.character"
1930 "illegal character")
1932 (js2-msg "msg.invalid.escape"
1933 "invalid Unicode escape sequence")
1935 (js2-msg "msg.bad.namespace"
1936 "not a valid default namespace statement. "
1937 "Syntax is: default xml namespace = EXPRESSION;")
1939 ;; TokensStream warnings
1940 (js2-msg "msg.bad.octal.literal"
1941 "illegal octal literal digit %s; "
1942 "interpreting it as a decimal digit")
1944 (js2-msg "msg.reserved.keyword"
1945 "illegal usage of future reserved keyword %s; "
1946 "interpreting it as ordinary identifier")
1948 (js2-msg "msg.script.is.not.constructor"
1949 "Script objects are not constructors.")
1952 (js2-msg "msg.arraylength.bad"
1953 "Inappropriate array length.")
1956 (js2-msg "msg.arraylength.too.big"
1957 "Array length %s exceeds supported capacity limit.")
1960 (js2-msg "msg.bad.uri"
1961 "Malformed URI sequence.")
1964 (js2-msg "msg.bad.precision"
1965 "Precision %s out of range.")
1968 (js2-msg "msg.send.newborn"
1969 "Attempt to send value to newborn generator")
1971 (js2-msg "msg.already.exec.gen"
1972 "Already executing generator")
1974 (js2-msg "msg.StopIteration.invalid"
1975 "StopIteration may not be changed to an arbitrary object.")
1978 (js2-msg "msg.yield.closing"
1979 "Yield from closing generator")
1983 (defun js2-delete-if (predicate list)
1984 "Remove all items satisfying PREDICATE in LIST."
1985 (loop for item in list
1986 if (not (funcall predicate item))
1989 (defun js2-position (element list)
1990 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1991 Returns nil if element is not found in the list."
1994 (while (and list (not found))
1995 (if (eq element (car list))
1997 (setq count (1+ count)
2001 (defun js2-find-if (predicate list)
2002 "Find first item satisfying PREDICATE in LIST."
2004 (while (and list (not result))
2005 (if (funcall predicate (car list))
2006 (setq result (car list)))
2007 (setq list (cdr list)))
2010 (defmacro js2-time (form)
2011 "Evaluate FORM, discard result, and return elapsed time in sec"
2013 (let ((beg (make-symbol "--js2-time-beg--"))
2014 (delta (make-symbol "--js2-time-end--")))
2015 `(let ((,beg (current-time))
2018 (/ (truncate (* (- (float-time (current-time))
2023 (defsubst js2-same-line (pos)
2024 "Return t if POS is on the same line as current point."
2025 (and (>= pos (point-at-bol))
2026 (<= pos (point-at-eol))))
2028 (defsubst js2-same-line-2 (p1 p2)
2029 "Return t if p1 is on the same line as p2."
2032 (js2-same-line p2)))
2034 (defun js2-code-bug ()
2035 "Signal an error when we encounter an unexpected code path."
2036 (error "failed assertion"))
2038 (defsubst js2-record-text-property (beg end prop value)
2039 "Record a text property to set when parsing finishes."
2040 (push (list beg end prop value) js2-mode-deferred-properties))
2042 ;; I'd like to associate errors with nodes, but for now the
2043 ;; easiest thing to do is get the context info from the last token.
2044 (defsubst js2-record-parse-error (msg &optional arg pos len)
2045 (push (list (list msg arg)
2046 (or pos js2-token-beg)
2047 (or len (- js2-token-end js2-token-beg)))
2050 (defsubst js2-report-error (msg &optional msg-arg pos len)
2051 "Signal a syntax error or record a parse error."
2052 (if js2-recover-from-parse-errors
2053 (js2-record-parse-error msg msg-arg pos len)
2054 (signal 'js2-syntax-error
2058 (goto-char js2-ts-cursor)
2062 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2063 (if js2-compiler-report-warning-as-error
2064 (js2-report-error msg msg-arg pos len)
2065 (push (list (list msg msg-arg)
2066 (or pos js2-token-beg)
2067 (or len (- js2-token-end js2-token-beg)))
2068 js2-parsed-warnings)))
2070 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2071 (if js2-compiler-strict-mode
2072 (js2-report-warning msg-id msg-arg beg
2073 (and beg end (- end beg)))))
2075 (put 'js2-syntax-error 'error-conditions
2076 '(error syntax-error js2-syntax-error))
2077 (put 'js2-syntax-error 'error-message "Syntax error")
2079 (put 'js2-parse-error 'error-conditions
2080 '(error parse-error js2-parse-error))
2081 (put 'js2-parse-error 'error-message "Parse error")
2083 (defmacro js2-clear-flag (flags flag)
2084 `(setq ,flags (logand ,flags (lognot ,flag))))
2086 (defmacro js2-set-flag (flags flag)
2087 "Logical-or FLAG into FLAGS."
2088 `(setq ,flags (logior ,flags ,flag)))
2090 (defsubst js2-flag-set-p (flags flag)
2091 (/= 0 (logand flags flag)))
2093 (defsubst js2-flag-not-set-p (flags flag)
2094 (zerop (logand flags flag)))
2096 ;; Stolen shamelessly from James Clark's nxml-mode.
2097 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2098 "Evaluate BODY without any text property changes modifying the buffer.
2099 Any text properties changes happen as usual but the changes are not treated as
2100 modifications to the buffer."
2101 (declare (indent 0) (debug t))
2102 (let ((modified (make-symbol "modified")))
2103 `(let ((,modified (buffer-modified-p))
2104 (inhibit-read-only t)
2105 (inhibit-modification-hooks t)
2106 (buffer-undo-list t)
2107 (deactivate-mark nil)
2108 ;; Apparently these avoid file locking problems.
2109 (buffer-file-name nil)
2110 (buffer-file-truename nil))
2114 (restore-buffer-modified-p nil))))))
2116 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2117 "Evaluate BODY with the _ character set to be word-syntax."
2118 (declare (indent 0) (debug t))
2119 (let ((old-syntax (make-symbol "old-syntax")))
2120 `(let ((,old-syntax (string (char-syntax ?_))))
2123 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2125 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2127 (defsubst js2-char-uppercase-p (c)
2128 "Return t if C is an uppercase character.
2129 Handles unicode and latin chars properly."
2130 (/= c (downcase c)))
2132 (defsubst js2-char-lowercase-p (c)
2133 "Return t if C is an uppercase character.
2134 Handles unicode and latin chars properly."
2137 ;;; AST struct and function definitions
2139 ;; flags for ast node property 'member-type (used for e4x operators)
2140 (defvar js2-property-flag #x1 "property access: element is valid name")
2141 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2142 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2144 (defsubst js2-relpos (pos anchor)
2145 "Convert POS to be relative to ANCHOR.
2146 If POS is nil, returns nil."
2147 (and pos (- pos anchor)))
2149 (defsubst js2-make-pad (indent)
2152 (make-string (* indent js2-basic-offset) ? )))
2154 (defsubst js2-visit-ast (node callback)
2155 "Visit every node in ast NODE with visitor CALLBACK.
2157 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2158 called twice: once to visit the node, and again after all the node's
2159 children have been processed. The END-P argument is nil on the first
2160 call and non-nil on the second call. The return value of the callback
2161 affects the traversal: if non-nil, the children of NODE are processed.
2162 If the callback returns nil, or if the node has no children, then the
2163 callback is called immediately with a non-nil END-P argument.
2165 The node traversal is approximately lexical-order, although there
2166 are currently no guarantees around this."
2168 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2170 (when (funcall callback node nil)
2173 ((eq vfunc 'js2-visit-none)
2174 nil) ; don't even bother calling it
2175 ;; Each AST node type has to define a `js2-visitor' function
2176 ;; that takes a node and a callback, and calls `js2-visit-ast'
2177 ;; on each child of the node.
2179 (funcall vfunc node callback))
2181 (error "%s does not define a visitor-traversal function"
2183 ;; call the end-visit
2184 (funcall callback node t))))
2186 (defstruct (js2-node
2187 (:constructor nil)) ; abstract
2188 "Base AST node type."
2189 (type -1) ; token type
2190 (pos -1) ; start position of this AST node in parsed input
2191 (len 1) ; num characters spanned by the node
2192 props ; optional node property list (an alist)
2193 parent) ; link to parent node; null for root
2195 (defsubst js2-node-get-prop (node prop &optional default)
2196 (or (cadr (assoc prop (js2-node-props node))) default))
2198 (defsubst js2-node-set-prop (node prop value)
2199 (setf (js2-node-props node)
2200 (cons (list prop value) (js2-node-props node))))
2202 (defsubst js2-fixup-starts (n nodes)
2203 "Adjust the start positions of NODES to be relative to N.
2204 Any node in the list may be nil, for convenience."
2205 (dolist (node nodes)
2207 (setf (js2-node-pos node) (- (js2-node-pos node)
2208 (js2-node-pos n))))))
2210 (defsubst js2-node-add-children (parent &rest nodes)
2211 "Set parent node of NODES to PARENT, and return PARENT.
2212 Does nothing if we're not recording parent links.
2213 If any given node in NODES is nil, doesn't record that link."
2214 (js2-fixup-starts parent nodes)
2215 (dolist (node nodes)
2217 (setf (js2-node-parent node) parent))))
2219 ;; Non-recursive since it's called a frightening number of times.
2220 (defsubst js2-node-abs-pos (n)
2221 (let ((pos (js2-node-pos n)))
2222 (while (setq n (js2-node-parent n))
2223 (setq pos (+ pos (js2-node-pos n))))
2226 (defsubst js2-node-abs-end (n)
2227 "Return absolute buffer position of end of N."
2228 (+ (js2-node-abs-pos n) (js2-node-len n)))
2230 ;; It's important to make sure block nodes have a lisp list for the
2231 ;; child nodes, to limit printing recursion depth in an AST that
2232 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2233 ;; a sufficiently large vector tree.
2235 (defstruct (js2-block-node
2238 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2243 "A block of statements."
2244 kids) ; a lisp list of the child statement nodes
2246 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2247 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2249 (defsubst js2-visit-block (ast callback)
2250 "Visit the `js2-block-node' children of AST."
2251 (dolist (kid (js2-block-node-kids ast))
2252 (js2-visit-ast kid callback)))
2254 (defun js2-print-block (n i)
2255 (let ((pad (js2-make-pad i)))
2257 (dolist (kid (js2-block-node-kids n))
2258 (js2-print-ast kid (1+ i)))
2261 (defstruct (js2-scope
2262 (:include js2-block-node)
2264 (:constructor make-js2-scope (&key (type js2-BLOCK)
2268 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2269 ;; I don't have one of those handy, so I'll use an alist for now.
2270 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2271 ;; and is much lighter-weight to construct (both CPU and mem).
2272 ;; The keys are interned strings (symbols) for faster lookup.
2273 ;; Should switch to hybrid alist/hashtable eventually.
2274 symbol-table ; an alist of (symbol . js2-symbol)
2275 parent-scope ; a `js2-scope'
2276 top) ; top-level `js2-scope' (script/function)
2278 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2279 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2281 (defun js2-scope-set-parent-scope (scope parent)
2282 (setf (js2-scope-parent-scope scope) parent
2283 (js2-scope-top scope) (if (null parent)
2285 (js2-scope-top parent))))
2287 (defun js2-node-get-enclosing-scope (node)
2288 "Return the innermost `js2-scope' node surrounding NODE.
2289 Returns nil if there is no enclosing scope node."
2290 (let ((parent (js2-node-parent node)))
2291 (while (not (js2-scope-p parent))
2292 (setq parent (js2-node-parent parent)))
2295 (defun js2-get-defining-scope (scope name)
2296 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2297 Returns `js2-scope' in which NAME is defined, or nil if not found."
2298 (let ((sym (if (symbolp name)
2304 (while (and scope continue)
2305 (if (and (setq table (js2-scope-symbol-table scope))
2309 (setq scope (js2-scope-parent-scope scope))))
2312 (defsubst js2-scope-get-symbol (scope name)
2313 "Return symbol table entry for NAME in SCOPE.
2314 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2315 (and (js2-scope-symbol-table scope)
2316 (cdr (assq (if (symbolp name)
2319 (js2-scope-symbol-table scope)))))
2321 (defsubst js2-scope-put-symbol (scope name symbol)
2322 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2323 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2324 (let* ((table (js2-scope-symbol-table scope))
2325 (sym (if (symbolp name) name (intern name)))
2326 (entry (assq sym table)))
2328 (setcdr entry symbol)
2329 (push (cons sym symbol)
2330 (js2-scope-symbol-table scope)))))
2332 (defstruct (js2-symbol
2334 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2335 "A symbol table entry."
2336 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2337 ;; js2-LET, or js2-CONST
2340 ast-node) ; a `js2-node'
2342 (defstruct (js2-error-node
2344 (:constructor nil) ; silence emacs21 byte-compiler
2345 (:constructor make-js2-error-node (&key (type js2-ERROR)
2348 "AST node representing a parse error.")
2350 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2351 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2353 (defstruct (js2-script-node
2354 (:include js2-scope)
2356 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2361 functions ; lisp list of nested functions
2362 regexps ; lisp list of (string . flags)
2363 symbols ; alist (every symbol gets unique index)
2365 var-names ; vector of string names
2366 consts ; bool-vector matching var-decls
2367 (temp-number 0)) ; for generating temp variables
2369 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2370 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2372 (defun js2-print-script (node indent)
2373 (dolist (kid (js2-block-node-kids node))
2374 (js2-print-ast kid indent)))
2376 (defstruct (js2-ast-root
2377 (:include js2-script-node)
2379 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2383 "The root node of a js2 AST."
2384 buffer ; the source buffer from which the code was parsed
2385 comments ; a lisp list of comments, ordered by start position
2386 errors ; a lisp list of errors found during parsing
2387 warnings ; a lisp list of warnings found during parsing
2388 node-count) ; number of nodes in the tree, including the root
2390 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2391 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2393 (defun js2-visit-ast-root (ast callback)
2394 (dolist (kid (js2-ast-root-kids ast))
2395 (js2-visit-ast kid callback))
2396 (dolist (comment (js2-ast-root-comments ast))
2397 (js2-visit-ast comment callback)))
2399 (defstruct (js2-comment-node
2402 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2405 (format js2-ts-comment-type))))
2406 format) ; 'line, 'block, 'jsdoc or 'html
2408 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2409 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2411 (defun js2-print-comment (n i)
2412 ;; We really ought to link end-of-line comments to their nodes.
2413 ;; Or maybe we could add a new comment type, 'endline.
2414 (insert (js2-make-pad i)
2415 (js2-node-string n)))
2417 (defstruct (js2-expr-stmt-node
2420 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2424 "An expression statement."
2427 (defsubst js2-expr-stmt-node-set-has-result (node)
2428 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2429 (setf (js2-node-type node) js2-EXPR_RESULT))
2431 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2432 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2434 (defun js2-visit-expr-stmt-node (n v)
2435 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2437 (defun js2-print-expr-stmt-node (n indent)
2438 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2441 (defstruct (js2-loop-node
2442 (:include js2-scope)
2444 "Abstract supertype of loop nodes."
2445 body ; a `js2-block-node'
2446 lp ; position of left-paren, nil if omitted
2447 rp) ; position of right-paren, nil if omitted
2449 (defstruct (js2-do-node
2450 (:include js2-loop-node)
2452 (:constructor make-js2-do-node (&key (type js2-DO)
2460 "AST node for do-loop."
2461 condition ; while (expression)
2462 while-pos) ; buffer position of 'while' keyword
2464 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2465 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2467 (defun js2-visit-do-node (n v)
2468 (js2-visit-ast (js2-do-node-body n) v)
2469 (js2-visit-ast (js2-do-node-condition n) v))
2471 (defun js2-print-do-node (n i)
2472 (let ((pad (js2-make-pad i)))
2473 (insert pad "do {\n")
2474 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2475 (js2-print-ast kid (1+ i)))
2476 (insert pad "} while (")
2477 (js2-print-ast (js2-do-node-condition n) 0)
2480 (defstruct (js2-while-node
2481 (:include js2-loop-node)
2483 (:constructor make-js2-while-node (&key (type js2-WHILE)
2490 "AST node for while-loop."
2491 condition) ; while-condition
2493 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2494 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2496 (defun js2-visit-while-node (n v)
2497 (js2-visit-ast (js2-while-node-condition n) v)
2498 (js2-visit-ast (js2-while-node-body n) v))
2500 (defun js2-print-while-node (n i)
2501 (let ((pad (js2-make-pad i)))
2502 (insert pad "while (")
2503 (js2-print-ast (js2-while-node-condition n) 0)
2505 (js2-print-body (js2-while-node-body n) (1+ i))
2506 (insert pad "}\n")))
2508 (defstruct (js2-for-node
2509 (:include js2-loop-node)
2511 (:constructor make-js2-for-node (&key (type js2-FOR)
2520 "AST node for a C-style for-loop."
2521 init ; initialization expression
2522 condition ; loop condition
2523 update) ; update clause
2525 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2526 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2528 (defun js2-visit-for-node (n v)
2529 (js2-visit-ast (js2-for-node-init n) v)
2530 (js2-visit-ast (js2-for-node-condition n) v)
2531 (js2-visit-ast (js2-for-node-update n) v)
2532 (js2-visit-ast (js2-for-node-body n) v))
2534 (defun js2-print-for-node (n i)
2535 (let ((pad (js2-make-pad i)))
2536 (insert pad "for (")
2537 (js2-print-ast (js2-for-node-init n) 0)
2539 (js2-print-ast (js2-for-node-condition n) 0)
2541 (js2-print-ast (js2-for-node-update n) 0)
2543 (js2-print-body (js2-for-node-body n) (1+ i))
2544 (insert pad "}\n")))
2546 (defstruct (js2-for-in-node
2547 (:include js2-loop-node)
2549 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2560 "AST node for a for..in loop."
2561 iterator ; [var] foo in ...
2562 object ; object over which we're iterating
2563 in-pos ; buffer position of 'in' keyword
2564 each-pos ; buffer position of 'each' keyword, if foreach-p
2565 foreach-p) ; t if it's a for-each loop
2567 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2568 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2570 (defun js2-visit-for-in-node (n v)
2571 (js2-visit-ast (js2-for-in-node-iterator n) v)
2572 (js2-visit-ast (js2-for-in-node-object n) v)
2573 (js2-visit-ast (js2-for-in-node-body n) v))
2575 (defun js2-print-for-in-node (n i)
2576 (let ((pad (js2-make-pad i))
2577 (foreach (js2-for-in-node-foreach-p n)))
2582 (js2-print-ast (js2-for-in-node-iterator n) 0)
2584 (js2-print-ast (js2-for-in-node-object n) 0)
2586 (js2-print-body (js2-for-in-node-body n) (1+ i))
2587 (insert pad "}\n")))
2589 (defstruct (js2-return-node
2592 (:constructor make-js2-return-node (&key (type js2-RETURN)
2596 "AST node for a return statement."
2597 retval) ; expression to return, or 'undefined
2599 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2600 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2602 (defun js2-visit-return-node (n v)
2603 (js2-visit-ast (js2-return-node-retval n) v))
2605 (defun js2-print-return-node (n i)
2606 (insert (js2-make-pad i) "return")
2607 (when (js2-return-node-retval n)
2609 (js2-print-ast (js2-return-node-retval n) 0))
2612 (defstruct (js2-if-node
2615 (:constructor make-js2-if-node (&key (type js2-IF)
2624 "AST node for an if-statement."
2625 condition ; expression
2626 then-part ; statement or block
2627 else-pos ; optional buffer position of 'else' keyword
2628 else-part ; optional statement or block
2629 lp ; position of left-paren, nil if omitted
2630 rp) ; position of right-paren, nil if omitted
2632 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2633 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2635 (defun js2-visit-if-node (n v)
2636 (js2-visit-ast (js2-if-node-condition n) v)
2637 (js2-visit-ast (js2-if-node-then-part n) v)
2638 (js2-visit-ast (js2-if-node-else-part n) v))
2640 (defun js2-print-if-node (n i)
2641 (let ((pad (js2-make-pad i))
2642 (then-part (js2-if-node-then-part n))
2643 (else-part (js2-if-node-else-part n)))
2645 (js2-print-ast (js2-if-node-condition n) 0)
2647 (js2-print-body then-part (1+ i))
2652 ((js2-if-node-p else-part)
2654 (js2-print-body else-part i))
2656 (insert " else {\n")
2657 (js2-print-body else-part (1+ i))
2658 (insert pad "}\n")))))
2660 (defstruct (js2-try-node
2663 (:constructor make-js2-try-node (&key (type js2-TRY)
2669 "AST node for a try-statement."
2671 catch-clauses ; a lisp list of `js2-catch-node'
2672 finally-block) ; a `js2-finally-node'
2674 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2675 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2677 (defun js2-visit-try-node (n v)
2678 (js2-visit-ast (js2-try-node-try-block n) v)
2679 (dolist (clause (js2-try-node-catch-clauses n))
2680 (js2-visit-ast clause v))
2681 (js2-visit-ast (js2-try-node-finally-block n) v))
2683 (defun js2-print-try-node (n i)
2684 (let ((pad (js2-make-pad i))
2685 (catches (js2-try-node-catch-clauses n))
2686 (finally (js2-try-node-finally-block n)))
2687 (insert pad "try {\n")
2688 (js2-print-body (js2-try-node-try-block n) (1+ i))
2691 (dolist (catch catches)
2692 (js2-print-ast catch i)))
2694 (js2-print-ast finally i)
2697 (defstruct (js2-catch-node
2700 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2709 "AST node for a catch clause."
2710 param ; destructuring form or simple name node
2711 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2712 guard-expr ; catch condition, a `js2-node'
2713 block ; statements, a `js2-block-node'
2714 lp ; buffer position of left-paren, nil if omitted
2715 rp) ; buffer position of right-paren, nil if omitted
2717 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2718 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2720 (defun js2-visit-catch-node (n v)
2721 (js2-visit-ast (js2-catch-node-param n) v)
2722 (when (js2-catch-node-guard-kwd n)
2723 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2724 (js2-visit-ast (js2-catch-node-block n) v))
2726 (defun js2-print-catch-node (n i)
2727 (let ((pad (js2-make-pad i))
2728 (guard-kwd (js2-catch-node-guard-kwd n))
2729 (guard-expr (js2-catch-node-guard-expr n)))
2731 (js2-print-ast (js2-catch-node-param n) 0)
2734 (js2-print-ast guard-expr 0))
2736 (js2-print-body (js2-catch-node-block n) (1+ i))
2739 (defstruct (js2-finally-node
2742 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2746 "AST node for a finally clause."
2747 body) ; a `js2-node', often but not always a block node
2749 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2750 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2752 (defun js2-visit-finally-node (n v)
2753 (js2-visit-ast (js2-finally-node-body n) v))
2755 (defun js2-print-finally-node (n i)
2756 (let ((pad (js2-make-pad i)))
2757 (insert " finally {\n")
2758 (js2-print-body (js2-finally-node-body n) (1+ i))
2759 (insert pad "}\n")))
2761 (defstruct (js2-switch-node
2764 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2771 "AST node for a switch statement."
2772 discriminant ; a `js2-node' (switch expression)
2773 cases ; a lisp list of `js2-case-node'
2774 lp ; position of open-paren for discriminant, nil if omitted
2775 rp) ; position of close-paren for discriminant, nil if omitted
2777 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2778 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2780 (defun js2-visit-switch-node (n v)
2781 (js2-visit-ast (js2-switch-node-discriminant n) v)
2782 (dolist (c (js2-switch-node-cases n))
2783 (js2-visit-ast c v)))
2785 (defun js2-print-switch-node (n i)
2786 (let ((pad (js2-make-pad i))
2787 (cases (js2-switch-node-cases n)))
2788 (insert pad "switch (")
2789 (js2-print-ast (js2-switch-node-discriminant n) 0)
2791 (dolist (case cases)
2792 (js2-print-ast case i))
2793 (insert pad "}\n")))
2795 (defstruct (js2-case-node
2796 (:include js2-block-node)
2798 (:constructor make-js2-case-node (&key (type js2-CASE)
2803 "AST node for a case clause of a switch statement."
2804 expr) ; the case expression (nil for default)
2806 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2807 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2809 (defun js2-visit-case-node (n v)
2810 (js2-visit-ast (js2-case-node-expr n) v)
2811 (js2-visit-block n v))
2813 (defun js2-print-case-node (n i)
2814 (let ((pad (js2-make-pad i))
2815 (expr (js2-case-node-expr n)))
2818 (insert "default:\n")
2820 (js2-print-ast expr 0)
2822 (dolist (kid (js2-case-node-kids n))
2823 (js2-print-ast kid (1+ i)))))
2825 (defstruct (js2-throw-node
2828 (:constructor make-js2-throw-node (&key (type js2-THROW)
2832 "AST node for a throw statement."
2833 expr) ; the expression to throw
2835 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2836 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2838 (defun js2-visit-throw-node (n v)
2839 (js2-visit-ast (js2-throw-node-expr n) v))
2841 (defun js2-print-throw-node (n i)
2842 (insert (js2-make-pad i) "throw ")
2843 (js2-print-ast (js2-throw-node-expr n) 0)
2846 (defstruct (js2-with-node
2849 (:constructor make-js2-with-node (&key (type js2-WITH)
2856 "AST node for a with-statement."
2859 lp ; buffer position of left-paren around object, nil if omitted
2860 rp) ; buffer position of right-paren around object, nil if omitted
2862 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2863 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2865 (defun js2-visit-with-node (n v)
2866 (js2-visit-ast (js2-with-node-object n) v)
2867 (js2-visit-ast (js2-with-node-body n) v))
2869 (defun js2-print-with-node (n i)
2870 (let ((pad (js2-make-pad i)))
2871 (insert pad "with (")
2872 (js2-print-ast (js2-with-node-object n) 0)
2874 (js2-print-body (js2-with-node-body n) (1+ i))
2875 (insert pad "}\n")))
2877 (defstruct (js2-label-node
2880 (:constructor make-js2-label-node (&key (type js2-LABEL)
2884 "AST node for a statement label or case label."
2886 loop) ; for validating and code-generating continue-to-label
2888 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2889 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2891 (defun js2-print-label (n i)
2892 (insert (js2-make-pad i)
2893 (js2-label-node-name n)
2896 (defstruct (js2-labeled-stmt-node
2899 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2900 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2901 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2906 "AST node for a statement with one or more labels.
2907 Multiple labels for a statement are collapsed into the labels field."
2908 labels ; lisp list of `js2-label-node'
2909 stmt) ; the statement these labels are for
2911 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2912 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2914 (defun js2-get-label-by-name (lbl-stmt name)
2915 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2916 Returns nil if no such label is in the list."
2917 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2919 (while (and label-list (not result))
2920 (if (string= (js2-label-node-name (car label-list)) name)
2921 (setq result (car label-list))
2922 (setq label-list (cdr label-list))))
2925 (defun js2-visit-labeled-stmt (n v)
2926 (dolist (label (js2-labeled-stmt-node-labels n))
2927 (js2-visit-ast label v))
2928 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2930 (defun js2-print-labeled-stmt (n i)
2931 (dolist (label (js2-labeled-stmt-node-labels n))
2932 (js2-print-ast label i))
2933 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2935 (defun js2-labeled-stmt-node-contains (node label)
2936 "Return t if NODE contains LABEL in its label set.
2937 NODE is a `js2-labels-node'. LABEL is an identifier."
2938 (loop for nl in (js2-labeled-stmt-node-labels node)
2939 if (string= label (js2-label-node-name nl))
2941 finally return nil))
2943 (defsubst js2-labeled-stmt-node-add-label (node label)
2944 "Add a `js2-label-node' to the label set for this statement."
2945 (setf (js2-labeled-stmt-node-labels node)
2946 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2948 (defstruct (js2-jump-node
2951 "Abstract supertype of break and continue nodes."
2952 label ; `js2-name-node' for location of label identifier, if present
2953 target) ; target js2-labels-node or loop/switch statement
2955 (defun js2-visit-jump-node (n v)
2956 (js2-visit-ast (js2-jump-node-label n) v))
2958 (defstruct (js2-break-node
2959 (:include js2-jump-node)
2961 (:constructor make-js2-break-node (&key (type js2-BREAK)
2966 "AST node for a break statement.
2967 The label field is a `js2-name-node', possibly nil, for the named label
2968 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2969 is the target of the break - a label node or enclosing loop/switch statement.")
2971 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2972 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2974 (defun js2-print-break-node (n i)
2975 (insert (js2-make-pad i) "break")
2976 (when (js2-break-node-label n)
2978 (js2-print-ast (js2-break-node-label n) 0))
2981 (defstruct (js2-continue-node
2982 (:include js2-jump-node)
2984 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2989 "AST node for a continue statement.
2990 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2991 It is nil if continue specifies no label. The target field is the jump target:
2992 a `js2-label-node' or the innermost enclosing loop.")
2994 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2995 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2997 (defun js2-print-continue-node (n i)
2998 (insert (js2-make-pad i) "continue")
2999 (when (js2-continue-node-label n)
3001 (js2-print-ast (js2-continue-node-label n) 0))
3004 (defstruct (js2-function-node
3005 (:include js2-script-node)
3007 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3011 (form 'FUNCTION_STATEMENT)
3017 "AST node for a function declaration.
3018 The `params' field is a lisp list of nodes. Each node is either a simple
3019 `js2-name-node', or if it's a destructuring-assignment parameter, a
3020 `js2-array-node' or `js2-object-node'."
3021 ftype ; FUNCTION, GETTER or SETTER
3022 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3023 name ; function name (a `js2-name-node', or nil if anonymous)
3024 params ; a lisp list of destructuring forms or simple name nodes
3025 body ; a `js2-block-node' or expression node (1.8 only)
3026 lp ; position of arg-list open-paren, or nil if omitted
3027 rp ; position of arg-list close-paren, or nil if omitted
3028 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3029 needs-activation ; t if we need an activation object for this frame
3030 is-generator ; t if this function contains a yield
3031 member-expr) ; nonstandard Ecma extension from Rhino
3033 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3034 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3036 (defun js2-visit-function-node (n v)
3037 (js2-visit-ast (js2-function-node-name n) v)
3038 (dolist (p (js2-function-node-params n))
3039 (js2-visit-ast p v))
3040 (js2-visit-ast (js2-function-node-body n) v))
3042 (defun js2-print-function-node (n i)
3043 (let ((pad (js2-make-pad i))
3044 (getter (js2-node-get-prop n 'GETTER_SETTER))
3045 (name (js2-function-node-name n))
3046 (params (js2-function-node-params n))
3047 (body (js2-function-node-body n))
3048 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3050 (insert pad "function"))
3053 (js2-print-ast name 0))
3055 (loop with len = (length params)
3059 (js2-print-ast param 0)
3065 ;; TODO: fix this to be smarter about indenting, etc.
3066 (js2-print-body body (1+ i))
3071 (defsubst js2-function-name (node)
3072 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3073 (and (js2-function-node-name node)
3074 (js2-name-node-name (js2-function-node-name node))))
3076 ;; Having this be an expression node makes it more flexible.
3077 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3078 ;; that work better if you assume it's an expression. Whenever we have
3079 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3080 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3081 (defstruct (js2-var-decl-node
3084 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3089 "AST node for a variable declaration list (VAR, CONST or LET).
3090 The node bounds differ depending on the declaration type. For VAR or
3091 CONST declarations, the bounds include the var/const keyword. For LET
3092 declarations, the node begins at the position of the first child."
3093 kids ; a lisp list of `js2-var-init-node' structs.
3094 decl-type) ; js2-VAR, js2-CONST or js2-LET
3096 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3097 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3099 (defun js2-visit-var-decl (n v)
3100 (dolist (kid (js2-var-decl-node-kids n))
3101 (js2-visit-ast kid v)))
3103 (defun js2-print-var-decl (n i)
3104 (let ((pad (js2-make-pad i))
3105 (tt (js2-var-decl-node-decl-type n)))
3108 ((= tt js2-VAR) "var ")
3109 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3110 ((= tt js2-CONST) "const ")
3112 (error "malformed var-decl node"))))
3113 (loop with kids = (js2-var-decl-node-kids n)
3114 with len = (length kids)
3118 (js2-print-ast kid 0)
3122 (defstruct (js2-var-init-node
3125 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3130 "AST node for a variable declaration.
3131 The type field will be js2-CONST for a const decl."
3132 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3133 initializer) ; initializer expression, a `js2-node'
3135 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3136 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3138 (defun js2-visit-var-init-node (n v)
3139 (js2-visit-ast (js2-var-init-node-target n) v)
3140 (js2-visit-ast (js2-var-init-node-initializer n) v))
3142 (defun js2-print-var-init-node (n i)
3143 (let ((pad (js2-make-pad i))
3144 (name (js2-var-init-node-target n))
3145 (init (js2-var-init-node-initializer n)))
3147 (js2-print-ast name 0)
3150 (js2-print-ast init 0))))
3152 (defstruct (js2-cond-node
3155 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3163 "AST node for the ternary operator"
3167 q-pos ; buffer position of ?
3168 c-pos) ; buffer position of :
3170 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3171 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3173 (defun js2-visit-cond-node (n v)
3174 (js2-visit-ast (js2-cond-node-test-expr n) v)
3175 (js2-visit-ast (js2-cond-node-true-expr n) v)
3176 (js2-visit-ast (js2-cond-node-false-expr n) v))
3178 (defun js2-print-cond-node (n i)
3179 (let ((pad (js2-make-pad i)))
3181 (js2-print-ast (js2-cond-node-test-expr n) 0)
3183 (js2-print-ast (js2-cond-node-true-expr n) 0)
3185 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3187 (defstruct (js2-infix-node
3190 (:constructor make-js2-infix-node (&key type
3196 "Represents infix expressions.
3197 Includes assignment ops like `|=', and the comma operator.
3198 The type field inherited from `js2-node' holds the operator."
3199 op-pos ; buffer position where operator begins
3200 left ; any `js2-node'
3201 right) ; any `js2-node'
3203 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3204 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3206 (defun js2-visit-infix-node (n v)
3207 (js2-visit-ast (js2-infix-node-left n) v)
3208 (js2-visit-ast (js2-infix-node-right n) v))
3210 (defconst js2-operator-tokens
3211 (let ((table (make-hash-table :test 'eq))
3213 (list (cons js2-IN "in")
3214 (cons js2-TYPEOF "typeof")
3215 (cons js2-INSTANCEOF "instanceof")
3216 (cons js2-DELPROP "delete")
3217 (cons js2-COMMA ",")
3218 (cons js2-COLON ":")
3223 (cons js2-BITOR "|")
3224 (cons js2-BITXOR "^")
3225 (cons js2-BITAND "&")
3234 (cons js2-URSH ">>>")
3235 (cons js2-ADD "+") ; infix plus
3236 (cons js2-SUB "-") ; infix minus
3241 (cons js2-BITNOT "~")
3242 (cons js2-POS "+") ; unary plus
3243 (cons js2-NEG "-") ; unary minus
3244 (cons js2-SHEQ "===") ; shallow equality
3245 (cons js2-SHNE "!==") ; shallow inequality
3246 (cons js2-ASSIGN "=")
3247 (cons js2-ASSIGN_BITOR "|=")
3248 (cons js2-ASSIGN_BITXOR "^=")
3249 (cons js2-ASSIGN_BITAND "&=")
3250 (cons js2-ASSIGN_LSH "<<=")
3251 (cons js2-ASSIGN_RSH ">>=")
3252 (cons js2-ASSIGN_URSH ">>>=")
3253 (cons js2-ASSIGN_ADD "+=")
3254 (cons js2-ASSIGN_SUB "-=")
3255 (cons js2-ASSIGN_MUL "*=")
3256 (cons js2-ASSIGN_DIV "/=")
3257 (cons js2-ASSIGN_MOD "%="))))
3258 (loop for (k . v) in tokens do
3259 (puthash k v table))
3262 (defun js2-print-infix-node (n i)
3263 (let* ((tt (js2-node-type n))
3264 (op (gethash tt js2-operator-tokens)))
3266 (error "unrecognized infix operator %s" (js2-node-type n)))
3267 (insert (js2-make-pad i))
3268 (js2-print-ast (js2-infix-node-left n) 0)
3269 (unless (= tt js2-COMMA)
3273 (js2-print-ast (js2-infix-node-right n) 0)))
3275 (defstruct (js2-assign-node
3276 (:include js2-infix-node)
3278 (:constructor make-js2-assign-node (&key type
3284 "Represents any assignment.
3285 The type field holds the actual assignment operator.")
3287 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3288 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3290 (defstruct (js2-unary-node
3293 (:constructor make-js2-unary-node (&key type ; required
3297 "AST node type for unary operator nodes.
3298 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3299 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3300 property is added if the operator follows the operand."
3301 operand) ; a `js2-node' expression
3303 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3304 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3306 (defun js2-visit-unary-node (n v)
3307 (js2-visit-ast (js2-unary-node-operand n) v))
3309 (defun js2-print-unary-node (n i)
3310 (let* ((tt (js2-node-type n))
3311 (op (gethash tt js2-operator-tokens))
3312 (postfix (js2-node-get-prop n 'postfix)))
3314 (error "unrecognized unary operator %s" tt))
3315 (insert (js2-make-pad i))
3318 (if (or (= tt js2-TYPEOF)
3321 (js2-print-ast (js2-unary-node-operand n) 0)
3325 (defstruct (js2-let-node
3326 (:include js2-scope)
3328 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3335 "AST node for a let expression or a let statement.
3336 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3337 vars ; a `js2-var-decl-node'
3338 body ; a `js2-node' representing the expression or body block
3342 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3343 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3345 (defun js2-visit-let-node (n v)
3346 (js2-visit-ast (js2-let-node-vars n) v)
3347 (js2-visit-ast (js2-let-node-body n) v))
3349 (defun js2-print-let-node (n i)
3350 (insert (js2-make-pad i) "let (")
3351 (js2-print-ast (js2-let-node-vars n) 0)
3353 (js2-print-ast (js2-let-node-body n) i))
3355 (defstruct (js2-keyword-node
3358 (:constructor make-js2-keyword-node (&key type
3360 (len (- js2-ts-cursor pos)))))
3361 "AST node representing a literal keyword such as `null'.
3362 Used for `null', `this', `true', `false' and `debugger'.
3363 The node type is set to js2-NULL, js2-THIS, etc.")
3365 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3366 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3368 (defun js2-print-keyword-node (n i)
3369 (insert (js2-make-pad i)
3370 (let ((tt (js2-node-type n)))
3372 ((= tt js2-THIS) "this")
3373 ((= tt js2-NULL) "null")
3374 ((= tt js2-TRUE) "true")
3375 ((= tt js2-FALSE) "false")
3376 ((= tt js2-DEBUGGER) "debugger")
3377 (t (error "Invalid keyword literal type: %d" tt))))))
3379 (defsubst js2-this-node-p (node)
3380 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3381 (eq (js2-node-type node) js2-THIS))
3383 (defstruct (js2-new-node
3386 (:constructor make-js2-new-node (&key (type js2-NEW)
3394 "AST node for new-expression such as new Foo()."
3395 target ; an identifier or reference
3396 args ; a lisp list of argument nodes
3397 lp ; position of left-paren, nil if omitted
3398 rp ; position of right-paren, nil if omitted
3399 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3401 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3402 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3404 (defun js2-visit-new-node (n v)
3405 (js2-visit-ast (js2-new-node-target n) v)
3406 (dolist (arg (js2-new-node-args n))
3407 (js2-visit-ast arg v))
3408 (js2-visit-ast (js2-new-node-initializer n) v))
3410 (defun js2-print-new-node (n i)
3411 (insert (js2-make-pad i) "new ")
3412 (js2-print-ast (js2-new-node-target n))
3414 (js2-print-list (js2-new-node-args n))
3416 (when (js2-new-node-initializer n)
3418 (js2-print-ast (js2-new-node-initializer n))))
3420 (defstruct (js2-name-node
3423 (:constructor make-js2-name-node (&key (type js2-NAME)
3425 (len (- js2-ts-cursor
3427 (name js2-ts-string))))
3428 "AST node for a JavaScript identifier"
3430 scope) ; a `js2-scope' (optional, used for codegen)
3432 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3433 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3435 (defun js2-print-name-node (n i)
3436 (insert (js2-make-pad i)
3437 (js2-name-node-name n)))
3439 (defsubst js2-name-node-length (node)
3440 "Return identifier length of NODE, a `js2-name-node'.
3441 Returns 0 if NODE is nil or its identifier field is nil."
3443 (length (js2-name-node-name node))
3446 (defstruct (js2-number-node
3449 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3451 (len (- js2-ts-cursor
3453 (value js2-ts-string)
3454 (num-value js2-ts-number))))
3455 "AST node for a number literal."
3456 value ; the original string, e.g. "6.02e23"
3457 num-value) ; the parsed number value
3459 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3460 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3462 (defun js2-print-number-node (n i)
3463 (insert (js2-make-pad i)
3464 (number-to-string (js2-number-node-num-value n))))
3466 (defstruct (js2-regexp-node
3469 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3471 (len (- js2-ts-cursor
3475 "AST node for a regular expression literal."
3476 value ; the regexp string, without // delimiters
3477 flags) ; a string of flags, e.g. `mi'.
3479 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3480 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3482 (defun js2-print-regexp (n i)
3483 (insert (js2-make-pad i)
3485 (js2-regexp-node-value n)
3487 (if (js2-regexp-node-flags n)
3488 (insert (js2-regexp-node-flags n))))
3490 (defstruct (js2-string-node
3493 (:constructor make-js2-string-node (&key (type js2-STRING)
3495 (len (- js2-ts-cursor
3497 (value js2-ts-string))))
3499 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3500 You can tell the quote type by looking at the first character."
3501 value) ; the characters of the string, including the quotes
3503 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3504 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3506 (defun js2-print-string-node (n i)
3507 (insert (js2-make-pad i)
3508 (js2-node-string n)))
3510 (defstruct (js2-array-node
3513 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3517 "AST node for an array literal."
3518 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3520 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3521 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3523 (defun js2-visit-array-node (n v)
3524 (dolist (e (js2-array-node-elems n))
3525 (js2-visit-ast e v)))
3527 (defun js2-print-array-node (n i)
3528 (insert (js2-make-pad i) "[")
3529 (js2-print-list (js2-array-node-elems n))
3532 (defstruct (js2-object-node
3535 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3539 "AST node for an object literal expression.
3540 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3541 the latter represents abbreviation in destructuring expressions."
3544 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3545 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3547 (defun js2-visit-object-node (n v)
3548 (dolist (e (js2-object-node-elems n))
3549 (js2-visit-ast e v)))
3551 (defun js2-print-object-node (n i)
3552 (insert (js2-make-pad i) "{")
3553 (js2-print-list (js2-object-node-elems n))
3556 (defstruct (js2-object-prop-node
3557 (:include js2-infix-node)
3559 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3565 "AST node for an object literal prop:value entry.
3566 The `left' field is the property: a name node, string node or number node.
3567 The `right' field is a `js2-node' representing the initializer value.")
3569 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3570 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3572 (defun js2-print-object-prop-node (n i)
3573 (insert (js2-make-pad i))
3574 (js2-print-ast (js2-object-prop-node-left n) 0)
3576 (js2-print-ast (js2-object-prop-node-right n) 0))
3578 (defstruct (js2-getter-setter-node
3579 (:include js2-infix-node)
3581 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3586 "AST node for a getter/setter property in an object literal.
3587 The `left' field is the `js2-name-node' naming the getter/setter prop.
3588 The `right' field is always an anonymous `js2-function-node' with a node
3589 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3591 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3592 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3594 (defun js2-print-getter-setter (n i)
3595 (let ((pad (js2-make-pad i))
3596 (left (js2-getter-setter-node-left n))
3597 (right (js2-getter-setter-node-right n)))
3599 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3600 (js2-print-ast left 0)
3601 (js2-print-ast right 0)))
3603 (defstruct (js2-prop-get-node
3604 (:include js2-infix-node)
3606 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3611 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3613 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3614 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3616 (defun js2-visit-prop-get-node (n v)
3617 (js2-visit-ast (js2-prop-get-node-left n) v)
3618 (js2-visit-ast (js2-prop-get-node-right n) v))
3620 (defun js2-print-prop-get-node (n i)
3621 (insert (js2-make-pad i))
3622 (js2-print-ast (js2-prop-get-node-left n) 0)
3624 (js2-print-ast (js2-prop-get-node-right n) 0))
3626 (defstruct (js2-elem-get-node
3629 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3636 "AST node for an array index expression such as foo[bar]."
3637 target ; a `js2-node' - the expression preceding the "."
3638 element ; a `js2-node' - the expression in brackets
3639 lb ; position of left-bracket, nil if omitted
3640 rb) ; position of right-bracket, nil if omitted
3642 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3643 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3645 (defun js2-visit-elem-get-node (n v)
3646 (js2-visit-ast (js2-elem-get-node-target n) v)
3647 (js2-visit-ast (js2-elem-get-node-element n) v))
3649 (defun js2-print-elem-get-node (n i)
3650 (insert (js2-make-pad i))
3651 (js2-print-ast (js2-elem-get-node-target n) 0)
3653 (js2-print-ast (js2-elem-get-node-element n) 0)
3656 (defstruct (js2-call-node
3659 (:constructor make-js2-call-node (&key (type js2-CALL)
3666 "AST node for a JavaScript function call."
3667 target ; a `js2-node' evaluating to the function to call
3668 args ; a lisp list of `js2-node' arguments
3669 lp ; position of open-paren, or nil if missing
3670 rp) ; position of close-paren, or nil if missing
3672 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3673 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3675 (defun js2-visit-call-node (n v)
3676 (js2-visit-ast (js2-call-node-target n) v)
3677 (dolist (arg (js2-call-node-args n))
3678 (js2-visit-ast arg v)))
3680 (defun js2-print-call-node (n i)
3681 (insert (js2-make-pad i))
3682 (js2-print-ast (js2-call-node-target n) 0)
3684 (js2-print-list (js2-call-node-args n))
3687 (defstruct (js2-yield-node
3690 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3694 "AST node for yield statement or expression."
3695 value) ; optional: value to be yielded
3697 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3698 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3700 (defun js2-visit-yield-node (n v)
3701 (js2-visit-ast (js2-yield-node-value n) v))
3703 (defun js2-print-yield-node (n i)
3704 (insert (js2-make-pad i))
3706 (when (js2-yield-node-value n)
3708 (js2-print-ast (js2-yield-node-value n) 0)))
3710 (defstruct (js2-paren-node
3713 (:constructor make-js2-paren-node (&key (type js2-LP)
3717 "AST node for a parenthesized expression.
3718 In particular, used when the parens are syntactically optional,
3719 as opposed to required parens such as those enclosing an if-conditional."
3722 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3723 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3725 (defun js2-visit-paren-node (n v)
3726 (js2-visit-ast (js2-paren-node-expr n) v))
3728 (defun js2-print-paren-node (n i)
3729 (insert (js2-make-pad i))
3731 (js2-print-ast (js2-paren-node-expr n) 0)
3734 (defstruct (js2-array-comp-node
3735 (:include js2-scope)
3737 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3746 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3747 result ; result expression (just after left-bracket)
3748 loops ; a lisp list of `js2-array-comp-loop-node'
3749 filter ; guard/filter expression
3750 if-pos ; buffer pos of 'if' keyword, if present, else nil
3751 lp ; buffer position of if-guard left-paren, or nil if not present
3752 rp) ; buffer position of if-guard right-paren, or nil if not present
3754 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3755 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3757 (defun js2-visit-array-comp-node (n v)
3758 (js2-visit-ast (js2-array-comp-node-result n) v)
3759 (dolist (l (js2-array-comp-node-loops n))
3760 (js2-visit-ast l v))
3761 (js2-visit-ast (js2-array-comp-node-filter n) v))
3763 (defun js2-print-array-comp-node (n i)
3764 (let ((pad (js2-make-pad i))
3765 (result (js2-array-comp-node-result n))
3766 (loops (js2-array-comp-node-loops n))
3767 (filter (js2-array-comp-node-filter n)))
3769 (js2-print-ast result 0)
3772 (js2-print-ast l 0))
3775 (js2-print-ast filter 0))
3778 (defstruct (js2-array-comp-loop-node
3779 (:include js2-for-in-node)
3781 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3791 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3793 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3794 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3796 (defun js2-visit-array-comp-loop (n v)
3797 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3798 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3800 (defun js2-print-array-comp-loop (n i)
3802 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3804 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3807 (defstruct (js2-empty-expr-node
3810 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3813 "AST node for an empty expression.")
3815 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3816 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3818 (defstruct (js2-xml-node
3819 (:include js2-block-node)
3821 (:constructor make-js2-xml-node (&key (type js2-XML)
3825 "AST node for initial parse of E4X literals.
3826 The kids field is a list of XML fragments, each a `js2-string-node' or
3827 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3829 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3830 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3832 (defun js2-print-xml-node (n i)
3833 (dolist (kid (js2-xml-node-kids n))
3834 (js2-print-ast kid i)))
3836 (defstruct (js2-xml-js-expr-node
3837 (:include js2-xml-node)
3839 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3843 "AST node for an embedded JavaScript {expression} in an E4X literal.
3844 The start and end fields correspond to the curly-braces."
3845 expr) ; a `js2-expr-node' of some sort
3847 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3848 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3850 (defun js2-visit-xml-js-expr (n v)
3851 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3853 (defun js2-print-xml-js-expr (n i)
3854 (insert (js2-make-pad i))
3856 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3859 (defstruct (js2-xml-dot-query-node
3860 (:include js2-infix-node)
3862 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3869 "AST node for an E4X foo.(bar) filter expression.
3870 Note that the left-paren is automatically the character immediately
3871 following the dot (.) in the operator. No whitespace is permitted
3872 between the dot and the lp by the scanner."
3875 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3876 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3878 (defun js2-print-xml-dot-query (n i)
3879 (insert (js2-make-pad i))
3880 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3882 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3885 (defstruct (js2-xml-ref-node
3887 (:constructor nil)) ; abstract
3888 "Base type for E4X XML attribute-access or property-get expressions.
3889 Such expressions can take a variety of forms. The general syntax has
3892 - (optional) an @ (specifying an attribute access)
3893 - (optional) a namespace (a `js2-name-node') and double-colon
3894 - (required) either a `js2-name-node' or a bracketed [expression]
3896 The property-name expressions (examples: ns::name, @name) are
3897 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3898 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3900 This node type (or more specifically, its subclasses) will sometimes
3901 be the right-hand child of a `js2-prop-get-node' or a
3902 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3903 The `js2-xml-ref-node' may also be a standalone primary expression with
3904 no explicit target, which is valid in certain expression contexts such as
3906 company..employee.(@id < 100)
3908 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3909 expression whose parent is a `js2-xml-dot-query-node'."
3914 (defsubst js2-xml-ref-node-attr-access-p (node)
3915 "Return non-nil if this expression began with an @-token."
3916 (and (numberp (js2-xml-ref-node-at-pos node))
3917 (plusp (js2-xml-ref-node-at-pos node))))
3919 (defstruct (js2-xml-prop-ref-node
3920 (:include js2-xml-ref-node)
3922 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3929 "AST node for an E4X XML [expr] property-ref expression.
3930 The JavaScript syntax is an optional @, an optional ns::, and a name.
3932 [ '@' ] [ name '::' ] name
3934 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3935 @ns::*, @*::attr, @*::*, and @*.
3937 The node starts at the @ token, if present. Otherwise it starts at the
3938 namespace name. The node bounds extend through the closing right-bracket,
3939 or if it is missing due to a syntax error, through the end of the index
3943 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3944 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3946 (defun js2-visit-xml-prop-ref-node (n v)
3947 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3948 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3950 (defun js2-print-xml-prop-ref-node (n i)
3951 (insert (js2-make-pad i))
3952 (if (js2-xml-ref-node-attr-access-p n)
3954 (when (js2-xml-prop-ref-node-namespace n)
3955 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3957 (if (js2-xml-prop-ref-node-propname n)
3958 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3960 (defstruct (js2-xml-elem-ref-node
3961 (:include js2-xml-ref-node)
3963 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3972 "AST node for an E4X XML [expr] member-ref expression.
3975 [ '@' ] [ name '::' ] '[' expr ']'
3977 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3979 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3980 is not a legal E4X XML element-ref expression, since it's already used
3981 for standard JavaScript element-get array indexing. Hence, a
3982 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3983 non-nil namespace node, or both.
3985 The node starts at the @ token, if present. Otherwise it starts
3986 at the namespace name. The node bounds extend through the closing
3987 right-bracket, or if it is missing due to a syntax error, through the
3988 end of the index expression."
3989 expr ; the bracketed index expression
3993 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3994 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3996 (defun js2-visit-xml-elem-ref-node (n v)
3997 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3998 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4000 (defun js2-print-xml-elem-ref-node (n i)
4001 (insert (js2-make-pad i))
4002 (if (js2-xml-ref-node-attr-access-p n)
4004 (when (js2-xml-elem-ref-node-namespace n)
4005 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4008 (if (js2-xml-elem-ref-node-expr n)
4009 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4012 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4014 (defstruct (js2-xml-start-tag-node
4015 (:include js2-xml-node)
4017 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4024 "AST node for an XML start-tag. Not currently used.
4025 The `kids' field is a lisp list of child content nodes."
4026 name ; a `js2-xml-name-node'
4027 attrs ; a lisp list of `js2-xml-attr-node'
4028 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4030 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4031 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4033 (defun js2-visit-xml-start-tag (n v)
4034 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4035 (dolist (attr (js2-xml-start-tag-node-attrs n))
4036 (js2-visit-ast attr v))
4037 (js2-visit-block n v))
4039 (defun js2-print-xml-start-tag (n i)
4040 (insert (js2-make-pad i) "<")
4041 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4042 (when (js2-xml-start-tag-node-attrs n)
4044 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4047 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4048 ;; and add the end-tag to the kids list of the parent as well.
4049 (defstruct (js2-xml-end-tag-node
4050 (:include js2-xml-node)
4052 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4056 "AST node for an XML end-tag. Not currently used."
4057 name) ; a `js2-xml-name-node'
4059 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4060 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4062 (defun js2-visit-xml-end-tag (n v)
4063 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4065 (defun js2-print-xml-end-tag (n i)
4066 (insert (js2-make-pad i))
4068 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4071 (defstruct (js2-xml-name-node
4072 (:include js2-xml-node)
4074 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4079 "AST node for an E4X XML name. Not currently used.
4080 Any XML name can be qualified with a namespace, hence the namespace field.
4081 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4082 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4083 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4084 namespace) ; a `js2-string-node'
4086 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4087 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4089 (defun js2-visit-xml-name-node (n v)
4090 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4092 (defun js2-print-xml-name-node (n i)
4093 (insert (js2-make-pad i))
4094 (when (js2-xml-name-node-namespace n)
4095 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4097 (dolist (kid (js2-xml-name-node-kids n))
4098 (js2-print-ast kid 0)))
4100 (defstruct (js2-xml-pi-node
4101 (:include js2-xml-node)
4103 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4108 "AST node for an E4X XML processing instruction. Not currently used."
4109 name ; a `js2-xml-name-node'
4110 attrs) ; a list of `js2-xml-attr-node'
4112 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4113 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4115 (defun js2-visit-xml-pi-node (n v)
4116 (js2-visit-ast (js2-xml-pi-node-name n) v)
4117 (dolist (attr (js2-xml-pi-node-attrs n))
4118 (js2-visit-ast attr v)))
4120 (defun js2-print-xml-pi-node (n i)
4121 (insert (js2-make-pad i) "<?")
4122 (js2-print-ast (js2-xml-pi-node-name n))
4123 (when (js2-xml-pi-node-attrs n)
4125 (js2-print-list (js2-xml-pi-node-attrs n)))
4128 (defstruct (js2-xml-cdata-node
4129 (:include js2-xml-node)
4131 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4135 "AST node for a CDATA escape section. Not currently used."
4136 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4138 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4139 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4141 (defun js2-visit-xml-cdata-node (n v)
4142 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4144 (defun js2-print-xml-cdata-node (n i)
4145 (insert (js2-make-pad i))
4146 (js2-print-ast (js2-xml-cdata-node-content n)))
4148 (defstruct (js2-xml-attr-node
4149 (:include js2-xml-node)
4151 (:constructor make-js2-attr-node (&key (type js2-XML)
4158 "AST node representing a foo='bar' XML attribute value. Not yet used."
4159 name ; a `js2-xml-name-node'
4160 value ; a `js2-xml-name-node'
4161 eq-pos ; buffer position of "=" sign
4162 quote-type) ; 'single or 'double
4164 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4165 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4167 (defun js2-visit-xml-attr-node (n v)
4168 (js2-visit-ast (js2-xml-attr-node-name n) v)
4169 (js2-visit-ast (js2-xml-attr-node-value n) v))
4171 (defun js2-print-xml-attr-node (n i)
4172 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4175 (insert (js2-make-pad i))
4176 (js2-print-ast (js2-xml-attr-node-name n) 0)
4178 (js2-print-ast (js2-xml-attr-node-value n) 0)
4181 (defstruct (js2-xml-text-node
4182 (:include js2-xml-node)
4184 (:constructor make-js2-text-node (&key (type js2-XML)
4188 "AST node for an E4X XML text node. Not currently used."
4189 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4191 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4192 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4194 (defun js2-visit-xml-text-node (n v)
4195 (js2-visit-ast (js2-xml-text-node-content n) v))
4197 (defun js2-print-xml-text-node (n i)
4198 (insert (js2-make-pad i))
4199 (dolist (kid (js2-xml-text-node-content n))
4200 (js2-print-ast kid)))
4202 (defstruct (js2-xml-comment-node
4203 (:include js2-xml-node)
4205 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4208 "AST node for E4X XML comment. Not currently used.")
4210 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4211 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4213 (defun js2-print-xml-comment (n i)
4214 (insert (js2-make-pad i)
4215 (js2-node-string n)))
4219 (defsubst js2-node-line (n)
4220 "Fetch the source line number at the start of node N.
4221 This is O(n) in the length of the source buffer; use prudently."
4222 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4224 (defsubst js2-block-node-kid (n i)
4225 "Return child I of node N, or nil if there aren't that many."
4226 (nth i (js2-block-node-kids n)))
4228 (defsubst js2-block-node-first (n)
4229 "Return first child of block node N, or nil if there is none."
4230 (first (js2-block-node-kids n)))
4232 (defun js2-node-root (n)
4233 "Return the root of the AST containing N.
4234 If N has no parent pointer, returns N."
4235 (let ((parent (js2-node-parent n)))
4237 (js2-node-root parent)
4240 (defun js2-node-position-in-parent (node &optional parent)
4241 "Return the position of NODE in parent's block-kids list.
4242 PARENT can be supplied if known. Positioned returned is zero-indexed.
4243 Returns 0 if NODE is not a child of a block statement, or if NODE
4244 is not a statement node."
4245 (let ((p (or parent (js2-node-parent node)))
4247 (if (not (js2-block-node-p p))
4249 (or (js2-position node (js2-block-node-kids p))
4252 (defsubst js2-node-short-name (n)
4253 "Return the short name of node N as a string, e.g. `js2-if-node'."
4254 (substring (symbol-name (aref n 0))
4255 (length "cl-struct-")))
4257 (defsubst js2-node-child-list (node)
4258 "Return the child list for NODE, a lisp list of nodes.
4259 Works for block nodes, array nodes, obj literals, funarg lists,
4260 var decls and try nodes (for catch clauses). Note that you should call
4261 `js2-block-node-kids' on the function body for the body statements.
4262 Returns nil for zero-length child lists or unsupported nodes."
4264 ((js2-function-node-p node)
4265 (js2-function-node-params node))
4266 ((js2-block-node-p node)
4267 (js2-block-node-kids node))
4268 ((js2-try-node-p node)
4269 (js2-try-node-catch-clauses node))
4270 ((js2-array-node-p node)
4271 (js2-array-node-elems node))
4272 ((js2-object-node-p node)
4273 (js2-object-node-elems node))
4274 ((js2-call-node-p node)
4275 (js2-call-node-args node))
4276 ((js2-new-node-p node)
4277 (js2-new-node-args node))
4278 ((js2-var-decl-node-p node)
4279 (js2-var-decl-node-kids node))
4283 (defsubst js2-node-set-child-list (node kids)
4284 "Set the child list for NODE to KIDS."
4286 ((js2-function-node-p node)
4287 (setf (js2-function-node-params node) kids))
4288 ((js2-block-node-p node)
4289 (setf (js2-block-node-kids node) kids))
4290 ((js2-try-node-p node)
4291 (setf (js2-try-node-catch-clauses node) kids))
4292 ((js2-array-node-p node)
4293 (setf (js2-array-node-elems node) kids))
4294 ((js2-object-node-p node)
4295 (setf (js2-object-node-elems node) kids))
4296 ((js2-call-node-p node)
4297 (setf (js2-call-node-args node) kids))
4298 ((js2-new-node-p node)
4299 (setf (js2-new-node-args node) kids))
4300 ((js2-var-decl-node-p node)
4301 (setf (js2-var-decl-node-kids node) kids))
4303 (error "Unsupported node type: %s" (js2-node-short-name node))))
4306 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4307 (defconst js2-paren-expr-nodes
4308 '(cl-struct-js2-array-comp-loop-node
4309 cl-struct-js2-array-comp-node
4310 cl-struct-js2-call-node
4311 cl-struct-js2-catch-node
4312 cl-struct-js2-do-node
4313 cl-struct-js2-elem-get-node
4314 cl-struct-js2-for-in-node
4315 cl-struct-js2-for-node
4316 cl-struct-js2-function-node
4317 cl-struct-js2-if-node
4318 cl-struct-js2-let-node
4319 cl-struct-js2-new-node
4320 cl-struct-js2-paren-node
4321 cl-struct-js2-switch-node
4322 cl-struct-js2-while-node
4323 cl-struct-js2-with-node
4324 cl-struct-js2-xml-dot-query-node)
4325 "Node types that can have a parenthesized child expression.
4326 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4328 (defsubst js2-paren-expr-node-p (node)
4329 "Return t for nodes that typically have a parenthesized child expression.
4330 Useful for computing the indentation anchors for arg-lists and conditions.
4331 Note that it may return a false positive, for instance when NODE is
4332 a `js2-new-node' and there are no arguments or parentheses."
4333 (memq (aref node 0) js2-paren-expr-nodes))
4335 ;; Fake polymorphism... yech.
4336 (defsubst js2-node-lp (node)
4337 "Return relative left-paren position for NODE, if applicable.
4338 For `js2-elem-get-node' structs, returns left-bracket position.
4339 Note that the position may be nil in the case of a parse error."
4341 ((js2-elem-get-node-p node)
4342 (js2-elem-get-node-lb node))
4343 ((js2-loop-node-p node)
4344 (js2-loop-node-lp node))
4345 ((js2-function-node-p node)
4346 (js2-function-node-lp node))
4347 ((js2-if-node-p node)
4348 (js2-if-node-lp node))
4349 ((js2-new-node-p node)
4350 (js2-new-node-lp node))
4351 ((js2-call-node-p node)
4352 (js2-call-node-lp node))
4353 ((js2-paren-node-p node)
4354 (js2-node-pos node))
4355 ((js2-switch-node-p node)
4356 (js2-switch-node-lp node))
4357 ((js2-catch-node-p node)
4358 (js2-catch-node-lp node))
4359 ((js2-let-node-p node)
4360 (js2-let-node-lp node))
4361 ((js2-array-comp-node-p node)
4362 (js2-array-comp-node-lp node))
4363 ((js2-with-node-p node)
4364 (js2-with-node-lp node))
4365 ((js2-xml-dot-query-node-p node)
4366 (1+ (js2-infix-node-op-pos node)))
4368 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4370 ;; Fake polymorphism... blech.
4371 (defsubst js2-node-rp (node)
4372 "Return relative right-paren position for NODE, if applicable.
4373 For `js2-elem-get-node' structs, returns right-bracket position.
4374 Note that the position may be nil in the case of a parse error."
4376 ((js2-elem-get-node-p node)
4377 (js2-elem-get-node-lb node))
4378 ((js2-loop-node-p node)
4379 (js2-loop-node-rp node))
4380 ((js2-function-node-p node)
4381 (js2-function-node-rp node))
4382 ((js2-if-node-p node)
4383 (js2-if-node-rp node))
4384 ((js2-new-node-p node)
4385 (js2-new-node-rp node))
4386 ((js2-call-node-p node)
4387 (js2-call-node-rp node))
4388 ((js2-paren-node-p node)
4389 (+ (js2-node-pos node) (js2-node-len node)))
4390 ((js2-switch-node-p node)
4391 (js2-switch-node-rp node))
4392 ((js2-catch-node-p node)
4393 (js2-catch-node-rp node))
4394 ((js2-let-node-p node)
4395 (js2-let-node-rp node))
4396 ((js2-array-comp-node-p node)
4397 (js2-array-comp-node-rp node))
4398 ((js2-with-node-p node)
4399 (js2-with-node-rp node))
4400 ((js2-xml-dot-query-node-p node)
4401 (1+ (js2-xml-dot-query-node-rp node)))
4403 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4405 (defsubst js2-node-first-child (node)
4406 "Returns the first element of `js2-node-child-list' for NODE."
4407 (car (js2-node-child-list node)))
4409 (defsubst js2-node-last-child (node)
4410 "Returns the last element of `js2-node-last-child' for NODE."
4411 (car (last (js2-node-child-list node))))
4413 (defun js2-node-prev-sibling (node)
4414 "Return the previous statement in parent.
4415 Works for parents supported by `js2-node-child-list'.
4416 Returns nil if NODE is not in the parent, or PARENT is
4417 not a supported node, or if NODE is the first child."
4418 (let* ((p (js2-node-parent node))
4419 (kids (js2-node-child-list p))
4422 (not (eq node (cadr kids))))
4423 (setq kids (cdr kids)
4427 (defun js2-node-next-sibling (node)
4428 "Return the next statement in parent block.
4429 Returns nil if NODE is not in the block, or PARENT is not
4430 a block node, or if NODE is the last statement."
4431 (let* ((p (js2-node-parent node))
4432 (kids (js2-node-child-list p)))
4434 (not (eq node (car kids))))
4435 (setq kids (cdr kids)))
4438 (defun js2-node-find-child-before (pos parent &optional after)
4439 "Find the last child that starts before POS in parent.
4440 If AFTER is non-nil, returns first child starting after POS.
4441 POS is an absolute buffer position. PARENT is any node
4442 supported by `js2-node-child-list'.
4443 Returns nil if no applicable child is found."
4444 (let ((kids (if (js2-function-node-p parent)
4445 (js2-block-node-kids (js2-function-node-body parent))
4446 (js2-node-child-list parent)))
4447 (beg (if (js2-function-node-p parent)
4448 (js2-node-abs-pos (js2-function-node-body parent))
4449 (js2-node-abs-pos parent)))
4454 (setq fn (if after '> '<))
4455 (while (and kids continue)
4456 (setq kid (car kids))
4457 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4459 continue (if after nil t))
4460 (setq continue (if after t nil)))
4461 (setq kids (cdr kids)))
4464 (defun js2-node-find-child-after (pos parent)
4465 "Find first child that starts after POS in parent.
4466 POS is an absolute buffer position. PARENT is any node
4467 supported by `js2-node-child-list'.
4468 Returns nil if no applicable child is found."
4469 (js2-node-find-child-before pos parent 'after))
4471 (defun js2-node-replace-child (pos parent new-node)
4472 "Replace node at index POS in PARENT with NEW-NODE.
4473 Only works for parents supported by `js2-node-child-list'."
4474 (let ((kids (js2-node-child-list parent))
4477 (setq kids (cdr kids)
4479 (setcar kids new-node)
4480 (js2-node-add-children parent new-node)))
4482 (defun js2-node-buffer (n)
4483 "Return the buffer associated with AST N.
4484 Returns nil if the buffer is not set as a property on the root
4485 node, or if parent links were not recorded during parsing."
4486 (let ((root (js2-node-root n)))
4488 (js2-ast-root-p root)
4489 (js2-ast-root-buffer root))))
4491 (defsubst js2-block-node-push (n kid)
4492 "Push js2-node KID onto the end of js2-block-node N's child list.
4493 KID is always added to the -end- of the kids list.
4494 Function also calls `js2-node-add-children' to add the parent link."
4495 (let ((kids (js2-node-child-list n)))
4497 (setcdr kids (nconc (cdr kids) (list kid)))
4498 (js2-node-set-child-list n (list kid)))
4499 (js2-node-add-children n kid)))
4501 (defun js2-node-string (node)
4502 (let ((buf (js2-node-buffer node))
4505 (error "No buffer available for node %s" node))
4508 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4509 (+ pos (js2-node-len node))))))
4511 ;; Container for storing the node we're looking for in a traversal.
4512 (js2-deflocal js2-discovered-node nil)
4514 ;; Keep track of absolute node position during traversals.
4515 (js2-deflocal js2-visitor-offset nil)
4517 (js2-deflocal js2-node-search-point nil)
4519 (when js2-mode-dev-mode-p
4520 (defun js2-find-node-at-point ()
4522 (let ((node (js2-node-at-point)))
4523 (message "%s" (or node "No node found at point"))))
4524 (defun js2-node-name-at-point ()
4526 (let ((node (js2-node-at-point)))
4527 (message "%s" (if node
4528 (js2-node-short-name node)
4529 "No node found at point.")))))
4531 (defun js2-node-at-point (&optional pos skip-comments)
4532 "Return AST node at POS, a buffer position, defaulting to current point.
4533 The `js2-mode-ast' variable must be set to the current parse tree.
4534 Signals an error if the AST (`js2-mode-ast') is nil.
4535 Always returns a node - if it can't find one, it returns the root.
4536 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4537 (let ((ast js2-mode-ast)
4540 (error "No JavaScript AST available"))
4541 ;; Look through comments first, since they may be inside nodes that
4542 ;; would otherwise report a match.
4543 (setq pos (or pos (point))
4544 result (if (> pos (js2-node-abs-end ast))
4546 (if (not skip-comments)
4547 (js2-comment-at-point pos))))
4549 (setq js2-discovered-node nil
4550 js2-visitor-offset 0
4551 js2-node-search-point pos)
4553 (catch 'js2-visit-done
4554 (js2-visit-ast ast #'js2-node-at-point-visitor))
4555 (setq js2-visitor-offset nil
4556 js2-node-search-point nil))
4557 (setq result js2-discovered-node))
4558 ;; may have found a comment beyond end of last child node,
4559 ;; since visiting the ast-root looks at the comment-list last.
4560 (if (and skip-comments
4561 (js2-comment-node-p result))
4563 (or result js2-mode-ast)))
4565 (defun js2-node-at-point-visitor (node end-p)
4566 (let ((rel-pos (js2-node-pos node))
4569 (point js2-node-search-point))
4572 ;; this evaluates to a non-nil return value, even if it's zero
4573 (decf js2-visitor-offset rel-pos))
4574 ;; we already looked for comments before visiting, and don't want them now
4575 ((js2-comment-node-p node)
4578 (setq abs-pos (incf js2-visitor-offset rel-pos)
4579 ;; we only want to use the node if the point is before
4580 ;; the last character position in the node, so we decrement
4581 ;; the absolute end by 1.
4582 abs-end (+ abs-pos (js2-node-len node) -1))
4584 ;; If this node starts after search-point, stop the search.
4586 (throw 'js2-visit-done nil))
4587 ;; If this node ends before the search-point, don't check kids.
4591 ;; Otherwise point is within this node, possibly in a child.
4592 (setq js2-discovered-node node)
4593 t)))))) ; keep processing kids to look for more specific match
4595 (defsubst js2-block-comment-p (node)
4596 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4597 (and (js2-comment-node-p node)
4598 (memq (js2-comment-node-format node) '(jsdoc block))))
4600 ;; TODO: put the comments in a vector and binary-search them instead
4601 (defun js2-comment-at-point (&optional pos)
4602 "Look through scanned comment nodes for one containing POS.
4603 POS is a buffer position that defaults to current point.
4604 Function returns nil if POS was not in any comment node."
4605 (let ((ast js2-mode-ast)
4606 (x (or pos (point)))
4610 (error "No JavaScript AST available"))
4612 ;; Comments are stored in lexical order.
4613 (dolist (comment (js2-ast-root-comments ast) nil)
4614 (setq beg (js2-node-abs-pos comment)
4615 end (+ beg (js2-node-len comment)))
4618 (throw 'done comment))))))
4620 (defun js2-mode-find-parent-fn (node)
4621 "Find function enclosing NODE.
4622 Returns nil if NODE is not inside a function."
4623 (setq node (js2-node-parent node))
4624 (while (and node (not (js2-function-node-p node)))
4625 (setq node (js2-node-parent node)))
4626 (and (js2-function-node-p node) node))
4628 (defun js2-mode-find-enclosing-fn (node)
4629 "Find function or root enclosing NODE."
4630 (if (js2-ast-root-p node)
4632 (setq node (js2-node-parent node))
4633 (while (not (or (js2-ast-root-p node)
4634 (js2-function-node-p node)))
4635 (setq node (js2-node-parent node)))
4638 (defun js2-mode-find-enclosing-node (beg end)
4639 "Find script or function fully enclosing BEG and END."
4640 (let ((node (js2-node-at-point beg))
4644 (if (or (js2-ast-root-p node)
4645 (and (js2-function-node-p node)
4646 (<= (setq pos (js2-node-abs-pos node)) beg)
4647 (>= (+ pos (js2-node-len node)) end)))
4649 (setq node (js2-node-parent node))))
4652 (defun js2-node-parent-script-or-fn (node)
4653 "Find script or function immediately enclosing NODE.
4654 If NODE is the ast-root, returns nil."
4655 (if (js2-ast-root-p node)
4657 (setq node (js2-node-parent node))
4658 (while (and node (not (or (js2-function-node-p node)
4659 (js2-script-node-p node))))
4660 (setq node (js2-node-parent node)))
4663 (defsubst js2-nested-function-p (node)
4664 "Return t if NODE is a nested function, or is inside a nested function."
4665 (unless (js2-ast-root-p node)
4666 (js2-function-node-p (if (js2-function-node-p node)
4667 (js2-node-parent-script-or-fn node)
4668 (js2-node-parent-script-or-fn
4669 (js2-node-parent-script-or-fn node))))))
4671 (defsubst js2-function-param-node-p (node)
4672 "Return non-nil if NODE is a param node of a `js2-function-node'."
4673 (let ((parent (js2-node-parent node)))
4675 (js2-function-node-p parent)
4676 (memq node (js2-function-node-params parent)))))
4678 (defsubst js2-mode-shift-kids (kids start offset)
4680 (if (> (js2-node-pos kid) start)
4681 (incf (js2-node-pos kid) offset))))
4683 (defsubst js2-mode-shift-children (parent start offset)
4684 "Update start-positions of all children of PARENT beyond START."
4685 (let ((root (js2-node-root parent)))
4686 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4687 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4689 (defsubst js2-node-is-descendant (node ancestor)
4690 "Return t if NODE is a descendant of ANCESTOR."
4692 (not (eq node ancestor)))
4693 (setq node (js2-node-parent node)))
4696 ;;; visitor infrastructure
4698 (defun js2-visit-none (node callback)
4699 "Visitor for AST node that have no node children."
4702 (defun js2-print-none (node indent)
4703 "Visitor for AST node with no printed representation.")
4705 (defun js2-print-body (node indent)
4706 "Print a statement, or a block without braces."
4707 (if (js2-block-node-p node)
4708 (dolist (kid (js2-block-node-kids node))
4709 (js2-print-ast kid indent))
4710 (js2-print-ast node indent)))
4712 (defun js2-print-list (args &optional delimiter)
4713 (loop with len = (length args)
4717 (js2-print-ast arg 0)
4719 (insert (or delimiter ", ")))))
4721 (defun js2-print-tree (ast)
4722 "Prints an AST to the current buffer.
4723 Makes `js2-ast-parent-nodes' available to the printer functions."
4724 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4725 (js2-print-ast ast)))
4727 (defun js2-print-ast (node &optional indent)
4728 "Helper function for printing AST nodes.
4729 Requires `js2-ast-parent-nodes' to be non-nil.
4730 You should use `js2-print-tree' instead of this function."
4731 (let ((printer (get (aref node 0) 'js2-printer))
4733 (pos (js2-node-abs-pos node)))
4734 ;; TODO: wedge comments in here somewhere
4736 (funcall printer node i))))
4738 (defconst js2-side-effecting-tokens
4739 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4740 (dolist (tt (list js2-ASSIGN
4809 (if js2-instanceof-has-side-effects
4810 (aset tokens js2-INSTANCEOF t))
4813 (defun js2-node-has-side-effects (node)
4814 "Return t if NODE has side effects."
4815 (when node ; makes it easier to handle malformed expressions
4816 (let ((tt (js2-node-type node)))
4818 ;; This doubtless needs some work, since EXPR_VOID is used
4819 ;; in several ways in Rhino, and I may not have caught them all.
4820 ;; I'll wait for people to notice incorrect warnings.
4821 ((and (= tt js2-EXPR_VOID)
4822 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4823 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4825 (js2-node-has-side-effects (js2-infix-node-right node)))
4828 (or (js2-node-has-side-effects (js2-infix-node-right node))
4829 (js2-node-has-side-effects (js2-infix-node-left node))))
4831 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4832 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4833 ((js2-paren-node-p node)
4834 (js2-node-has-side-effects (js2-paren-node-expr node)))
4835 ((= tt js2-ERROR) ; avoid cascaded error messages
4838 (aref js2-side-effecting-tokens tt))))))
4840 (defun js2-member-expr-leftmost-name (node)
4841 "For an expr such as foo.bar.baz, return leftmost node foo.
4842 NODE is any `js2-node' object. If it represents a member expression,
4843 which is any sequence of property gets, element-gets, function calls,
4844 or xml descendants/filter operators, then we look at the lexically
4845 leftmost (first) node in the chain. If it is a name-node we return it.
4846 Note that NODE can be a raw name-node and it will be returned as well.
4847 If NODE is not a name-node or member expression, or if it is a member
4848 expression whose leftmost target is not a name node, returns nil."
4851 (while (and continue (not result))
4853 ((js2-name-node-p node)
4855 ((js2-prop-get-node-p node)
4856 (setq node (js2-prop-get-node-left node)))
4857 ;; TODO: handle call-nodes, xml-nodes, others?
4859 (setq continue nil))))
4862 (defconst js2-stmt-node-types
4866 js2-DEFAULT ; e4x "default xml namespace" statement
4878 "Node types that only appear in statement contexts.
4879 The list does not include nodes that always appear as the child
4880 of another specific statement type, such as switch-cases,
4881 catch and finally blocks, and else-clauses. The list also excludes
4882 nodes like yield, let and var, which may appear in either expression
4883 or statement context, and in the latter context always have a
4884 `js2-expr-stmt-node' parent. Finally, the list does not include
4885 functions or scripts, which are treated separately from statements
4886 by the JavaScript parser and runtime.")
4888 (defun js2-stmt-node-p (node)
4889 "Heuristic for figuring out if NODE is a statement.
4890 Some node types can appear in either an expression context or a
4891 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4892 For these node types in a statement context, the parent will be a
4893 `js2-expr-stmt-node'.
4894 Functions aren't included in the check."
4895 (memq (js2-node-type node) js2-stmt-node-types))
4897 (defsubst js2-mode-find-first-stmt (node)
4898 "Search upward starting from NODE looking for a statement.
4899 For purposes of this function, a `js2-function-node' counts."
4900 (while (not (or (js2-stmt-node-p node)
4901 (js2-function-node-p node)))
4902 (setq node (js2-node-parent node)))
4905 (defun js2-node-parent-stmt (node)
4906 "Return the node's first ancestor that is a statement.
4907 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4908 appearing in a statement context will have a parent that is a
4909 `js2-expr-stmt-node' that will be returned by this function."
4910 (let ((parent (js2-node-parent node)))
4911 (if (or (null parent)
4912 (js2-stmt-node-p parent)
4913 (and (js2-function-node-p parent)
4914 (not (eq (js2-function-node-form parent)
4915 'FUNCTION_EXPRESSION))))
4917 (js2-node-parent-stmt parent))))
4919 ;; In the Mozilla Rhino sources, Roshan James writes:
4920 ;; Does consistent-return analysis on the function body when strict mode is
4923 ;; function (x) { return (x+1) }
4927 ;; function (x) { if (x < 0) return (x+1); }
4929 ;; is not because the function can potentially return a value when the
4930 ;; condition is satisfied and if not, the function does not explicitly
4933 ;; This extends to checking mismatches such as "return" and "return <value>"
4934 ;; used in the same function. Warnings are not emitted if inconsistent
4935 ;; returns exist in code that can be statically shown to be unreachable.
4937 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4939 ;; emits no warning. However if the loop had a break statement, then a
4940 ;; warning would be emitted.
4942 ;; The consistency analysis looks at control structures such as loops, ifs,
4943 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4944 ;; warns the user about an inconsistent set of termination possibilities.
4946 ;; These flags enumerate the possible ways a statement/function can
4947 ;; terminate. These flags are used by endCheck() and by the Parser to
4948 ;; detect inconsistent return usage.
4950 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4951 ;; able to execute (example: throw, continue)
4953 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4954 ;; next one. Statement such as return dont. A compound statement may have
4955 ;; some branch that drops off control to the next statement.
4957 ;; END_RETURNS indicates that the statement can return with no value.
4958 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4960 ;; A compound statement such as
4964 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4966 (defconst js2-END_UNREACHED 0)
4967 (defconst js2-END_DROPS_OFF 1)
4968 (defconst js2-END_RETURNS 2)
4969 (defconst js2-END_RETURNS_VALUE 4)
4970 (defconst js2-END_YIELDS 8)
4972 (defun js2-has-consistent-return-usage (node)
4973 "Check that every return usage in a function body is consistent.
4974 Returns t if the function satisfies strict mode requirement."
4975 (let ((n (js2-end-check node)))
4976 ;; either it doesn't return a value in any branch...
4977 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4978 ;; or it returns a value (or is unreached) at every branch
4979 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4983 (defun js2-end-check-if (node)
4984 "Returns in the then and else blocks must be consistent with each other.
4985 If there is no else block, then the return statement can fall through.
4986 Returns logical OR of END_* flags"
4987 (let ((th (js2-if-node-then-part node))
4988 (el (js2-if-node-else-part node)))
4991 (logior (js2-end-check th) (if el
4993 js2-END_DROPS_OFF)))))
4995 (defun js2-end-check-switch (node)
4996 "Consistency of return statements is checked between the case statements.
4997 If there is no default, then the switch can fall through. If there is a
4998 default, we check to see if all code paths in the default return or if
4999 there is a code path that can fall through.
5000 Returns logical OR of END_* flags."
5001 (let ((rv js2-END_UNREACHED)
5003 ;; examine the cases
5005 (dolist (c (js2-switch-node-cases node))
5006 (if (js2-case-node-expr c)
5007 (js2-set-flag rv (js2-end-check-block c))
5008 (setq default-case c)
5009 (throw 'break nil))))
5010 ;; we don't care how the cases drop into each other
5011 (js2-clear-flag rv js2-END_DROPS_OFF)
5012 ;; examine the default
5013 (js2-set-flag rv (if default-case
5014 (js2-end-check default-case)
5018 (defun js2-end-check-try (node)
5019 "If the block has a finally, return consistency is checked in the
5020 finally block. If all code paths in the finally return, then the
5021 returns in the try-catch blocks don't matter. If there is a code path
5022 that does not return or if there is no finally block, the returns
5023 of the try and catch blocks are checked for mismatch.
5024 Returns logical OR of END_* flags."
5025 (let ((finally (js2-try-node-finally-block node))
5027 ;; check the finally if it exists
5028 (setq rv (if finally
5029 (js2-end-check (js2-finally-node-body finally))
5031 ;; If the finally block always returns, then none of the returns
5032 ;; in the try or catch blocks matter.
5033 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5034 (js2-clear-flag rv js2-END_DROPS_OFF)
5035 ;; examine the try block
5036 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5037 ;; check each catch block
5038 (dolist (cb (js2-try-node-catch-clauses node))
5039 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5042 (defun js2-end-check-loop (node)
5043 "Return statement in the loop body must be consistent. The default
5044 assumption for any kind of a loop is that it will eventually terminate.
5045 The only exception is a loop with a constant true condition. Code that
5046 follows such a loop is examined only if one can statically determine
5047 that there is a break out of the loop.
5049 for(... ; ... ; ...) {}
5054 Returns logical OR of END_* flags."
5055 (let ((rv (js2-end-check (js2-loop-node-body node)))
5057 ((js2-while-node-p node)
5058 (js2-while-node-condition node))
5059 ((js2-do-node-p node)
5060 (js2-do-node-condition node))
5061 ((js2-for-node-p node)
5062 (js2-for-node-condition node)))))
5064 ;; check to see if the loop condition is always true
5066 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5067 (js2-clear-flag rv js2-END_DROPS_OFF))
5069 ;; look for effect of breaks
5070 (js2-set-flag rv (js2-node-get-prop node
5075 (defun js2-end-check-block (node)
5076 "A general block of code is examined statement by statement.
5077 If any statement (even a compound one) returns in all branches, then
5078 subsequent statements are not examined.
5079 Returns logical OR of END_* flags."
5080 (let* ((rv js2-END_DROPS_OFF)
5081 (kids (js2-block-node-kids node))
5083 ;; Check each statment. If the statement can continue onto the next
5084 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5085 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5086 (js2-clear-flag rv js2-END_DROPS_OFF)
5087 (js2-set-flag rv (js2-end-check n))
5088 (setq kids (cdr kids)
5092 (defun js2-end-check-label (node)
5093 "A labeled statement implies that there may be a break to the label.
5094 The function processes the labeled statement and then checks the
5095 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5097 Returns logical OR of END_* flags."
5098 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5099 (logior rv (js2-node-get-prop node
5101 js2-END_UNREACHED))))
5103 (defun js2-end-check-break (node)
5104 "When a break is encountered annotate the statement being broken
5105 out of by setting its CONTROL_BLOCK_PROP property.
5106 Returns logical OR of END_* flags."
5107 (and (js2-break-node-target node)
5108 (js2-node-set-prop (js2-break-node-target node)
5113 (defun js2-end-check (node)
5114 "Examine the body of a function, doing a basic reachability analysis.
5115 Returns a combination of flags END_* flags that indicate
5116 how the function execution can terminate. These constitute only the
5117 pessimistic set of termination conditions. It is possible that at
5118 runtime certain code paths will never be actually taken. Hence this
5119 analysis will flag errors in cases where there may not be errors.
5120 Returns logical OR of END_* flags"
5123 ((js2-break-node-p node)
5124 (js2-end-check-break node))
5125 ((js2-expr-stmt-node-p node)
5126 (if (setq kid (js2-expr-stmt-node-expr node))
5129 ((or (js2-continue-node-p node)
5130 (js2-throw-node-p node))
5132 ((js2-return-node-p node)
5133 (if (setq kid (js2-return-node-retval node))
5134 js2-END_RETURNS_VALUE
5136 ((js2-loop-node-p node)
5137 (js2-end-check-loop node))
5138 ((js2-switch-node-p node)
5139 (js2-end-check-switch node))
5140 ((js2-labeled-stmt-node-p node)
5141 (js2-end-check-label node))
5142 ((js2-if-node-p node)
5143 (js2-end-check-if node))
5144 ((js2-try-node-p node)
5145 (js2-end-check-try node))
5146 ((js2-block-node-p node)
5147 (if (null (js2-block-node-kids node))
5149 (js2-end-check-block node)))
5150 ((js2-yield-node-p node)
5153 js2-END_DROPS_OFF))))
5155 (defun js2-always-defined-boolean-p (node)
5156 "Check if NODE always evaluates to true or false in boolean context.
5157 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5159 (let ((tt (js2-node-type node))
5162 ((or (= tt js2-FALSE) (= tt js2-NULL))
5167 (setq num (js2-number-node-num-value node))
5168 (if (and (not (eq num 0.0e+NaN))
5175 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5176 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5178 (defvar js2-tokens nil
5179 "List of all defined token names.") ; initialized in `js2-token-names'
5181 (defconst js2-token-names
5182 (let* ((names (make-vector js2-num-tokens -1))
5183 (case-fold-search nil) ; only match js2-UPPER_CASE
5184 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5185 (loop for sym in syms
5188 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5190 (aset names (symbol-value sym) ; code, e.g. 152
5191 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5192 (push sym js2-tokens)))
5194 "Vector mapping int values to token string names, sans `js2-' prefix.")
5196 (defun js2-token-name (tok)
5197 "Return a string name for TOK, a token symbol or code.
5198 Signals an error if it's not a recognized token."
5201 (setq code (symbol-value tok)))
5204 (if (and (numberp code)
5206 (< code js2-num-tokens))
5207 (aref js2-token-names code)
5208 (error "Invalid token: %s" code)))))
5210 (defsubst js2-token-sym (tok)
5211 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5212 (intern (js2-token-name tok)))
5214 (defconst js2-token-codes
5215 (let ((table (make-hash-table :test 'eq :size 256)))
5216 (loop for name across js2-token-names
5217 for sym = (intern (concat "js2-" name))
5219 (puthash sym (symbol-value sym) table))
5220 ;; clean up a few that are "wrong" in Rhino's token codes
5221 (puthash 'js2-DELETE js2-DELPROP table)
5223 "Hashtable mapping token symbols to their bytecodes.")
5225 (defsubst js2-token-code (sym)
5226 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5227 (or (gethash sym js2-token-codes)
5228 (error "Invalid token symbol: %s " sym))) ; signal code bug
5230 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5231 (setq js2-token-end js2-ts-cursor)
5232 (js2-report-error msg nil
5233 (or beg js2-token-beg)
5234 (or len (- js2-token-end js2-token-beg)))
5236 (throw 'return js2-ERROR)))
5238 (defsubst js2-get-string-from-buffer ()
5239 "Reverse the char accumulator and return it as a string."
5240 (setq js2-token-end js2-ts-cursor)
5241 (if js2-ts-string-buffer
5242 (apply #'string (nreverse js2-ts-string-buffer))
5245 ;; TODO: could potentially avoid a lot of consing by allocating a
5246 ;; char buffer the way Rhino does.
5247 (defsubst js2-add-to-string (c)
5248 (push c js2-ts-string-buffer))
5250 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5251 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5252 ;; any other character: when it's not part of the current token, we
5253 ;; unget it, allowing it to be read again by the following call.
5254 (defsubst js2-unget-char ()
5255 (decf js2-ts-cursor))
5257 ;; Rhino distinguishes \r and \n line endings. We don't need to
5258 ;; because we only scan from Emacs buffers, which always use \n.
5259 (defsubst js2-get-char ()
5260 "Read and return the next character from the input buffer.
5261 Increments `js2-ts-lineno' if the return value is a newline char.
5262 Updates `js2-ts-cursor' to the point after the returned char.
5263 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5264 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5266 ;; check for end of buffer
5267 (if (>= js2-ts-cursor (point-max))
5268 (setq js2-ts-hit-eof t
5269 js2-ts-cursor (1+ js2-ts-cursor)
5270 c js2-EOF_CHAR) ; return value
5271 ;; otherwise read next char
5272 (setq c (char-before (incf js2-ts-cursor)))
5273 ;; if we read a newline, update counters
5275 (setq js2-ts-line-start js2-ts-cursor
5276 js2-ts-lineno (1+ js2-ts-lineno)))
5277 ;; TODO: skip over format characters
5280 (defsubst js2-read-unicode-escape ()
5281 "Read a \\uNNNN sequence from the input.
5282 Assumes the ?\ and ?u have already been read.
5283 Returns the unicode character, or nil if it wasn't a valid character.
5284 Doesn't change the values of any scanner variables."
5285 ;; I really wish I knew a better way to do this, but I can't
5286 ;; find the Emacs function that takes a 16-bit int and converts
5287 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5288 ;; Have to first check that it's 4 hex characters or it may stop
5291 (let ((s (buffer-substring-no-properties js2-ts-cursor
5292 (+ 4 js2-ts-cursor))))
5293 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5294 (read (concat "?\\u" s))))))
5296 (defsubst js2-match-char (test)
5297 "Consume and return next character if it matches TEST, a character.
5298 Returns nil and consumes nothing if TEST is not the next character."
5299 (let ((c (js2-get-char)))
5305 (defsubst js2-peek-char ()
5310 (defsubst js2-java-identifier-start-p (c)
5313 (js2-char-uppercase-p c)
5314 (js2-char-lowercase-p c)))
5316 (defsubst js2-java-identifier-part-p (c)
5317 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5318 ;; TODO: make me Unicode-friendly. See comments above.
5321 (js2-char-uppercase-p c)
5322 (js2-char-lowercase-p c)
5323 (and (>= c ?0) (<= c ?9))))
5325 (defsubst js2-alpha-p (c)
5326 (cond ((and (<= ?A c) (<= c ?Z)) t)
5327 ((and (<= ?a c) (<= c ?z)) t)
5330 (defsubst js2-digit-p (c)
5331 (and (<= ?0 c) (<= c ?9)))
5333 (defsubst js2-js-space-p (c)
5335 (memq c '(#x20 #x9 #xB #xC #xD))
5338 ;; TODO: change this nil to check for Unicode space character
5341 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5343 (defsubst js2-skip-line ()
5344 "Skip to end of line"
5346 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5348 (setq js2-token-end js2-ts-cursor)))
5350 (defun js2-init-scanner (&optional buf line)
5351 "Create token stream for BUF starting on LINE.
5352 BUF defaults to current-buffer and line defaults to 1.
5354 A buffer can only have one scanner active at a time, which yields
5355 dramatically simpler code than using a defstruct. If you need to
5356 have simultaneous scanners in a buffer, copy the regions to scan
5361 (setq js2-ts-dirty-line nil
5362 js2-ts-regexp-flags nil
5367 js2-ts-lineno (or line 1)
5368 js2-ts-line-end-char -1
5369 js2-ts-cursor (point-min)
5370 js2-ts-is-xml-attribute nil
5371 js2-ts-xml-is-tag-content nil
5372 js2-ts-xml-open-tags-count 0
5373 js2-ts-string-buffer nil)))
5375 ;; This function uses the cached op, string and number fields in
5376 ;; TokenStream; if getToken has been called since the passed token
5377 ;; was scanned, the op or string printed may be incorrect.
5378 (defun js2-token-to-string (token)
5379 ;; Not sure where this function is used in Rhino. Not tested.
5380 (if (not js2-debug-print-trees)
5382 (let ((name (js2-token-name token)))
5384 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5385 (concat name " `" js2-ts-string "'"))
5386 ((eq token js2-NUMBER)
5387 (format "NUMBER %g" js2-ts-number))
5391 (defconst js2-keywords
5393 case catch const continue
5394 debugger default delete do
5396 false finally for function
5397 if in instanceof import
5402 this throw true try typeof
5407 ;; Token names aren't exactly the same as the keywords, unfortunately.
5408 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5409 (defconst js2-kwd-tokens
5410 (let ((table (make-vector js2-num-tokens nil))
5413 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5414 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5416 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5417 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5422 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5427 (aset table i 'font-lock-keyword-face))
5428 (aset table js2-STRING 'font-lock-string-face)
5429 (aset table js2-REGEXP 'font-lock-string-face)
5430 (aset table js2-COMMENT 'font-lock-comment-face)
5431 (aset table js2-THIS 'font-lock-builtin-face)
5432 (aset table js2-VOID 'font-lock-constant-face)
5433 (aset table js2-NULL 'font-lock-constant-face)
5434 (aset table js2-TRUE 'font-lock-constant-face)
5435 (aset table js2-FALSE 'font-lock-constant-face)
5437 "Vector whose values are non-nil for tokens that are keywords.
5438 The values are default faces to use for highlighting the keywords.")
5440 (defconst js2-reserved-words
5448 implements import int interface
5451 package private protected public
5452 short static super synchronized
5456 (defconst js2-keyword-names
5457 (let ((table (make-hash-table :test 'equal)))
5458 (loop for k in js2-keywords
5460 (symbol-name k) ; instanceof
5461 (intern (concat "js2-"
5462 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5465 "JavaScript keywords by name, mapped to their symbols.")
5467 (defconst js2-reserved-word-names
5468 (let ((table (make-hash-table :test 'equal)))
5469 (loop for k in js2-reserved-words
5471 (puthash (symbol-name k) 'js2-RESERVED table))
5473 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5475 (defsubst js2-collect-string (buf)
5476 "Convert BUF, a list of chars, to a string.
5477 Reverses BUF before converting."
5481 ((null buf) ; for emacs21 compat
5485 (apply #'string (nreverse buf))
5488 (defun js2-string-to-keyword (s)
5489 "Return token for S, a string, if S is a keyword or reserved word.
5490 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5491 (or (gethash s js2-keyword-names)
5492 (gethash s js2-reserved-word-names)))
5494 (defsubst js2-ts-set-char-token-bounds ()
5495 "Used when next token is one character."
5496 (setq js2-token-beg (1- js2-ts-cursor)
5497 js2-token-end js2-ts-cursor))
5499 (defsubst js2-ts-return (token)
5500 "Return an N-character TOKEN from `js2-get-token'.
5501 Updates `js2-token-end' accordingly."
5502 (setq js2-token-end js2-ts-cursor)
5503 (throw 'return token))
5505 (defsubst js2-x-digit-to-int (c accumulator)
5506 "Build up a hex number.
5507 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5508 corresponding number. Otherwise return -1."
5511 ;; Use 0..9 < A..Z < a..z
5516 (throw 'check nil)))
5520 (throw 'check nil)))
5524 (throw 'check nil))))
5526 (logior c (lsh accumulator 4))))
5528 (defun js2-get-token ()
5529 "Return next JavaScript token, an int such as js2-RETURN."
5533 is-unicode-escape-start
5547 ;; Eat whitespace, possibly sensitive to newlines.
5550 (setq c (js2-get-char))
5552 ((eq c js2-EOF_CHAR)
5553 (js2-ts-set-char-token-bounds)
5554 (throw 'return js2-EOF))
5556 (js2-ts-set-char-token-bounds)
5557 (setq js2-ts-dirty-line nil)
5558 (throw 'return js2-EOL))
5559 ((not (js2-js-space-p c))
5560 (if (/= c ?-) ; in case end of HTML comment
5561 (setq js2-ts-dirty-line t))
5562 (setq continue nil))))
5563 ;; Assume the token will be 1 char - fixed up below.
5564 (js2-ts-set-char-token-bounds)
5566 (throw 'return js2-XMLATTR))
5567 ;; identifier/keyword/instanceof?
5568 ;; watch out for starting with a <backslash>
5571 (setq c (js2-get-char))
5573 (setq identifier-start t
5574 is-unicode-escape-start t
5575 js2-ts-string-buffer nil)
5576 (setq identifier-start nil)
5580 (when (setq identifier-start (js2-java-identifier-start-p c))
5581 (setq js2-ts-string-buffer nil)
5582 (js2-add-to-string c))))
5583 (when identifier-start
5584 (setq contains-escape is-unicode-escape-start)
5587 (if is-unicode-escape-start
5588 ;; strictly speaking we should probably push-back
5589 ;; all the bad characters if the <backslash>uXXXX
5590 ;; sequence is malformed. But since there isn't a
5591 ;; correct context(is there?) for a bad Unicode
5592 ;; escape sequence in an identifier, we can report
5597 (setq c (js2-get-char)
5598 escape-val (js2-x-digit-to-int c escape-val))
5599 ;; Next check takes care of c < 0 and bad escape
5600 (if (minusp escape-val)
5601 (throw 'break nil)))
5602 (if (minusp escape-val)
5603 (js2-report-scan-error "msg.invalid.escape" t))
5604 (js2-add-to-string escape-val)
5605 (setq is-unicode-escape-start nil))
5606 (setq c (js2-get-char))
5609 (setq c (js2-get-char))
5611 (setq is-unicode-escape-start t
5613 (js2-report-scan-error "msg.illegal.character" t)))
5615 (if (or (eq c js2-EOF_CHAR)
5616 (not (js2-java-identifier-part-p c)))
5618 (js2-add-to-string c))))))
5620 (setq str (js2-get-string-from-buffer))
5621 (unless contains-escape
5622 ;; OPT we shouldn't have to make a string (object!) to
5623 ;; check if it's a keyword.
5624 ;; Return the corresponding token if it's a keyword
5625 (when (setq result (js2-string-to-keyword str))
5626 (if (and (< js2-language-version 170)
5627 (memq result '(js2-LET js2-YIELD)))
5628 ;; LET and YIELD are tokens only in 1.7 and later
5629 (setq result 'js2-NAME))
5630 (if (not (eq result 'js2-RESERVED))
5631 (throw 'return (js2-token-code result)))
5632 (js2-report-warning "msg.reserved.keyword" str)))
5633 ;; If we want to intern these as Rhino does, just use (intern str)
5634 (setq js2-ts-string str)
5635 (throw 'return js2-NAME)) ; end identifier/kwd check
5637 (when (or (js2-digit-p c)
5638 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5639 (setq js2-ts-string-buffer nil
5642 (setq c (js2-get-char))
5644 ((or (eq c ?x) (eq c ?X))
5646 (setq c (js2-get-char)))
5650 (js2-add-to-string ?0))))
5652 (while (<= 0 (js2-x-digit-to-int c 0))
5653 (js2-add-to-string c)
5654 (setq c (js2-get-char)))
5655 (while (and (<= ?0 c) (<= c ?9))
5656 ;; We permit 08 and 09 as decimal numbers, which
5657 ;; makes our behavior a superset of the ECMA
5658 ;; numeric grammar. We might not always be so
5659 ;; permissive, so we warn about it.
5660 (when (and (eq base 8) (>= c ?8))
5661 (js2-report-warning "msg.bad.octal.literal"
5662 (if (eq c ?8) "8" "9"))
5664 (js2-add-to-string c)
5665 (setq c (js2-get-char))))
5667 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5668 (setq is-integer nil)
5671 (js2-add-to-string c)
5672 (setq c (js2-get-char))
5673 while (js2-digit-p c)))
5674 (when (memq c '(?e ?E))
5675 (js2-add-to-string c)
5676 (setq c (js2-get-char))
5677 (when (memq c '(?+ ?-))
5678 (js2-add-to-string c)
5679 (setq c (js2-get-char)))
5680 (unless (js2-digit-p c)
5681 (js2-report-scan-error "msg.missing.exponent" t))
5683 (js2-add-to-string c)
5684 (setq c (js2-get-char))
5685 while (js2-digit-p c))))
5687 (setq js2-ts-string (js2-get-string-from-buffer)
5689 (if (and (eq base 10) (not is-integer))
5690 (string-to-number js2-ts-string)
5691 ;; TODO: call runtime number-parser. Some of it is in
5692 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5693 (string-to-number js2-ts-string)))
5694 (throw 'return js2-NUMBER))
5696 (when (memq c '(?\" ?\'))
5697 ;; We attempt to accumulate a string the fast way, by
5698 ;; building it directly out of the reader. But if there
5699 ;; are any escaped characters in the string, we revert to
5700 ;; building it out of a string buffer.
5702 js2-ts-string-buffer nil
5705 (while (/= c quote-char)
5707 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5709 (setq js2-token-end js2-ts-cursor)
5710 (js2-report-error "msg.unterminated.string.lit")
5711 (throw 'return js2-STRING))
5713 ;; We've hit an escaped character
5714 (setq c (js2-get-char))
5723 (setq c1 (js2-read-unicode-escape))
5724 (if js2-parse-ide-mode
5727 ;; just copy the string in IDE-mode
5728 (js2-add-to-string ?\\)
5729 (js2-add-to-string ?u)
5731 (js2-add-to-string (js2-get-char)))
5732 (setq c (js2-get-char))) ; added at end of loop
5733 ;; flag it as an invalid escape
5734 (js2-report-warning "msg.invalid.escape"
5735 nil (- js2-ts-cursor 2) 6))
5736 ;; Get 4 hex digits; if the u escape is not
5737 ;; followed by 4 hex digits, use 'u' + the
5738 ;; literal character sequence that follows.
5739 (js2-add-to-string ?u)
5742 (setq c (js2-get-char)
5743 escape-val (js2-x-digit-to-int c escape-val))
5744 (if (minusp escape-val)
5745 (throw 'continue nil))
5746 (js2-add-to-string c))
5747 ;; prepare for replace of stored 'u' sequence by escape value
5748 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5751 ;; Get 2 hex digits, defaulting to 'x'+literal
5752 ;; sequence, as above.
5753 (setq c (js2-get-char)
5754 escape-val (js2-x-digit-to-int c 0))
5755 (if (minusp escape-val)
5757 (js2-add-to-string ?x)
5758 (throw 'continue nil))
5761 escape-val (js2-x-digit-to-int c escape-val))
5762 (if (minusp escape-val)
5764 (js2-add-to-string ?x)
5765 (js2-add-to-string c1)
5766 (throw 'continue nil))
5768 (setq c escape-val))))
5770 ;; Remove line terminator after escape to follow
5771 ;; SpiderMonkey and C/C++
5772 (setq c (js2-get-char))
5773 (throw 'continue nil))
5775 (when (and (<= ?0 c) (< c ?8))
5778 (when (and (<= ?0 c) (< c ?8))
5779 (setq val (- (+ (* 8 val) c) ?0)
5781 (when (and (<= ?0 c)
5784 ;; c is 3rd char of octal sequence only
5785 ;; if the resulting val <= 0377
5786 (setq val (- (+ (* 8 val) c) ?0)
5790 (js2-add-to-string c)
5791 (setq c (js2-get-char)))))
5792 (setq js2-ts-string (js2-get-string-from-buffer))
5793 (throw 'return js2-STRING))
5796 (throw 'return js2-SEMI))
5798 (throw 'return js2-LB))
5800 (throw 'return js2-RB))
5802 (throw 'return js2-LC))
5804 (throw 'return js2-RC))
5806 (throw 'return js2-LP))
5808 (throw 'return js2-RP))
5810 (throw 'return js2-COMMA))
5812 (throw 'return js2-HOOK))
5814 (if (js2-match-char ?:)
5815 (js2-ts-return js2-COLONCOLON)
5816 (throw 'return js2-COLON)))
5818 (if (js2-match-char ?.)
5819 (js2-ts-return js2-DOTDOT)
5820 (if (js2-match-char ?\()
5821 (js2-ts-return js2-DOTQUERY)
5822 (throw 'return js2-DOT))))
5824 (if (js2-match-char ?|)
5825 (throw 'return js2-OR)
5826 (if (js2-match-char ?=)
5827 (js2-ts-return js2-ASSIGN_BITOR)
5828 (throw 'return js2-BITOR))))
5830 (if (js2-match-char ?=)
5831 (js2-ts-return js2-ASSIGN_BITOR)
5832 (throw 'return js2-BITXOR)))
5834 (if (js2-match-char ?&)
5835 (throw 'return js2-AND)
5836 (if (js2-match-char ?=)
5837 (js2-ts-return js2-ASSIGN_BITAND)
5838 (throw 'return js2-BITAND))))
5840 (if (js2-match-char ?=)
5841 (if (js2-match-char ?=)
5842 (js2-ts-return js2-SHEQ)
5843 (throw 'return js2-EQ))
5844 (throw 'return js2-ASSIGN)))
5846 (if (js2-match-char ?=)
5847 (if (js2-match-char ?=)
5848 (js2-ts-return js2-SHNE)
5849 (js2-ts-return js2-NE))
5850 (throw 'return js2-NOT)))
5852 ;; NB:treat HTML begin-comment as comment-till-eol
5853 (when (js2-match-char ?!)
5854 (when (js2-match-char ?-)
5855 (when (js2-match-char ?-)
5857 (setq js2-ts-comment-type 'html)
5858 (throw 'return js2-COMMENT)))
5860 (if (js2-match-char ?<)
5861 (if (js2-match-char ?=)
5862 (js2-ts-return js2-ASSIGN_LSH)
5863 (js2-ts-return js2-LSH))
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-LE)
5866 (throw 'return js2-LT))))
5868 (if (js2-match-char ?>)
5869 (if (js2-match-char ?>)
5870 (if (js2-match-char ?=)
5871 (js2-ts-return js2-ASSIGN_URSH)
5872 (js2-ts-return js2-URSH))
5873 (if (js2-match-char ?=)
5874 (js2-ts-return js2-ASSIGN_RSH)
5875 (js2-ts-return js2-RSH)))
5876 (if (js2-match-char ?=)
5877 (js2-ts-return js2-GE)
5878 (throw 'return js2-GT))))
5880 (if (js2-match-char ?=)
5881 (js2-ts-return js2-ASSIGN_MUL)
5882 (throw 'return js2-MUL)))
5884 ;; is it a // comment?
5885 (when (js2-match-char ?/)
5886 (setq js2-token-beg (- js2-ts-cursor 2))
5888 (setq js2-ts-comment-type 'line)
5889 ;; include newline so highlighting goes to end of window
5890 (incf js2-token-end)
5891 (throw 'return js2-COMMENT))
5892 ;; is it a /* comment?
5893 (when (js2-match-char ?*)
5894 (setq look-for-slash nil
5895 js2-token-beg (- js2-ts-cursor 2)
5897 (if (js2-match-char ?*)
5899 (setq look-for-slash t)
5903 (setq c (js2-get-char))
5905 ((eq c js2-EOF_CHAR)
5906 (setq js2-token-end (1- js2-ts-cursor))
5907 (js2-report-error "msg.unterminated.comment")
5908 (throw 'return js2-COMMENT))
5910 (setq look-for-slash t))
5913 (js2-ts-return js2-COMMENT)))
5915 (setq look-for-slash nil
5916 js2-token-end js2-ts-cursor)))))
5917 (if (js2-match-char ?=)
5918 (js2-ts-return js2-ASSIGN_DIV)
5919 (throw 'return js2-DIV)))
5921 (when js2-skip-preprocessor-directives
5923 (setq js2-ts-comment-type 'preprocessor
5924 js2-token-end js2-ts-cursor)
5925 (throw 'return js2-COMMENT))
5926 (throw 'return js2-ERROR))
5928 (if (js2-match-char ?=)
5929 (js2-ts-return js2-ASSIGN_MOD)
5930 (throw 'return js2-MOD)))
5932 (throw 'return js2-BITNOT))
5934 (if (js2-match-char ?=)
5935 (js2-ts-return js2-ASSIGN_ADD)
5936 (if (js2-match-char ?+)
5937 (js2-ts-return js2-INC)
5938 (throw 'return js2-ADD))))
5941 ((js2-match-char ?=)
5942 (setq c js2-ASSIGN_SUB))
5943 ((js2-match-char ?-)
5944 (unless js2-ts-dirty-line
5945 ;; treat HTML end-comment after possible whitespace
5946 ;; after line start as comment-until-eol
5947 (when (js2-match-char ?>)
5949 (setq js2-ts-comment-type 'html)
5950 (throw 'return js2-COMMENT)))
5954 (setq js2-ts-dirty-line t)
5957 (js2-report-scan-error "msg.illegal.character")))))))
5959 (defun js2-read-regexp (start-token)
5960 "Called by parser when it gets / or /= in literal context."
5963 in-class ; inside a '[' .. ']' character-class
5966 (setq js2-token-beg js2-ts-cursor
5967 js2-ts-string-buffer nil
5968 js2-ts-regexp-flags nil)
5969 (if (eq start-token js2-ASSIGN_DIV)
5971 (js2-add-to-string ?=)
5972 (if (not (eq start-token js2-DIV))
5973 (error "failed assertion")))
5974 (while (and (not err)
5975 (or (/= (setq c (js2-get-char)) ?/)
5980 (setq js2-token-end (1- js2-ts-cursor)
5982 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5983 (js2-report-error "msg.unterminated.re.lit"))
5986 (js2-add-to-string c)
5987 (setq c (js2-get-char)))
5991 (setq in-class nil)))
5992 (js2-add-to-string c))))
5996 ((js2-match-char ?g)
5998 ((js2-match-char ?i)
6000 ((js2-match-char ?m)
6003 (setq continue nil))))
6004 (if (js2-alpha-p (js2-peek-char))
6005 (js2-report-scan-error "msg.invalid.re.flag" t
6007 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6008 js2-ts-regexp-flags (js2-collect-string flags)
6009 js2-token-end js2-ts-cursor)
6010 ;; tell `parse-partial-sexp' to ignore this range of chars
6011 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6013 (defun js2-get-first-xml-token ()
6014 (setq js2-ts-xml-open-tags-count 0
6015 js2-ts-is-xml-attribute nil
6016 js2-ts-xml-is-tag-content nil)
6018 (js2-get-next-xml-token))
6020 (defsubst js2-xml-discard-string ()
6021 "Throw away the string in progress and flag an XML parse error."
6022 (setq js2-ts-string-buffer nil
6024 (js2-report-scan-error "msg.XML.bad.form" t))
6026 (defun js2-get-next-xml-token ()
6027 (setq js2-ts-string-buffer nil ; for recording the XML
6028 js2-token-beg js2-ts-cursor)
6033 (setq c (js2-get-char))
6036 (throw 'return js2-ERROR))
6037 (js2-ts-xml-is-tag-content
6040 (js2-add-to-string c)
6041 (setq js2-ts-xml-is-tag-content nil
6042 js2-ts-is-xml-attribute nil))
6044 (js2-add-to-string c)
6045 (when (eq ?> (js2-peek-char))
6046 (setq c (js2-get-char))
6047 (js2-add-to-string c)
6048 (setq js2-ts-xml-is-tag-content nil)
6049 (decf js2-ts-xml-open-tags-count)))
6052 (setq js2-ts-string (js2-get-string-from-buffer))
6053 (throw 'return js2-XML))
6055 (js2-add-to-string c)
6056 (unless (js2-read-quoted-string c)
6057 (throw 'return js2-ERROR)))
6059 (js2-add-to-string c)
6060 (setq js2-ts-is-xml-attribute t))
6062 (js2-add-to-string c))
6064 (js2-add-to-string c)
6065 (setq js2-ts-is-xml-attribute nil)))
6066 (when (and (not js2-ts-xml-is-tag-content)
6067 (zerop js2-ts-xml-open-tags-count))
6068 (setq js2-ts-string (js2-get-string-from-buffer))
6069 (throw 'return js2-XMLEND)))
6071 ;; else not tag content
6074 (js2-add-to-string c)
6075 (setq c (js2-peek-char))
6078 (setq c (js2-get-char)) ;; skip !
6079 (js2-add-to-string c)
6080 (setq c (js2-peek-char))
6083 (setq c (js2-get-char)) ;; skip -
6084 (js2-add-to-string c)
6087 (js2-add-to-string c)
6088 (unless (js2-read-xml-comment)
6089 (throw 'return js2-ERROR)))
6090 (js2-xml-discard-string)
6091 (throw 'return js2-ERROR)))
6093 (setq c (js2-get-char)) ;; skip [
6094 (js2-add-to-string c)
6095 (if (and (= (js2-get-char) ?C)
6096 (= (js2-get-char) ?D)
6097 (= (js2-get-char) ?A)
6098 (= (js2-get-char) ?T)
6099 (= (js2-get-char) ?A)
6100 (= (js2-get-char) ?\[))
6102 (js2-add-to-string ?C)
6103 (js2-add-to-string ?D)
6104 (js2-add-to-string ?A)
6105 (js2-add-to-string ?T)
6106 (js2-add-to-string ?A)
6107 (js2-add-to-string ?\[)
6108 (unless (js2-read-cdata)
6109 (throw 'return js2-ERROR)))
6110 (js2-xml-discard-string)
6111 (throw 'return js2-ERROR)))
6113 (unless (js2-read-entity)
6114 (throw 'return js2-ERROR))))
6115 ;; allow bare CDATA section
6116 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6117 (when (zerop js2-ts-xml-open-tags-count)
6118 (throw 'return js2-XMLEND)))
6120 (setq c (js2-get-char)) ;; skip ?
6121 (js2-add-to-string c)
6122 (unless (js2-read-PI)
6123 (throw 'return js2-ERROR)))
6126 (setq c (js2-get-char)) ;; skip /
6127 (js2-add-to-string c)
6128 (when (zerop js2-ts-xml-open-tags-count)
6129 (js2-xml-discard-string)
6130 (throw 'return js2-ERROR))
6131 (setq js2-ts-xml-is-tag-content t)
6132 (decf js2-ts-xml-open-tags-count))
6135 (setq js2-ts-xml-is-tag-content t)
6136 (incf js2-ts-xml-open-tags-count))))
6139 (setq js2-ts-string (js2-get-string-from-buffer))
6140 (throw 'return js2-XML))
6142 (js2-add-to-string c))))))))
6143 (setq js2-token-end js2-ts-cursor)
6146 (defun js2-read-quoted-string (quote)
6149 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6150 (js2-add-to-string c)
6153 (js2-xml-discard-string) ;; throw away string in progress
6156 (defun js2-read-xml-comment ()
6157 (let ((c (js2-get-char)))
6159 (while (/= c js2-EOF_CHAR)
6161 (js2-add-to-string c)
6162 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6163 (setq c (js2-get-char))
6164 (js2-add-to-string c)
6165 (if (eq (js2-peek-char) ?>)
6167 (setq c (js2-get-char)) ;; skip >
6168 (js2-add-to-string c)
6170 (throw 'continue nil)))
6171 (setq c (js2-get-char))))
6172 (js2-xml-discard-string)
6175 (defun js2-read-cdata ()
6176 (let ((c (js2-get-char)))
6178 (while (/= c js2-EOF_CHAR)
6180 (js2-add-to-string c)
6181 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6182 (setq c (js2-get-char))
6183 (js2-add-to-string c)
6184 (if (eq (js2-peek-char) ?>)
6186 (setq c (js2-get-char)) ;; Skip >
6187 (js2-add-to-string c)
6189 (throw 'continue nil)))
6190 (setq c (js2-get-char))))
6191 (js2-xml-discard-string)
6194 (defun js2-read-entity ()
6198 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6199 (js2-add-to-string c)
6205 (if (zerop decl-tags)
6206 (throw 'return t)))))
6207 (js2-xml-discard-string)
6210 (defun js2-read-PI ()
6211 "Scan an XML processing instruction."
6214 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6215 (js2-add-to-string c)
6216 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6217 (setq c (js2-get-char)) ;; Skip >
6218 (js2-add-to-string c)
6220 (js2-xml-discard-string)
6223 (defun js2-scanner-get-line ()
6224 "Return the text of the current scan line."
6225 (buffer-substring (point-at-bol) (point-at-eol)))
6229 (defsubst js2-set-face (beg end face &optional record)
6230 "Fontify a region. If RECORD is non-nil, record for later."
6231 (when (plusp js2-highlight-level)
6232 (setq beg (min (point-max) beg)
6233 beg (max (point-min) beg)
6234 end (min (point-max) end)
6235 end (max (point-min) end))
6237 (push (list beg end face) js2-mode-fontifications)
6238 (put-text-property beg end 'face face))))
6240 (defsubst js2-set-kid-face (pos kid len face)
6241 "Set-face on a child node.
6242 POS is absolute buffer position of parent.
6243 KID is the child node.
6244 LEN is the length to fontify.
6245 FACE is the face to fontify with."
6246 (js2-set-face (+ pos (js2-node-pos kid))
6247 (+ pos (js2-node-pos kid) (js2-node-len kid))
6250 (defsubst js2-fontify-kwd (start length)
6251 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6253 (defsubst js2-clear-face (beg end)
6254 (remove-text-properties beg end '(face nil
6259 (defconst js2-ecma-global-props
6262 '("Infinity" "NaN" "undefined" "arguments") t)
6264 "Value properties of the Ecma-262 Global Object.
6265 Shown at or above `js2-highlight-level' 2.")
6267 ;; might want to add the name "arguments" to this list?
6268 (defconst js2-ecma-object-props
6271 '("prototype" "__proto__" "__parent__") t)
6273 "Value properties of the Ecma-262 Object constructor.
6274 Shown at or above `js2-highlight-level' 2.")
6276 (defconst js2-ecma-global-funcs
6280 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6281 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6283 "Function properties of the Ecma-262 Global object.
6284 Shown at or above `js2-highlight-level' 2.")
6286 (defconst js2-ecma-number-props
6288 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6290 "POSITIVE_INFINITY") t)
6292 "Properties of the Ecma-262 Number constructor.
6293 Shown at or above `js2-highlight-level' 2.")
6295 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6296 "Properties of the Ecma-262 Date constructor.
6297 Shown at or above `js2-highlight-level' 2.")
6299 (defconst js2-ecma-math-props
6302 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6305 "Properties of the Ecma-262 Math object.
6306 Shown at or above `js2-highlight-level' 2.")
6308 (defconst js2-ecma-math-funcs
6311 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6312 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6314 "Function properties of the Ecma-262 Math object.
6315 Shown at or above `js2-highlight-level' 2.")
6317 (defconst js2-ecma-function-props
6321 '(;; properties of the Object prototype object
6322 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6323 "toLocaleString" "toString" "valueOf"
6324 ;; properties of the Function prototype object
6326 ;; properties of the Array prototype object
6327 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6329 ;; properties of the String prototype object
6330 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6331 "localeCompare" "match" "replace" "search" "split" "substring"
6332 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6334 ;; properties of the Number prototype object
6335 "toExponential" "toFixed" "toPrecision"
6336 ;; properties of the Date prototype object
6337 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6338 "getMinutes" "getMonth" "getSeconds" "getTime"
6339 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6340 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6341 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6342 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6343 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6344 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6345 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6346 "toTimeString" "toUTCString"
6347 ;; properties of the RegExp prototype object
6349 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6350 "toSource" "__defineGetter__" "__defineSetter__"
6351 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6352 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6355 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6356 Shown at or above `js2-highlight-level' 3.")
6358 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6359 (let ((target-name (and target
6360 (js2-name-node-p target)
6361 (js2-name-node-name target)))
6362 (prop-name (if prop (js2-name-node-name prop)))
6363 (level1 (>= js2-highlight-level 1))
6364 (level2 (>= js2-highlight-level 2))
6365 (level3 (>= js2-highlight-level 3))
6373 ((and level3 (string-match js2-ecma-function-props prop-name))
6374 (setq face 'font-lock-builtin-face))
6375 ((and target-name prop)
6377 ((string= target-name "Date")
6378 (if (string-match js2-ecma-date-props prop-name)
6379 (setq face 'font-lock-builtin-face)))
6380 ((string= target-name "Math")
6381 (if (string-match js2-ecma-math-funcs prop-name)
6382 (setq face 'font-lock-builtin-face)))))))
6384 (if (string-match js2-ecma-global-funcs prop-name)
6385 (setq face 'font-lock-builtin-face))))
6389 ((string= target-name "Number")
6390 (if (string-match js2-ecma-number-props prop-name)
6391 (setq face 'font-lock-constant-face)))
6392 ((string= target-name "Math")
6393 (if (string-match js2-ecma-math-props prop-name)
6394 (setq face 'font-lock-constant-face)))))
6396 (if (string-match js2-ecma-object-props prop-name)
6397 (setq face 'font-lock-constant-face)))))
6399 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6400 (js2-node-pos prop))) ; relative
6401 (+ pos (js2-node-len prop))
6404 (defun js2-parse-highlight-member-expr-node (node)
6405 "Perform syntax highlighting of EcmaScript built-in properties.
6406 The variable `js2-highlight-level' governs this highighting."
6407 (let (face target prop name pos end parent call-p callee)
6409 ;; case 1: simple name, e.g. foo
6410 ((js2-name-node-p node)
6411 (setq name (js2-name-node-name node))
6412 ;; possible for name to be nil in rare cases - saw it when
6413 ;; running js2-mode on an elisp buffer. Might as well try to
6414 ;; make it so js2-mode never barfs.
6416 (setq face (if (string-match js2-ecma-global-props name)
6417 'font-lock-constant-face))
6419 (setq pos (js2-node-pos node)
6420 end (+ pos (js2-node-len node)))
6421 (js2-set-face pos end face))))
6422 ;; case 2: property access or function call
6423 ((or (js2-prop-get-node-p node)
6424 ;; highlight function call if expr is a prop-get node
6425 ;; or a plain name (i.e. unqualified function call)
6426 (and (setq call-p (js2-call-node-p node))
6427 (setq callee (js2-call-node-target node)) ; separate setq!
6428 (or (js2-prop-get-node-p callee)
6429 (js2-name-node-p callee))))
6431 node (if call-p callee node))
6432 (if (and call-p (js2-name-node-p callee))
6434 (setq target (js2-prop-get-node-left node)
6435 prop (js2-prop-get-node-right node)))
6437 ((js2-name-node-p target)
6438 (if (js2-name-node-p prop)
6439 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6440 (js2-parse-highlight-prop-get parent target prop call-p)
6441 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6442 (js2-parse-highlight-prop-get parent target nil call-p)))
6443 ((js2-name-node-p prop)
6444 ;; case 2c: complex target, simple name, e.g. x[y].bar
6445 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6447 (defun js2-parse-highlight-member-expr-fn-name (expr)
6448 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6449 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6450 We currently only handle the case where the last component is a prop-get
6451 of a simple name. Called before EXPR has a parent node."
6453 (name (and (js2-prop-get-node-p expr)
6454 (js2-prop-get-node-right expr))))
6455 (when (js2-name-node-p name)
6456 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6457 (js2-node-pos name)))
6458 (+ pos (js2-node-len name))
6459 'font-lock-function-name-face
6462 ;; source: http://jsdoc.sourceforge.net/
6463 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6464 ;; allows type specifications, and needs work before entering the wild.
6466 (defconst js2-jsdoc-param-tag-regexp
6467 (concat "^\\s-*\\*+\\s-*\\(@"
6468 "\\(?:param\\|argument\\)"
6470 "\\s-*\\({[^}]+}\\)?" ; optional type
6471 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6473 "Matches jsdoc tags with optional type and optional param name.")
6475 (defconst js2-jsdoc-typed-tag-regexp
6476 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6490 "\\)\\)\\s-*\\({[^}]+}\\)?")
6491 "Matches jsdoc tags with optional type.")
6493 (defconst js2-jsdoc-arg-tag-regexp
6494 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6517 "\\)\\)\\s-+\\([^ \t]+\\)")
6518 "Matches jsdoc tags with a single argument.")
6520 (defconst js2-jsdoc-empty-tag-regexp
6521 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6561 "Matches empty jsdoc tags.")
6563 (defconst js2-jsdoc-link-tag-regexp
6564 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6565 "Matches a jsdoc link or code tag.")
6567 (defconst js2-jsdoc-see-tag-regexp
6568 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6569 "Matches a jsdoc @see tag.")
6571 (defconst js2-jsdoc-html-tag-regexp
6572 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6573 "Matches a simple (no attributes) html start- or end-tag.")
6575 (defsubst js2-jsdoc-highlight-helper ()
6576 (js2-set-face (match-beginning 1)
6578 'js2-jsdoc-tag-face)
6579 (if (match-beginning 2)
6581 (goto-char (match-beginning 2))
6582 (= (char-after) ?{))
6583 (js2-set-face (1+ (match-beginning 2))
6585 'js2-jsdoc-type-face)
6586 (js2-set-face (match-beginning 2)
6588 'js2-jsdoc-value-face)))
6589 (if (match-beginning 3)
6590 (js2-set-face (match-beginning 3)
6592 'js2-jsdoc-value-face)))
6594 (defun js2-highlight-jsdoc (ast)
6595 "Highlight doc comment tags."
6596 (let ((comments (js2-ast-root-comments ast))
6599 (dolist (node comments)
6600 (when (eq (js2-comment-node-format node) 'jsdoc)
6601 (setq beg (js2-node-abs-pos node)
6602 end (+ beg (js2-node-len node)))
6604 (narrow-to-region beg end)
6605 (dolist (re (list js2-jsdoc-param-tag-regexp
6606 js2-jsdoc-typed-tag-regexp
6607 js2-jsdoc-arg-tag-regexp
6608 js2-jsdoc-link-tag-regexp
6609 js2-jsdoc-see-tag-regexp
6610 js2-jsdoc-empty-tag-regexp))
6612 (while (re-search-forward re nil t)
6613 (js2-jsdoc-highlight-helper)))
6614 ;; simple highlighting for html tags
6616 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6617 (js2-set-face (match-beginning 1)
6619 'js2-jsdoc-html-tag-delimiter-face)
6620 (js2-set-face (match-beginning 2)
6622 'js2-jsdoc-html-tag-name-face)
6623 (js2-set-face (match-beginning 3)
6625 'js2-jsdoc-html-tag-delimiter-face))))))))
6627 (defun js2-highlight-assign-targets (node left right)
6628 "Highlight function properties and external variables."
6629 (let (leftpos end name)
6630 ;; highlight vars and props assigned function values
6631 (when (js2-function-node-p right)
6633 ;; var foo = function() {...}
6634 ((js2-name-node-p left)
6636 ;; foo.bar.baz = function() {...}
6637 ((and (js2-prop-get-node-p left)
6638 (js2-name-node-p (js2-prop-get-node-right left)))
6639 (setq name (js2-prop-get-node-right left))))
6641 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6642 (+ leftpos (js2-node-len name))
6643 'font-lock-function-name-face
6646 (defun js2-record-name-node (node)
6647 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6648 later. NODE must be a name node."
6650 (push (list node js2-current-scope
6651 (setq leftpos (js2-node-abs-pos node))
6652 (setq end (+ leftpos (js2-node-len node))))
6653 js2-recorded-identifiers)))
6655 (defun js2-highlight-undeclared-vars ()
6656 "After entire parse is finished, look for undeclared variable references.
6657 We have to wait until entire buffer is parsed, since JavaScript permits var
6658 decls to occur after they're used.
6660 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6661 it is considered declared."
6663 (dolist (entry js2-recorded-identifiers)
6664 (destructuring-bind (name-node scope pos end) entry
6665 (setq name (js2-name-node-name name-node))
6666 (unless (or (member name js2-global-externs)
6667 (member name js2-default-externs)
6668 (member name js2-additional-externs)
6669 (js2-get-defining-scope scope name))
6670 (js2-set-face pos end 'js2-external-variable-face 'record)
6671 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6672 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6673 (setq js2-recorded-identifiers nil)))
6677 ;; We currently only support imenu, but eventually should support speedbar and
6678 ;; possibly other browsing mechanisms.
6680 ;; The basic strategy is to identify function assignment targets of the form
6681 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6682 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6683 ;; for imenu after parsing is finished.
6685 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6686 ;; JavaScript, and the general problem is undecidable. However, several forms
6687 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6690 ;; function foo() -- function declaration
6691 ;; foo = function() -- function expression assigned to variable
6692 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6693 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6694 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6695 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6696 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6697 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6698 ;; function foo() {function bar() {...}} -- nested function
6699 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6701 ;; This list boils down to a few forms that can be combined recursively.
6702 ;; Top-level named function declarations include both the left-hand (name)
6703 ;; and the right-hand (function value) expressions needed to produce an imenu
6704 ;; entry. The other "right-hand" forms we need to look for are:
6705 ;; - functions declared as props/getters/setters in object literals
6706 ;; - nested named function declarations
6707 ;; The "left-hand" expressions that functions can be assigned to include:
6708 ;; - local/global variables
6709 ;; - nested property-get expressions like a.b.c.d
6710 ;; - element gets like foo[10] or foo['bar'] where the index
6711 ;; expression can be trivially converted to a property name. They
6712 ;; effectively then become property gets.
6714 ;; All the different definition types are canonicalized into the form
6715 ;; foo.bar.baz = position-of-function-keyword
6717 ;; We need to build a trie-like structure for imenu. As an example,
6718 ;; consider the following JavaScript code:
6720 ;; a = function() {...} // function at position 5
6721 ;; b = function() {...} // function at position 25
6722 ;; foo = function() {...} // function at position 100
6723 ;; foo.bar = function() {...} // function at position 200
6724 ;; foo.bar.baz = function() {...} // function at position 300
6725 ;; foo.bar.zab = function() {...} // function at position 400
6727 ;; During parsing we accumulate an entry for each definition in
6728 ;; the variable `js2-imenu-recorder', like so:
6734 ;; (foo bar baz 300)
6735 ;; (foo bar zab 400))
6737 ;; After parsing these entries are merged into this alist-trie:
6741 ;; (foo (<definition> . 3)
6742 ;; (bar (<definition> . 6)
6746 ;; Note the wacky need for a <definition> name. The token can be anything
6747 ;; that isn't a valid JavaScript identifier, because you might make foo
6748 ;; a function and then start setting properties on it that are also functions.
6750 (defsubst js2-prop-node-name (node)
6751 "Return the name of a node that may be a property-get/property-name.
6752 If NODE is not a valid name-node, string-node or integral number-node,
6753 returns nil. Otherwise returns the string name/value of the node."
6755 ((js2-name-node-p node)
6756 (js2-name-node-name node))
6757 ((js2-string-node-p node)
6758 (js2-string-node-value node))
6759 ((and (js2-number-node-p node)
6760 (string-match "^[0-9]+$" (js2-number-node-value node)))
6761 (js2-number-node-value node))
6762 ((js2-this-node-p node)
6765 (defsubst js2-node-qname-component (node)
6766 "Test function: return the name of this node, if it contributes to a qname.
6767 Returns nil if the node doesn't contribute."
6769 (or (js2-prop-node-name node)
6770 (if (and (js2-function-node-p node)
6771 (js2-function-node-name node))
6772 (js2-name-node-name (js2-function-node-name node))))))
6774 (defsubst js2-record-function-qname (fn-node qname)
6775 "Associate FN-NODE with its QNAME for later lookup.
6776 This is used in postprocessing the chain list. When we find a chain
6777 whose first element is a js2-THIS keyword node, we look up the parent
6778 function and see (using this map) whether it is the tail of a chain.
6779 If so, we replace the this-node with a copy of the parent's qname."
6780 (unless js2-imenu-function-map
6781 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6782 (puthash fn-node qname js2-imenu-function-map))
6784 (defun js2-record-imenu-functions (node &optional var)
6785 "Record function definitions for imenu.
6786 NODE is a function node or an object literal.
6787 VAR, if non-nil, is the expression that NODE is being assigned to."
6788 (when js2-parse-ide-mode
6789 (let ((fun-p (js2-function-node-p node))
6790 qname left fname-node pos)
6792 ;; non-anonymous function declaration?
6795 (setq fname-node (js2-function-node-name node)))
6796 (push (setq qname (list fname-node (js2-node-pos node)))
6798 (js2-record-function-qname node qname))
6799 ;; for remaining forms, compute left-side tree branch first
6800 ((and var (setq qname (js2-compute-nested-prop-get var)))
6802 ;; foo.bar.baz = function
6804 (push (nconc qname (list (js2-node-pos node)))
6806 (js2-record-function-qname node qname))
6807 ;; foo.bar.baz = object-literal
6808 ;; look for nested functions: {a: {b: function() {...} }}
6809 ((js2-object-node-p node)
6810 ;; Node position here is still absolute, since the parser
6811 ;; passes the assignment target and value expressions
6812 ;; to us before they are added as children of the assignment node.
6813 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6815 (defun js2-compute-nested-prop-get (node)
6816 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6817 component nodes as a list. Otherwise return nil. Element-gets are treated
6818 as property-gets if the index expression is a string, or a positive integer."
6819 (let (left right head)
6821 ((or (js2-name-node-p node)
6822 (js2-this-node-p node))
6824 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6825 ((js2-prop-get-node-p node) ; foo.bar
6826 (setq left (js2-prop-get-node-left node)
6827 right (js2-prop-get-node-right node))
6828 (if (setq head (js2-compute-nested-prop-get left))
6829 (nconc head (list right))))
6830 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6831 (setq left (js2-elem-get-node-target node)
6832 right (js2-elem-get-node-element node))
6833 (if (or (js2-string-node-p right) ; ['bar']
6834 (and (js2-number-node-p right) ; [10]
6835 (string-match "^[0-9]+$"
6836 (js2-number-node-value right))))
6837 (if (setq head (js2-compute-nested-prop-get left))
6838 (nconc head (list right))))))))
6840 (defun js2-record-object-literal (node qname pos)
6841 "Recursively process an object literal looking for functions.
6842 NODE is an object literal that is the right-hand child of an assignment
6843 expression. QNAME is a list of nodes representing the assignment target,
6844 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6845 POS is the absolute position of the node.
6846 We do a depth-first traversal of NODE. Any functions we find are prefixed
6847 with QNAME plus the property name of the function and appended to the
6848 variable `js2-imenu-recorder'."
6850 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6851 (let ((left (js2-infix-node-left e))
6852 ;; Element positions are relative to the parent position.
6853 (pos (+ pos (js2-node-pos e))))
6855 ;; foo: function() {...}
6856 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6857 (when (js2-prop-node-name left)
6858 ;; As a policy decision, we record the position of the property,
6859 ;; not the position of the `function' keyword, since the property
6860 ;; is effectively the name of the function.
6861 (push (append qname (list left pos))
6863 (js2-record-function-qname right qname)))
6864 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6865 ((js2-object-node-p right)
6866 (js2-record-object-literal right
6867 (append qname (list (js2-infix-node-left e)))
6868 (+ pos (js2-node-pos right)))))))))
6870 (defsubst js2-node-top-level-decl-p (node)
6871 "Return t if NODE's name is defined in the top-level scope.
6872 Also returns t if NODE's name is not defined in any scope, since it implies
6873 that it's an external variable, which must also be in the top-level scope."
6874 (let* ((name (js2-prop-node-name node))
6875 (this-scope (js2-node-get-enclosing-scope node))
6878 ((js2-this-node-p node)
6882 ((setq defining-scope (js2-get-defining-scope this-scope name))
6883 (js2-ast-root-p defining-scope))
6886 (defsubst js2-wrapper-function-p (node)
6887 "Returns t if NODE is a function expression that's immediately invoked.
6888 NODE must be `js2-function-node'."
6889 (let ((parent (js2-node-parent node)))
6891 ;; function(){...}();
6892 (js2-call-node-p parent)
6893 (and (js2-paren-node-p parent)
6894 ;; (function(){...})();
6895 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6896 ;; (function(){...}).call(this);
6897 (and (js2-prop-get-node-p parent)
6898 (member (js2-name-node-name (js2-prop-get-node-right parent))
6900 (js2-call-node-p (js2-node-parent parent))))))))
6902 (defun js2-browse-postprocess-chains (chains)
6903 "Modify function-declaration name chains after parsing finishes.
6904 Some of the information is only available after the parse tree is complete.
6905 For instance, following a 'this' reference requires a parent function node."
6906 (let ((js2-imenu-fn-type-map (make-hash-table :test 'eq))
6907 result head fn fn-type parent-chain p elem parent)
6908 (dolist (chain chains)
6909 ;; examine the head of each node to get its defining scope
6910 (setq head (car chain))
6911 ;; if top-level/external, keep as-is
6912 (if (js2-node-top-level-decl-p head)
6915 ;; starts with this-reference
6916 ((js2-this-node-p head)
6917 (setq fn (js2-node-parent-script-or-fn head)
6918 chain (cdr chain))) ; discard this-node
6919 ;; nested named function
6920 ((js2-function-node-p (setq parent (js2-node-parent head)))
6921 (setq fn (js2-node-parent-script-or-fn parent)))
6922 ;; variable assigned a function expression
6923 (t (setq fn (js2-node-parent-script-or-fn head))))
6925 (setq fn-type (gethash fn js2-imenu-fn-type-map))
6928 (cond ((js2-nested-function-p fn) 'skip)
6930 (gethash fn js2-imenu-function-map))
6932 ((js2-wrapper-function-p fn) 'anon)
6934 (puthash fn fn-type js2-imenu-fn-type-map))
6936 ('anon (push chain result)) ; anonymous top-level wrapper
6937 ('named ; top-level named function
6938 ;; prefix parent fn qname, which is
6939 ;; parent-chain sans last elem, to this chain.
6940 (push (append (butlast parent-chain) chain) result))))))
6941 ;; finally replace each node in each chain with its name.
6942 (dolist (chain result)
6945 (if (js2-node-p (setq elem (car p)))
6946 (setcar p (js2-node-qname-component elem)))
6950 ;; Merge name chains into a trie-like tree structure of nested lists.
6951 ;; To simplify construction of the trie, we first build it out using the rule
6952 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6953 ;; [key, num-or-list]. The second element can be a number; if so, this key
6954 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6955 ;; associated with the key at this level.) Otherwise the second element is
6956 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6957 ;; a simple recursive formulation.
6959 ;; js2-mode is building the data structure for imenu. The imenu documentation
6960 ;; claims that it's the structure above, but in practice it wants the children
6961 ;; at the same list level as the key for that level, which is how I've drawn
6962 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6963 ;; list wrapper around the children at each level.
6965 ;; A completed nested imenu-alist entry looks like this:
6967 ;; ("<definition>" . 7)
6972 ;; In particular, the documentation for `imenu--index-alist' says that
6973 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6974 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6976 (defsubst js2-treeify (lst)
6977 "Convert (a b c d) to (a ((b ((c d)))))"
6978 (if (null (cddr lst)) ; list length <= 2
6980 (list (car lst) (list (js2-treeify (cdr lst))))))
6982 (defun js2-build-alist-trie (chains trie)
6983 "Merge declaration name chains into a trie-like alist structure for imenu.
6984 CHAINS is the qname chain list produced during parsing. TRIE is a
6985 list of elements built up so far."
6986 (let (head tail pos branch kids)
6987 (dolist (chain chains)
6988 (setq head (car chain)
6990 pos (if (numberp (car tail)) (car tail))
6991 branch (js2-find-if (lambda (n)
6992 (string= (car n) head))
6994 kids (second branch))
6996 ;; case 1: this key isn't in the trie yet
6999 (setcdr (last trie) (list (js2-treeify chain)))
7000 (setq trie (list (js2-treeify chain)))))
7001 ;; case 2: key is present with a single number entry: replace w/ list
7002 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7003 ;; ("<definition>" 20)))
7005 (setcar (cdr branch)
7006 (list (list "<definition-1>" kids)
7008 (list "<definition-2>" pos)
7009 (js2-treeify tail)))))
7010 ;; case 3: key is there (with kids), and we're a number entry
7014 (list (format "<definition-%d>"
7015 (1+ (loop for kid in kids
7016 count (eq ?< (aref (car kid) 0)))))
7018 ;; case 4: key is there with kids, need to merge in our chain
7020 (js2-build-alist-trie (list tail) kids))))
7023 (defun js2-flatten-trie (trie)
7024 "Convert TRIE to imenu-format.
7025 Recurses through nodes, and for each one whose second element is a list,
7026 appends the list's flattened elements to the current element. Also
7027 changes the tails into conses. For instance, this pre-flattened trie
7039 Note that the root of the trie has no key, just a list of chains.
7040 This is also true for the value of any key with multiple children,
7041 e.g. key 'c' in the example above."
7044 (mapcar #'js2-flatten-trie trie))
7046 (if (numberp (second trie))
7047 (cons (car trie) (second trie))
7048 ;; else pop list and append its kids
7049 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7051 (defun js2-build-imenu-index ()
7052 "Turn `js2-imenu-recorder' into an imenu data structure."
7053 (unless (eq js2-imenu-recorder 'empty)
7054 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7055 (result (js2-build-alist-trie chains nil)))
7056 (js2-flatten-trie result))))
7058 (defun js2-test-print-chains (chains)
7059 "Print a list of qname chains.
7060 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7061 i.e. one or more nodes, and an integer position as the list tail."
7062 (mapconcat (lambda (chain)
7064 (mapconcat (lambda (elem)
7065 (if (js2-node-p elem)
7066 (or (js2-node-qname-component elem)
7068 (number-to-string elem)))
7077 (defconst js2-version "1.8.0"
7078 "Version of JavaScript supported, plus minor js2 version.")
7080 (defmacro js2-record-face (face)
7081 "Record a style run of FACE for the current token."
7082 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7084 (defsubst js2-node-end (n)
7085 "Computes the absolute end of node N.
7086 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7087 is only true until the node is added to its parent; i.e., while parsing."
7091 (defsubst js2-record-comment ()
7092 "Record a comment in `js2-scanned-comments'."
7093 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7094 :format js2-ts-comment-type)
7095 js2-scanned-comments)
7096 (when js2-parse-ide-mode
7097 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7099 'font-lock-comment-face))
7100 (when (memq js2-ts-comment-type '(html preprocessor))
7101 ;; Tell cc-engine the bounds of the comment.
7102 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7104 ;; This function is called depressingly often, so it should be fast.
7105 ;; Most of the time it's looking at the same token it peeked before.
7106 (defsubst js2-peek-token ()
7107 "Returns the next token without consuming it.
7108 If previous token was consumed, calls scanner to get new token.
7109 If previous token was -not- consumed, returns it (idempotent).
7111 This function will not return a newline (js2-EOL) - instead, it
7112 gobbles newlines until it finds a non-newline token, and flags
7113 that token as appearing just after a newline.
7115 This function will also not return a js2-COMMENT. Instead, it
7116 records comments found in `js2-scanned-comments'. If the token
7117 returned by this function immediately follows a jsdoc comment,
7118 the token is flagged as such.
7120 Note that this function always returned the un-flagged token!
7121 The flags, if any, are saved in `js2-current-flagged-token'."
7122 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7123 js2-current-token ; most common case - return already-peeked token
7124 (let ((tt (js2-get-token)) ; call scanner
7127 ;; process comments and whitespace
7128 (while (or (= tt js2-EOL)
7133 (if js2-record-comments
7134 (js2-record-comment)))
7135 (setq tt (js2-get-token))) ; call scanner
7136 (setq js2-current-token tt
7137 js2-current-flagged-token (if saw-eol
7138 (logior tt js2-ti-after-eol)
7140 ;; perform lexical fontification as soon as token is scanned
7141 (when js2-parse-ide-mode
7144 (js2-record-face 'js2-error-face))
7145 ((setq face (aref js2-kwd-tokens tt))
7146 (js2-record-face face))
7147 ((and (= tt js2-NAME)
7148 (equal js2-ts-string "undefined"))
7149 (js2-record-face 'font-lock-constant-face))))
7150 tt))) ; return unflagged token
7152 (defsubst js2-peek-flagged-token ()
7153 "Returns the current token along with any flags set for it."
7155 js2-current-flagged-token)
7157 (defsubst js2-consume-token ()
7158 (setq js2-current-flagged-token js2-EOF))
7160 (defsubst js2-next-token ()
7163 (js2-consume-token)))
7165 (defsubst js2-next-flagged-token ()
7167 (prog1 js2-current-flagged-token
7168 (js2-consume-token)))
7170 (defsubst js2-match-token (match)
7171 "Consume and return t if next token matches MATCH, a bytecode.
7172 Returns nil and consumes nothing if MATCH is not the next token."
7173 (if (/= (js2-peek-token) match)
7178 (defsubst js2-valid-prop-name-token (tt)
7180 (and js2-allow-keywords-as-property-names
7182 (aref js2-kwd-tokens tt))))
7184 (defsubst js2-match-prop-name ()
7185 "Consume token and return t if next token is a valid property name.
7186 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7187 is non-nil and it's a keyword token."
7188 (if (js2-valid-prop-name-token (js2-peek-token))
7194 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7195 (if (js2-match-prop-name)
7197 (js2-report-error msg-id nil pos len)
7200 (defsubst js2-peek-token-or-eol ()
7201 "Return js2-EOL if the current token immediately follows a newline.
7202 Else returns the current token. Used in situations where we don't
7203 consider certain token types valid if they are preceded by a newline.
7204 One example is the postfix ++ or -- operator, which has to be on the
7205 same line as its operand."
7206 (let ((tt (js2-peek-token)))
7207 ;; Check for last peeked token flags
7208 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7212 (defsubst js2-set-check-for-label ()
7213 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7214 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7216 (defsubst js2-must-match (token msg-id &optional pos len)
7217 "Match next token to token code TOKEN, or record a syntax error.
7218 MSG-ID is the error message to report if the match fails.
7219 Returns t on match, nil if no match."
7220 (if (js2-match-token token)
7222 (js2-report-error msg-id nil pos len)
7225 (defsubst js2-inside-function ()
7226 (plusp js2-nesting-of-function))
7228 (defsubst js2-set-requires-activation ()
7229 (if (js2-function-node-p js2-current-script-or-fn)
7230 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7232 (defsubst js2-check-activation-name (name token)
7233 (when (js2-inside-function)
7234 ;; skip language-version 1.2 check from Rhino
7235 (if (or (string= "arguments" name)
7236 (and js2-compiler-activation-names ; only used in codegen
7237 (gethash name js2-compiler-activation-names)))
7238 (js2-set-requires-activation))))
7240 (defsubst js2-set-is-generator ()
7241 (if (js2-function-node-p js2-current-script-or-fn)
7242 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7244 (defsubst js2-must-have-xml ()
7245 (unless js2-compiler-xml-available
7246 (js2-report-error "msg.XML.not.available")))
7248 (defsubst js2-push-scope (scope)
7249 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7250 (assert (js2-scope-p scope))
7251 (assert (null (js2-scope-parent-scope scope)))
7252 (assert (not (eq js2-current-scope scope)))
7253 (setf (js2-scope-parent-scope scope) js2-current-scope
7254 js2-current-scope scope))
7256 (defsubst js2-pop-scope ()
7257 (setq js2-current-scope
7258 (js2-scope-parent-scope js2-current-scope)))
7260 (defsubst js2-enter-loop (loop-node)
7261 (push loop-node js2-loop-set)
7262 (push loop-node js2-loop-and-switch-set)
7263 (js2-push-scope loop-node)
7264 ;; Tell the current labeled statement (if any) its statement,
7265 ;; and set the jump target of the first label to the loop.
7266 ;; These are used in `js2-parse-continue' to verify that the
7267 ;; continue target is an actual labeled loop. (And for codegen.)
7268 (when js2-labeled-stmt
7269 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7270 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7271 js2-labeled-stmt))) loop-node)))
7273 (defsubst js2-exit-loop ()
7275 (pop js2-loop-and-switch-set)
7278 (defsubst js2-enter-switch (switch-node)
7279 (push switch-node js2-loop-and-switch-set))
7281 (defsubst js2-exit-switch ()
7282 (pop js2-loop-and-switch-set))
7284 (defun js2-parse (&optional buf cb)
7285 "Tells the js2 parser to parse a region of JavaScript.
7287 BUF is a buffer or buffer name containing the code to parse.
7288 Call `narrow-to-region' first to parse only part of the buffer.
7290 The returned AST root node is given some additional properties:
7291 `node-count' - total number of nodes in the AST
7292 `buffer' - BUF. The buffer it refers to may change or be killed,
7293 so the value is not necessarily reliable.
7295 An optional callback CB can be specified to report parsing
7296 progress. If `(functionp CB)' returns t, it will be called with
7297 the current line number once before parsing begins, then again
7298 each time the lexer reaches a new line number.
7300 CB can also be a list of the form `(symbol cb ...)' to specify
7301 multiple callbacks with different criteria. Each symbol is a
7302 criterion keyword, and the following element is the callback to
7305 :line - called whenever the line number changes
7306 :token - called for each new token consumed
7308 The list of criteria could be extended to include entering or
7309 leaving a statement, an expression, or a function definition."
7310 (if (and cb (not (functionp cb)))
7311 (error "criteria callbacks not yet implemented"))
7312 (let ((inhibit-point-motion-hooks t)
7313 (js2-compiler-xml-available (>= js2-language-version 160))
7314 ;; This is a recursive-descent parser, so give it a big stack.
7315 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7316 (max-specpdl-size (max max-specpdl-size 3000))
7317 (case-fold-search nil)
7319 (or buf (setq buf (current-buffer)))
7320 (message nil) ; clear any error message from previous parse
7323 (setq js2-scanned-comments nil
7324 js2-parsed-errors nil
7325 js2-parsed-warnings nil
7326 js2-imenu-recorder nil
7327 js2-imenu-function-map nil
7330 (setq ast (js2-with-unmodifying-text-property-changes
7332 (unless js2-ts-hit-eof
7333 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7334 (setf (js2-ast-root-errors ast) js2-parsed-errors
7335 (js2-ast-root-warnings ast) js2-parsed-warnings)
7336 ;; if we didn't find any declarations, put a dummy in this list so we
7337 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7338 (unless js2-imenu-recorder
7339 (setq js2-imenu-recorder 'empty))
7340 (run-hooks 'js2-parse-finished-hook)
7343 ;; Corresponds to Rhino's Parser.parse() method.
7344 (defun js2-do-parse ()
7345 "Parse current buffer starting from current point.
7346 Scanner should be initialized."
7347 (let ((pos js2-ts-cursor)
7348 (end js2-ts-cursor) ; in case file is empty
7350 ;; initialize buffer-local parsing vars
7351 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7352 js2-current-script-or-fn root
7353 js2-current-scope root
7354 js2-current-flagged-token js2-EOF
7355 js2-nesting-of-function 0
7356 js2-labeled-stmt nil
7357 js2-recorded-identifiers nil) ; for js2-highlight
7358 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7359 (if (= tt js2-FUNCTION)
7362 (setq n (js2-parse-function (if js2-called-by-compile-function
7363 'FUNCTION_EXPRESSION
7364 'FUNCTION_STATEMENT))))
7365 ;; not a function - parse a statement
7366 (setq n (js2-parse-statement)))
7367 ;; add function or statement to script
7368 (setq end (js2-node-end n))
7369 (js2-block-node-push root n))
7370 ;; add comments to root in lexical order
7371 (when js2-scanned-comments
7372 ;; if we find a comment beyond end of normal kids, use its end
7373 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7374 (dolist (comment js2-scanned-comments)
7375 (push comment (js2-ast-root-comments root))
7376 (js2-node-add-children root comment)))
7377 (setf (js2-node-len root) (- end pos))
7378 ;; Give extensions a chance to muck with things before highlighting starts.
7379 (let ((js2-additional-externs js2-additional-externs))
7380 (dolist (callback js2-post-parse-callbacks)
7382 (js2-highlight-undeclared-vars))
7385 (defun js2-function-parser ()
7387 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7389 (defun js2-parse-function-closure-body (fn-node)
7390 "Parse a JavaScript 1.8 function closure body."
7391 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7393 (js2-report-error "msg.no.brace.body" nil
7394 (js2-node-pos fn-node)
7395 (- js2-ts-cursor (js2-node-pos fn-node)))
7396 (js2-node-add-children fn-node
7397 (setf (js2-function-node-body fn-node)
7398 (js2-parse-expr t))))))
7400 (defun js2-parse-function-body (fn-node)
7401 (js2-must-match js2-LC "msg.no.brace.body"
7402 (js2-node-pos fn-node)
7403 (- js2-ts-cursor (js2-node-pos fn-node)))
7404 (let ((pos js2-token-beg) ; LC position
7405 (pn (make-js2-block-node)) ; starts at LC position
7408 (incf js2-nesting-of-function)
7410 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7413 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7414 (js2-parse-statement)
7416 (js2-parse-function 'FUNCTION_STATEMENT))))
7417 (decf js2-nesting-of-function))
7418 (setq end js2-token-end) ; assume no curly and leave at current token
7419 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7420 (setq end js2-token-end))
7421 (setf (js2-node-pos pn) pos
7422 (js2-node-len pn) (- end pos))
7423 (setf (js2-function-node-body fn-node) pn)
7424 (js2-node-add-children fn-node pn)
7427 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7428 "Declare and fontify destructuring parameters inside NODE.
7429 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7431 ((js2-name-node-p node)
7433 (js2-define-symbol decl-type (js2-name-node-name node)
7434 node ignore-not-in-block)
7436 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7437 (+ leftpos (js2-node-len node))
7439 ((js2-object-node-p node)
7440 (dolist (elem (js2-object-node-elems node))
7441 (js2-define-destruct-symbols
7442 (if (js2-object-prop-node-p elem)
7443 (js2-object-prop-node-right elem)
7444 ;; abbreviated destructuring {a, b}
7446 decl-type face ignore-not-in-block)))
7447 ((js2-array-node-p node)
7448 (dolist (elem (js2-array-node-elems node))
7450 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7451 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7452 (js2-node-len node)))))
7454 (defun js2-parse-function-params (fn-node pos)
7455 (if (js2-match-token js2-RP)
7456 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7457 (let (params len param)
7458 (loop for tt = (js2-peek-token)
7461 ;; destructuring param
7462 ((or (= tt js2-LB) (= tt js2-LC))
7463 (setq param (js2-parse-primary-expr-lhs))
7464 (js2-define-destruct-symbols param
7466 'js2-function-param-face)
7467 (push param params))
7470 (js2-must-match js2-NAME "msg.no.parm")
7471 (js2-record-face 'js2-function-param-face)
7472 (setq param (js2-create-name-node))
7473 (js2-define-symbol js2-LP js2-ts-string param)
7474 (push param params)))
7476 (js2-match-token js2-COMMA))
7477 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7478 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7480 (js2-node-add-children fn-node p)
7481 (push p (js2-function-node-params fn-node))))))
7483 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7484 "Possibly show inconsistent-return warning.
7485 Last token scanned is the close-curly for the function body."
7486 (when (and js2-mode-show-strict-warnings
7487 js2-strict-inconsistent-return-warning
7488 (not (js2-has-consistent-return-usage
7489 (js2-function-node-body fn-node))))
7490 ;; Have it extend from close-curly to bol or beginning of block.
7491 (let ((pos (save-excursion
7492 (goto-char js2-token-end)
7493 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7495 (end js2-token-end))
7496 (if (plusp (js2-name-node-length name))
7497 (js2-add-strict-warning "msg.no.return.value"
7498 (js2-name-node-name name) pos end)
7499 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7501 (defun js2-parse-function (function-type)
7502 "Function parser. FUNCTION-TYPE is a symbol."
7503 (let ((pos js2-token-beg) ; start of 'function' keyword
7509 (synthetic-type function-type)
7511 ;; parse function name, expression, or non-name (anonymous)
7513 ;; function foo(...)
7514 ((js2-match-token js2-NAME)
7515 (setq name (js2-create-name-node t)
7516 name-beg js2-token-beg
7517 name-end js2-token-end)
7518 (unless (js2-match-token js2-LP)
7519 (when js2-allow-member-expr-as-function-name
7520 ;; function foo.bar(...)
7521 (setq member-expr-node name
7523 member-expr-node (js2-parse-member-expr-tail
7524 nil member-expr-node)))
7525 (js2-must-match js2-LP "msg.no.paren.parms")))
7526 ((js2-match-token js2-LP)
7527 nil) ; anonymous function: leave name as null
7529 ;; function random-member-expr(...)
7530 (when js2-allow-member-expr-as-function-name
7531 ;; Note that memberExpr can not start with '(' like
7532 ;; in function (1+2).toString(), because 'function (' already
7533 ;; processed as anonymous function
7534 (setq member-expr-node (js2-parse-member-expr)))
7535 (js2-must-match js2-LP "msg.no.paren.parms")))
7536 (if (= js2-current-token js2-LP) ; eventually matched LP?
7537 (setq lp js2-token-beg))
7538 (if member-expr-node
7540 (setq synthetic-type 'FUNCTION_EXPRESSION)
7541 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7543 (js2-set-face name-beg name-end
7544 'font-lock-function-name-face 'record)))
7545 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7546 (plusp (js2-name-node-length name)))
7547 ;; Function statements define a symbol in the enclosing scope
7548 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7549 (setf fn-node (make-js2-function-node :pos pos
7552 :lp (if lp (- lp pos))))
7553 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7554 ;; 1. Nested functions are not affected by the dynamic scope flag
7555 ;; as dynamic scope is already a parent of their scope.
7556 ;; 2. Functions defined under the with statement also immune to
7557 ;; this setup, in which case dynamic scope is ignored in favor
7558 ;; of the with object.
7559 (setf (js2-function-node-ignore-dynamic fn-node) t))
7560 ;; dynamically bind all the per-function variables
7561 (let ((js2-current-script-or-fn fn-node)
7562 (js2-current-scope fn-node)
7563 (js2-nesting-of-with 0)
7567 js2-loop-and-switch-set)
7568 (js2-parse-function-params fn-node pos)
7569 (if (and (>= js2-language-version 180)
7570 (/= (js2-peek-token) js2-LC))
7571 (js2-parse-function-closure-body fn-node)
7572 (js2-parse-function-body fn-node))
7574 (js2-node-add-children fn-node name))
7575 (js2-check-inconsistent-return-warning fn-node name)
7576 ;; Function expressions define a name only in the body of the
7577 ;; function, and only if not hidden by a parameter name
7579 (eq synthetic-type 'FUNCTION_EXPRESSION)
7580 (null (js2-scope-get-symbol js2-current-scope
7581 (js2-name-node-name name))))
7582 (js2-define-symbol js2-FUNCTION
7583 (js2-name-node-name name)
7586 (not (eq function-type 'FUNCTION_EXPRESSION)))
7587 (js2-record-imenu-functions fn-node)))
7588 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7589 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7590 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7591 ;; We wait until after parsing the function to set its parent scope,
7592 ;; since `js2-define-symbol' needs the defining-scope check to stop
7593 ;; at the function boundary when checking for redeclarations.
7594 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7597 (defun js2-parse-statements (&optional parent)
7598 "Parse a statement list. Last token consumed must be js2-LC.
7600 PARENT can be a `js2-block-node', in which case the statements are
7601 appended to PARENT. Otherwise a new `js2-block-node' is created
7604 This function does not match the closing js2-RC: the caller
7605 matches the RC so it can provide a suitable error message if not
7606 matched. This means it's up to the caller to set the length of
7607 the node to include the closing RC. The node start pos is set to
7608 the absolute buffer start position, and the caller should fix it
7609 up to be relative to the parent node. All children of this block
7610 node are given relative start positions and correct lengths."
7611 (let ((pn (or parent (make-js2-block-node)))
7613 (setf (js2-node-pos pn) js2-token-beg)
7614 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7616 (js2-block-node-push pn (js2-parse-statement)))
7619 (defun js2-parse-statement ()
7620 (let (tt pn beg end)
7621 ;; coarse-grained user-interrupt check - needs work
7622 (and js2-parse-interruptable-p
7623 (zerop (% (incf js2-parse-stmt-count)
7624 js2-statements-per-pause))
7626 (throw 'interrupted t))
7627 (setq pn (js2-statement-helper))
7628 ;; no-side-effects warning check
7629 (unless (js2-node-has-side-effects pn)
7630 (setq end (js2-node-end pn))
7633 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7634 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7637 ;; These correspond to the switch cases in Parser.statementHelper
7638 (defconst js2-parsers
7639 (let ((parsers (make-vector js2-num-tokens
7640 #'js2-parse-expr-stmt)))
7641 (aset parsers js2-BREAK #'js2-parse-break)
7642 (aset parsers js2-CONST #'js2-parse-const-var)
7643 (aset parsers js2-CONTINUE #'js2-parse-continue)
7644 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7645 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7646 (aset parsers js2-DO #'js2-parse-do)
7647 (aset parsers js2-FOR #'js2-parse-for)
7648 (aset parsers js2-FUNCTION #'js2-function-parser)
7649 (aset parsers js2-IF #'js2-parse-if)
7650 (aset parsers js2-LC #'js2-parse-block)
7651 (aset parsers js2-LET #'js2-parse-let-stmt)
7652 (aset parsers js2-NAME #'js2-parse-name-or-label)
7653 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7654 (aset parsers js2-SEMI #'js2-parse-semi)
7655 (aset parsers js2-SWITCH #'js2-parse-switch)
7656 (aset parsers js2-THROW #'js2-parse-throw)
7657 (aset parsers js2-TRY #'js2-parse-try)
7658 (aset parsers js2-VAR #'js2-parse-const-var)
7659 (aset parsers js2-WHILE #'js2-parse-while)
7660 (aset parsers js2-WITH #'js2-parse-with)
7661 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7663 "A vector mapping token types to parser functions.")
7665 (defsubst js2-parse-warn-missing-semi (beg end)
7666 (and js2-mode-show-strict-warnings
7667 js2-strict-missing-semi-warning
7668 (js2-add-strict-warning
7669 "msg.missing.semi" nil
7670 ;; back up to beginning of statement or line
7671 (max beg (save-excursion
7676 (defconst js2-no-semi-insertion
7688 "List of tokens that don't do automatic semicolon insertion.")
7690 (defconst js2-autoinsert-semi-and-warn
7691 (list js2-ERROR js2-EOF js2-RC))
7693 (defun js2-statement-helper ()
7694 (let* ((tt (js2-peek-token))
7697 (parser (if (= tt js2-ERROR)
7699 (aref js2-parsers tt)))
7702 ;; If the statement is set, then it's been told its label by now.
7703 (and js2-labeled-stmt
7704 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7705 (setq js2-labeled-stmt nil))
7706 (setq pn (funcall parser))
7707 ;; Don't do auto semi insertion for certain statement types.
7708 (unless (or (memq first-tt js2-no-semi-insertion)
7709 (js2-labeled-stmt-node-p pn))
7710 (js2-auto-insert-semicolon pn))
7713 (defun js2-auto-insert-semicolon (pn)
7714 (let* ((tt-flagged (js2-peek-flagged-token))
7715 (tt (logand tt-flagged js2-clear-ti-mask))
7716 (pos (js2-node-pos pn)))
7719 ;; Consume ';' as a part of expression
7721 ;; extend the node bounds to include the semicolon.
7722 (setf (js2-node-len pn) (- js2-token-end pos)))
7723 ((memq tt js2-autoinsert-semi-and-warn)
7725 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7727 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7728 ;; Report error if no EOL or autoinsert ';' otherwise
7729 (js2-report-error "msg.no.semi.stmt")
7730 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7732 (defun js2-parse-condition ()
7733 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7734 The parens are discarded and the expression node is returned.
7735 The `pos' field of the return value is set to an absolute position
7736 that must be fixed up by the caller.
7737 Return value is a list (EXPR LP RP), with absolute paren positions."
7739 (if (js2-must-match js2-LP "msg.no.paren.cond")
7740 (setq lp js2-token-beg))
7741 (setq pn (js2-parse-expr))
7742 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7743 (setq rp js2-token-beg))
7744 ;; Report strict warning on code like "if (a = 7) ..."
7745 (if (and js2-strict-cond-assign-warning
7746 (js2-assign-node-p pn))
7747 (js2-add-strict-warning "msg.equal.as.assign" nil
7749 (+ (js2-node-pos pn)
7750 (js2-node-len pn))))
7753 (defun js2-parse-if ()
7754 "Parser for if-statement. Last matched token must be js2-IF."
7755 (let ((pos js2-token-beg)
7763 (setq cond (js2-parse-condition)
7764 if-true (js2-parse-statement)
7765 if-false (if (js2-match-token js2-ELSE)
7767 (setq else-pos (- js2-token-beg pos))
7768 (js2-parse-statement)))
7769 end (js2-node-end (or if-false if-true))
7770 pn (make-js2-if-node :pos pos
7772 :condition (car cond)
7776 :lp (js2-relpos (second cond) pos)
7777 :rp (js2-relpos (third cond) pos)))
7778 (js2-node-add-children pn (car cond) if-true if-false)
7781 (defun js2-parse-switch ()
7782 "Parser for if-statement. Last matched token must be js2-SWITCH."
7783 (let ((pos js2-token-beg)
7796 (if (js2-must-match js2-LP "msg.no.paren.switch")
7797 (setq lp js2-token-beg))
7798 (setq discriminant (js2-parse-expr)
7799 pn (make-js2-switch-node :discriminant discriminant
7801 :lp (js2-relpos lp pos)))
7802 (js2-node-add-children pn discriminant)
7803 (js2-enter-switch pn)
7806 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7807 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7808 (js2-must-match js2-LC "msg.no.brace.switch")
7811 (setq tt (js2-next-token)
7812 case-pos js2-token-beg)
7815 (setf (js2-node-len pn) (- js2-token-end pos))
7816 (throw 'break nil)) ; done
7818 (setq case-expr (js2-parse-expr))
7819 (js2-must-match js2-COLON "msg.no.colon.case"))
7822 (js2-report-error "msg.double.switch.default"))
7825 (js2-must-match js2-COLON "msg.no.colon.case"))
7827 (js2-report-error "msg.bad.switch")
7828 (throw 'break nil)))
7829 (setq case-node (make-js2-case-node :pos case-pos
7830 :len (- js2-token-end case-pos)
7832 (js2-node-add-children case-node case-expr)
7833 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7837 (setf stmt (js2-parse-statement)
7838 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7839 (js2-block-node-push case-node stmt))
7840 (push case-node cases)))
7841 ;; add cases last, as pushing reverses the order to be correct
7843 (js2-node-add-children pn kid)
7844 (push kid (js2-switch-node-cases pn)))
7846 (js2-exit-switch))))
7848 (defun js2-parse-while ()
7849 "Parser for while-statement. Last matched token must be js2-WHILE."
7850 (let ((pos js2-token-beg)
7851 (pn (make-js2-while-node))
7858 (setf cond (js2-parse-condition)
7859 (js2-while-node-condition pn) (car cond)
7860 body (js2-parse-statement)
7861 (js2-while-node-body pn) body
7862 (js2-node-len pn) (- (js2-node-end body) pos)
7863 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7864 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7865 (js2-node-add-children pn body (car cond)))
7869 (defun js2-parse-do ()
7870 "Parser for do-statement. Last matched token must be js2-DO."
7871 (let ((pos js2-token-beg)
7872 (pn (make-js2-do-node))
7880 (setq body (js2-parse-statement))
7881 (js2-must-match js2-WHILE "msg.no.while.do")
7882 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7883 cond (js2-parse-condition)
7884 (js2-do-node-condition pn) (car cond)
7885 (js2-do-node-body pn) body
7887 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7888 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7889 (js2-node-add-children pn (car cond) body))
7891 ;; Always auto-insert semicolon to follow SpiderMonkey:
7892 ;; It is required by ECMAScript but is ignored by the rest of
7893 ;; world; see bug 238945
7894 (if (js2-match-token js2-SEMI)
7895 (setq end js2-ts-cursor))
7896 (setf (js2-node-len pn) (- end pos))
7899 (defun js2-parse-for ()
7900 "Parser for for-statement. Last matched token must be js2-FOR.
7901 Parses for, for-in, and for each-in statements."
7902 (let ((for-pos js2-token-beg)
7909 init ; Node init is also foo in 'foo in object'
7910 cond ; Node cond is also object in 'foo in object'
7911 incr ; 3rd section of for-loop initializer
7917 ;; See if this is a for each () instead of just a for ()
7918 (when (js2-match-token js2-NAME)
7919 (if (string= "each" js2-ts-string)
7922 each-pos (- js2-token-beg for-pos)) ; relative
7923 (js2-record-face 'font-lock-keyword-face))
7924 (js2-report-error "msg.no.paren.for")))
7925 (if (js2-must-match js2-LP "msg.no.paren.for")
7926 (setq lp (- js2-token-beg for-pos)))
7927 (setq tt (js2-peek-token))
7928 ;; 'for' makes local scope
7929 (js2-push-scope (make-js2-scope))
7931 ;; parse init clause
7932 (let ((js2-in-for-init t)) ; set as dynamic variable
7935 (setq init (make-js2-empty-expr-node)))
7936 ((or (= tt js2-VAR) (= tt js2-LET))
7938 (setq init (js2-parse-variables tt js2-token-beg)))
7940 (setq init (js2-parse-expr)))))
7941 (if (js2-match-token js2-IN)
7943 in-pos (- js2-token-beg for-pos)
7944 ;; scope of iteration target object is not the scope we've created above.
7945 ;; stash current scope temporary.
7946 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7947 (js2-parse-expr))) ; object over which we're iterating
7948 ;; else ordinary for loop - parse cond and incr
7949 (js2-must-match js2-SEMI "msg.no.semi.for")
7950 (setq cond (if (= (js2-peek-token) js2-SEMI)
7951 (make-js2-empty-expr-node) ; no loop condition
7953 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7954 (setq tmp-pos js2-token-end
7955 incr (if (= (js2-peek-token) js2-RP)
7956 (make-js2-empty-expr-node :pos tmp-pos)
7958 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7959 (setq rp (- js2-token-beg for-pos)))
7961 (setq pn (make-js2-for-node :init init
7966 ;; cond could be null if 'in obj' got eaten by the init node.
7967 (if (js2-infix-node-p init)
7968 ;; it was (foo in bar) instead of (var foo in bar)
7969 (setq cond (js2-infix-node-right init)
7970 init (js2-infix-node-left init))
7971 (if (and (js2-var-decl-node-p init)
7972 (> (length (js2-var-decl-node-kids init)) 1))
7973 (js2-report-error "msg.mult.index")))
7974 (setq pn (make-js2-for-in-node :iterator init
7977 :foreach-p is-for-each
7984 ;; We have to parse the body -after- creating the loop node,
7985 ;; so that the loop node appears in the js2-loop-set, allowing
7986 ;; break/continue statements to find the enclosing loop.
7987 (setf body (js2-parse-statement)
7988 (js2-loop-node-body pn) body
7989 (js2-node-pos pn) for-pos
7990 (js2-node-len pn) (- (js2-node-end body) for-pos))
7991 (js2-node-add-children pn init cond incr body))
7997 (defun js2-parse-try ()
7998 "Parser for try-statement. Last matched token must be js2-TRY."
7999 (let ((try-pos js2-token-beg)
8017 (if (/= (js2-peek-token) js2-LC)
8018 (js2-report-error "msg.no.brace.try"))
8019 (setq try-block (js2-parse-statement)
8020 try-end (js2-node-end try-block)
8021 peek (js2-peek-token))
8024 (while (js2-match-token js2-CATCH)
8025 (setq catch-pos js2-token-beg
8030 (if saw-default-catch
8031 (js2-report-error "msg.catch.unreachable"))
8032 (if (js2-must-match js2-LP "msg.no.paren.catch")
8033 (setq lp (- js2-token-beg catch-pos)))
8034 (js2-push-scope (make-js2-scope))
8035 (let ((tt (js2-peek-token)))
8037 ;; destructuring pattern
8038 ;; catch ({ message, file }) { ... }
8039 ((or (= tt js2-LB) (= tt js2-LC))
8041 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
8045 (js2-must-match js2-NAME "msg.bad.catchcond")
8046 (setq param (js2-create-name-node))
8047 (js2-define-symbol js2-LET js2-ts-string param))))
8049 (if (js2-match-token js2-IF)
8050 (setq guard-kwd (- js2-token-beg catch-pos)
8051 catch-cond (js2-parse-expr))
8052 (setq saw-default-catch t))
8053 (if (js2-must-match js2-RP "msg.bad.catchcond")
8054 (setq rp (- js2-token-beg catch-pos)))
8055 (js2-must-match js2-LC "msg.no.brace.catchblock")
8056 (setq block (js2-parse-statements)
8057 try-end (js2-node-end block)
8058 catch-node (make-js2-catch-node :pos catch-pos
8060 :guard-expr catch-cond
8061 :guard-kwd guard-kwd
8066 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8067 (setq try-end js2-token-beg))
8068 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8069 (js2-node-len catch-node) (- try-end catch-pos))
8070 (js2-node-add-children catch-node param catch-cond block)
8071 (push catch-node catch-blocks)))
8072 ((/= peek js2-FINALLY)
8073 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8074 (js2-node-pos try-block)
8075 (- (setq try-end (js2-node-end try-block))
8076 (js2-node-pos try-block)))))
8077 (when (js2-match-token js2-FINALLY)
8078 (setq finally-pos js2-token-beg
8079 block (js2-parse-statement)
8080 try-end (js2-node-end block)
8081 finally-block (make-js2-finally-node :pos finally-pos
8082 :len (- try-end finally-pos)
8084 (js2-node-add-children finally-block block))
8085 (setq pn (make-js2-try-node :pos try-pos
8086 :len (- try-end try-pos)
8087 :try-block try-block
8088 :finally-block finally-block))
8089 (js2-node-add-children pn try-block finally-block)
8090 ;; push them onto the try-node, which reverses and corrects their order
8091 (dolist (cb catch-blocks)
8092 (js2-node-add-children pn cb)
8093 (push cb (js2-try-node-catch-clauses pn)))
8096 (defun js2-parse-throw ()
8097 "Parser for throw-statement. Last matched token must be js2-THROW."
8098 (let ((pos js2-token-beg)
8102 (if (= (js2-peek-token-or-eol) js2-EOL)
8103 ;; ECMAScript does not allow new lines before throw expression,
8105 (js2-report-error "msg.bad.throw.eol"))
8106 (setq expr (js2-parse-expr)
8107 pn (make-js2-throw-node :pos pos
8108 :len (- (js2-node-end expr) pos)
8110 (js2-node-add-children pn expr)
8113 (defsubst js2-match-jump-label-name (label-name)
8114 "If break/continue specified a label, return that label's labeled stmt.
8115 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8116 does not match an existing label, reports an error and returns nil."
8117 (let ((bundle (cdr (assoc label-name js2-label-set))))
8119 (js2-report-error "msg.undef.label"))
8122 (defun js2-parse-break ()
8123 "Parser for break-statement. Last matched token must be js2-BREAK."
8124 (let ((pos js2-token-beg)
8126 break-target ; statement to break from
8127 break-label ; in "break foo", name-node representing the foo
8128 labels ; matching labeled statement to break to
8130 (js2-consume-token) ; `break'
8131 (when (eq (js2-peek-token-or-eol) js2-NAME)
8133 (setq break-label (js2-create-name-node)
8134 end (js2-node-end break-label)
8135 ;; matchJumpLabelName only matches if there is one
8136 labels (js2-match-jump-label-name js2-ts-string)
8137 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8138 (unless (or break-target break-label)
8139 ;; no break target specified - try for innermost enclosing loop/switch
8140 (if (null js2-loop-and-switch-set)
8142 (js2-report-error "msg.bad.break" nil pos (length "break")))
8143 (setq break-target (car js2-loop-and-switch-set))))
8144 (setq pn (make-js2-break-node :pos pos
8147 :target break-target))
8148 (js2-node-add-children pn break-label) ; but not break-target
8151 (defun js2-parse-continue ()
8152 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8153 (let ((pos js2-token-beg)
8155 label ; optional user-specified label, a `js2-name-node'
8156 labels ; current matching labeled stmt, if any
8157 target ; the `js2-loop-node' target of this continue stmt
8159 (js2-consume-token) ; `continue'
8160 (when (= (js2-peek-token-or-eol) js2-NAME)
8162 (setq label (js2-create-name-node)
8163 end (js2-node-end label)
8164 ;; matchJumpLabelName only matches if there is one
8165 labels (js2-match-jump-label-name js2-ts-string)))
8167 ((null labels) ; no current label to go to
8168 (if (null js2-loop-set) ; no loop to continue to
8169 (js2-report-error "msg.continue.outside" nil pos
8170 (length "continue"))
8171 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8173 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8174 (setq target (js2-labeled-stmt-node-stmt labels))
8175 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8176 (setq pn (make-js2-continue-node :pos pos
8180 (js2-node-add-children pn label) ; but not target - it's not our child
8183 (defun js2-parse-with ()
8184 "Parser for with-statement. Last matched token must be js2-WITH."
8186 (let ((pos js2-token-beg)
8188 (if (js2-must-match js2-LP "msg.no.paren.with")
8189 (setq lp js2-token-beg))
8190 (setq obj (js2-parse-expr))
8191 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8192 (setq rp js2-token-beg))
8193 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8194 (setq body (js2-parse-statement)))
8195 (setq pn (make-js2-with-node :pos pos
8196 :len (- (js2-node-end body) pos)
8199 :lp (js2-relpos lp pos)
8200 :rp (js2-relpos rp pos)))
8201 (js2-node-add-children pn obj body)
8204 (defun js2-parse-const-var ()
8205 "Parser for var- or const-statement.
8206 Last matched token must be js2-CONST or js2-VAR."
8207 (let ((tt (js2-peek-token))
8212 (setq expr (js2-parse-variables tt js2-token-beg)
8213 pn (make-js2-expr-stmt-node :pos pos
8214 :len (- (js2-node-end expr) pos)
8216 (js2-node-add-children pn expr)
8219 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8220 (let ((pn (make-js2-expr-stmt-node :pos pos
8221 :len (js2-node-len expr)
8222 :type (if (js2-inside-function)
8227 (js2-node-add-children pn expr))
8230 (defun js2-parse-let-stmt ()
8231 "Parser for let-statement. Last matched token must be js2-LET."
8233 (let ((pos js2-token-beg)
8236 (if (= (js2-peek-token) js2-LP)
8237 ;; let expression in statement context
8238 (setq expr (js2-parse-let pos 'statement)
8239 pn (js2-wrap-with-expr-stmt pos expr t))
8240 ;; else we're looking at a statement like let x=6, y=7;
8241 (setf expr (js2-parse-variables js2-LET pos)
8242 pn (js2-wrap-with-expr-stmt pos expr t)
8243 (js2-node-type pn) js2-EXPR_RESULT))
8246 (defun js2-parse-ret-yield ()
8247 (js2-parse-return-or-yield (js2-peek-token) nil))
8249 (defconst js2-parse-return-stmt-enders
8250 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8252 (defsubst js2-now-all-set (before after mask)
8253 "Return whether or not the bits in the mask have changed to all set.
8254 BEFORE is bits before change, AFTER is bits after change, and MASK is
8255 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8257 (and (/= (logand before mask) mask)
8258 (= (logand after mask) mask)))
8260 (defun js2-parse-return-or-yield (tt expr-context)
8261 (let ((pos js2-token-beg)
8263 (before js2-end-flags)
8264 (inside-function (js2-inside-function))
8268 (unless inside-function
8269 (js2-report-error (if (eq tt js2-RETURN)
8273 ;; This is ugly, but we don't want to require a semicolon.
8274 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8275 (setq e (js2-parse-expr)
8276 end (js2-node-end e)))
8279 (js2-set-flag js2-end-flags (if (null e)
8281 js2-end-returns-value))
8282 (setq ret (make-js2-return-node :pos pos
8285 (js2-node-add-children ret e)
8286 ;; See if we need a strict mode warning.
8287 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8288 ;; more thorough and accurate than this before/after flag check.
8289 ;; E.g. if there's a finally-block that always returns, we shouldn't
8290 ;; show a warning generated by inconsistent returns in the catch blocks.
8291 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8292 ;; so we know which returns/yields to highlight, and we should get rid of
8293 ;; all the checking in `js2-parse-return-or-yield'.
8294 (if (and js2-strict-inconsistent-return-warning
8295 (js2-now-all-set before js2-end-flags
8296 (logior js2-end-returns js2-end-returns-value)))
8297 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8299 (unless (js2-inside-function)
8300 (js2-report-error "msg.bad.yield"))
8301 (js2-set-flag js2-end-flags js2-end-yields)
8302 (setq ret (make-js2-yield-node :pos pos
8305 (js2-node-add-children ret e)
8306 (unless expr-context
8308 ret (js2-wrap-with-expr-stmt pos e t))
8309 (js2-set-requires-activation)
8310 (js2-set-is-generator))))
8311 ;; see if we are mixing yields and value returns.
8312 (when (and inside-function
8313 (js2-now-all-set before js2-end-flags
8314 (logior js2-end-yields js2-end-returns-value)))
8315 (setq name (js2-function-name js2-current-script-or-fn))
8316 (if (zerop (length name))
8317 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8318 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8321 (defun js2-parse-debugger ()
8323 (make-js2-keyword-node :type js2-DEBUGGER))
8325 (defun js2-parse-block ()
8326 "Parser for a curly-delimited statement block.
8327 Last token matched must be js2-LC."
8328 (let ((pos js2-token-beg)
8329 (pn (make-js2-scope)))
8334 (js2-parse-statements pn)
8335 (js2-must-match js2-RC "msg.no.brace.block")
8336 (setf (js2-node-len pn) (- js2-token-end pos)))
8340 ;; for js2-ERROR too, to have a node for error recovery to work on
8341 (defun js2-parse-semi ()
8342 "Parse a statement or handle an error.
8343 Last matched token is js-SEMI or js-ERROR."
8344 (let ((tt (js2-peek-token)) pos len)
8346 (if (eq tt js2-SEMI)
8347 (make-js2-empty-expr-node :len 1)
8348 (setq pos js2-token-beg
8349 len (- js2-token-beg pos))
8350 (js2-report-error "msg.syntax" nil pos len)
8351 (make-js2-error-node :pos pos :len len))))
8353 (defun js2-parse-default-xml-namespace ()
8354 "Parse a `default xml namespace = <expr>' e4x statement."
8355 (let ((pos js2-token-beg)
8356 end len expr unary es)
8359 (js2-set-requires-activation)
8360 (setq len (- js2-ts-cursor pos))
8361 (unless (and (js2-match-token js2-NAME)
8362 (string= js2-ts-string "xml"))
8363 (js2-report-error "msg.bad.namespace" nil pos len))
8364 (unless (and (js2-match-token js2-NAME)
8365 (string= js2-ts-string "namespace"))
8366 (js2-report-error "msg.bad.namespace" nil pos len))
8367 (unless (js2-match-token js2-ASSIGN)
8368 (js2-report-error "msg.bad.namespace" nil pos len))
8369 (setq expr (js2-parse-expr)
8370 end (js2-node-end expr)
8371 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8375 (js2-node-add-children unary expr)
8376 (make-js2-expr-stmt-node :pos pos
8380 (defun js2-record-label (label bundle)
8381 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8383 (let ((name (js2-label-node-name label))
8386 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8387 ;; flag both labels if possible when used in editing mode
8388 (if (and js2-parse-ide-mode
8389 (setq dup (js2-get-label-by-name labeled-stmt name)))
8390 (js2-report-error "msg.dup.label" nil
8391 (js2-node-abs-pos dup) (js2-node-len dup)))
8392 (js2-report-error "msg.dup.label" nil
8393 (js2-node-pos label) (js2-node-len label)))
8394 (js2-labeled-stmt-node-add-label bundle label)
8395 (js2-node-add-children bundle label)
8396 ;; Add one reference to the bundle per label in `js2-label-set'
8397 (push (cons name bundle) js2-label-set)))
8399 (defun js2-parse-name-or-label ()
8400 "Parser for identifier or label. Last token matched must be js2-NAME.
8401 Called when we found a name in a statement context. If it's a label, we gather
8402 up any following labels and the next non-label statement into a
8403 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8404 expression and return it wrapped in a `js2-expr-stmt-node'."
8405 (let ((pos js2-token-beg)
8412 ;; set check for label and call down to `js2-parse-primary-expr'
8413 (js2-set-check-for-label)
8414 (setq expr (js2-parse-expr))
8415 (if (/= (js2-node-type expr) js2-LABEL)
8416 ;; Parsed non-label expression - wrap with expression stmt.
8417 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8418 ;; else parsed a label
8419 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8420 (js2-record-label expr bundle)
8421 ;; look for more labels
8422 (while (and continue (= (js2-peek-token) js2-NAME))
8423 (js2-set-check-for-label)
8424 (setq expr (js2-parse-expr))
8425 (if (/= (js2-node-type expr) js2-LABEL)
8427 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8429 (js2-auto-insert-semicolon stmt))
8430 (js2-record-label expr bundle)))
8431 ;; no more labels; now parse the labeled statement
8434 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8435 (setq stmt (js2-statement-helper))))
8436 ;; remove the labels for this statement from the global set
8437 (dolist (label (js2-labeled-stmt-node-labels bundle))
8438 (setq js2-label-set (remove label js2-label-set))))
8439 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8440 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8441 (js2-node-add-children bundle stmt)
8444 (defun js2-parse-expr-stmt ()
8445 "Default parser in statement context, if no recognized statement found."
8446 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8448 (defun js2-parse-variables (decl-type pos)
8449 "Parse a comma-separated list of variable declarations.
8450 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8452 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8453 For 'var' or 'const', the keyword should be the token last scanned.
8455 POS is the position where the node should start. It's sometimes the
8456 var/const/let keyword, and other times the beginning of the first token
8457 in the first variable declaration.
8459 Returns the parsed `js2-var-decl-node' expression node."
8460 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8472 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8473 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8474 ;; var {a, b} = baz;
8476 (setq destructuring nil
8479 kid-pos js2-token-beg
8482 (if (or (= tt js2-LB) (= tt js2-LC))
8483 ;; Destructuring assignment, e.g., var [a, b] = ...
8484 (setq destructuring (js2-parse-primary-expr-lhs)
8485 end (js2-node-end destructuring))
8486 ;; Simple variable name
8487 (when (js2-must-match js2-NAME "msg.bad.var")
8488 (setq name (js2-create-name-node)
8492 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8493 (when (js2-match-token js2-ASSIGN)
8494 (setq init (js2-parse-assign-expr)
8495 end (js2-node-end init))
8496 (if (and js2-parse-ide-mode
8497 (or (js2-object-node-p init)
8498 (js2-function-node-p init)))
8499 (js2-record-imenu-functions init name)))
8501 (js2-set-face nbeg nend (if (js2-function-node-p init)
8502 'font-lock-function-name-face
8503 'font-lock-variable-name-face)
8505 (setq vi (make-js2-var-init-node :pos kid-pos
8506 :len (- end kid-pos)
8510 (if (and (null init) (not js2-in-for-init))
8511 (js2-report-error "msg.destruct.assign.no.init"))
8512 (js2-define-destruct-symbols destructuring
8514 'font-lock-variable-name-face)
8515 (setf (js2-var-init-node-target vi) destructuring))
8516 (setf (js2-var-init-node-target vi) name))
8517 (setf (js2-var-init-node-initializer vi) init)
8518 (js2-node-add-children vi name destructuring init)
8519 (js2-block-node-push result vi)
8520 (unless (js2-match-token js2-COMMA)
8521 (setq continue nil)))
8522 (setf (js2-node-len result) (- end pos))
8525 (defun js2-parse-let (pos &optional stmt-p)
8526 "Parse a let expression or statement.
8527 A let-expression is of the form `let (vars) expr'.
8528 A let-statment is of the form `let (vars) {statements}'.
8529 The third form of let is a variable declaration list, handled
8530 by `js2-parse-variables'."
8531 (let ((pn (make-js2-let-node :pos pos))
8533 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8534 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8538 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8539 (if (js2-must-match js2-RP "msg.no.paren.let")
8540 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8541 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8545 (setf beg js2-token-beg ; position stmt at LC
8546 body (js2-parse-statements))
8547 (js2-must-match js2-RC "msg.no.curly.let")
8548 (setf (js2-node-len body) (- js2-token-end beg)
8549 (js2-node-len pn) (- js2-token-end pos)
8550 (js2-let-node-body pn) body
8551 (js2-node-type pn) js2-LET))
8553 (setf body (js2-parse-expr)
8554 (js2-node-len pn) (- (js2-node-end body) pos)
8555 (js2-let-node-body pn) body))
8556 (js2-node-add-children pn vars body))
8560 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8561 (js2-scope-put-symbol (or scope js2-current-scope)
8563 (make-js2-symbol decl-type name node)))
8565 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8566 "Define a symbol in the current scope.
8567 If NODE is non-nil, it is the AST node associated with the symbol."
8568 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8569 (symbol (if defining-scope
8570 (js2-scope-get-symbol defining-scope name)))
8571 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8573 ((and symbol ; already defined
8574 (or (= sdt js2-CONST) ; old version is const
8575 (= decl-type js2-CONST) ; new version is const
8576 ;; two let-bound vars in this block have same name
8577 (and (= sdt js2-LET)
8578 (eq defining-scope js2-current-scope))))
8581 ((= sdt js2-CONST) "msg.const.redecl")
8582 ((= sdt js2-LET) "msg.let.redecl")
8583 ((= sdt js2-VAR) "msg.var.redecl")
8584 ((= sdt js2-FUNCTION) "msg.function.redecl")
8585 (t "msg.parm.redecl"))
8587 ((= decl-type js2-LET)
8588 (if (and (not ignore-not-in-block)
8589 (or (= (js2-node-type js2-current-scope) js2-IF)
8590 (js2-loop-node-p js2-current-scope)))
8591 (js2-report-error "msg.let.decl.not.in.block")
8592 (js2-define-new-symbol decl-type name node)))
8593 ((or (= decl-type js2-VAR)
8594 (= decl-type js2-CONST)
8595 (= decl-type js2-FUNCTION))
8597 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8598 (js2-add-strict-warning "msg.var.redecl" name)
8599 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8600 (js2-add-strict-warning "msg.var.hides.arg" name)))
8601 (js2-define-new-symbol decl-type name node
8602 js2-current-script-or-fn)))
8603 ((= decl-type js2-LP)
8605 ;; must be duplicate parameter. Second parameter hides the
8606 ;; first, so go ahead and add the second pararameter
8607 (js2-report-warning "msg.dup.parms" name))
8608 (js2-define-new-symbol decl-type name node))
8609 (t (js2-code-bug)))))
8611 (defun js2-parse-expr (&optional oneshot)
8612 (let* ((pn (js2-parse-assign-expr))
8613 (pos (js2-node-pos pn))
8617 (while (and (not oneshot)
8618 (js2-match-token js2-COMMA))
8619 (setq op-pos (- js2-token-beg pos)) ; relative
8620 (if (= (js2-peek-token) js2-YIELD)
8621 (js2-report-error "msg.yield.parenthesized"))
8622 (setq right (js2-parse-assign-expr)
8624 pn (make-js2-infix-node :type js2-COMMA
8626 :len (- js2-ts-cursor pos)
8630 (js2-node-add-children pn left right))
8633 (defun js2-parse-assign-expr ()
8634 (let ((tt (js2-peek-token))
8640 (if (= tt js2-YIELD)
8641 (js2-parse-return-or-yield tt t)
8642 ;; not yield - parse assignment expression
8643 (setq pn (js2-parse-cond-expr)
8644 tt (js2-peek-token))
8645 (when (and (<= js2-first-assign tt)
8646 (<= tt js2-last-assign))
8647 ;; tt express assignment (=, |=, ^=, ..., %=)
8649 (setq op-pos (- js2-token-beg pos) ; relative
8651 right (js2-parse-assign-expr)
8652 pn (make-js2-assign-node :type tt
8654 :len (- (js2-node-end right) pos)
8658 (when js2-parse-ide-mode
8659 (js2-highlight-assign-targets pn left right)
8660 (if (or (js2-function-node-p right)
8661 (js2-object-node-p right))
8662 (js2-record-imenu-functions right left)))
8663 ;; do this last so ide checks above can use absolute positions
8664 (js2-node-add-children pn left right))
8667 (defun js2-parse-cond-expr ()
8668 (let ((pos js2-token-beg)
8669 (pn (js2-parse-or-expr))
8675 (when (js2-match-token js2-HOOK)
8676 (setq q-pos (- js2-token-beg pos)
8677 if-true (js2-parse-assign-expr))
8678 (js2-must-match js2-COLON "msg.no.colon.cond")
8679 (setq c-pos (- js2-token-beg pos)
8680 if-false (js2-parse-assign-expr)
8682 pn (make-js2-cond-node :pos pos
8683 :len (- (js2-node-end if-false) pos)
8684 :test-expr test-expr
8686 :false-expr if-false
8689 (js2-node-add-children pn test-expr if-true if-false))
8692 (defun js2-make-binary (type left parser)
8693 "Helper for constructing a binary-operator AST node.
8694 LEFT is the left-side-expression, already parsed, and the
8695 binary operator should have just been matched.
8696 PARSER is a function to call to parse the right operand,
8697 or a `js2-node' struct if it has already been parsed."
8698 (let* ((pos (js2-node-pos left))
8699 (op-pos (- js2-token-beg pos))
8700 (right (if (js2-node-p parser)
8703 (pn (make-js2-infix-node :type type
8705 :len (- (js2-node-end right) pos)
8709 (js2-node-add-children pn left right)
8712 (defun js2-parse-or-expr ()
8713 (let ((pn (js2-parse-and-expr)))
8714 (when (js2-match-token js2-OR)
8715 (setq pn (js2-make-binary js2-OR
8717 'js2-parse-or-expr)))
8720 (defun js2-parse-and-expr ()
8721 (let ((pn (js2-parse-bit-or-expr)))
8722 (when (js2-match-token js2-AND)
8723 (setq pn (js2-make-binary js2-AND
8725 'js2-parse-and-expr)))
8728 (defun js2-parse-bit-or-expr ()
8729 (let ((pn (js2-parse-bit-xor-expr)))
8730 (while (js2-match-token js2-BITOR)
8731 (setq pn (js2-make-binary js2-BITOR
8733 'js2-parse-bit-xor-expr)))
8736 (defun js2-parse-bit-xor-expr ()
8737 (let ((pn (js2-parse-bit-and-expr)))
8738 (while (js2-match-token js2-BITXOR)
8739 (setq pn (js2-make-binary js2-BITXOR
8741 'js2-parse-bit-and-expr)))
8744 (defun js2-parse-bit-and-expr ()
8745 (let ((pn (js2-parse-eq-expr)))
8746 (while (js2-match-token js2-BITAND)
8747 (setq pn (js2-make-binary js2-BITAND
8749 'js2-parse-eq-expr)))
8752 (defconst js2-parse-eq-ops
8753 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8755 (defun js2-parse-eq-expr ()
8756 (let ((pn (js2-parse-rel-expr))
8758 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8760 (setq pn (js2-make-binary tt
8762 'js2-parse-rel-expr)))
8765 (defconst js2-parse-rel-ops
8766 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8768 (defun js2-parse-rel-expr ()
8769 (let ((pn (js2-parse-shift-expr))
8773 (setq tt (js2-peek-token))
8775 ((and js2-in-for-init (= tt js2-IN))
8776 (setq continue nil))
8777 ((memq tt js2-parse-rel-ops)
8779 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8781 (setq continue nil))))
8784 (defconst js2-parse-shift-ops
8785 (list js2-LSH js2-URSH js2-RSH))
8787 (defun js2-parse-shift-expr ()
8788 (let ((pn (js2-parse-add-expr))
8792 (setq tt (js2-peek-token))
8793 (if (memq tt js2-parse-shift-ops)
8796 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8797 (setq continue nil)))
8800 (defun js2-parse-add-expr ()
8801 (let ((pn (js2-parse-mul-expr))
8805 (setq tt (js2-peek-token))
8806 (if (or (= tt js2-ADD) (= tt js2-SUB))
8809 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8810 (setq continue nil)))
8813 (defconst js2-parse-mul-ops
8814 (list js2-MUL js2-DIV js2-MOD))
8816 (defun js2-parse-mul-expr ()
8817 (let ((pn (js2-parse-unary-expr))
8821 (setq tt (js2-peek-token))
8822 (if (memq tt js2-parse-mul-ops)
8825 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8826 (setq continue nil)))
8829 (defsubst js2-make-unary (type parser &rest args)
8830 "Make a unary node of type TYPE.
8831 PARSER is either a node (for postfix operators) or a function to call
8832 to parse the operand (for prefix operators)."
8833 (let* ((pos js2-token-beg)
8834 (postfix (js2-node-p parser))
8837 (apply parser args)))
8840 (if postfix ; e.g. i++
8841 (setq pos (js2-node-pos expr)
8843 (setq end (js2-node-end expr)))
8844 (setq pn (make-js2-unary-node :type type
8848 (js2-node-add-children pn expr)
8851 (defconst js2-incrementable-node-types
8852 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8853 "Node types that can be the operand of a ++ or -- operator.")
8855 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8856 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8857 js2-incrementable-node-types)
8858 (js2-report-error (if (= tt js2-INC)
8861 nil beg (- end beg))))
8863 (defun js2-parse-unary-expr ()
8864 (let ((tt (js2-peek-token))
8867 ((or (= tt js2-VOID)
8872 (js2-make-unary tt 'js2-parse-unary-expr))
8875 ;; Convert to special POS token in decompiler and parse tree
8876 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8879 ;; Convert to special NEG token in decompiler and parse tree
8880 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8885 (setq beg js2-token-beg
8887 expr (js2-make-unary tt 'js2-parse-member-expr t))
8888 (js2-check-bad-inc-dec tt beg end expr)))
8891 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8894 (make-js2-error-node)) ; try to continue
8896 js2-compiler-xml-available)
8897 ;; XML stream encountered in expression.
8899 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8901 (setq pn (js2-parse-member-expr t)
8902 ;; Don't look across a newline boundary for a postfix incop.
8903 tt (js2-peek-token-or-eol))
8904 (when (or (= tt js2-INC) (= tt js2-DEC))
8907 pn (js2-make-unary tt expr))
8908 (js2-node-set-prop pn 'postfix t)
8909 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8912 (defun js2-parse-xml-initializer ()
8913 "Parse an E4X XML initializer.
8914 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8915 Then I'll postprocess the result, depending on whether we're in IDE
8916 mode or codegen mode, and generate the appropriate rewritten AST.
8917 IDE mode uses a rich AST that models the XML structure. Codegen mode
8918 just concatenates everything and makes a new XML or XMLList out of it."
8919 (let ((tt (js2-get-first-xml-token))
8927 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8928 (js2-report-error "msg.syntax"))
8929 (setq pn-xml (make-js2-xml-node))
8932 (setq first-token nil)
8933 (setq tt (js2-get-next-xml-token)))
8935 ;; js2-XML means we found a {expr} in the XML stream.
8936 ;; The js2-ts-string is the XML up to the left-curly.
8938 (push (make-js2-string-node :pos js2-token-beg
8939 :len (- js2-ts-cursor js2-token-beg))
8941 (js2-must-match js2-LC "msg.syntax")
8942 (setq expr-pos js2-ts-cursor
8943 expr (if (eq (js2-peek-token) js2-RC)
8944 (make-js2-empty-expr-node :pos expr-pos)
8946 (js2-must-match js2-RC "msg.syntax")
8947 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8948 :len (js2-node-len expr)
8950 (js2-node-add-children pn expr)
8952 ;; a js2-XMLEND token means we hit the final close-tag.
8954 (push (make-js2-string-node :pos js2-token-beg
8955 :len (- js2-ts-cursor js2-token-beg))
8957 (dolist (kid (nreverse kids))
8958 (js2-block-node-push pn-xml kid))
8959 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8960 (js2-node-pos pn-xml))
8963 (js2-report-error "msg.syntax")
8964 (setq continue nil))))
8968 (defun js2-parse-argument-list ()
8969 "Parse an argument list and return it as a lisp list of nodes.
8970 Returns the list in reverse order. Consumes the right-paren token."
8972 (unless (js2-match-token js2-RP)
8974 (if (= (js2-peek-token) js2-YIELD)
8975 (js2-report-error "msg.yield.parenthesized"))
8976 (push (js2-parse-assign-expr) result)
8978 (js2-match-token js2-COMMA))
8979 (js2-must-match js2-RP "msg.no.paren.arg")
8982 (defun js2-parse-member-expr (&optional allow-call-syntax)
8983 (let ((tt (js2-peek-token))
8993 (setq pn (js2-parse-primary-expr))
8994 ;; parse a 'new' expression
8996 (setq pos js2-token-beg
8998 target (js2-parse-member-expr)
8999 end (js2-node-end target)
9000 pn (make-js2-new-node :pos pos
9003 (js2-node-add-children pn target)
9004 (when (js2-match-token js2-LP)
9005 ;; Add the arguments to pn, if any are supplied.
9006 (setf beg pos ; start of "new" keyword
9008 args (nreverse (js2-parse-argument-list))
9009 (js2-new-node-args pn) args
9011 (js2-new-node-lp pn) (- pos beg)
9012 (js2-new-node-rp pn) (- end 1 beg))
9013 (apply #'js2-node-add-children pn args))
9014 (when (and js2-allow-rhino-new-expr-initializer
9015 (js2-match-token js2-LC))
9016 (setf init (js2-parse-object-literal)
9017 end (js2-node-end init)
9018 (js2-new-node-initializer pn) init)
9019 (js2-node-add-children pn init))
9020 (setf (js2-node-len pn) (- end beg))) ; end outer if
9021 (js2-parse-member-expr-tail allow-call-syntax pn)))
9023 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9024 "Parse a chain of property/array accesses or function calls.
9025 Includes parsing for E4X operators like `..' and `.@'.
9026 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9027 Returns an expression tree that includes PN, the parent node."
9028 (let ((beg (js2-node-pos pn))
9032 (setq tt (js2-peek-token))
9034 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9035 (setq pn (js2-parse-property-access tt pn)))
9036 ((= tt js2-DOTQUERY)
9037 (setq pn (js2-parse-dot-query pn)))
9039 (setq pn (js2-parse-element-get pn)))
9041 (if allow-call-syntax
9042 (setq pn (js2-parse-function-call pn))
9043 (setq continue nil)))
9045 (setq continue nil))))
9046 (if (>= js2-highlight-level 2)
9047 (js2-parse-highlight-member-expr-node pn))
9050 (defun js2-parse-dot-query (pn)
9051 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9052 Last token parsed must be `js2-DOTQUERY'."
9053 (let ((pos (js2-node-pos pn))
9059 (js2-set-requires-activation)
9060 (setq op-pos js2-token-beg
9061 expr (js2-parse-expr)
9062 end (js2-node-end expr)
9063 pn (make-js2-xml-dot-query-node :left pn
9067 (js2-node-add-children pn
9068 (js2-xml-dot-query-node-left pn)
9069 (js2-xml-dot-query-node-right pn))
9070 (if (js2-must-match js2-RP "msg.no.paren")
9071 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9073 (setf (js2-node-len pn) (- end pos))
9076 (defun js2-parse-element-get (pn)
9077 "Parse an element-get expression, e.g. foo[bar].
9078 Last token parsed must be `js2-RB'."
9079 (let ((lb js2-token-beg)
9080 (pos (js2-node-pos pn))
9084 (setq expr (js2-parse-expr))
9085 (if (js2-must-match js2-RB "msg.no.bracket.index")
9086 (setq rb js2-token-beg))
9087 (setq pn (make-js2-elem-get-node :target pn
9090 :lb (js2-relpos lb pos)
9091 :rb (js2-relpos rb pos)
9092 :len (- js2-token-end pos)))
9093 (js2-node-add-children pn
9094 (js2-elem-get-node-target pn)
9095 (js2-elem-get-node-element pn))
9098 (defun js2-parse-function-call (pn)
9100 (pos (js2-node-pos pn)))
9102 (setq pn (make-js2-call-node :pos pos
9104 :lp (- js2-token-beg pos)))
9105 (js2-node-add-children pn (js2-call-node-target pn))
9106 ;; Add the arguments to pn, if any are supplied.
9107 (setf args (nreverse (js2-parse-argument-list))
9108 (js2-call-node-rp pn) (- js2-token-beg pos)
9109 (js2-call-node-args pn) args)
9110 (apply #'js2-node-add-children pn args)
9111 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9114 (defun js2-parse-property-access (tt pn)
9115 "Parse a property access, XML descendants access, or XML attr access."
9116 (let ((member-type-flags 0)
9117 (dot-pos js2-token-beg)
9118 (dot-len (if (= tt js2-DOTDOT) 2 1))
9120 ref ; right side of . or .. operator
9123 (when (= tt js2-DOTDOT)
9125 (setq member-type-flags js2-descendants-flag))
9126 (if (not js2-compiler-xml-available)
9128 (js2-must-match-prop-name "msg.no.name.after.dot")
9129 (setq name (js2-create-name-node t js2-GETPROP)
9130 result (make-js2-prop-get-node :left pn
9133 :len (- js2-token-end
9135 (js2-node-add-children result pn name)
9137 ;; otherwise look for XML operators
9138 (setf result (if (= tt js2-DOT)
9139 (make-js2-prop-get-node)
9140 (make-js2-infix-node :type js2-DOTDOT))
9141 (js2-node-pos result) (js2-node-pos pn)
9142 (js2-infix-node-op-pos result) dot-pos
9143 (js2-infix-node-left result) pn ; do this after setting position
9144 tt (js2-next-token))
9146 ;; needed for generator.throw()
9148 (js2-save-name-token-data js2-token-beg "throw")
9149 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9150 ;; handles: name, ns::name, ns::*, ns::[expr]
9151 ((js2-valid-prop-name-token tt)
9152 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9153 ;; handles: *, *::name, *::*, *::[expr]
9155 (js2-save-name-token-data js2-token-beg "*")
9156 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9157 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9159 (setq result (js2-parse-attribute-access)))
9161 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9163 (setf (js2-node-len result) (- (js2-node-end ref)
9164 (js2-node-pos result))
9165 (js2-infix-node-right result) ref))
9166 (if (js2-infix-node-p result)
9167 (js2-node-add-children result
9168 (js2-infix-node-left result)
9169 (js2-infix-node-right result)))
9172 (defun js2-parse-attribute-access ()
9173 "Parse an E4X XML attribute expression.
9174 This includes expressions of the forms:
9176 @attr @ns::attr @ns::*
9178 @[expr] @*::[expr] @ns::[expr]
9180 Called if we peeked an '@' token."
9181 (let ((tt (js2-next-token))
9182 (at-pos js2-token-beg))
9184 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9185 ((js2-valid-prop-name-token tt)
9186 (js2-parse-property-name at-pos js2-ts-string 0))
9187 ;; handles: @*, @*::name, @*::*, @*::[expr]
9189 (js2-save-name-token-data js2-token-beg "*")
9190 (js2-parse-property-name js2-token-beg "*" 0))
9193 (js2-parse-xml-elem-ref at-pos))
9195 (js2-report-error "msg.no.name.after.xmlAttr")
9196 ;; Avoid cascaded errors that happen if we make an error node here.
9197 (js2-save-name-token-data js2-token-beg "")
9198 (js2-parse-property-name js2-token-beg "" 0)))))
9200 (defun js2-parse-property-name (at-pos s member-type-flags)
9201 "Check if :: follows name in which case it becomes qualified name.
9203 AT-POS is a natural number if we just read an '@' token, else nil.
9204 S is the name or string that was matched: an identifier, 'throw' or '*'.
9205 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9207 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9208 operator, or the name is followed by ::. For a plain name, returns a
9209 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9210 (let ((pos (or at-pos js2-token-beg))
9212 (name (js2-create-name-node t js2-current-token))
9218 (when (js2-match-token js2-COLONCOLON)
9220 colon-pos js2-token-beg
9221 tt (js2-next-token))
9223 ;; handles name::name
9224 ((js2-valid-prop-name-token tt)
9225 (setq name (js2-create-name-node)))
9228 (js2-save-name-token-data js2-token-beg "*")
9229 (setq name (js2-create-name-node)))
9230 ;; handles name::[expr]
9232 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9234 (js2-report-error "msg.no.name.after.coloncolon"))))
9235 (if (and (null ns) (zerop member-type-flags))
9239 (make-js2-xml-prop-ref-node :pos pos
9240 :len (- (js2-node-end name) pos)
9242 :colon-pos colon-pos
9244 (js2-node-add-children pn name))))))
9246 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9247 "Parse the [expr] portion of an xml element reference.
9248 For instance, @[expr], @*::[expr], or ns::[expr]."
9249 (let* ((lb js2-token-beg)
9250 (pos (or at-pos lb))
9252 (expr (js2-parse-expr))
9253 (end (js2-node-end expr))
9255 (if (js2-must-match js2-RB "msg.no.bracket.index")
9256 (setq rb js2-token-beg
9260 (make-js2-xml-elem-ref-node :pos pos
9262 :namespace namespace
9263 :colon-pos colon-pos
9266 :lb (js2-relpos lb pos)
9267 :rb (js2-relpos rb pos)))
9268 (js2-node-add-children pn namespace expr))))
9270 (defsubst js2-parse-primary-expr-lhs ()
9271 (let ((js2-is-in-lhs t))
9272 (js2-parse-primary-expr)))
9274 (defun js2-parse-primary-expr ()
9275 "Parses a literal (leaf) expression of some sort.
9276 Includes complex literals such as functions, object-literals,
9277 array-literals, array comprehensions and regular expressions."
9278 (let ((tt-flagged (js2-next-flagged-token))
9279 pn ; parent node (usually return value)
9281 px-pos ; paren-expr pos
9283 flags ; regexp flags
9285 (setq tt js2-current-token)
9287 ((= tt js2-FUNCTION)
9288 (js2-parse-function 'FUNCTION_EXPRESSION))
9290 (js2-parse-array-literal))
9292 (js2-parse-object-literal))
9294 (js2-parse-let js2-token-beg))
9296 (setq px-pos js2-token-beg
9297 expr (js2-parse-expr))
9298 (js2-must-match js2-RP "msg.no.paren")
9299 (setq pn (make-js2-paren-node :pos px-pos
9301 :len (- js2-token-end px-pos)))
9302 (js2-node-add-children pn (js2-paren-node-expr pn))
9306 (js2-parse-attribute-access))
9308 (js2-parse-name tt-flagged tt))
9310 (make-js2-number-node))
9313 (make-js2-string-node)
9314 (js2-record-face 'font-lock-string-face)))
9315 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9316 ;; Got / or /= which in this context means a regexp literal
9317 (setq px-pos js2-token-beg)
9318 (js2-read-regexp tt)
9319 (setq flags js2-ts-regexp-flags
9320 js2-ts-regexp-flags nil)
9322 (make-js2-regexp-node :pos px-pos
9323 :len (- js2-ts-cursor px-pos)
9324 :value js2-ts-string
9326 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9327 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9328 ((or (= tt js2-NULL)
9332 (make-js2-keyword-node :type tt))
9333 ((= tt js2-RESERVED)
9334 (js2-report-error "msg.reserved.id")
9335 (make-js2-name-node))
9337 ;; the scanner or one of its subroutines reported the error.
9338 (make-js2-error-node))
9340 (setq px-pos (point-at-bol)
9341 len (- js2-ts-cursor px-pos))
9342 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9343 (make-js2-error-node :pos px-pos :len len))
9345 (js2-report-error "msg.syntax")
9346 (make-js2-error-node)))))
9348 (defun js2-parse-name (tt-flagged tt)
9349 (let ((name js2-ts-string)
9350 (name-pos js2-token-beg)
9352 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9353 (= (js2-peek-token) js2-COLON))
9355 ;; Do not consume colon, it is used as unwind indicator
9356 ;; to return to statementHelper.
9357 (make-js2-label-node :pos name-pos
9358 :len (- js2-token-end name-pos)
9360 (js2-set-face name-pos
9362 'font-lock-variable-name-face 'record))
9363 ;; Otherwise not a label, just a name. Unfortunately peeking
9364 ;; the next token to check for a colon has biffed js2-token-beg
9365 ;; and js2-token-end. We store the name's bounds in buffer vars
9366 ;; and `js2-create-name-node' uses them.
9367 (js2-save-name-token-data name-pos name)
9368 (setq node (if js2-compiler-xml-available
9369 (js2-parse-property-name nil name 0)
9370 (js2-create-name-node 'check-activation)))
9371 (if js2-highlight-external-variables
9372 (js2-record-name-node node))
9375 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9376 (js2-add-strict-warning
9378 ;; back up from comma to beginning of line or array/objlit
9380 (js2-node-pos (car elems))
9383 (goto-char comma-pos)
9384 (back-to-indentation)
9388 (defun js2-parse-array-literal ()
9389 (let ((pos js2-token-beg)
9391 (after-lb-or-comma t)
9397 (unless js2-is-in-lhs
9398 (js2-push-scope (make-js2-scope))) ; for array comp
9400 (setq tt (js2-peek-token))
9405 (setq after-comma js2-token-end)
9406 (if (not after-lb-or-comma)
9407 (setq after-lb-or-comma t)
9411 (= tt js2-EOF)) ; prevent infinite loop
9413 (js2-report-error "msg.no.bracket.arg" nil pos)
9414 (js2-consume-token))
9417 pn (make-js2-array-node :pos pos
9418 :len (- js2-ts-cursor pos)
9419 :elems (nreverse elems)))
9420 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9422 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9423 pos elems after-comma)))
9424 ;; destructuring binding
9426 (push (if (or (= tt js2-LC)
9429 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9430 (js2-parse-primary-expr-lhs)
9433 (js2-report-error "msg.bad.var")
9434 (make-js2-error-node))
9436 (setq after-lb-or-comma nil
9439 ((and (>= js2-language-version 170)
9440 (= tt js2-FOR) ; check for array comprehension
9441 (not after-lb-or-comma) ; "for" can't follow a comma
9442 elems ; must have at least 1 element
9443 (not (cdr elems))) ; but no 2nd element
9445 pn (js2-parse-array-comprehension (car elems) pos)))
9449 (unless after-lb-or-comma
9450 (js2-report-error "msg.no.bracket.arg"))
9451 (push (js2-parse-assign-expr) elems)
9452 (setq after-lb-or-comma nil
9454 (unless js2-is-in-lhs
9458 (defun js2-parse-array-comprehension (expr pos)
9459 "Parse a JavaScript 1.7 Array Comprehension.
9460 EXPR is the first expression after the opening left-bracket.
9461 POS is the beginning of the LB token preceding EXPR.
9462 We should have just parsed the 'for' keyword before calling this function."
9470 (while (= (js2-peek-token) js2-FOR)
9471 (let ((prev (car loops))) ; rearrange scope chain
9472 (push (setq loop (js2-parse-array-comp-loop)) loops)
9473 (if prev ; each loop is parent scope to the next one
9474 (setf (js2-scope-parent-scope loop) prev)
9475 ; first loop takes expr scope's parent
9476 (setf (js2-scope-parent-scope (setq first loop))
9477 (js2-scope-parent-scope js2-current-scope)))))
9478 ;; set expr scope's parent to the last loop
9479 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9480 (when (= (js2-peek-token) js2-IF)
9482 (setq if-pos (- js2-token-beg pos) ; relative
9483 filter (js2-parse-condition)))
9484 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9485 (setq result (make-js2-array-comp-node :pos pos
9486 :len (- js2-ts-cursor pos)
9488 :loops (nreverse loops)
9489 :filter (car filter)
9490 :lp (js2-relpos (second filter) pos)
9491 :rp (js2-relpos (third filter) pos)
9493 (apply #'js2-node-add-children result expr (car filter)
9494 (js2-array-comp-node-loops result))
9495 (setq js2-current-scope first) ; pop to the first loop
9498 (defun js2-parse-array-comp-loop ()
9499 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9500 Last token peeked should be the initial FOR."
9501 (let ((pos js2-token-beg)
9502 (pn (make-js2-array-comp-loop-node))
9511 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9515 (when (js2-match-token js2-NAME)
9516 (if (string= js2-ts-string "each")
9519 each-pos (- js2-token-beg pos)) ; relative
9520 (js2-record-face 'font-lock-keyword-face))
9521 (js2-report-error "msg.no.paren.for")))
9522 (if (js2-must-match js2-LP "msg.no.paren.for")
9523 (setq lp (- js2-token-beg pos)))
9524 (setq tt (js2-peek-token))
9528 ;; handle destructuring assignment
9529 (setq iter (js2-parse-primary-expr-lhs))
9530 (js2-define-destruct-symbols iter js2-LET
9531 'font-lock-variable-name-face t))
9532 ((js2-valid-prop-name-token tt)
9534 (setq iter (js2-create-name-node)))
9536 (js2-report-error "msg.bad.var")))
9537 ;; Define as a let since we want the scope of the variable to
9538 ;; be restricted to the array comprehension
9539 (if (js2-name-node-p iter)
9540 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9541 (if (js2-must-match js2-IN "msg.in.after.for.name")
9542 (setq in-pos (- js2-token-beg pos)))
9543 (setq obj (js2-parse-expr))
9544 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9545 (setq rp (- js2-token-beg pos)))
9546 (setf (js2-node-pos pn) pos
9547 (js2-node-len pn) (- js2-ts-cursor pos)
9548 (js2-array-comp-loop-node-iterator pn) iter
9549 (js2-array-comp-loop-node-object pn) obj
9550 (js2-array-comp-loop-node-in-pos pn) in-pos
9551 (js2-array-comp-loop-node-each-pos pn) each-pos
9552 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9553 (js2-array-comp-loop-node-lp pn) lp
9554 (js2-array-comp-loop-node-rp pn) rp)
9555 (js2-node-add-children pn iter obj))
9559 (defun js2-parse-object-literal ()
9560 (let ((pos js2-token-beg)
9567 (setq tt (js2-peek-token))
9569 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9570 ((or (js2-valid-prop-name-token tt)
9572 (setq after-comma nil
9573 result (js2-parse-named-prop tt))
9574 (if (and (null result)
9575 (not js2-recover-from-parse-errors))
9577 (push result elems)))
9578 ;; {12: x} or {10.7: x}
9581 (setq after-comma nil)
9582 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9587 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9588 pos elems after-comma)))
9590 (js2-report-error "msg.bad.prop")
9591 (unless js2-recover-from-parse-errors
9592 (setq continue nil)))) ; end switch
9593 (if (js2-match-token js2-COMMA)
9594 (setq after-comma js2-token-end)
9595 (setq continue nil))) ; end loop
9596 (js2-must-match js2-RC "msg.no.brace.prop")
9597 (setq result (make-js2-object-node :pos pos
9598 :len (- js2-ts-cursor pos)
9599 :elems (nreverse elems)))
9600 (apply #'js2-node-add-children result (js2-object-node-elems result))
9603 (defun js2-parse-named-prop (tt)
9604 "Parse a name, string, or getter/setter object property.
9605 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9607 (let ((string-prop (and (= tt js2-STRING)
9608 (make-js2-string-node)))
9610 (ppos js2-token-beg)
9611 (pend js2-token-end)
9612 (name (js2-create-name-node))
9613 (prop js2-ts-string))
9615 ;; getter/setter prop
9616 ((and (= tt js2-NAME)
9617 (= (js2-peek-token) js2-NAME)
9618 (or (string= prop "get")
9619 (string= prop "set")))
9621 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9622 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9623 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9624 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9625 ;; abbreviated destructuring bind e.g., {a, b} = c;
9626 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9627 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9628 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9629 ;; assignment but it's difficult because it requires looking ahead of expression.
9632 (let ((ctk (js2-peek-token)))
9633 (or (= ctk js2-COMMA)
9635 (js2-valid-prop-name-token ctk))))
9640 (setq expr (js2-parse-plain-property (or string-prop name)))
9641 (js2-set-face ppos pend
9642 (if (js2-function-node-p
9643 (js2-object-prop-node-right expr))
9644 'font-lock-function-name-face
9645 'font-lock-variable-name-face)
9648 (defun js2-parse-plain-property (prop)
9649 "Parse a non-getter/setter property in an object literal.
9650 PROP is the node representing the property: a number, name or string."
9651 (js2-must-match js2-COLON "msg.no.colon.prop")
9652 (let* ((pos (js2-node-pos prop))
9653 (colon (- js2-token-beg pos))
9654 (expr (js2-parse-assign-expr))
9655 (result (make-js2-object-prop-node
9657 ;; don't include last consumed token in length
9658 :len (- (+ (js2-node-pos expr)
9659 (js2-node-len expr))
9664 (js2-node-add-children result prop expr)
9667 (defun js2-parse-getter-setter-prop (pos prop get-p)
9668 "Parse getter or setter property in an object literal.
9669 JavaScript syntax is:
9671 { get foo() {...}, set foo(x) {...} }
9673 and expression closure style is also supported
9675 { get foo() x, set foo(x) _x = x }
9677 POS is the start position of the `get' or `set' keyword.
9678 PROP is the `js2-name-node' representing the property name.
9679 GET-P is non-nil if the keyword was `get'."
9680 (let ((type (if get-p js2-GET js2-SET))
9683 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9684 ;; it has to be an anonymous function, as we already parsed the name
9685 (if (/= (js2-node-type fn) js2-FUNCTION)
9686 (js2-report-error "msg.bad.prop")
9687 (if (plusp (length (js2-function-name fn)))
9688 (js2-report-error "msg.bad.prop")))
9689 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9690 (setq end (js2-node-end fn)
9691 result (make-js2-getter-setter-node :type type
9696 (js2-node-add-children result prop fn)
9699 (defun js2-create-name-node (&optional check-activation-p token)
9700 "Create a name node using the token info from last scanned name.
9701 In some cases we need to either synthesize a name node, or we lost
9702 the name token information by peeking. If the TOKEN parameter is
9703 not `js2-NAME', then we use the token info saved in instance vars."
9704 (let ((beg js2-token-beg)
9707 (when (/= js2-current-token js2-NAME)
9708 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9709 s js2-prev-name-token-string
9710 js2-prev-name-token-start nil
9711 js2-prev-name-token-string nil))
9712 (setq name (make-js2-name-node :pos beg
9715 (if check-activation-p
9716 (js2-check-activation-name s (or token js2-NAME)))
9719 ;;; Indentation support
9721 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9722 ;; Karl cleverly deduces that the desired indentation level is often a
9723 ;; function of paren/bracket/brace nesting depth, which can be determined
9724 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9725 ;; then does some equally clever checks to see if we're in the context of a
9726 ;; substatement of a possibly braceless statement keyword such as if, while,
9727 ;; or finally. This approach yields pretty good results.
9729 ;; The indenter is often "wrong", however, and needs to be overridden.
9730 ;; The right long-term solution is probably to emulate (or integrate
9731 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9732 ;; parse tree from `js2-parse' is present, which is not true at the
9733 ;; moment the user is typing, computing indentation is still thousands
9734 ;; of lines of code to handle every possible syntactic edge case.
9736 ;; In the meantime, the compromise solution is that we offer a "bounce
9737 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9738 ;; current line indent among various likely guess points. This approach
9739 ;; is far from perfect, but should at least make it slightly easier to
9740 ;; move the line towards its desired indentation when manually
9741 ;; overriding Karl's heuristic nesting guesser.
9743 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9744 ;; extensions such as `let' and Array comprehensions. Major kudos to
9745 ;; Karl for coming up with the initial approach, which packs a lot of
9746 ;; punch for so little code.
9748 (defconst js-possibly-braceless-keywords-re
9749 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9750 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9751 "try" "while" "with" "let")))
9752 "Regular expression matching keywords that are optionally
9753 followed by an opening brace.")
9755 (defconst js-indent-operator-re
9756 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9757 (regexp-opt '("in" "instanceof") 'words))
9758 "Regular expression matching operators that affect indentation
9759 of continued expressions.")
9761 (defconst js-declaration-keyword-re
9762 (regexp-opt '("var" "let" "const") 'words)
9763 "Regular expression matching variable declaration keywords.")
9765 ;; This function has horrible results if you're typing an array
9766 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9767 ;; in conjunction with electric-indent, so just disabling it.
9768 (defsubst js2-code-at-bol-p ()
9769 "Return t if the first character on line is non-whitespace."
9772 (defun js2-insert-and-indent (key)
9773 "Run command bound to key and indent current line. Runs the command
9774 bound to KEY in the global keymap and indents the current line."
9775 (interactive (list (this-command-keys)))
9776 (let ((cmd (lookup-key (current-global-map) key)))
9778 (call-interactively cmd)))
9779 ;; don't do the electric keys inside comments or strings,
9780 ;; and don't do bounce-indent with them.
9781 (let ((parse-state (syntax-ppss (point)))
9782 (js2-bounce-indent-p (js2-code-at-bol-p)))
9783 (unless (or (nth 3 parse-state)
9784 (nth 4 parse-state))
9785 (indent-according-to-mode))))
9787 (defun js-re-search-forward-inner (regexp &optional bound count)
9788 "Auxiliary function for `js-re-search-forward'."
9789 (let (parse saved-point)
9791 (re-search-forward regexp bound)
9792 (setq parse (if saved-point
9793 (parse-partial-sexp saved-point (point))
9794 (syntax-ppss (point))))
9795 (cond ((nth 3 parse)
9797 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9798 (save-excursion (end-of-line) (point)) t))
9802 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9803 (re-search-forward "\\*/"))
9805 (setq count (1- count))))
9806 (setq saved-point (point))))
9809 (defun js-re-search-forward (regexp &optional bound noerror count)
9810 "Search forward but ignore strings and comments. Invokes
9811 `re-search-forward' but treats the buffer as if strings and
9812 comments have been removed."
9813 (let ((saved-point (point))
9816 '(js-re-search-forward-inner regexp bound 1))
9818 '(js-re-search-backward-inner regexp bound (- count)))
9820 '(js-re-search-forward-inner regexp bound count)))))
9824 (goto-char saved-point)
9826 (error (error-message-string err)))))))
9828 (defun js-re-search-backward-inner (regexp &optional bound count)
9829 "Auxiliary function for `js-re-search-backward'."
9830 (let (parse saved-point)
9832 (re-search-backward regexp bound)
9833 (setq parse (if saved-point
9834 (parse-partial-sexp saved-point (point))
9835 (syntax-ppss (point))))
9836 (cond ((nth 3 parse)
9838 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9839 (save-excursion (beginning-of-line) (point)) t))
9841 (goto-char (nth 8 parse)))
9843 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9844 (re-search-backward "/\\*"))
9846 (setq count (1- count))))))
9849 (defun js-re-search-backward (regexp &optional bound noerror count)
9850 "Search backward but ignore strings and comments. Invokes
9851 `re-search-backward' but treats the buffer as if strings and
9852 comments have been removed."
9853 (let ((saved-point (point))
9856 '(js-re-search-backward-inner regexp bound 1))
9858 '(js-re-search-forward-inner regexp bound (- count)))
9860 '(js-re-search-backward-inner regexp bound count)))))
9864 (goto-char saved-point)
9866 (error (error-message-string err)))))))
9868 (defun js-looking-at-operator-p ()
9869 "Return non-nil if text after point is an operator (that is not
9872 (and (looking-at js-indent-operator-re)
9873 (or (not (looking-at ":"))
9875 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9876 (looking-at "?")))))))
9878 (defun js-continued-expression-p ()
9879 "Returns non-nil if the current line continues an expression."
9881 (back-to-indentation)
9882 (or (js-looking-at-operator-p)
9884 (and (js-re-search-backward "\n" nil t)
9886 (skip-chars-backward " \t")
9888 (and (js-looking-at-operator-p)
9889 (and (progn (backward-char)
9890 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9892 (defun js-end-of-do-while-loop-p ()
9893 "Returns non-nil if word after point is `while' of a do-while
9894 statement, else returns nil. A braceless do-while statement
9895 spanning several lines requires that the start of the loop is
9896 indented to the same column as the current line."
9900 (when (looking-at "\\s-*\\<while\\>")
9902 (skip-chars-backward "[ \t\n]*}")
9903 (looking-at "[ \t\n]*}"))
9905 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9906 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9907 (or (looking-at "\\<do\\>")
9908 (let ((saved-indent (current-indentation)))
9909 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9910 (/= (current-indentation) saved-indent)))
9911 (and (looking-at "[ \t]*\\<do\\>")
9912 (not (js-re-search-forward
9913 "\\<while\\>" (point-at-eol) t))
9914 (= (current-indentation) saved-indent)))))))))
9916 (defun js-multiline-decl-indentation ()
9917 "Returns the declaration indentation column if the current line belongs
9918 to a multiline declaration statement. All declarations are lined up vertically:
9924 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9925 assigned expression is a function or array/object literal, it will be indented
9928 var o = { var bar = 2,
9933 (let (forward-sexp-function ; use lisp version
9936 (back-to-indentation)
9937 (when (not (looking-at js-declaration-keyword-re))
9938 (when (looking-at js-indent-operator-re)
9939 (goto-char (match-end 0))) ; continued expressions are ok
9940 (while (and (not at-opening-bracket)
9942 (let ((pos (point)))
9945 (or (eq (char-before) ?,)
9946 (and (not (eq (char-before) ?\;))
9948 (prog2 (skip-chars-backward "[[:punct:]]")
9949 (looking-at js-indent-operator-re)
9951 (not (eq (char-before) ?\;))))
9952 (js2-same-line pos)))))
9955 (scan-error (setq at-opening-bracket t))))
9956 (when (looking-at js-declaration-keyword-re)
9957 (- (1+ (match-end 0)) (point-at-bol)))))))
9959 (defun js-ctrl-statement-indentation ()
9960 "Returns the proper indentation of the current line if it
9961 starts the body of a control statement without braces, else
9963 (let (forward-sexp-function) ; temporarily unbind it
9965 (back-to-indentation)
9966 (when (and (not (js2-same-line (point-min)))
9967 (not (looking-at "{"))
9968 (js-re-search-backward "[[:graph:]]" nil t)
9969 (not (looking-at "[{([]"))
9972 (when (= (char-before) ?\))
9973 ;; scan-sexps sometimes throws an error
9974 (ignore-errors (backward-sexp))
9975 (skip-chars-backward " \t" (point-at-bol)))
9977 (back-to-indentation)
9978 (and (looking-at js-possibly-braceless-keywords-re)
9979 (= (match-end 0) pt)
9980 (not (js-end-of-do-while-loop-p))))))
9981 (+ (current-indentation) js2-basic-offset)))))
9983 (defun js2-indent-in-array-comp (parse-status)
9984 "Return non-nil if we think we're in an array comprehension.
9985 In particular, return the buffer position of the first `for' kwd."
9986 (let ((end (point)))
9987 (when (nth 1 parse-status)
9989 (goto-char (nth 1 parse-status))
9990 (when (looking-at "\\[")
9993 (if (looking-at "[[{]")
9994 (let (forward-sexp-function) ; use lisp version
9995 (forward-sexp) ; skip destructuring form
9997 (if (and (/= (char-after) ?,) ; regular array
9999 (match-beginning 0)))
10000 ;; to skip arbitrary expressions we need the parser,
10001 ;; so we'll just guess at it.
10002 (if (and (> end (point)) ; not empty literal
10003 (re-search-forward "[^,]]* \\(for\\) " end t))
10004 (match-beginning 1))))))))
10006 (defun js2-array-comp-indentation (parse-status for-kwd)
10007 (if (js2-same-line for-kwd)
10008 ;; first continuation line
10010 (goto-char (nth 1 parse-status))
10012 (skip-chars-forward " \t")
10015 (goto-char for-kwd)
10016 (current-column))))
10018 (defun js-proper-indentation (parse-status)
10019 "Return the proper indentation for the current line."
10021 (back-to-indentation)
10022 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
10023 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10024 (continued-expr-p (js-continued-expression-p))
10025 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
10026 (js-multiline-decl-indentation)))
10027 (bracket (nth 1 parse-status))
10030 ;; indent array comprehension continuation lines specially
10032 (not (js2-same-line bracket))
10033 (setq beg (js2-indent-in-array-comp parse-status))
10034 (>= (point) (save-excursion
10036 (point-at-bol)))) ; at or after first loop?
10037 (js2-array-comp-indentation parse-status beg))
10041 ((and declaration-indent continued-expr-p)
10042 (+ declaration-indent js2-basic-offset))
10044 (declaration-indent)
10047 (goto-char bracket)
10049 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10050 (let ((p (parse-partial-sexp (point-at-bol) (point))))
10051 (when (save-excursion (skip-chars-backward " \t)")
10055 (not js2-consistent-level-indent-inner-bracket-p))
10056 (progn (goto-char (1+ (nth 1 p)))
10057 (skip-chars-forward " \t"))
10058 (back-to-indentation)
10059 (when (and js2-pretty-multiline-decl-indentation-p
10060 js2-always-indent-assigned-expr-in-decls-p
10061 (looking-at js-declaration-keyword-re))
10062 (goto-char (1+ (match-end 0)))))
10063 (cond (same-indent-p
10066 (+ (current-column) (* 2 js2-basic-offset)))
10068 (+ (current-column) js2-basic-offset)))))
10070 (unless same-indent-p
10072 (skip-chars-forward " \t"))
10073 (current-column))))
10075 (continued-expr-p js2-basic-offset)
10079 (defun js2-lineup-comment (parse-status)
10080 "Indent a multi-line block comment continuation line."
10081 (let* ((beg (nth 8 parse-status))
10082 (first-line (js2-same-line beg))
10083 (offset (save-excursion
10085 (if (looking-at "/\\*")
10086 (+ 1 (current-column))
10089 (indent-line-to offset))))
10091 (defun js2-backward-sws ()
10092 "Move backward through whitespace and comments."
10094 (while (forward-comment -1)))
10096 (defun js2-forward-sws ()
10097 "Move forward through whitespace and comments."
10099 (while (forward-comment 1)))
10101 (defsubst js2-current-indent (&optional pos)
10102 "Return column of indentation on current line.
10103 If POS is non-nil, go to that point and return indentation for that line."
10107 (back-to-indentation)
10110 (defsubst js2-arglist-close ()
10111 "Return non-nil if we're on a line beginning with a close-paren/brace."
10114 (goto-char (point-at-bol))
10116 (looking-at "[])}]"))))
10118 (defsubst js2-indent-looks-like-label-p ()
10119 (goto-char (point-at-bol))
10121 (looking-at (concat js2-mode-identifier-re ":")))
10123 (defun js2-indent-in-objlit-p (parse-status)
10124 "Return non-nil if this looks like an object-literal entry."
10125 (let ((start (nth 1 parse-status)))
10129 (and (zerop (forward-line -1))
10130 (not (< (point) start)) ; crossed a {} boundary
10131 (js2-indent-looks-like-label-p)))
10133 (js2-indent-looks-like-label-p)))))
10135 ;; if prev line looks like foobar({ then we're passing an object
10136 ;; literal to a function call, and people pretty much always want to
10137 ;; de-dent back to the previous line, so move the 'basic-offset'
10138 ;; position to the front.
10139 (defsubst js2-indent-objlit-arg-p (parse-status)
10141 (back-to-indentation)
10143 (and (eq (1- (point)) (nth 1 parse-status))
10144 (eq (char-before) ?{)
10147 (skip-chars-backward " \t")
10148 (eq (char-before) ?\()))))
10150 (defsubst js2-indent-case-block-p ()
10152 (back-to-indentation)
10154 (goto-char (point-at-bol))
10155 (skip-chars-forward " \t")
10157 (looking-at "case\\s-.+:"))))
10159 (defsubst js2-syntax-bol ()
10160 "Return the point at the first non-whitespace char on the line.
10161 Returns `point-at-bol' if the line is empty."
10163 (beginning-of-line)
10164 (skip-chars-forward " \t")
10167 (defun js2-bounce-indent (normal-col parse-status backwards)
10168 "Cycle among alternate computed indentation positions.
10169 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10170 of the buffer to the current point. NORMAL-COL is the indentation
10171 column computed by the heuristic guesser based on current paren,
10172 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10174 (let ((cur-indent (js2-current-indent))
10175 (old-buffer-undo-list buffer-undo-list)
10176 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10177 (current-line (save-excursion
10178 (forward-line 0) ; move to bol
10179 (1+ (count-lines (point-min) (point)))))
10189 ;; temporarily don't record undo info, if user requested this
10190 (if js2-mode-indent-inhibit-undo
10191 (setq buffer-undo-list t))
10194 ;; first likely point: indent from beginning of previous code line
10195 (push (setq basic-offset
10197 (back-to-indentation)
10199 (back-to-indentation)
10200 (setq prev-line-col (current-column)))
10204 ;; (first + epsilon) likely point: indent 2x from beginning of
10205 ;; previous code line. Some companies like this approach. Ahem.
10206 ;; Seriously, though -- 4-space indent for expression continuation
10207 ;; lines isn't a bad idea. We should eventually implement it
10209 (push (setq basic-offset
10211 (back-to-indentation)
10213 (back-to-indentation)
10214 (setq prev-line-col (current-column)))
10215 (* 2 js2-basic-offset)))
10218 ;; second likely point: indent from assign-expr RHS. This
10219 ;; is just a crude guess based on finding " = " on the previous
10220 ;; line containing actual code.
10221 (setq pos (save-excursion
10224 (goto-char (point-at-bol))
10225 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10227 (goto-char (match-end 1))
10228 (skip-chars-forward " \t\r\n")
10229 (current-column)))))
10231 (incf pos js2-basic-offset)
10232 (push pos positions))
10234 ;; third likely point: same indent as previous line of code.
10235 ;; Make it the first likely point if we're not on an
10236 ;; arglist-close line and previous line ends in a comma, or
10237 ;; both this line and prev line look like object-literal
10239 (setq pos (save-excursion
10240 (goto-char (point-at-bol))
10242 (back-to-indentation)
10245 ;; while we're here, look for trailing comma
10246 (if (save-excursion
10247 (goto-char (point-at-eol))
10249 (eq (char-before) ?,))
10250 (setq arglist-cont (1- (point)))))))
10252 (if (and (or arglist-cont
10253 (js2-indent-in-objlit-p parse-status))
10254 (not (js2-arglist-close)))
10255 (setq same-indent pos))
10256 (push pos positions))
10258 ;; fourth likely point: first preceding code with less indentation
10259 ;; than the immediately preceding code line.
10260 (setq pos (save-excursion
10261 (back-to-indentation)
10263 (back-to-indentation)
10264 (setq anchor (current-column))
10265 (while (and (zerop (forward-line -1))
10267 (back-to-indentation)
10270 (setq pos (current-column))))
10271 (push pos positions)
10273 ;; nesting-heuristic position, main by default
10274 (push (setq main-pos normal-col) positions)
10276 ;; delete duplicates and sort positions list
10277 (setq positions (sort (delete-dups positions) '<))
10279 ;; comma-list continuation lines: prev line indent takes precedence
10281 (setq main-pos same-indent))
10283 ;; common special cases where we want to indent in from previous line
10284 (if (or (js2-indent-case-block-p)
10285 (js2-indent-objlit-arg-p parse-status))
10286 (setq main-pos basic-offset))
10288 ;; if bouncing backwards, reverse positions list
10290 (setq positions (reverse positions)))
10292 ;; record whether we're already sitting on one of the alternatives
10293 (setq pos (member cur-indent positions))
10296 ;; case 0: we're one one of the alternatives and this is the
10297 ;; first time they've pressed TAB on this line (best-guess).
10298 ((and js2-mode-indent-ignore-first-tab
10300 ;; first time pressing TAB on this line?
10301 (not (eq js2-mode-last-indented-line current-line)))
10303 (setq computed-pos nil))
10304 ;; case 1: only one computed position => use it
10305 ((null (cdr positions))
10306 (setq computed-pos 0))
10307 ;; case 2: not on any of the computed spots => use main spot
10309 (setq computed-pos (js2-position main-pos positions)))
10310 ;; case 3: on last position: cycle to first position
10312 (setq computed-pos 0))
10313 ;; case 4: on intermediate position: cycle to next position
10315 (setq computed-pos (js2-position (second pos) positions))))
10317 ;; see if any hooks want to indent; otherwise we do it
10318 (loop with result = nil
10319 for hook in js2-indent-hook
10320 while (null result)
10322 (setq result (funcall hook positions computed-pos))
10324 (unless (or result (null computed-pos))
10325 (indent-line-to (nth computed-pos positions)))))
10328 (if js2-mode-indent-inhibit-undo
10329 (setq buffer-undo-list old-buffer-undo-list))
10330 ;; see commentary for `js2-mode-last-indented-line'
10331 (setq js2-mode-last-indented-line current-line))))
10333 (defun js2-indent-bounce-backwards ()
10334 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10335 cycles between the computed indentation positions in reverse order."
10337 (js2-indent-line t))
10339 (defsubst js2-1-line-comment-continuation-p ()
10340 "Return t if we're in a 1-line comment continuation.
10341 If so, we don't ever want to use bounce-indent."
10346 (looking-at "\\s-*//"))
10350 (when (looking-at "\\s-*$")
10353 (looking-at "\\s-*//"))))))
10355 (defun js2-indent-line (&optional bounce-backwards)
10356 "Indent the current line as JavaScript source text."
10362 ;; don't whine about errors/warnings when we're indenting.
10363 ;; This has to be set before calling parse-partial-sexp below.
10364 (inhibit-point-motion-hooks t))
10365 (setq parse-status (save-excursion
10366 (syntax-ppss (point-at-bol)))
10367 offset (- (point) (save-excursion
10368 (back-to-indentation)
10370 (js2-with-underscore-as-word-syntax
10371 (if (nth 4 parse-status)
10372 (js2-lineup-comment parse-status)
10373 (setq indent-col (js-proper-indentation parse-status))
10374 ;; see comments below about js2-mode-last-indented-line
10376 ;; bounce-indenting is disabled during electric-key indent.
10377 ;; It doesn't work well on first line of buffer.
10378 ((and js2-bounce-indent-p
10379 (not (js2-same-line (point-min)))
10380 (not (js2-1-line-comment-continuation-p)))
10381 (js2-bounce-indent indent-col parse-status bounce-backwards))
10382 ;; just indent to the guesser's likely spot
10383 (t (indent-line-to indent-col)))
10384 (when (plusp offset)
10385 (forward-char offset))))))
10387 (defun js2-indent-region (start end)
10388 "Indent the region, but don't use bounce indenting."
10389 (let ((js2-bounce-indent-p nil)
10390 (indent-region-function nil)
10391 (after-change-functions (remq 'js2-mode-edit
10392 after-change-functions)))
10393 (indent-region start end nil) ; nil for byte-compiler
10394 (js2-mode-edit start end (- end start))))
10396 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10400 "Major mode for editing JavaScript code."
10402 (kill-all-local-variables)
10403 (set-syntax-table js2-mode-syntax-table)
10404 (use-local-map js2-mode-map)
10405 (make-local-variable 'comment-start)
10406 (make-local-variable 'comment-end)
10407 (make-local-variable 'comment-start-skip)
10408 (setq major-mode 'js2-mode
10409 mode-name "JavaScript-IDE"
10410 comment-start "//" ; used by comment-region; don't change it
10412 (setq local-abbrev-table js2-mode-abbrev-table)
10413 (set (make-local-variable 'max-lisp-eval-depth)
10414 (max max-lisp-eval-depth 3000))
10415 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10416 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10418 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10419 ;; on most platforms other than the one I originally wrote it on. So it's
10420 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10421 ;; with our binding of the RET key inside comments: short lines stay short.
10422 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10424 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10425 (set (make-local-variable 'next-error-function) #'js2-next-error)
10426 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10427 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10428 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10429 ;; for characters inside regexp literals.
10430 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10431 ;; this is necessary to make `show-paren-function' work properly
10432 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10433 ;; needed for M-x rgrep, among other things
10434 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10436 ;; some variables needed by cc-engine for paragraph-fill, etc.
10437 (setq c-buffer-is-cc-mode t
10438 c-comment-prefix-regexp js2-comment-prefix-regexp
10439 c-comment-start-regexp "/[*/]\\|\\s|"
10440 c-paragraph-start js2-paragraph-start
10441 c-paragraph-separate "$"
10442 comment-start-skip js2-comment-start-skip
10443 c-syntactic-ws-start js2-syntactic-ws-start
10444 c-syntactic-ws-end js2-syntactic-ws-end
10445 c-syntactic-eol js2-syntactic-eol)
10447 (setq js2-default-externs
10448 (append js2-ecma-262-externs
10449 (if js2-include-browser-externs
10450 js2-browser-externs)
10451 (if js2-include-gears-externs
10453 (if js2-include-rhino-externs
10454 js2-rhino-externs)))
10456 ;; We do our own syntax highlighting based on the parse tree.
10457 ;; However, we want minor modes that add keywords to highlight properly
10458 ;; (examples: doxymacs, column-marker). We do this by not letting
10459 ;; font-lock unfontify anything, and telling it to fontify after we
10460 ;; re-parse and re-highlight the buffer. (We currently don't do any
10461 ;; work with regions other than the whole buffer.)
10462 (dolist (var '(font-lock-unfontify-buffer-function
10463 font-lock-unfontify-region-function))
10464 (set (make-local-variable var) (lambda (&rest args) t)))
10466 ;; Don't let font-lock do syntactic (string/comment) fontification.
10467 (set (make-local-variable #'font-lock-syntactic-face-function)
10468 (lambda (state) nil))
10470 ;; Experiment: make reparse-delay longer for longer files.
10471 (if (plusp js2-dynamic-idle-timer-adjust)
10472 (setq js2-idle-timer-delay
10473 (* js2-idle-timer-delay
10474 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10476 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10477 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10478 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10479 (imenu-add-to-menubar (concat "IM-" mode-name))
10480 (when js2-mirror-mode
10481 (js2-enter-mirror-mode))
10482 (add-to-invisibility-spec '(js2-outline . t))
10483 (set (make-local-variable 'line-move-ignore-invisible) t)
10484 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10485 (setq js2-mode-functions-hidden nil
10486 js2-mode-comments-hidden nil
10487 js2-mode-buffer-dirty-p t
10488 js2-mode-parsing nil)
10491 (if (fboundp 'run-mode-hooks)
10492 (run-mode-hooks 'js2-mode-hook)
10493 (run-hooks 'js2-mode-hook)))
10495 (defun js2-mode-exit ()
10496 "Exit `js2-mode' and clean up."
10498 (when js2-mode-node-overlay
10499 (delete-overlay js2-mode-node-overlay)
10500 (setq js2-mode-node-overlay nil))
10501 (js2-remove-overlays)
10502 (setq js2-mode-ast nil)
10503 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10504 (remove-from-invisibility-spec '(js2-outline . t))
10505 (js2-mode-show-all)
10506 (js2-with-unmodifying-text-property-changes
10507 (js2-clear-face (point-min) (point-max))))
10509 (defun js2-before-save ()
10510 "Clean up whitespace before saving file.
10511 You can disable this by customizing `js2-cleanup-whitespace'."
10512 (when js2-cleanup-whitespace
10513 (let ((col (current-column)))
10514 (delete-trailing-whitespace)
10515 ;; don't change trailing whitespace on current line
10516 (unless (eq (current-column) col)
10517 (indent-to col)))))
10519 (defsubst js2-mode-reset-timer ()
10520 "Cancel any existing parse timer and schedule a new one."
10521 (if js2-mode-parse-timer
10522 (cancel-timer js2-mode-parse-timer))
10523 (setq js2-mode-parsing nil)
10524 (setq js2-mode-parse-timer
10525 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10527 (defun js2-mode-edit (beg end len)
10528 "Schedule a new parse after buffer is edited.
10529 Buffer edit spans from BEG to END and is of length LEN.
10530 Also clears the `js2-magic' bit on autoinserted parens/brackets
10531 if the edit occurred on a line different from the magic paren."
10532 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10533 (line (if magic-pos (line-number-at-pos magic-pos))))
10535 (or (/= (line-number-at-pos beg) line)
10537 (/= (line-number-at-pos end) line)))
10538 (js2-mode-mundanify-parens)))
10539 (setq js2-mode-buffer-dirty-p t)
10540 (js2-mode-hide-overlay)
10541 (js2-mode-reset-timer))
10543 (defun js2-mode-run-font-lock ()
10544 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10545 This is intended to allow modes that install their own font-lock keywords
10546 to work with js2-mode. In practice it never seems to work for long.
10547 Hopefully the Emacs maintainers can help figure out a way to make it work."
10548 (when (and (boundp 'font-lock-keywords)
10550 (boundp 'font-lock-mode)
10552 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10553 ;; play nicely with js2-mode. They go out of their way to fail to
10554 ;; provide any option for saying "look, fontify the farging buffer
10555 ;; with just the keywords already". Argh.
10556 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10557 (let (font-lock-verbose)
10558 (font-lock-fontify-buffer))))
10560 (defun js2-reparse (&optional force)
10561 "Re-parse current buffer after user finishes some data entry.
10562 If we get any user input while parsing, including cursor motion,
10563 we discard the parse and reschedule it. If FORCE is nil, then the
10564 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10567 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10568 (unless js2-mode-parsing
10569 (setq js2-mode-parsing t)
10571 (when (or js2-mode-buffer-dirty-p force)
10572 (js2-remove-overlays)
10573 (js2-with-unmodifying-text-property-changes
10574 (setq js2-mode-buffer-dirty-p nil
10575 js2-mode-fontifications nil
10576 js2-mode-deferred-properties nil)
10577 (if js2-mode-verbose-parse-p
10578 (message "parsing..."))
10581 (setq interrupted-p
10582 (catch 'interrupted
10583 (setq js2-mode-ast (js2-parse))
10584 ;; if parsing is interrupted, comments and regex
10585 ;; literals stay ignored by `parse-partial-sexp'
10586 (remove-text-properties (point-min) (point-max)
10588 (js2-mode-apply-deferred-properties)
10589 (js2-mode-remove-suppressed-warnings)
10590 (js2-mode-show-warnings)
10591 (js2-mode-show-errors)
10592 (js2-mode-run-font-lock) ; note: doesn't work
10593 (js2-mode-highlight-magic-parens)
10594 (if (>= js2-highlight-level 1)
10595 (js2-highlight-jsdoc js2-mode-ast))
10599 ;; unfinished parse => try again
10600 (setq js2-mode-buffer-dirty-p t)
10601 (js2-mode-reset-timer))
10602 (if js2-mode-verbose-parse-p
10603 (message "Parse time: %s" time)))))
10604 (setq js2-mode-parsing nil)
10605 (unless interrupted-p
10606 (setq js2-mode-parse-timer nil))))))
10608 (defun js2-mode-show-node ()
10609 "Debugging aid: highlight selected AST node on mouse click."
10611 (let ((node (js2-node-at-point))
10614 (when js2-mode-show-overlay
10616 (message "No node found at location %s" (point))
10617 (setq beg (js2-node-abs-pos node)
10618 end (+ beg (js2-node-len node)))
10619 (if js2-mode-node-overlay
10620 (move-overlay js2-mode-node-overlay beg end)
10621 (setq js2-mode-node-overlay (make-overlay beg end))
10622 (overlay-put js2-mode-node-overlay 'face 'highlight))
10623 (js2-with-unmodifying-text-property-changes
10624 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10625 (message "%s, parent: %s"
10626 (js2-node-short-name node)
10627 (if (js2-node-parent node)
10628 (js2-node-short-name (js2-node-parent node))
10631 (defun js2-mode-hide-overlay (&optional p1 p2)
10632 "Remove the debugging overlay when the point moves.
10633 P1 and P2 are the old and new values of point, respectively."
10634 (when js2-mode-node-overlay
10635 (let ((beg (overlay-start js2-mode-node-overlay))
10636 (end (overlay-end js2-mode-node-overlay)))
10637 ;; Sometimes we're called spuriously.
10641 (js2-with-unmodifying-text-property-changes
10642 (remove-text-properties beg end '(point-left nil)))
10643 (delete-overlay js2-mode-node-overlay)
10644 (setq js2-mode-node-overlay nil)))))
10646 (defun js2-mode-reset ()
10647 "Debugging helper: reset everything."
10652 (defsubst js2-mode-show-warn-or-err (e face)
10653 "Highlight a warning or error E with FACE.
10654 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10655 (let* ((key (first e))
10657 (end (+ beg (third e)))
10658 ;; Don't inadvertently go out of bounds.
10659 (beg (max (point-min) (min beg (point-max))))
10660 (end (max (point-min) (min end (point-max))))
10661 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10662 (ovl (make-overlay beg end)))
10663 (overlay-put ovl 'face face)
10664 (overlay-put ovl 'js2-error t)
10665 (put-text-property beg end 'help-echo (js2-get-msg key))
10666 (put-text-property beg end 'point-entered #'js2-echo-error)))
10668 (defun js2-remove-overlays ()
10669 "Remove overlays from buffer that have a `js2-error' property."
10670 (let ((beg (point-min))
10673 (dolist (o (overlays-in beg end))
10674 (when (overlay-get o 'js2-error)
10675 (delete-overlay o))))))
10677 (defun js2-error-at-point (&optional pos)
10678 "Return non-nil if there's an error overlay at POS.
10679 Defaults to point."
10680 (loop with pos = (or pos (point))
10681 for o in (overlays-at pos)
10682 thereis (overlay-get o 'js2-error)))
10684 (defun js2-mode-apply-deferred-properties ()
10685 "Apply fontifications and other text properties recorded during parsing."
10686 (when (plusp js2-highlight-level)
10687 ;; We defer clearing faces as long as possible to eliminate flashing.
10688 (js2-clear-face (point-min) (point-max))
10689 ;; Have to reverse the recorded fontifications list so that errors
10690 ;; and warnings overwrite the normal fontifications.
10691 (dolist (f (nreverse js2-mode-fontifications))
10692 (put-text-property (first f) (second f) 'face (third f)))
10693 (setq js2-mode-fontifications nil))
10694 (dolist (p js2-mode-deferred-properties)
10695 (apply #'put-text-property p))
10696 (setq js2-mode-deferred-properties nil))
10698 (defun js2-mode-show-errors ()
10699 "Highlight syntax errors."
10700 (when js2-mode-show-parse-errors
10701 (dolist (e (js2-ast-root-errors js2-mode-ast))
10702 (js2-mode-show-warn-or-err e 'js2-error-face))))
10704 (defun js2-mode-remove-suppressed-warnings ()
10705 "Take suppressed warnings out of the AST warnings list.
10706 This ensures that the counts and `next-error' are correct."
10707 (setf (js2-ast-root-warnings js2-mode-ast)
10710 (let ((key (caar e)))
10712 (and (not js2-strict-trailing-comma-warning)
10713 (string-match "trailing\\.comma" key))
10714 (and (not js2-strict-cond-assign-warning)
10715 (string= key "msg.equal.as.assign"))
10716 (and js2-missing-semi-one-line-override
10717 (string= key "msg.missing.semi")
10718 (let* ((beg (second e))
10719 (node (js2-node-at-point beg))
10720 (fn (js2-mode-find-parent-fn node))
10721 (body (and fn (js2-function-node-body fn)))
10722 (lc (and body (js2-node-abs-pos body)))
10723 (rc (and lc (+ lc (js2-node-len body)))))
10728 (and (js2-same-line lc)
10729 (js2-same-line rc))))))))))
10730 (js2-ast-root-warnings js2-mode-ast))))
10732 (defun js2-mode-show-warnings ()
10733 "Highlight strict-mode warnings."
10734 (when js2-mode-show-strict-warnings
10735 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10736 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10738 (defun js2-echo-error (old-point new-point)
10739 "Called by point-motion hooks."
10740 (let ((msg (get-text-property new-point 'help-echo)))
10744 (defalias #'js2-echo-help #'js2-echo-error)
10746 (defun js2-enter-key ()
10747 "Handle user pressing the Enter key."
10749 (let ((parse-status (save-excursion
10750 (syntax-ppss (point)))))
10752 ;; check if we're inside a string
10753 ((nth 3 parse-status)
10754 (js2-mode-split-string parse-status))
10755 ;; check if inside a block comment
10756 ((nth 4 parse-status)
10757 (js2-mode-extend-comment))
10759 ;; should probably figure out what the mode-map says we should do
10760 (if js2-indent-on-enter-key
10761 (let ((js2-bounce-indent-p nil))
10762 (js2-indent-line)))
10764 (if js2-enter-indents-newline
10765 (let ((js2-bounce-indent-p nil))
10766 (js2-indent-line)))))))
10768 (defun js2-mode-split-string (parse-status)
10769 "Turn a newline in mid-string into a string concatenation.
10770 PARSE-STATUS is as documented in `parse-partial-sexp'."
10771 (let* ((col (current-column))
10772 (quote-char (nth 3 parse-status))
10773 (quote-string (string quote-char))
10774 (string-beg (nth 8 parse-status))
10775 (indent (save-match-data
10778 (back-to-indentation)
10779 (if (looking-at "\\+")
10782 (goto-char string-beg)
10783 (if (looking-back "\\+\\s-+")
10784 (goto-char (match-beginning 0)))
10785 (current-column))))))
10786 (insert quote-char "\n")
10788 (insert "+ " quote-string)
10790 (insert quote-string)
10791 (backward-char 1))))
10793 (defun js2-mode-extend-comment ()
10794 "When inside a comment block, add comment prefix."
10795 (let (star single col first-line needs-close)
10797 (back-to-indentation)
10799 ((looking-at "\\*[^/]")
10801 col (current-column)))
10802 ((looking-at "/\\*")
10805 col (1+ (current-column))))
10808 col (current-column)))))
10809 ;; Heuristic for whether we need to close the comment:
10810 ;; if we've got a parse error here, assume it's an unterminated
10814 (eq (get-text-property (1- (point)) 'point-entered)
10816 ;; The heuristic above doesn't work well when we're
10817 ;; creating a comment and there's another one downstream,
10818 ;; as our parser thinks this one ends at the end of the
10819 ;; next one. (You can have a /* inside a js block comment.)
10820 ;; So just close it if the next non-ws char isn't a *.
10824 (skip-chars-forward " \t\r\n")
10825 (not (eq (char-after) ?*))))))
10831 (if (and first-line needs-close)
10837 (when (save-excursion
10838 (and (zerop (forward-line 1))
10839 (looking-at "\\s-*//")))
10841 (insert "// "))))))
10843 (defun js2-beginning-of-line ()
10844 "Toggles point between bol and first non-whitespace char in line.
10845 Also moves past comment delimiters when inside comments."
10850 (back-to-indentation))
10852 (skip-chars-forward "/ \t"))
10853 ((and (eq (char-after) ?*)
10854 (setq node (js2-comment-at-point))
10855 (memq (js2-comment-node-format node) '(jsdoc block))
10857 (skip-chars-backward " \t")
10859 (skip-chars-forward "\* \t"))
10861 (goto-char (point-at-bol))))))
10863 (defun js2-end-of-line ()
10864 "Toggles point between eol and last non-whitespace char in line."
10867 (skip-chars-backward " \t")
10868 (goto-char (point-at-eol))))
10870 (defun js2-enter-mirror-mode()
10871 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10874 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10875 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10876 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10877 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10878 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10879 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10880 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10881 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10883 (defun js2-leave-mirror-mode()
10884 "Turns off mirror mode."
10886 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10887 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10889 (defsubst js2-mode-inside-string ()
10890 "Return non-nil if inside a string.
10891 Actually returns the quote character that begins the string."
10892 (let ((parse-state (save-excursion
10893 (syntax-ppss (point)))))
10894 (nth 3 parse-state)))
10896 (defsubst js2-mode-inside-comment-or-string ()
10897 "Return non-nil if inside a comment or string."
10899 (let ((comment-start
10901 (goto-char (point-at-bol))
10902 (if (re-search-forward "//" (point-at-eol) t)
10903 (match-beginning 0)))))
10905 (<= comment-start (point))))
10906 (let ((parse-state (save-excursion
10907 (syntax-ppss (point)))))
10908 (or (nth 3 parse-state)
10909 (nth 4 parse-state)))))
10911 (defsubst js2-make-magic-delimiter (delim &optional pos)
10912 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10913 Sets value of `js2-magic' text property to line number at POS."
10915 'js2-magic (line-number-at-pos pos)
10916 'face 'js2-magic-paren-face))
10918 (defun js2-mode-match-delimiter (open close)
10919 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10920 The rule we use, which as far as we can tell is how Eclipse works,
10921 is that we insert the match if we're not in a comment or string,
10922 and the next non-whitespace character is either punctuation or
10923 occurs on another line."
10925 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10926 (not (js2-mode-inside-comment-or-string)))
10928 (insert (js2-make-magic-delimiter close)))
10929 (when js2-auto-indent-p
10930 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10931 (js2-indent-line)))))
10933 (defun js2-mode-match-bracket ()
10934 "Insert matching bracket."
10936 (js2-mode-match-delimiter "[" "]"))
10938 (defun js2-mode-match-paren ()
10939 "Insert matching paren unless already inserted."
10941 (js2-mode-match-delimiter "(" ")"))
10943 (defun js2-mode-match-curly (arg)
10944 "Insert matching curly-brace.
10945 With prefix arg, no formatting or indentation will occur -- the close-brace
10946 is simply inserted directly at the point."
10950 (current-prefix-arg
10951 (js2-mode-match-delimiter "{" "}"))
10952 ((and js2-auto-insert-catch-block
10953 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10955 (match-beginning 1))))
10956 (js2-insert-catch-skel try-pos))
10958 ;; Otherwise try to do something smarter.
10960 (unless (or (not (looking-at "\\s-*$"))
10962 (skip-chars-forward " \t\r\n")
10963 (and (looking-at "}")
10964 (js2-error-at-point)))
10965 (js2-mode-inside-comment-or-string))
10967 ;; absolutely mystifying bug: when inserting the next "\n",
10968 ;; the buffer-undo-list is given two new entries: the inserted range,
10969 ;; and the incorrect position of the point. It's recorded incorrectly
10970 ;; as being before the opening "{", not after it. But it's recorded
10971 ;; as the correct value if you're debugging `js2-mode-match-curly'
10972 ;; in edebug. I have no idea why it's doing this, but incrementing
10973 ;; the inserted position fixes the problem, so that the undo takes us
10974 ;; back to just after the user-inserted "{".
10977 (incf (cadr buffer-undo-list)))
10981 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10982 (js2-indent-line))))))))
10984 (defun js2-insert-catch-skel (try-pos)
10985 "Complete a try/catch block after inserting a { following a try keyword.
10986 Rationale is that a try always needs a catch or a finally, and the catch is
10987 the more likely of the two.
10989 TRY-POS is the buffer position of the try keyword. The open-curly should
10990 already have been inserted."
10992 (let ((try-col (save-excursion
10993 (goto-char try-pos)
10994 (current-column))))
10997 (js2-indent-line) ;; indent the blank line where cursor will end up
11000 (indent-to try-col)
11001 (insert "} catch (x) {\n\n")
11002 (indent-to try-col)
11005 (defun js2-mode-highlight-magic-parens ()
11006 "Re-highlight magic parens after parsing nukes the 'face prop."
11007 (let ((beg (point-min))
11009 (while (setq beg (next-single-property-change beg 'js2-magic))
11010 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11011 (if (get-text-property beg 'js2-magic)
11012 (js2-with-unmodifying-text-property-changes
11013 (put-text-property beg (or end (1+ beg))
11014 'face 'js2-magic-paren-face))))))
11016 (defun js2-mode-mundanify-parens ()
11017 "Clear all magic parens and brackets."
11018 (let ((beg (point-min))
11020 (while (setq beg (next-single-property-change beg 'js2-magic))
11021 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11022 (remove-text-properties beg (or end (1+ beg))
11023 '(js2-magic face)))))
11025 (defsubst js2-match-quote (quote-string)
11026 (let ((start-quote (js2-mode-inside-string)))
11028 ;; inside a comment - don't do quote-matching, since we can't
11029 ;; reliably figure out if we're in a string inside the comment
11030 ((js2-comment-at-point)
11031 (insert quote-string))
11033 ;; not in string => insert matched quotes
11034 (insert quote-string)
11035 ;; exception: if we're just before a word, don't double it.
11036 (unless (looking-at "[^ \t\r\n]")
11038 (insert quote-string))))
11039 ((looking-at quote-string)
11040 (if (looking-back "[^\\]\\\\")
11041 (insert quote-string)
11043 ((and js2-mode-escape-quotes
11046 (re-search-forward quote-string (point-at-eol) t))))
11047 ;; inside terminated string, escape quote (unless already escaped)
11048 (insert (if (looking-back "[^\\]\\\\")
11050 (concat "\\" quote-string))))
11052 (insert quote-string))))) ; else terminate the string
11054 (defun js2-mode-match-single-quote ()
11055 "Insert matching single-quote."
11057 (let ((parse-status (syntax-ppss (point))))
11058 ;; don't match inside comments, since apostrophe is more common
11059 (if (nth 4 parse-status)
11061 (js2-match-quote "'"))))
11063 (defun js2-mode-match-double-quote ()
11064 "Insert matching double-quote."
11066 (js2-match-quote "\""))
11068 ;; Eclipse works as follows:
11069 ;; * type an open-paren and it auto-inserts close-paren
11070 ;; - auto-inserted paren gets a green bracket
11071 ;; - green bracket means typing close-paren there will skip it
11072 ;; * if you insert any text on a different line, it turns off
11073 (defun js2-mode-magic-close-paren ()
11074 "Skip over close-paren rather than inserting, where appropriate."
11076 (let* ((here (point))
11077 (parse-status (syntax-ppss here))
11078 (open-pos (nth 1 parse-status))
11079 (close last-input-event)
11088 (if (and (eq (char-after) close)
11089 (eq open (char-after open-pos))
11090 (js2-same-line open-pos)
11091 (get-text-property here 'js2-magic))
11093 (remove-text-properties here (1+ here) '(js2-magic face))
11095 (insert-char close 1))
11096 (blink-matching-open)))
11098 (defun js2-mode-wait-for-parse (callback)
11099 "Invoke CALLBACK when parsing is finished.
11100 If parsing is already finished, calls CALLBACK immediately."
11101 (if (not js2-mode-buffer-dirty-p)
11103 (push callback js2-mode-pending-parse-callbacks)
11104 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11106 (defun js2-mode-parse-finished ()
11107 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11108 ;; We can't let errors propagate up, since it prevents the
11109 ;; `js2-parse' method from completing normally and returning
11110 ;; the ast, which makes things mysteriously not work right.
11112 (dolist (cb js2-mode-pending-parse-callbacks)
11113 (condition-case err
11115 (error (message "%s" err))))
11116 (setq js2-mode-pending-parse-callbacks nil)))
11118 (defun js2-mode-flag-region (from to flag)
11119 "Hide or show text from FROM to TO, according to FLAG.
11120 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11121 Returns the created overlay if FLAG is non-nil."
11122 (remove-overlays from to 'invisible 'js2-outline)
11124 (let ((o (make-overlay from to)))
11125 (overlay-put o 'invisible 'js2-outline)
11126 (overlay-put o 'isearch-open-invisible
11127 'js2-isearch-open-invisible)
11130 ;; Function to be set as an outline-isearch-open-invisible' property
11131 ;; to the overlay that makes the outline invisible (see
11132 ;; `js2-mode-flag-region').
11133 (defun js2-isearch-open-invisible (overlay)
11134 ;; We rely on the fact that isearch places point on the matched text.
11135 (js2-mode-show-element))
11137 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11138 "Return cons cell of bounds of folding overlay at POS.
11139 Returns nil if not found."
11140 (let ((overlays (overlays-at (or pos (point))))
11142 (while (and overlays
11144 (if (overlay-get (car overlays) 'invisible)
11145 (setq o (car overlays))
11146 (setq overlays (cdr overlays))))
11148 (cons (overlay-start o) (overlay-end o)))))
11150 (defun js2-mode-function-at-point (&optional pos)
11151 "Return the innermost function node enclosing current point.
11152 Returns nil if point is not in a function."
11153 (let ((node (js2-node-at-point pos)))
11154 (while (and node (not (js2-function-node-p node)))
11155 (setq node (js2-node-parent node)))
11156 (if (js2-function-node-p node)
11159 (defun js2-mode-toggle-element ()
11160 "Hide or show the foldable element at the point."
11162 (let (comment fn pos)
11166 ;; /* ... */ comment?
11167 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11168 (if (js2-mode-invisible-overlay-bounds
11169 (setq pos (+ 3 (js2-node-abs-pos comment))))
11172 (js2-mode-show-element))
11173 (js2-mode-hide-element)))
11176 (back-to-indentation)
11177 (looking-at js2-mode-//-comment-re))
11178 (js2-mode-toggle-//-comment))
11180 ((setq fn (js2-mode-function-at-point))
11181 (setq pos (and (js2-function-node-body fn)
11182 (js2-node-abs-pos (js2-function-node-body fn))))
11183 (goto-char (1+ pos))
11184 (if (js2-mode-invisible-overlay-bounds)
11185 (js2-mode-show-element)
11186 (js2-mode-hide-element)))
11188 (message "Nothing at point to hide or show")))))))
11190 (defun js2-mode-hide-element ()
11191 "Fold/hide contents of a block, showing ellipses.
11192 Show the hidden text with \\[js2-mode-show-element]."
11194 (if js2-mode-buffer-dirty-p
11195 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11196 (let (node body beg end)
11198 ((js2-mode-invisible-overlay-bounds)
11199 (message "already hidden"))
11201 (setq node (js2-node-at-point))
11203 ((js2-block-comment-p node)
11204 (js2-mode-hide-comment node))
11206 (while (and node (not (js2-function-node-p node)))
11207 (setq node (js2-node-parent node)))
11209 (setq body (js2-function-node-body node)))
11211 (setq beg (js2-node-abs-pos body)
11212 end (+ beg (js2-node-len body)))
11213 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11214 (message "No collapsable element found at point"))))))))
11216 (defun js2-mode-show-element ()
11217 "Show the hidden element at current point."
11219 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11221 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11222 (message "Nothing to un-hide"))))
11224 (defun js2-mode-show-all ()
11225 "Show all of the text in the buffer."
11227 (js2-mode-flag-region (point-min) (point-max) nil))
11229 (defun js2-mode-toggle-hide-functions ()
11231 (if js2-mode-functions-hidden
11232 (js2-mode-show-functions)
11233 (js2-mode-hide-functions)))
11235 (defun js2-mode-hide-functions ()
11236 "Hides all non-nested function bodies in the buffer.
11237 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11238 to open an individual entry."
11240 (if js2-mode-buffer-dirty-p
11241 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11242 (if (null js2-mode-ast)
11243 (message "Oops - parsing failed")
11244 (setq js2-mode-functions-hidden t)
11245 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11247 (defun js2-mode-function-hider (n endp)
11249 (let ((tt (js2-node-type n))
11252 ((and (= tt js2-FUNCTION)
11253 (setq body (js2-function-node-body n)))
11254 (setq beg (js2-node-abs-pos body)
11255 end (+ beg (js2-node-len body)))
11256 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11257 nil) ; don't process children of function
11259 t))))) ; keep processing other AST nodes
11261 (defun js2-mode-show-functions ()
11262 "Un-hide any folded function bodies in the buffer."
11264 (setq js2-mode-functions-hidden nil)
11266 (goto-char (point-min))
11267 (while (/= (goto-char (next-overlay-change (point)))
11269 (dolist (o (overlays-at (point)))
11270 (when (and (overlay-get o 'invisible)
11271 (not (overlay-get o 'comment)))
11272 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11274 (defun js2-mode-hide-comment (n)
11275 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11278 (beg (+ (js2-node-abs-pos n) head))
11279 (end (- (+ beg (js2-node-len n)) head 2))
11280 (o (js2-mode-flag-region beg end 'hide)))
11281 (overlay-put o 'comment t)))
11283 (defun js2-mode-toggle-hide-comments ()
11284 "Folds all block comments in the buffer.
11285 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11286 to open an individual entry."
11288 (if js2-mode-comments-hidden
11289 (js2-mode-show-comments)
11290 (js2-mode-hide-comments)))
11292 (defun js2-mode-hide-comments ()
11294 (if js2-mode-buffer-dirty-p
11295 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11296 (if (null js2-mode-ast)
11297 (message "Oops - parsing failed")
11298 (setq js2-mode-comments-hidden t)
11299 (dolist (n (js2-ast-root-comments js2-mode-ast))
11300 (let ((format (js2-comment-node-format n)))
11301 (when (js2-block-comment-p n)
11302 (js2-mode-hide-comment n))))
11303 (js2-mode-hide-//-comments)))
11305 (defsubst js2-mode-extend-//-comment (direction)
11306 "Find start or end of a block of similar //-comment lines.
11307 DIRECTION is -1 to look back, 1 to look forward.
11308 INDENT is the indentation level to match.
11309 Returns the end-of-line position of the furthest adjacent
11310 //-comment line with the same indentation as the current line.
11311 If there is no such matching line, returns current end of line."
11312 (let ((pos (point-at-eol))
11313 (indent (current-indentation)))
11316 (while (and (zerop (forward-line direction))
11317 (looking-at js2-mode-//-comment-re)
11318 (eq indent (length (match-string 1))))
11319 (setq pos (point-at-eol)))
11322 (defun js2-mode-hide-//-comments ()
11323 "Fold adjacent 1-line comments, showing only snippet of first one."
11327 (goto-char (point-min))
11328 (while (re-search-forward js2-mode-//-comment-re nil t)
11330 end (js2-mode-extend-//-comment 1))
11331 (unless (eq beg end)
11332 (overlay-put (js2-mode-flag-region beg end 'hide)
11335 (forward-char 1))))))
11337 (defun js2-mode-toggle-//-comment ()
11338 "Fold or un-fold any multi-line //-comment at point.
11339 Caller should have determined that this line starts with a //-comment."
11340 (let* ((beg (point-at-eol))
11344 (if (js2-mode-invisible-overlay-bounds)
11345 (js2-mode-show-element)
11346 ;; else hide the comment
11347 (setq beg (js2-mode-extend-//-comment -1)
11348 end (js2-mode-extend-//-comment 1))
11349 (unless (eq beg end)
11350 (overlay-put (js2-mode-flag-region beg end 'hide)
11353 (defun js2-mode-show-comments ()
11354 "Un-hide any hidden comments, leaving other hidden elements alone."
11356 (setq js2-mode-comments-hidden nil)
11358 (goto-char (point-min))
11359 (while (/= (goto-char (next-overlay-change (point)))
11361 (dolist (o (overlays-at (point)))
11362 (when (overlay-get o 'comment)
11363 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11365 (defun js2-mode-display-warnings-and-errors ()
11366 "Turn on display of warnings and errors."
11368 (setq js2-mode-show-parse-errors t
11369 js2-mode-show-strict-warnings t)
11370 (js2-reparse 'force))
11372 (defun js2-mode-hide-warnings-and-errors ()
11373 "Turn off display of warnings and errors."
11375 (setq js2-mode-show-parse-errors nil
11376 js2-mode-show-strict-warnings nil)
11377 (js2-reparse 'force))
11379 (defun js2-mode-toggle-warnings-and-errors ()
11380 "Toggle the display of warnings and errors.
11381 Some users don't like having warnings/errors reported while they type."
11383 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11384 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11385 (if (interactive-p)
11386 (message "warnings and errors %s"
11387 (if js2-mode-show-parse-errors
11390 (js2-reparse 'force))
11392 (defun js2-mode-customize ()
11394 (customize-group 'js2-mode))
11396 (defun js2-mode-forward-sexp (&optional arg)
11397 "Move forward across one statement or balanced expression.
11398 With ARG, do it that many times. Negative arg -N means
11399 move backward across N balanced expressions."
11401 (setq arg (or arg 1))
11402 (if js2-mode-buffer-dirty-p
11403 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11404 (let (node end (start (point)))
11407 ;; could probably make this better for some cases:
11408 ;; - if in statement block (e.g. function body), go to parent
11409 ;; - infix exprs like (foo in bar) - maybe go to beginning
11410 ;; of infix expr if in the right-side expression?
11411 ((and arg (minusp arg))
11412 (dotimes (i (- arg))
11414 (forward-char -1) ; enter the node we backed up to
11415 (setq node (js2-node-at-point (point) t))
11416 (goto-char (if node
11417 (js2-node-abs-pos node)
11424 (setq node (js2-node-at-point (point) t)
11425 end (if node (+ (js2-node-abs-pos node)
11426 (js2-node-len node))))
11427 (goto-char (or end (point-max))))))))
11429 (defun js2-next-error (&optional arg reset)
11430 "Move to next parse error.
11431 Typically invoked via \\[next-error].
11432 ARG is the number of errors, forward or backward, to move.
11433 RESET means start over from the beginning."
11435 (if (or (null js2-mode-ast)
11436 (and (null (js2-ast-root-errors js2-mode-ast))
11437 (null (js2-ast-root-warnings js2-mode-ast))))
11438 (message "No errors")
11440 (goto-char (point-min)))
11441 (let* ((errs (copy-sequence
11442 (append (js2-ast-root-errors js2-mode-ast)
11443 (js2-ast-root-warnings js2-mode-ast))))
11447 (backward (minusp count))
11448 (sorter (if backward '> '<))
11449 (stopper (if backward '< '>))
11450 (count (abs count))
11453 ;; sort by start position
11454 (setq errs (sort errs (lambda (e1 e2)
11455 (funcall sorter (second e1) (second e2))))
11457 ;; find nth error with pos > start
11458 (while (and errs continue)
11459 (when (funcall stopper (cadar errs) start)
11460 (setq err (car errs))
11461 (if (zerop (decf count))
11462 (setq continue nil)))
11463 (setq errs (cdr errs)))
11465 (goto-char (second err))
11466 ;; wrap around to first error
11467 (goto-char (second (car all-errs)))
11468 ;; if we were already on it, echo msg again
11469 (if (= (point) start)
11470 (js2-echo-error (point) (point)))))))
11472 (defun js2-down-mouse-3 ()
11473 "Make right-click move the point to the click location.
11474 This makes right-click context menu operations a bit more intuitive.
11475 The point will not move if the region is active, however, to avoid
11476 destroying the region selection."
11478 (when (and js2-move-point-on-right-click
11480 (let ((e last-input-event))
11482 (goto-char (cadadr e))))))
11484 (defun js2-mode-create-imenu-index ()
11485 "Return an alist for `imenu--index-alist'."
11486 ;; This is built up in `js2-parse-record-imenu' during parsing.
11488 ;; if we have an ast but no recorder, they're requesting a rescan
11489 (unless js2-imenu-recorder
11490 (js2-reparse 'force))
11492 (js2-build-imenu-index)
11493 (setq js2-imenu-recorder nil
11494 js2-imenu-function-map nil))))
11496 (defun js2-mode-find-tag ()
11497 "Replacement for `find-tag-default'.
11498 `find-tag-default' returns a ridiculous answer inside comments."
11500 (js2-with-underscore-as-word-syntax
11502 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11503 (looking-back "[A-Za-z0-9_$]"))
11504 (setq beg (progn (forward-word -1) (point))
11505 end (progn (forward-word 1) (point)))
11506 (setq beg (progn (forward-word 1) (point))
11507 end (progn (forward-word -1) (point))))
11508 (replace-regexp-in-string
11510 (buffer-substring-no-properties beg end))))))
11512 (defun js2-mode-forward-sibling ()
11513 "Move to the end of the sibling following point in parent.
11514 Returns non-nil if successful, or nil if there was no following sibling."
11515 (let* ((node (js2-node-at-point))
11516 (parent (js2-mode-find-enclosing-fn node))
11518 (when (setq sib (js2-node-find-child-after (point) parent))
11519 (goto-char (+ (js2-node-abs-pos sib)
11520 (js2-node-len sib))))))
11522 (defun js2-mode-backward-sibling ()
11523 "Move to the beginning of the sibling node preceding point in parent.
11524 Parent is defined as the enclosing script or function."
11525 (let* ((node (js2-node-at-point))
11526 (parent (js2-mode-find-enclosing-fn node))
11528 (when (setq sib (js2-node-find-child-before (point) parent))
11529 (goto-char (js2-node-abs-pos sib)))))
11531 (defun js2-beginning-of-defun ()
11532 "Go to line on which current function starts, and return non-nil.
11533 If we're not in a function, go to beginning of previous script-level element."
11535 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11538 ((and (js2-function-node-p parent)
11539 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11542 (js2-mode-backward-sibling)))))
11544 (defun js2-end-of-defun ()
11545 "Go to the char after the last position of the current function.
11546 If we're not in a function, skips over the next script-level element."
11548 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11549 (if (not (js2-function-node-p parent))
11550 ;; punt: skip over next script-level element beyond point
11551 (js2-mode-forward-sibling)
11552 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11553 (js2-node-len parent)))))))
11555 (defun js2-mark-defun (&optional allow-extend)
11556 "Put mark at end of this function, point at beginning.
11557 The function marked is the one that contains point.
11559 Interactively, if this command is repeated,
11560 or (in Transient Mark mode) if the mark is active,
11561 it marks the next defun after the ones already marked."
11564 (when (and allow-extend
11565 (or (and (eq last-command this-command) (mark t))
11566 (and transient-mark-mode mark-active)))
11567 (let ((sib (save-excursion
11569 (if (js2-mode-forward-sibling)
11576 ;; no more siblings - try extending to enclosing node
11577 (goto-char (mark t)))))
11578 (when (not extended)
11579 (let ((node (js2-node-at-point (point) t)) ; skip comments
11580 ast fn stmt parent beg end)
11581 (when (js2-ast-root-p node)
11583 node (or (js2-node-find-child-after (point) node)
11584 (js2-node-find-child-before (point) node))))
11585 ;; only mark whole buffer if we can't find any children
11588 (if (js2-function-node-p node)
11590 (setq fn (js2-mode-find-enclosing-fn node)
11591 stmt (if (or (null fn)
11592 (js2-ast-root-p fn))
11593 (js2-mode-find-first-stmt node))
11594 parent (or stmt fn)))
11595 (setq beg (js2-node-abs-pos parent)
11596 end (+ beg (js2-node-len parent)))
11599 (exchange-point-and-mark)))))
11601 (defun js2-narrow-to-defun ()
11602 "Narrow to the function enclosing point."
11604 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11605 (fn (if (js2-script-node-p node)
11607 (js2-mode-find-enclosing-fn node)))
11608 (beg (js2-node-abs-pos fn)))
11609 (unless (js2-ast-root-p fn)
11610 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11612 (provide 'js2-mode)
11614 ;;; js2-mode.el ends here