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 JSON
83 Math NaN Number Object RangeError ReferenceError RegExp
84 String SyntaxError TypeError URIError arguments
85 decodeURI decodeURIComponent encodeURI
86 encodeURIComponent escape eval isFinite isNaN
87 parseFloat parseInt undefined unescape))
88 "Ecma-262 externs. Included in `js2-externs' by default.")
90 (defvar js2-browser-externs
93 Attr CDATASection CharacterData Comment DOMException
94 DOMImplementation Document DocumentFragment
95 DocumentType Element Entity EntityReference
96 ExceptionCode NamedNodeMap Node NodeList Notation
97 ProcessingInstruction Text
100 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
101 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
102 HTMLBodyElement HTMLButtonElement HTMLCollection
103 HTMLDListElement HTMLDirectoryElement HTMLDivElement
104 HTMLDocument HTMLElement HTMLFieldSetElement
105 HTMLFontElement HTMLFormElement HTMLFrameElement
106 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
107 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
108 HTMLImageElement HTMLInputElement HTMLIsIndexElement
109 HTMLLIElement HTMLLabelElement HTMLLegendElement
110 HTMLLinkElement HTMLMapElement HTMLMenuElement
111 HTMLMetaElement HTMLModElement HTMLOListElement
112 HTMLObjectElement HTMLOptGroupElement
113 HTMLOptionElement HTMLOptionsCollection
114 HTMLParagraphElement HTMLParamElement HTMLPreElement
115 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
116 HTMLStyleElement HTMLTableCaptionElement
117 HTMLTableCellElement HTMLTableColElement
118 HTMLTableElement HTMLTableRowElement
119 HTMLTableSectionElement HTMLTextAreaElement
120 HTMLTitleElement HTMLUListElement
123 DOMConfiguration DOMError DOMException
124 DOMImplementationList DOMImplementationSource
125 DOMLocator DOMStringList NameList TypeInfo
129 window alert confirm document java navigator prompt screen
133 CSSCharsetRule CSSFontFace CSSFontFaceRule
134 CSSImportRule CSSMediaRule CSSPageRule
135 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
136 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
137 CSSValue CSSValueList Counter DOMImplementationCSS
138 DocumentCSS DocumentStyle ElementCSSInlineStyle
139 LinkStyle MediaList RGBColor Rect StyleSheet
140 StyleSheetList ViewCSS
143 EventListener EventTarget Event DocumentEvent UIEvent
144 MouseEvent MutationEvent KeyboardEvent
147 DocumentRange Range RangeException
150 XPathResult XMLHttpRequest))
152 You can cause these to be included or excluded with the custom
153 variable `js2-include-browser-externs'.")
155 (defvar js2-rhino-externs
157 '(Packages importClass importPackage com org java
158 ;; Global object (shell) externs
159 defineClass deserialize doctest gc help load
160 loadClass print quit readFile readUrl runCommand seal
161 serialize spawn sync toint32 version))
162 "Mozilla Rhino externs.
163 Set `js2-include-rhino-externs' to t to include them.")
165 (defvar js2-gears-externs
168 ;; TODO(stevey): add these
170 "Google Gears externs.
171 Set `js2-include-gears-externs' to t to include them.")
175 (defun js2-mark-safe-local (name pred)
176 "Make the variable NAME buffer-local and mark it as safe file-local
177 variable with predicate PRED."
178 (make-variable-buffer-local name)
179 (put name 'safe-local-variable pred))
181 (defvar js2-emacs22 (>= emacs-major-version 22))
183 (defcustom js2-highlight-level 2
184 "Amount of syntax highlighting to perform.
185 0 or a negative value means do no highlighting.
186 1 adds basic syntax highlighting.
187 2 adds highlighting of some Ecma built-in properties.
188 3 adds highlighting of many Ecma built-in functions."
190 :type '(choice (const :tag "None" 0)
191 (const :tag "Basic" 1)
192 (const :tag "Include Properties" 2)
193 (const :tag "Include Functions" 3)))
195 (defvar js2-mode-dev-mode-p nil
196 "Non-nil if running in development mode. Normally nil.")
198 (defgroup js2-mode nil
199 "An improved JavaScript mode."
202 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
203 (numberp c-basic-offset))
206 "Number of spaces to indent nested statements.
207 Similar to `c-basic-offset'."
210 (js2-mark-safe-local 'js2-basic-offset 'integerp)
212 ;; TODO(stevey): move this code into a separate minor mode.
213 (defcustom js2-mirror-mode nil
214 "Non-nil to insert closing brackets, parens, etc. automatically."
218 (defcustom js2-auto-indent-p nil
219 "Automatic indentation with punctuation characters.
220 If non-nil, the current line is indented when certain punctuations
225 (defcustom js2-bounce-indent-p nil
226 "Non-nil to have indent-line function choose among alternatives.
227 If nil, the indent-line function will indent to a predetermined column
228 based on heuristic guessing. If non-nil, then if the current line is
229 already indented to that predetermined column, indenting will choose
230 another likely column and indent to that spot. Repeated invocation of
231 the indent-line function will cycle among the computed alternatives.
232 See the function `js2-bounce-indent' for details. When it is non-nil,
233 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
237 (defcustom js2-pretty-multiline-declarations t
238 "Non-nil to line up multiline declarations vertically:
244 If the value is not `all', and the first assigned value in
245 declaration is a function/array/object literal spanning several
246 lines, it won't be indented additionally:
248 var o = { var bar = 2,
254 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
256 (defcustom js2-indent-on-enter-key nil
257 "Non-nil to have Enter/Return key indent the line.
258 This is unusual for Emacs modes but common in IDEs like Eclipse."
262 (defcustom js2-enter-indents-newline nil
263 "Non-nil to have Enter/Return key indent the newly-inserted line.
264 This is unusual for Emacs modes but common in IDEs like Eclipse."
268 (defcustom js2-rebind-eol-bol-keys t
269 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
270 If non-nil, bounce between bol/eol and first/last non-whitespace char."
274 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
275 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
276 Each value in the list is passed to `define-key'."
280 (defcustom js2-idle-timer-delay 0.2
281 "Delay in secs before re-parsing after user makes changes.
282 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
285 (make-variable-buffer-local 'js2-idle-timer-delay)
287 (defcustom js2-dynamic-idle-timer-adjust 0
288 "Positive to adjust `js2-idle-timer-delay' based on file size.
289 The idea is that for short files, parsing is faster so we can be
290 more responsive to user edits without interfering with editing.
291 The buffer length in characters (typically bytes) is divided by
292 this value and used to multiply `js2-idle-timer-delay' for the
293 buffer. For example, a 21k file and 10k adjust yields 21k/10k
294 == 2, so js2-idle-timer-delay is multiplied by 2.
295 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
296 `js2-idle-timer-delay' is not dependent on the file size."
300 (defcustom js2-mode-escape-quotes t
301 "Non-nil to disable automatic quote-escaping inside strings."
305 (defcustom js2-concat-multiline-strings t
306 "Non-nil to automatically turn a newline in mid-string into a
307 string concatenation. When `eol', the '+' will be inserted at the
308 end of the line, otherwise, at the beginning of the next line."
309 :type '(choice (const t) (const eol) (const nil))
312 (defcustom js2-mode-squeeze-spaces t
313 "Non-nil to normalize whitespace when filling in comments.
314 Multiple runs of spaces are converted to a single space."
318 (defcustom js2-mode-show-parse-errors t
319 "True to highlight parse errors."
323 (defcustom js2-mode-show-strict-warnings t
324 "Non-nil to emit Ecma strict-mode warnings.
325 Some of the warnings can be individually disabled by other flags,
326 even if this flag is non-nil."
330 (defcustom js2-strict-trailing-comma-warning t
331 "Non-nil to warn about trailing commas in array literals.
332 Ecma-262 forbids them, but many browsers permit them. IE is the
333 big exception, and can produce bugs if you have trailing commas."
337 (defcustom js2-strict-missing-semi-warning t
338 "Non-nil to warn about semicolon auto-insertion after statement.
339 Technically this is legal per Ecma-262, but some style guides disallow
344 (defcustom js2-missing-semi-one-line-override nil
345 "Non-nil to permit missing semicolons in one-line functions.
346 In one-liner functions such as `function identity(x) {return x}'
347 people often omit the semicolon for a cleaner look. If you are
348 such a person, you can suppress the missing-semicolon warning
349 by setting this variable to t."
353 (defcustom js2-strict-inconsistent-return-warning t
354 "Non-nil to warn about mixing returns with value-returns.
355 It's perfectly legal to have a `return' and a `return foo' in the
356 same function, but it's often an indicator of a bug, and it also
357 interferes with type inference (in systems that support it.)"
361 (defcustom js2-strict-cond-assign-warning t
362 "Non-nil to warn about expressions like if (a = b).
363 This often should have been '==' instead of '='. If the warning
364 is enabled, you can suppress it on a per-expression basis by
365 parenthesizing the expression, e.g. if ((a = b)) ..."
369 (defcustom js2-strict-var-redeclaration-warning t
370 "Non-nil to warn about redeclaring variables in a script or function."
374 (defcustom js2-strict-var-hides-function-arg-warning t
375 "Non-nil to warn about a var decl hiding a function argument."
379 (defcustom js2-skip-preprocessor-directives nil
380 "Non-nil to treat lines beginning with # as comments.
381 Useful for viewing Mozilla JavaScript source code."
385 (defcustom js2-language-version 200
386 "Configures what JavaScript language version to recognize.
387 Currently versions 150, 160, 170, 180 and 200 are supported,
388 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
389 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
390 yield, and Array comprehensions, and 1.8 adds function closures."
394 (defcustom js2-allow-keywords-as-property-names t
395 "If non-nil, you can use JavaScript keywords as object property names.
398 var foo = {int: 5, while: 6, continue: 7};
401 Ecma-262 forbids this syntax, but many browsers support it."
405 (defcustom js2-instanceof-has-side-effects nil
406 "If non-nil, treats the instanceof operator as having side effects.
407 This is useful for xulrunner apps."
411 (defcustom js2-cleanup-whitespace nil
412 "Non-nil to invoke `delete-trailing-whitespace' before saves."
416 (defcustom js2-move-point-on-right-click t
417 "Non-nil to move insertion point when you right-click.
418 This makes right-click context menu behavior a bit more intuitive,
419 since menu operations generally apply to the point. The exception
420 is if there is a region selection, in which case the point does -not-
421 move, so cut/copy/paste etc. can work properly.
423 Note that IntelliJ moves the point, and Eclipse leaves it alone,
424 so this behavior is customizable."
428 (defcustom js2-allow-rhino-new-expr-initializer t
429 "Non-nil to support a Rhino's experimental syntactic construct.
431 Rhino supports the ability to follow a `new' expression with an object
432 literal, which is used to set additional properties on the new object
433 after calling its constructor. Syntax:
435 new <expr> [ ( arglist ) ] [initializer]
437 Hence, this expression:
439 new Object {a: 1, b: 2}
441 results in an Object with properties a=1 and b=2. This syntax is
442 apparently not configurable in Rhino - it's currently always enabled,
443 as of Rhino version 1.7R2."
447 (defcustom js2-allow-member-expr-as-function-name nil
448 "Non-nil to support experimental Rhino syntax for function names.
450 Rhino supports an experimental syntax configured via the Rhino Context
451 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
453 function <member-expr> ( [ arg-list ] ) { <body> }
455 Where member-expr is a non-parenthesized 'member expression', which
456 is anything at the grammar level of a new-expression or lower, meaning
457 any expression that does not involve infix or unary operators.
459 When <member-expr> is not a simple identifier, then it is syntactic
460 sugar for assigning the anonymous function to the <member-expr>. Hence,
463 function a.b().c[2] (x, y) { ... }
467 a.b().c[2] = function(x, y) {...}
469 which doesn't seem particularly useful, but Rhino permits it."
473 (defvar js2-mode-version 20101228
474 "Release number for `js2-mode'.")
478 (defmacro js2-deflocal (name value &optional comment)
479 "Define a buffer-local variable NAME with VALUE and COMMENT."
481 (defvar ,name ,value ,comment)
482 (make-variable-buffer-local ',name)))
484 ;; We record the start and end position of each token.
485 (js2-deflocal js2-token-beg 1)
486 (js2-deflocal js2-token-end -1)
488 (defvar js2-EOF_CHAR -1
489 "Represents end of stream. Distinct from js2-EOF token type.")
491 ;; I originally used symbols to represent tokens, but Rhino uses
492 ;; ints and then sets various flag bits in them, so ints it is.
493 ;; The upshot is that we need a `js2-' prefix in front of each name.
494 (defvar js2-ERROR -1)
497 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
498 (defvar js2-LEAVEWITH 3)
499 (defvar js2-RETURN 4)
503 (defvar js2-SETNAME 8)
505 (defvar js2-BITXOR 10)
506 (defvar js2-BITAND 11)
516 (defvar js2-ADD 21) ; infix plus
517 (defvar js2-SUB 22) ; infix minus
522 (defvar js2-BITNOT 27)
523 (defvar js2-POS 28) ; unary plus
524 (defvar js2-NEG 29) ; unary minus
526 (defvar js2-DELPROP 31)
527 (defvar js2-TYPEOF 32)
528 (defvar js2-GETPROP 33)
529 (defvar js2-GETPROPNOWARN 34)
530 (defvar js2-SETPROP 35)
531 (defvar js2-GETELEM 36)
532 (defvar js2-SETELEM 37)
534 (defvar js2-NAME 39) ; an identifier
535 (defvar js2-NUMBER 40)
536 (defvar js2-STRING 41)
539 (defvar js2-FALSE 44)
541 (defvar js2-SHEQ 46) ; shallow equality (===)
542 (defvar js2-SHNE 47) ; shallow inequality (!==)
543 (defvar js2-REGEXP 48)
544 (defvar js2-BINDNAME 49)
545 (defvar js2-THROW 50)
546 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
548 (defvar js2-INSTANCEOF 53)
549 (defvar js2-LOCAL_LOAD 54)
550 (defvar js2-GETVAR 55)
551 (defvar js2-SETVAR 56)
552 (defvar js2-CATCH_SCOPE 57)
553 (defvar js2-ENUM_INIT_KEYS 58)
554 (defvar js2-ENUM_INIT_VALUES 59)
555 (defvar js2-ENUM_INIT_ARRAY 60)
556 (defvar js2-ENUM_NEXT 61)
557 (defvar js2-ENUM_ID 62)
558 (defvar js2-THISFN 63)
559 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
560 (defvar js2-ARRAYLIT 65) ; array literal
561 (defvar js2-OBJECTLIT 66) ; object literal
562 (defvar js2-GET_REF 67) ; *reference
563 (defvar js2-SET_REF 68) ; *reference = something
564 (defvar js2-DEL_REF 69) ; delete reference
565 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
566 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
567 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
570 (defvar js2-DEFAULTNAMESPACE 73)
571 (defvar js2-ESCXMLATTR 74)
572 (defvar js2-ESCXMLTEXT 75)
573 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
574 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
575 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
576 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
578 (defvar js2-first-bytecode js2-ENTERWITH)
579 (defvar js2-last-bytecode js2-REF_NS_NAME)
582 (defvar js2-SEMI 81) ; semicolon
583 (defvar js2-LB 82) ; left and right brackets
585 (defvar js2-LC 84) ; left and right curly-braces
587 (defvar js2-LP 86) ; left and right parens
589 (defvar js2-COMMA 88) ; comma operator
591 (defvar js2-ASSIGN 89) ; simple assignment (=)
592 (defvar js2-ASSIGN_BITOR 90) ; |=
593 (defvar js2-ASSIGN_BITXOR 91) ; ^=
594 (defvar js2-ASSIGN_BITAND 92) ; &=
595 (defvar js2-ASSIGN_LSH 93) ; <<=
596 (defvar js2-ASSIGN_RSH 94) ; >>=
597 (defvar js2-ASSIGN_URSH 95) ; >>>=
598 (defvar js2-ASSIGN_ADD 96) ; +=
599 (defvar js2-ASSIGN_SUB 97) ; -=
600 (defvar js2-ASSIGN_MUL 98) ; *=
601 (defvar js2-ASSIGN_DIV 99) ; /=
602 (defvar js2-ASSIGN_MOD 100) ; %=
604 (defvar js2-first-assign js2-ASSIGN)
605 (defvar js2-last-assign js2-ASSIGN_MOD)
607 (defvar js2-HOOK 101) ; conditional (?:)
608 (defvar js2-COLON 102)
609 (defvar js2-OR 103) ; logical or (||)
610 (defvar js2-AND 104) ; logical and (&&)
611 (defvar js2-INC 105) ; increment/decrement (++ --)
613 (defvar js2-DOT 107) ; member operator (.)
614 (defvar js2-FUNCTION 108) ; function keyword
615 (defvar js2-EXPORT 109) ; export keyword
616 (defvar js2-IMPORT 110) ; import keyword
617 (defvar js2-IF 111) ; if keyword
618 (defvar js2-ELSE 112) ; else keyword
619 (defvar js2-SWITCH 113) ; switch keyword
620 (defvar js2-CASE 114) ; case keyword
621 (defvar js2-DEFAULT 115) ; default keyword
622 (defvar js2-WHILE 116) ; while keyword
623 (defvar js2-DO 117) ; do keyword
624 (defvar js2-FOR 118) ; for keyword
625 (defvar js2-BREAK 119) ; break keyword
626 (defvar js2-CONTINUE 120) ; continue keyword
627 (defvar js2-VAR 121) ; var keyword
628 (defvar js2-WITH 122) ; with keyword
629 (defvar js2-CATCH 123) ; catch keyword
630 (defvar js2-FINALLY 124) ; finally keyword
631 (defvar js2-VOID 125) ; void keyword
632 (defvar js2-RESERVED 126) ; reserved keywords
634 (defvar js2-EMPTY 127)
636 ;; Types used for the parse tree - never returned by scanner.
638 (defvar js2-BLOCK 128) ; statement block
639 (defvar js2-LABEL 129) ; label
640 (defvar js2-TARGET 130)
641 (defvar js2-LOOP 131)
642 (defvar js2-EXPR_VOID 132) ; expression statement in functions
643 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
645 (defvar js2-SCRIPT 135) ; top-level node for entire script
646 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
647 (defvar js2-USE_STACK 137)
648 (defvar js2-SETPROP_OP 138) ; x.y op= something
649 (defvar js2-SETELEM_OP 139) ; x[y] op= something
650 (defvar js2-LOCAL_BLOCK 140)
651 (defvar js2-SET_REF_OP 141) ; *reference op= something
654 (defvar js2-DOTDOT 142) ; member operator (..)
655 (defvar js2-COLONCOLON 143) ; namespace::name
656 (defvar js2-XML 144) ; XML type
657 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
658 (defvar js2-XMLATTR 146) ; @
659 (defvar js2-XMLEND 147)
661 ;; Optimizer-only tokens
662 (defvar js2-TO_OBJECT 148)
663 (defvar js2-TO_DOUBLE 149)
665 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
666 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
667 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
668 (defvar js2-CONST 153)
669 (defvar js2-SETCONST 154)
670 (defvar js2-SETCONSTVAR 155)
671 (defvar js2-ARRAYCOMP 156)
672 (defvar js2-LETEXPR 157)
673 (defvar js2-WITHEXPR 158)
674 (defvar js2-DEBUGGER 159)
676 (defvar js2-COMMENT 160)
677 (defvar js2-ENUM 161) ; for "enum" reserved word
678 (defvar js2-TRIPLEDOT 162) ; for rest parameter
680 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
682 (defconst js2-debug-print-trees nil)
684 ;; Rhino accepts any string or stream as input. Emacs character
685 ;; processing works best in buffers, so we'll assume the input is a
686 ;; buffer. JavaScript strings can be copied into temp buffers before
689 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
690 ;; They're the Emacs equivalent of instance variables, more or less.
692 (js2-deflocal js2-ts-dirty-line nil
693 "Token stream buffer-local variable.
694 Indicates stuff other than whitespace since start of line.")
696 (js2-deflocal js2-ts-regexp-flags nil
697 "Token stream buffer-local variable.")
699 (js2-deflocal js2-ts-string ""
700 "Token stream buffer-local variable.
701 Last string scanned.")
703 (js2-deflocal js2-ts-number nil
704 "Token stream buffer-local variable.
705 Last literal number scanned.")
707 (js2-deflocal js2-ts-hit-eof nil
708 "Token stream buffer-local variable.")
710 (js2-deflocal js2-ts-line-start 0
711 "Token stream buffer-local variable.")
713 (js2-deflocal js2-ts-lineno 1
714 "Token stream buffer-local variable.")
716 (js2-deflocal js2-ts-line-end-char -1
717 "Token stream buffer-local variable.")
719 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
720 "Token stream buffer-local variable.
721 Current scan position.")
723 (js2-deflocal js2-ts-is-xml-attribute nil
724 "Token stream buffer-local variable.")
726 (js2-deflocal js2-ts-xml-is-tag-content nil
727 "Token stream buffer-local variable.")
729 (js2-deflocal js2-ts-xml-open-tags-count 0
730 "Token stream buffer-local variable.")
732 (js2-deflocal js2-ts-string-buffer nil
733 "Token stream buffer-local variable.
734 List of chars built up while scanning various tokens.")
736 (js2-deflocal js2-ts-comment-type nil
737 "Token stream buffer-local variable.")
741 (js2-deflocal js2-parsed-errors nil
742 "List of errors produced during scanning/parsing.")
744 (js2-deflocal js2-parsed-warnings nil
745 "List of warnings produced during scanning/parsing.")
747 (js2-deflocal js2-recover-from-parse-errors t
748 "Non-nil to continue parsing after a syntax error.
750 In recovery mode, the AST will be built in full, and any error
751 nodes will be flagged with appropriate error information. If
752 this flag is nil, a syntax error will result in an error being
755 The variable is automatically buffer-local, because different
756 modes that use the parser will need different settings.")
758 (js2-deflocal js2-parse-hook nil
759 "List of callbacks for receiving parsing progress.")
761 (defvar js2-parse-finished-hook nil
762 "List of callbacks to notify when parsing finishes.
763 Not called if parsing was interrupted.")
765 (js2-deflocal js2-is-eval-code nil
766 "True if we're evaluating code in a string.
767 If non-nil, the tokenizer will record the token text, and the AST nodes
768 will record their source text. Off by default for IDE modes, since the
769 text is available in the buffer.")
771 (defvar js2-parse-ide-mode t
772 "Non-nil if the parser is being used for `js2-mode'.
773 If non-nil, the parser will set text properties for fontification
774 and the syntax table. The value should be nil when using the
775 parser as a frontend to an interpreter or byte compiler.")
777 ;;; Parser instance variables (buffer-local vars for js2-parse)
779 (defconst js2-clear-ti-mask #xFFFF
780 "Mask to clear token information bits.")
782 (defconst js2-ti-after-eol (lsh 1 16)
783 "Flag: first token of the source line.")
785 (defconst js2-ti-check-label (lsh 1 17)
786 "Flag: indicates to check for label.")
788 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
790 (js2-deflocal js2-compiler-generate-debug-info t)
791 (js2-deflocal js2-compiler-use-dynamic-scope nil)
792 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
793 (js2-deflocal js2-compiler-xml-available t)
794 (js2-deflocal js2-compiler-optimization-level 0)
795 (js2-deflocal js2-compiler-generating-source t)
796 (js2-deflocal js2-compiler-strict-mode nil)
797 (js2-deflocal js2-compiler-report-warning-as-error nil)
798 (js2-deflocal js2-compiler-generate-observer-count nil)
799 (js2-deflocal js2-compiler-activation-names nil)
803 ;; There's a compileFunction method in Context.java - may need it.
804 (js2-deflocal js2-called-by-compile-function nil
805 "True if `js2-parse' was called by `js2-compile-function'.
806 Will only be used when we finish implementing the interpreter.")
808 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
810 (js2-deflocal js2-current-flagged-token js2-EOF)
811 (js2-deflocal js2-current-token js2-EOF)
813 ;; SKIP: node factory - we're going to just call functions directly,
814 ;; and eventually go to a unified AST format.
816 (js2-deflocal js2-nesting-of-function 0)
818 (js2-deflocal js2-recorded-identifiers nil
819 "Tracks identifiers found during parsing.")
821 (js2-deflocal js2-is-in-destructuring nil
822 "True while parsing destructuring expression.")
824 (defcustom js2-global-externs nil
825 "A list of any extern names you'd like to consider always declared.
826 This list is global and is used by all js2-mode files.
827 You can create buffer-local externs list using `js2-additional-externs'.
829 There is also a buffer-local variable `js2-default-externs',
830 which is initialized by default to include the Ecma-262 externs
831 and the standard browser externs. The three lists are all
832 checked during highlighting."
836 (js2-deflocal js2-default-externs nil
837 "Default external declarations.
839 These are currently only used for highlighting undeclared variables,
840 which only worries about top-level (unqualified) references.
841 As js2-mode's processing improves, we will flesh out this list.
843 The initial value is set to `js2-ecma-262-externs', unless you
844 have set `js2-include-browser-externs', in which case the browser
845 externs are also included.
847 See `js2-additional-externs' for more information.")
849 (defcustom js2-include-browser-externs t
850 "Non-nil to include browser externs in the master externs list.
851 If you work on JavaScript files that are not intended for browsers,
852 such as Mozilla Rhino server-side JavaScript, set this to nil.
853 You can always include them on a per-file basis by calling
854 `js2-add-browser-externs' from a function on `js2-mode-hook'.
856 See `js2-additional-externs' for more information about externs."
860 (defcustom js2-include-rhino-externs t
861 "Non-nil to include Mozilla Rhino externs in the master externs list.
862 See `js2-additional-externs' for more information about externs."
866 (defcustom js2-include-gears-externs t
867 "Non-nil to include Google Gears externs in the master externs list.
868 See `js2-additional-externs' for more information about externs."
872 (js2-deflocal js2-additional-externs nil
873 "A buffer-local list of additional external declarations.
874 It is used to decide whether variables are considered undeclared
875 for purposes of highlighting.
877 Each entry is a lisp string. The string should be the fully qualified
878 name of an external entity. All externs should be added to this list,
879 so that as js2-mode's processing improves it can take advantage of them.
881 You may want to declare your externs in three ways.
882 First, you can add externs that are valid for all your JavaScript files.
883 You should probably do this by adding them to `js2-global-externs', which
884 is a global list used for all js2-mode files.
886 Next, you can add a function to `js2-mode-hook' that adds additional
887 externs appropriate for the specific file, perhaps based on its path.
888 These should go in `js2-additional-externs', which is buffer-local.
890 Finally, you can add a function to `js2-post-parse-callbacks',
891 which is called after parsing completes, and `root' is bound to
892 the root of the parse tree. At this stage you can set up an AST
893 node visitor using `js2-visit-ast' and examine the parse tree
894 for specific import patterns that may imply the existence of
895 other externs, possibly tied to your build system. These should also
896 be added to `js2-additional-externs'.
898 Your post-parse callback may of course also use the simpler and
899 faster (but perhaps less robust) approach of simply scanning the
900 buffer text for your imports, using regular expressions.")
903 ;; SKIP: encoded-source
905 ;;; The following variables are per-function and should be saved/restored
906 ;;; during function parsing...
908 (js2-deflocal js2-current-script-or-fn nil)
909 (js2-deflocal js2-current-scope nil)
910 (js2-deflocal js2-nesting-of-with 0)
911 (js2-deflocal js2-label-set nil
912 "An alist mapping label names to nodes.")
914 (js2-deflocal js2-loop-set nil)
915 (js2-deflocal js2-loop-and-switch-set nil)
916 (js2-deflocal js2-has-return-value nil)
917 (js2-deflocal js2-end-flags 0)
919 ;;; ...end of per function variables
921 ;; Without 2-token lookahead, labels are a problem.
922 ;; These vars store the token info of the last matched name,
923 ;; iff it wasn't the last matched token. Only valid in some contexts.
924 (defvar js2-prev-name-token-start nil)
925 (defvar js2-prev-name-token-string nil)
927 (defsubst js2-save-name-token-data (pos name)
928 (setq js2-prev-name-token-start pos
929 js2-prev-name-token-string name))
931 ;; These flags enumerate the possible ways a statement/function can
932 ;; terminate. These flags are used by endCheck() and by the Parser to
933 ;; detect inconsistent return usage.
935 ;; END_UNREACHED is reserved for code paths that are assumed to always be
936 ;; able to execute (example: throw, continue)
938 ;; END_DROPS_OFF indicates if the statement can transfer control to the
939 ;; next one. Statement such as return dont. A compound statement may have
940 ;; some branch that drops off control to the next statement.
942 ;; END_RETURNS indicates that the statement can return (without arguments)
943 ;; END_RETURNS_VALUE indicates that the statement can return a value.
945 ;; A compound statement such as
949 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
951 (defconst js2-end-unreached #x0)
952 (defconst js2-end-drops-off #x1)
953 (defconst js2-end-returns #x2)
954 (defconst js2-end-returns-value #x4)
955 (defconst js2-end-yields #x8)
957 ;; Rhino awkwardly passes a statementLabel parameter to the
958 ;; statementHelper() function, the main statement parser, which
959 ;; is then used by quite a few of the sub-parsers. We just make
960 ;; it a buffer-local variable and make sure it's cleaned up properly.
961 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
963 ;; Similarly, Rhino passes an inForInit boolean through about half
964 ;; the expression parsers. We use a dynamically-scoped variable,
965 ;; which makes it easier to funcall the parsers individually without
966 ;; worrying about whether they take the parameter or not.
967 (js2-deflocal js2-in-for-init nil)
968 (js2-deflocal js2-temp-name-counter 0)
969 (js2-deflocal js2-parse-stmt-count 0)
971 (defsubst js2-get-next-temp-name ()
972 (format "$%d" (incf js2-temp-name-counter)))
974 (defvar js2-parse-interruptable-p t
975 "Set this to nil to force parse to continue until finished.
976 This will mostly be useful for interpreters.")
978 (defvar js2-statements-per-pause 50
979 "Pause after this many statements to check for user input.
980 If user input is pending, stop the parse and discard the tree.
981 This makes for a smoother user experience for large files.
982 You may have to wait a second or two before the highlighting
983 and error-reporting appear, but you can always type ahead if
984 you wish. This appears to be more or less how Eclipse, IntelliJ
985 and other editors work.")
987 (js2-deflocal js2-record-comments t
988 "Instructs the scanner to record comments in `js2-scanned-comments'.")
990 (js2-deflocal js2-scanned-comments nil
991 "List of all comments from the current parse.")
993 (defcustom js2-mode-indent-inhibit-undo nil
994 "Non-nil to disable collection of Undo information when indenting lines.
995 Some users have requested this behavior. It's nil by default because
996 other Emacs modes don't work this way."
1000 (defcustom js2-mode-indent-ignore-first-tab nil
1001 "If non-nil, ignore first TAB keypress if we look indented properly.
1002 It's fairly common for users to navigate to an already-indented line
1003 and press TAB for reassurance that it's been indented. For this class
1004 of users, we want the first TAB press on a line to be ignored if the
1005 line is already indented to one of the precomputed alternatives.
1007 This behavior is only partly implemented. If you TAB-indent a line,
1008 navigate to another line, and then navigate back, it fails to clear
1009 the last-indented variable, so it thinks you've already hit TAB once,
1010 and performs the indent. A full solution would involve getting on the
1011 point-motion hooks for the entire buffer. If we come across another
1012 use cases that requires watching point motion, I'll consider doing it.
1014 If you set this variable to nil, then the TAB key will always change
1015 the indentation of the current line, if more than one alternative
1016 indentation spot exists."
1020 (defvar js2-indent-hook nil
1021 "A hook for user-defined indentation rules.
1023 Functions on this hook should expect two arguments: (LIST INDEX)
1024 The LIST argument is the list of computed indentation points for
1025 the current line. INDEX is the list index of the indentation point
1026 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1027 indent function is not going to change the current line indentation.
1029 If a hook function on this list returns a non-nil value, then
1030 `js2-bounce-indent' assumes the hook function has performed its own
1031 indentation, and will do nothing. If all hook functions on the list
1032 return nil, then `js2-bounce-indent' will use its computed indentation
1033 and reindent the line.
1035 When hook functions on this hook list are called, the variable
1036 `js2-mode-ast' may or may not be set, depending on whether the
1037 parse tree is available. If the variable is nil, you can pass a
1038 callback to `js2-mode-wait-for-parse', and your callback will be
1039 called after the new parse tree is built. This can take some time
1042 (defface js2-warning-face
1043 `((((class color) (background light))
1044 (:underline "orange"))
1045 (((class color) (background dark))
1046 (:underline "orange"))
1048 "Face for JavaScript warnings."
1051 (defface js2-error-face
1052 `((((class color) (background light))
1053 (:foreground "red"))
1054 (((class color) (background dark))
1055 (:foreground "red"))
1056 (t (:foreground "red")))
1057 "Face for JavaScript errors."
1060 (defface js2-jsdoc-tag-face
1061 '((t :foreground "SlateGray"))
1062 "Face used to highlight @whatever tags in jsdoc comments."
1065 (defface js2-jsdoc-type-face
1066 '((t :foreground "SteelBlue"))
1067 "Face used to highlight {FooBar} types in jsdoc comments."
1070 (defface js2-jsdoc-value-face
1071 '((t :foreground "PeachPuff3"))
1072 "Face used to highlight tag values in jsdoc comments."
1075 (defface js2-function-param-face
1076 '((t :foreground "SeaGreen"))
1077 "Face used to highlight function parameters in javascript."
1080 (defface js2-instance-member-face
1081 '((t :foreground "DarkOrchid"))
1082 "Face used to highlight instance variables in javascript.
1083 Not currently used."
1086 (defface js2-private-member-face
1087 '((t :foreground "PeachPuff3"))
1088 "Face used to highlight calls to private methods in javascript.
1089 Not currently used."
1092 (defface js2-private-function-call-face
1093 '((t :foreground "goldenrod"))
1094 "Face used to highlight calls to private functions in javascript.
1095 Not currently used."
1098 (defface js2-jsdoc-html-tag-name-face
1100 '((((class color) (min-colors 88) (background light))
1101 (:foreground "rosybrown"))
1102 (((class color) (min-colors 8) (background dark))
1103 (:foreground "yellow"))
1104 (((class color) (min-colors 8) (background light))
1105 (:foreground "magenta")))
1106 '((((type tty pc) (class color) (background light))
1107 (:foreground "magenta"))
1108 (((type tty pc) (class color) (background dark))
1109 (:foreground "yellow"))
1110 (t (:foreground "RosyBrown"))))
1111 "Face used to highlight jsdoc html tag names"
1114 (defface js2-jsdoc-html-tag-delimiter-face
1116 '((((class color) (min-colors 88) (background light))
1117 (:foreground "dark khaki"))
1118 (((class color) (min-colors 8) (background dark))
1119 (:foreground "green"))
1120 (((class color) (min-colors 8) (background light))
1121 (:foreground "green")))
1122 '((((type tty pc) (class color) (background light))
1123 (:foreground "green"))
1124 (((type tty pc) (class color) (background dark))
1125 (:foreground "green"))
1126 (t (:foreground "dark khaki"))))
1127 "Face used to highlight brackets in jsdoc html tags."
1130 (defface js2-magic-paren-face
1132 "Face used to color parens that will be auto-overwritten."
1135 (defcustom js2-post-parse-callbacks nil
1136 "A list of callback functions invoked after parsing finishes.
1137 Currently, the main use for this function is to add synthetic
1138 declarations to `js2-recorded-identifiers', which see."
1142 (defface js2-external-variable-face
1143 '((t :foreground "orange"))
1144 "Face used to highlight undeclared variable identifiers.
1145 An undeclared variable is any variable not declared with var or let
1146 in the current scope or any lexically enclosing scope. If you use
1147 such a variable, then you are either expecting it to originate from
1148 another file, or you've got a potential bug."
1151 (defcustom js2-highlight-external-variables t
1152 "Non-nil to highlight undeclared variable identifiers."
1156 (defcustom js2-auto-insert-catch-block t
1157 "Non-nil to insert matching catch block on open-curly after `try'."
1161 (defvar js2-mode-map
1162 (let ((map (make-sparse-keymap))
1164 (define-key map [mouse-1] #'js2-mode-show-node)
1165 (define-key map (kbd "C-m") #'js2-enter-key)
1166 (when js2-rebind-eol-bol-keys
1167 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1168 (define-key map (kbd "C-e") #'js2-end-of-line))
1169 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1170 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1171 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1172 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1173 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1174 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1175 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1176 (define-key map (kbd "C-c C-`") #'js2-next-error)
1177 ;; also define user's preference for next-error, if available
1178 (if (setq keys (where-is-internal #'next-error))
1179 (define-key map (car keys) #'js2-next-error))
1180 (define-key map (or (car (where-is-internal #'mark-defun))
1183 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1185 #'js2-narrow-to-defun)
1186 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1187 (when js2-auto-indent-p
1189 (define-key map key #'js2-insert-and-indent))
1191 (when js2-bounce-indent-p
1192 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1194 (define-key map [menu-bar javascript]
1195 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1197 (define-key map [menu-bar javascript customize-js2-mode]
1198 '(menu-item "Customize js2-mode" js2-mode-customize
1199 :help "Customize the behavior of this mode"))
1201 (define-key map [menu-bar javascript js2-force-refresh]
1202 '(menu-item "Force buffer refresh" js2-mode-reset
1203 :help "Re-parse the buffer from scratch"))
1205 (define-key map [menu-bar javascript separator-2]
1208 (define-key map [menu-bar javascript next-error]
1209 '(menu-item "Next warning or error" js2-next-error
1210 :enabled (and js2-mode-ast
1211 (or (js2-ast-root-errors js2-mode-ast)
1212 (js2-ast-root-warnings js2-mode-ast)))
1213 :help "Move to next warning or error"))
1215 (define-key map [menu-bar javascript display-errors]
1216 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1217 :visible (not js2-mode-show-parse-errors)
1218 :help "Turn on display of warnings and errors"))
1220 (define-key map [menu-bar javascript hide-errors]
1221 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1222 :visible js2-mode-show-parse-errors
1223 :help "Turn off display of warnings and errors"))
1225 (define-key map [menu-bar javascript separator-1]
1228 (define-key map [menu-bar javascript js2-toggle-function]
1229 '(menu-item "Show/collapse element" js2-mode-toggle-element
1230 :help "Hide or show function body or comment"))
1232 (define-key map [menu-bar javascript show-comments]
1233 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1234 :visible js2-mode-comments-hidden
1235 :help "Expand all hidden block comments"))
1237 (define-key map [menu-bar javascript hide-comments]
1238 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1239 :visible (not js2-mode-comments-hidden)
1240 :help "Show block comments as /*...*/"))
1242 (define-key map [menu-bar javascript show-all-functions]
1243 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1244 :visible js2-mode-functions-hidden
1245 :help "Expand all hidden function bodies"))
1247 (define-key map [menu-bar javascript hide-all-functions]
1248 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1249 :visible (not js2-mode-functions-hidden)
1250 :help "Show {...} for all top-level function bodies"))
1253 "Keymap used in `js2-mode' buffers.")
1255 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1257 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1258 "Matches a //-comment line. Must be first non-whitespace on line.
1259 First match-group is the leading whitespace.")
1261 (defvar js2-mode-hook nil)
1263 (js2-deflocal js2-mode-ast nil "Private variable.")
1264 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1265 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1266 (js2-deflocal js2-mode-parsing nil "Private variable.")
1267 (js2-deflocal js2-mode-node-overlay nil)
1269 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1270 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1272 (js2-deflocal js2-mode-fontifications nil "Private variable")
1273 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1274 (js2-deflocal js2-imenu-recorder nil "Private variable")
1275 (js2-deflocal js2-imenu-function-map nil "Private variable")
1277 (defvar js2-paragraph-start
1278 "\\(@[a-zA-Z]+\\>\\|$\\)")
1280 ;; Note that we also set a 'c-in-sws text property in html comments,
1281 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1282 (defvar js2-syntactic-ws-start
1283 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1285 (defvar js2-syntactic-ws-end
1286 "\\s \\|[\n\r/]\\|\\s!")
1288 (defvar js2-syntactic-eol
1289 (concat "\\s *\\(/\\*[^*\n\r]*"
1290 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1292 "\\(//\\|/\\*[^*\n\r]*"
1293 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1295 "Copied from `java-mode'. Needed for some cc-engine functions.")
1297 (defvar js2-comment-prefix-regexp
1300 (defvar js2-comment-start-skip
1301 "\\(//+\\|/\\*+\\)\\s *")
1303 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1304 "Non-nil to emit status messages during parsing.")
1306 (defvar js2-mode-functions-hidden nil "private variable")
1307 (defvar js2-mode-comments-hidden nil "private variable")
1309 (defvar js2-mode-syntax-table
1310 (let ((table (make-syntax-table)))
1311 (c-populate-syntax-table table)
1313 "Syntax table used in js2-mode buffers.")
1315 (defvar js2-mode-abbrev-table nil
1316 "Abbrev table in use in `js2-mode' buffers.")
1317 (define-abbrev-table 'js2-mode-abbrev-table ())
1319 (defvar js2-mode-pending-parse-callbacks nil
1320 "List of functions waiting to be notified that parse is finished.")
1322 (defvar js2-mode-last-indented-line -1)
1324 ;;; Localizable error and warning messages
1326 ;; Messages are copied from Rhino's Messages.properties.
1327 ;; Many of the Java-specific messages have been elided.
1328 ;; Add any js2-specific ones at the end, so we can keep
1329 ;; this file synced with changes to Rhino's.
1331 (defvar js2-message-table
1332 (make-hash-table :test 'equal :size 250)
1333 "Contains localized messages for js2-mode.")
1335 ;; TODO(stevey): construct this table at compile-time.
1336 (defmacro js2-msg (key &rest strings)
1337 `(puthash ,key (funcall #'concat ,@strings)
1340 (defun js2-get-msg (msg-key)
1341 "Look up a localized message.
1342 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1343 the correct number of ARGS must be provided."
1344 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1345 (args (if (listp msg-key) (cdr msg-key)))
1346 (msg (gethash key js2-message-table)))
1348 (apply #'format msg args)
1349 key))) ; default to showing the key
1351 (js2-msg "msg.dup.parms"
1352 "Duplicate parameter name '%s'.")
1354 (js2-msg "msg.too.big.jump"
1355 "Program too complex: jump offset too big.")
1357 (js2-msg "msg.too.big.index"
1358 "Program too complex: internal index exceeds 64K limit.")
1360 (js2-msg "msg.while.compiling.fn"
1361 "Encountered code generation error while compiling function '%s': %s")
1363 (js2-msg "msg.while.compiling.script"
1364 "Encountered code generation error while compiling script: %s")
1367 (js2-msg "msg.ctor.not.found"
1368 "Constructor for '%s' not found.")
1370 (js2-msg "msg.not.ctor"
1371 "'%s' is not a constructor.")
1374 (js2-msg "msg.varargs.ctor"
1375 "Method or constructor '%s' must be static "
1376 "with the signature (Context cx, Object[] args, "
1377 "Function ctorObj, boolean inNewExpr) "
1378 "to define a variable arguments constructor.")
1380 (js2-msg "msg.varargs.fun"
1381 "Method '%s' must be static with the signature "
1382 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1383 "to define a variable arguments function.")
1385 (js2-msg "msg.incompat.call"
1386 "Method '%s' called on incompatible object.")
1388 (js2-msg "msg.bad.parms"
1389 "Unsupported parameter type '%s' in method '%s'.")
1391 (js2-msg "msg.bad.method.return"
1392 "Unsupported return type '%s' in method '%s'.")
1394 (js2-msg "msg.bad.ctor.return"
1395 "Construction of objects of type '%s' is not supported.")
1397 (js2-msg "msg.no.overload"
1398 "Method '%s' occurs multiple times in class '%s'.")
1400 (js2-msg "msg.method.not.found"
1401 "Method '%s' not found in '%s'.")
1405 (js2-msg "msg.bad.for.in.lhs"
1406 "Invalid left-hand side of for..in loop.")
1408 (js2-msg "msg.mult.index"
1409 "Only one variable allowed in for..in loop.")
1411 (js2-msg "msg.bad.for.in.destruct"
1412 "Left hand side of for..in loop must be an array of "
1413 "length 2 to accept key/value pair.")
1415 (js2-msg "msg.cant.convert"
1416 "Can't convert to type '%s'.")
1418 (js2-msg "msg.bad.assign.left"
1419 "Invalid assignment left-hand side.")
1421 (js2-msg "msg.bad.decr"
1422 "Invalid decerement operand.")
1424 (js2-msg "msg.bad.incr"
1425 "Invalid increment operand.")
1427 (js2-msg "msg.bad.yield"
1428 "yield must be in a function.")
1430 (js2-msg "msg.yield.parenthesized"
1431 "yield expression must be parenthesized.")
1434 (js2-msg "msg.cant.call.indirect"
1435 "Function '%s' must be called directly, and not by way of a "
1436 "function of another name.")
1438 (js2-msg "msg.eval.nonstring"
1439 "Calling eval() with anything other than a primitive "
1440 "string value will simply return the value. "
1441 "Is this what you intended?")
1443 (js2-msg "msg.eval.nonstring.strict"
1444 "Calling eval() with anything other than a primitive "
1445 "string value is not allowed in strict mode.")
1447 (js2-msg "msg.bad.destruct.op"
1448 "Invalid destructuring assignment operator")
1451 (js2-msg "msg.only.from.new"
1452 "'%s' may only be invoked from a `new' expression.")
1454 (js2-msg "msg.deprec.ctor"
1455 "The '%s' constructor is deprecated.")
1458 (js2-msg "msg.no.function.ref.found"
1459 "no source found to decompile function reference %s")
1461 (js2-msg "msg.arg.isnt.array"
1462 "second argument to Function.prototype.apply must be an array")
1465 (js2-msg "msg.bad.esc.mask"
1466 "invalid string escape mask")
1469 (js2-msg "msg.bad.quant"
1470 "Invalid quantifier %s")
1472 (js2-msg "msg.overlarge.backref"
1473 "Overly large back reference %s")
1475 (js2-msg "msg.overlarge.min"
1476 "Overly large minimum %s")
1478 (js2-msg "msg.overlarge.max"
1479 "Overly large maximum %s")
1481 (js2-msg "msg.zero.quant"
1482 "Zero quantifier %s")
1484 (js2-msg "msg.max.lt.min"
1485 "Maximum %s less than minimum")
1487 (js2-msg "msg.unterm.quant"
1488 "Unterminated quantifier %s")
1490 (js2-msg "msg.unterm.paren"
1491 "Unterminated parenthetical %s")
1493 (js2-msg "msg.unterm.class"
1494 "Unterminated character class %s")
1496 (js2-msg "msg.bad.range"
1497 "Invalid range in character class.")
1499 (js2-msg "msg.trail.backslash"
1500 "Trailing \\ in regular expression.")
1502 (js2-msg "msg.re.unmatched.right.paren"
1503 "unmatched ) in regular expression.")
1505 (js2-msg "msg.no.regexp"
1506 "Regular expressions are not available.")
1508 (js2-msg "msg.bad.backref"
1509 "back-reference exceeds number of capturing parentheses.")
1511 (js2-msg "msg.bad.regexp.compile"
1512 "Only one argument may be specified if the first "
1513 "argument to RegExp.prototype.compile is a RegExp object.")
1516 (js2-msg "msg.got.syntax.errors"
1517 "Compilation produced %s syntax errors.")
1519 (js2-msg "msg.var.redecl"
1520 "TypeError: redeclaration of var %s.")
1522 (js2-msg "msg.const.redecl"
1523 "TypeError: redeclaration of const %s.")
1525 (js2-msg "msg.let.redecl"
1526 "TypeError: redeclaration of variable %s.")
1528 (js2-msg "msg.parm.redecl"
1529 "TypeError: redeclaration of formal parameter %s.")
1531 (js2-msg "msg.fn.redecl"
1532 "TypeError: redeclaration of function %s.")
1534 (js2-msg "msg.let.decl.not.in.block"
1535 "SyntaxError: let declaration not directly within block")
1538 (js2-msg "msg.dup.label"
1541 (js2-msg "msg.undef.label"
1544 (js2-msg "msg.bad.break"
1545 "unlabelled break must be inside loop or switch")
1547 (js2-msg "msg.continue.outside"
1548 "continue must be inside loop")
1550 (js2-msg "msg.continue.nonloop"
1551 "continue can only use labels of iteration statements")
1553 (js2-msg "msg.bad.throw.eol"
1554 "Line terminator is not allowed between the throw "
1555 "keyword and throw expression.")
1557 (js2-msg "msg.no.paren.parms"
1558 "missing ( before function parameters.")
1560 (js2-msg "msg.no.parm"
1561 "missing formal parameter")
1563 (js2-msg "msg.no.paren.after.parms"
1564 "missing ) after formal parameters")
1566 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1567 "parameter without default follows parameter with default")
1569 (js2-msg "msg.param.after.rest" ; added by js2-mode
1570 "parameter after rest parameter")
1572 (js2-msg "msg.no.brace.body"
1573 "missing '{' before function body")
1575 (js2-msg "msg.no.brace.after.body"
1576 "missing } after function body")
1578 (js2-msg "msg.no.paren.cond"
1579 "missing ( before condition")
1581 (js2-msg "msg.no.paren.after.cond"
1582 "missing ) after condition")
1584 (js2-msg "msg.no.semi.stmt"
1585 "missing ; before statement")
1587 (js2-msg "msg.missing.semi"
1588 "missing ; after statement")
1590 (js2-msg "msg.no.name.after.dot"
1591 "missing name after . operator")
1593 (js2-msg "msg.no.name.after.coloncolon"
1594 "missing name after :: operator")
1596 (js2-msg "msg.no.name.after.dotdot"
1597 "missing name after .. operator")
1599 (js2-msg "msg.no.name.after.xmlAttr"
1600 "missing name after .@")
1602 (js2-msg "msg.no.bracket.index"
1603 "missing ] in index expression")
1605 (js2-msg "msg.no.paren.switch"
1606 "missing ( before switch expression")
1608 (js2-msg "msg.no.paren.after.switch"
1609 "missing ) after switch expression")
1611 (js2-msg "msg.no.brace.switch"
1612 "missing '{' before switch body")
1614 (js2-msg "msg.bad.switch"
1615 "invalid switch statement")
1617 (js2-msg "msg.no.colon.case"
1618 "missing : after case expression")
1620 (js2-msg "msg.double.switch.default"
1621 "double default label in the switch statement")
1623 (js2-msg "msg.no.while.do"
1624 "missing while after do-loop body")
1626 (js2-msg "msg.no.paren.for"
1627 "missing ( after for")
1629 (js2-msg "msg.no.semi.for"
1630 "missing ; after for-loop initializer")
1632 (js2-msg "msg.no.semi.for.cond"
1633 "missing ; after for-loop condition")
1635 (js2-msg "msg.in.after.for.name"
1636 "missing in or of after for")
1638 (js2-msg "msg.no.paren.for.ctrl"
1639 "missing ) after for-loop control")
1641 (js2-msg "msg.no.paren.with"
1642 "missing ( before with-statement object")
1644 (js2-msg "msg.no.paren.after.with"
1645 "missing ) after with-statement object")
1647 (js2-msg "msg.no.paren.after.let"
1648 "missing ( after let")
1650 (js2-msg "msg.no.paren.let"
1651 "missing ) after variable list")
1653 (js2-msg "msg.no.curly.let"
1654 "missing } after let statement")
1656 (js2-msg "msg.bad.return"
1659 (js2-msg "msg.no.brace.block"
1660 "missing } in compound statement")
1662 (js2-msg "msg.bad.label"
1665 (js2-msg "msg.bad.var"
1666 "missing variable name")
1668 (js2-msg "msg.bad.var.init"
1669 "invalid variable initialization")
1671 (js2-msg "msg.no.colon.cond"
1672 "missing : in conditional expression")
1674 (js2-msg "msg.no.paren.arg"
1675 "missing ) after argument list")
1677 (js2-msg "msg.no.bracket.arg"
1678 "missing ] after element list")
1680 (js2-msg "msg.bad.prop"
1681 "invalid property id")
1683 (js2-msg "msg.no.colon.prop"
1684 "missing : after property id")
1686 (js2-msg "msg.no.brace.prop"
1687 "missing } after property list")
1689 (js2-msg "msg.no.paren"
1690 "missing ) in parenthetical")
1692 (js2-msg "msg.reserved.id"
1693 "identifier is a reserved word")
1695 (js2-msg "msg.no.paren.catch"
1696 "missing ( before catch-block condition")
1698 (js2-msg "msg.bad.catchcond"
1699 "invalid catch block condition")
1701 (js2-msg "msg.catch.unreachable"
1702 "any catch clauses following an unqualified catch are unreachable")
1704 (js2-msg "msg.no.brace.try"
1705 "missing '{' before try block")
1707 (js2-msg "msg.no.brace.catchblock"
1708 "missing '{' before catch-block body")
1710 (js2-msg "msg.try.no.catchfinally"
1711 "'try' without 'catch' or 'finally'")
1713 (js2-msg "msg.no.return.value"
1714 "function %s does not always return a value")
1716 (js2-msg "msg.anon.no.return.value"
1717 "anonymous function does not always return a value")
1719 (js2-msg "msg.return.inconsistent"
1720 "return statement is inconsistent with previous usage")
1722 (js2-msg "msg.generator.returns"
1723 "TypeError: generator function '%s' returns a value")
1725 (js2-msg "msg.anon.generator.returns"
1726 "TypeError: anonymous generator function returns a value")
1728 (js2-msg "msg.syntax"
1731 (js2-msg "msg.unexpected.eof"
1732 "Unexpected end of file")
1734 (js2-msg "msg.XML.bad.form"
1735 "illegally formed XML syntax")
1737 (js2-msg "msg.XML.not.available"
1738 "XML runtime not available")
1740 (js2-msg "msg.too.deep.parser.recursion"
1741 "Too deep recursion while parsing")
1743 (js2-msg "msg.no.side.effects"
1744 "Code has no side effects")
1746 (js2-msg "msg.extra.trailing.comma"
1747 "Trailing comma is not legal in an ECMA-262 object initializer")
1749 (js2-msg "msg.array.trailing.comma"
1750 "Trailing comma yields different behavior across browsers")
1752 (js2-msg "msg.equal.as.assign"
1753 (concat "Test for equality (==) mistyped as assignment (=)?"
1754 " (parenthesize to suppress warning)"))
1756 (js2-msg "msg.var.hides.arg"
1757 "Variable %s hides argument")
1759 (js2-msg "msg.destruct.assign.no.init"
1760 "Missing = in destructuring declaration")
1763 (js2-msg "msg.no.properties"
1764 "%s has no properties.")
1766 (js2-msg "msg.invalid.iterator"
1767 "Invalid iterator value")
1769 (js2-msg "msg.iterator.primitive"
1770 "__iterator__ returned a primitive value")
1772 (js2-msg "msg.assn.create.strict"
1773 "Assignment to undeclared variable %s")
1775 (js2-msg "msg.ref.undefined.prop"
1776 "Reference to undefined property '%s'")
1778 (js2-msg "msg.prop.not.found"
1779 "Property %s not found.")
1781 (js2-msg "msg.invalid.type"
1782 "Invalid JavaScript value of type %s")
1784 (js2-msg "msg.primitive.expected"
1785 "Primitive type expected (had %s instead)")
1787 (js2-msg "msg.namespace.expected"
1788 "Namespace object expected to left of :: (found %s instead)")
1790 (js2-msg "msg.null.to.object"
1791 "Cannot convert null to an object.")
1793 (js2-msg "msg.undef.to.object"
1794 "Cannot convert undefined to an object.")
1796 (js2-msg "msg.cyclic.value"
1797 "Cyclic %s value not allowed.")
1799 (js2-msg "msg.is.not.defined"
1800 "'%s' is not defined.")
1802 (js2-msg "msg.undef.prop.read"
1803 "Cannot read property '%s' from %s")
1805 (js2-msg "msg.undef.prop.write"
1806 "Cannot set property '%s' of %s to '%s'")
1808 (js2-msg "msg.undef.prop.delete"
1809 "Cannot delete property '%s' of %s")
1811 (js2-msg "msg.undef.method.call"
1812 "Cannot call method '%s' of %s")
1814 (js2-msg "msg.undef.with"
1815 "Cannot apply 'with' to %s")
1817 (js2-msg "msg.isnt.function"
1818 "%s is not a function, it is %s.")
1820 (js2-msg "msg.isnt.function.in"
1821 "Cannot call property %s in object %s. "
1822 "It is not a function, it is '%s'.")
1824 (js2-msg "msg.function.not.found"
1825 "Cannot find function %s.")
1827 (js2-msg "msg.function.not.found.in"
1828 "Cannot find function %s in object %s.")
1830 (js2-msg "msg.isnt.xml.object"
1831 "%s is not an xml object.")
1833 (js2-msg "msg.no.ref.to.get"
1834 "%s is not a reference to read reference value.")
1836 (js2-msg "msg.no.ref.to.set"
1837 "%s is not a reference to set reference value to %s.")
1839 (js2-msg "msg.no.ref.from.function"
1840 "Function %s can not be used as the left-hand "
1841 "side of assignment or as an operand of ++ or -- operator.")
1843 (js2-msg "msg.bad.default.value"
1844 "Object's getDefaultValue() method returned an object.")
1846 (js2-msg "msg.instanceof.not.object"
1847 "Can't use instanceof on a non-object.")
1849 (js2-msg "msg.instanceof.bad.prototype"
1850 "'prototype' property of %s is not an object.")
1852 (js2-msg "msg.bad.radix"
1853 "illegal radix %s.")
1856 (js2-msg "msg.default.value"
1857 "Cannot find default value for object.")
1859 (js2-msg "msg.zero.arg.ctor"
1860 "Cannot load class '%s' which has no zero-parameter constructor.")
1862 (js2-msg "msg.ctor.multiple.parms"
1863 "Can't define constructor or class %s since more than "
1864 "one constructor has multiple parameters.")
1866 (js2-msg "msg.extend.scriptable"
1867 "%s must extend ScriptableObject in order to define property %s.")
1869 (js2-msg "msg.bad.getter.parms"
1870 "In order to define a property, getter %s must have zero "
1871 "parameters or a single ScriptableObject parameter.")
1873 (js2-msg "msg.obj.getter.parms"
1874 "Expected static or delegated getter %s to take "
1875 "a ScriptableObject parameter.")
1877 (js2-msg "msg.getter.static"
1878 "Getter and setter must both be static or neither be static.")
1880 (js2-msg "msg.setter.return"
1881 "Setter must have void return type: %s")
1883 (js2-msg "msg.setter2.parms"
1884 "Two-parameter setter must take a ScriptableObject as "
1885 "its first parameter.")
1887 (js2-msg "msg.setter1.parms"
1888 "Expected single parameter setter for %s")
1890 (js2-msg "msg.setter2.expected"
1891 "Expected static or delegated setter %s to take two parameters.")
1893 (js2-msg "msg.setter.parms"
1894 "Expected either one or two parameters for setter.")
1896 (js2-msg "msg.setter.bad.type"
1897 "Unsupported parameter type '%s' in setter '%s'.")
1899 (js2-msg "msg.add.sealed"
1900 "Cannot add a property to a sealed object: %s.")
1902 (js2-msg "msg.remove.sealed"
1903 "Cannot remove a property from a sealed object: %s.")
1905 (js2-msg "msg.modify.sealed"
1906 "Cannot modify a property of a sealed object: %s.")
1908 (js2-msg "msg.modify.readonly"
1909 "Cannot modify readonly property: %s.")
1912 (js2-msg "msg.missing.exponent"
1915 (js2-msg "msg.caught.nfe"
1916 "number format error")
1918 (js2-msg "msg.unterminated.string.lit"
1919 "unterminated string literal")
1921 (js2-msg "msg.unterminated.comment"
1922 "unterminated comment")
1924 (js2-msg "msg.unterminated.re.lit"
1925 "unterminated regular expression literal")
1927 (js2-msg "msg.invalid.re.flag"
1928 "invalid flag after regular expression")
1930 (js2-msg "msg.no.re.input.for"
1933 (js2-msg "msg.illegal.character"
1934 "illegal character")
1936 (js2-msg "msg.invalid.escape"
1937 "invalid Unicode escape sequence")
1939 (js2-msg "msg.bad.namespace"
1940 "not a valid default namespace statement. "
1941 "Syntax is: default xml namespace = EXPRESSION;")
1943 ;; TokensStream warnings
1944 (js2-msg "msg.bad.octal.literal"
1945 "illegal octal literal digit %s; "
1946 "interpreting it as a decimal digit")
1948 (js2-msg "msg.reserved.keyword"
1949 "illegal usage of future reserved keyword %s; "
1950 "interpreting it as ordinary identifier")
1952 (js2-msg "msg.script.is.not.constructor"
1953 "Script objects are not constructors.")
1956 (js2-msg "msg.arraylength.bad"
1957 "Inappropriate array length.")
1960 (js2-msg "msg.arraylength.too.big"
1961 "Array length %s exceeds supported capacity limit.")
1964 (js2-msg "msg.bad.uri"
1965 "Malformed URI sequence.")
1968 (js2-msg "msg.bad.precision"
1969 "Precision %s out of range.")
1972 (js2-msg "msg.send.newborn"
1973 "Attempt to send value to newborn generator")
1975 (js2-msg "msg.already.exec.gen"
1976 "Already executing generator")
1978 (js2-msg "msg.StopIteration.invalid"
1979 "StopIteration may not be changed to an arbitrary object.")
1982 (js2-msg "msg.yield.closing"
1983 "Yield from closing generator")
1987 (defun js2-delete-if (predicate list)
1988 "Remove all items satisfying PREDICATE in LIST."
1989 (loop for item in list
1990 if (not (funcall predicate item))
1993 (defun js2-position (element list)
1994 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1995 Returns nil if element is not found in the list."
1998 (while (and list (not found))
1999 (if (eq element (car list))
2001 (setq count (1+ count)
2005 (defun js2-find-if (predicate list)
2006 "Find first item satisfying PREDICATE in LIST."
2008 (while (and list (not result))
2009 (if (funcall predicate (car list))
2010 (setq result (car list)))
2011 (setq list (cdr list)))
2014 (defmacro js2-time (form)
2015 "Evaluate FORM, discard result, and return elapsed time in sec"
2017 (let ((beg (make-symbol "--js2-time-beg--"))
2018 (delta (make-symbol "--js2-time-end--")))
2019 `(let ((,beg (current-time))
2022 (/ (truncate (* (- (float-time (current-time))
2027 (defsubst js2-same-line (pos)
2028 "Return t if POS is on the same line as current point."
2029 (and (>= pos (point-at-bol))
2030 (<= pos (point-at-eol))))
2032 (defsubst js2-same-line-2 (p1 p2)
2033 "Return t if p1 is on the same line as p2."
2036 (js2-same-line p2)))
2038 (defun js2-code-bug ()
2039 "Signal an error when we encounter an unexpected code path."
2040 (error "failed assertion"))
2042 (defsubst js2-record-text-property (beg end prop value)
2043 "Record a text property to set when parsing finishes."
2044 (push (list beg end prop value) js2-mode-deferred-properties))
2046 ;; I'd like to associate errors with nodes, but for now the
2047 ;; easiest thing to do is get the context info from the last token.
2048 (defsubst js2-record-parse-error (msg &optional arg pos len)
2049 (push (list (list msg arg)
2050 (or pos js2-token-beg)
2051 (or len (- js2-token-end js2-token-beg)))
2054 (defsubst js2-report-error (msg &optional msg-arg pos len)
2055 "Signal a syntax error or record a parse error."
2056 (if js2-recover-from-parse-errors
2057 (js2-record-parse-error msg msg-arg pos len)
2058 (signal 'js2-syntax-error
2062 (goto-char js2-ts-cursor)
2066 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2067 (if js2-compiler-report-warning-as-error
2068 (js2-report-error msg msg-arg pos len)
2069 (push (list (list msg msg-arg)
2070 (or pos js2-token-beg)
2071 (or len (- js2-token-end js2-token-beg)))
2072 js2-parsed-warnings)))
2074 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2075 (if js2-compiler-strict-mode
2076 (js2-report-warning msg-id msg-arg beg
2077 (and beg end (- end beg)))))
2079 (put 'js2-syntax-error 'error-conditions
2080 '(error syntax-error js2-syntax-error))
2081 (put 'js2-syntax-error 'error-message "Syntax error")
2083 (put 'js2-parse-error 'error-conditions
2084 '(error parse-error js2-parse-error))
2085 (put 'js2-parse-error 'error-message "Parse error")
2087 (defmacro js2-clear-flag (flags flag)
2088 `(setq ,flags (logand ,flags (lognot ,flag))))
2090 (defmacro js2-set-flag (flags flag)
2091 "Logical-or FLAG into FLAGS."
2092 `(setq ,flags (logior ,flags ,flag)))
2094 (defsubst js2-flag-set-p (flags flag)
2095 (/= 0 (logand flags flag)))
2097 (defsubst js2-flag-not-set-p (flags flag)
2098 (zerop (logand flags flag)))
2100 ;; Stolen shamelessly from James Clark's nxml-mode.
2101 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2102 "Evaluate BODY without any text property changes modifying the buffer.
2103 Any text properties changes happen as usual but the changes are not treated as
2104 modifications to the buffer."
2105 (declare (indent 0) (debug t))
2106 (let ((modified (make-symbol "modified")))
2107 `(let ((,modified (buffer-modified-p))
2108 (inhibit-read-only t)
2109 (inhibit-modification-hooks t)
2110 (buffer-undo-list t)
2111 (deactivate-mark nil)
2112 ;; Apparently these avoid file locking problems.
2113 (buffer-file-name nil)
2114 (buffer-file-truename nil))
2118 (restore-buffer-modified-p nil))))))
2120 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2121 "Evaluate BODY with the _ character set to be word-syntax."
2122 (declare (indent 0) (debug t))
2123 (let ((old-syntax (make-symbol "old-syntax")))
2124 `(let ((,old-syntax (string (char-syntax ?_))))
2127 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2129 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2131 (defsubst js2-char-uppercase-p (c)
2132 "Return t if C is an uppercase character.
2133 Handles unicode and latin chars properly."
2134 (/= c (downcase c)))
2136 (defsubst js2-char-lowercase-p (c)
2137 "Return t if C is an uppercase character.
2138 Handles unicode and latin chars properly."
2141 ;;; AST struct and function definitions
2143 ;; flags for ast node property 'member-type (used for e4x operators)
2144 (defvar js2-property-flag #x1 "property access: element is valid name")
2145 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2146 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2148 (defsubst js2-relpos (pos anchor)
2149 "Convert POS to be relative to ANCHOR.
2150 If POS is nil, returns nil."
2151 (and pos (- pos anchor)))
2153 (defsubst js2-make-pad (indent)
2156 (make-string (* indent js2-basic-offset) ? )))
2158 (defsubst js2-visit-ast (node callback)
2159 "Visit every node in ast NODE with visitor CALLBACK.
2161 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2162 called twice: once to visit the node, and again after all the node's
2163 children have been processed. The END-P argument is nil on the first
2164 call and non-nil on the second call. The return value of the callback
2165 affects the traversal: if non-nil, the children of NODE are processed.
2166 If the callback returns nil, or if the node has no children, then the
2167 callback is called immediately with a non-nil END-P argument.
2169 The node traversal is approximately lexical-order, although there
2170 are currently no guarantees around this."
2172 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2174 (when (funcall callback node nil)
2177 ((eq vfunc 'js2-visit-none)
2178 nil) ; don't even bother calling it
2179 ;; Each AST node type has to define a `js2-visitor' function
2180 ;; that takes a node and a callback, and calls `js2-visit-ast'
2181 ;; on each child of the node.
2183 (funcall vfunc node callback))
2185 (error "%s does not define a visitor-traversal function"
2187 ;; call the end-visit
2188 (funcall callback node t))))
2190 (defstruct (js2-node
2191 (:constructor nil)) ; abstract
2192 "Base AST node type."
2193 (type -1) ; token type
2194 (pos -1) ; start position of this AST node in parsed input
2195 (len 1) ; num characters spanned by the node
2196 props ; optional node property list (an alist)
2197 parent) ; link to parent node; null for root
2199 (defsubst js2-node-get-prop (node prop &optional default)
2200 (or (cadr (assoc prop (js2-node-props node))) default))
2202 (defsubst js2-node-set-prop (node prop value)
2203 (setf (js2-node-props node)
2204 (cons (list prop value) (js2-node-props node))))
2206 (defsubst js2-fixup-starts (n nodes)
2207 "Adjust the start positions of NODES to be relative to N.
2208 Any node in the list may be nil, for convenience."
2209 (dolist (node nodes)
2211 (setf (js2-node-pos node) (- (js2-node-pos node)
2212 (js2-node-pos n))))))
2214 (defsubst js2-node-add-children (parent &rest nodes)
2215 "Set parent node of NODES to PARENT, and return PARENT.
2216 Does nothing if we're not recording parent links.
2217 If any given node in NODES is nil, doesn't record that link."
2218 (js2-fixup-starts parent nodes)
2219 (dolist (node nodes)
2221 (setf (js2-node-parent node) parent))))
2223 ;; Non-recursive since it's called a frightening number of times.
2224 (defsubst js2-node-abs-pos (n)
2225 (let ((pos (js2-node-pos n)))
2226 (while (setq n (js2-node-parent n))
2227 (setq pos (+ pos (js2-node-pos n))))
2230 (defsubst js2-node-abs-end (n)
2231 "Return absolute buffer position of end of N."
2232 (+ (js2-node-abs-pos n) (js2-node-len n)))
2234 ;; It's important to make sure block nodes have a lisp list for the
2235 ;; child nodes, to limit printing recursion depth in an AST that
2236 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2237 ;; a sufficiently large vector tree.
2239 (defstruct (js2-block-node
2242 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2247 "A block of statements."
2248 kids) ; a lisp list of the child statement nodes
2250 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2251 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2253 (defsubst js2-visit-block (ast callback)
2254 "Visit the `js2-block-node' children of AST."
2255 (dolist (kid (js2-block-node-kids ast))
2256 (js2-visit-ast kid callback)))
2258 (defun js2-print-block (n i)
2259 (let ((pad (js2-make-pad i)))
2261 (dolist (kid (js2-block-node-kids n))
2262 (js2-print-ast kid (1+ i)))
2265 (defstruct (js2-scope
2266 (:include js2-block-node)
2268 (:constructor make-js2-scope (&key (type js2-BLOCK)
2272 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2273 ;; I don't have one of those handy, so I'll use an alist for now.
2274 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2275 ;; and is much lighter-weight to construct (both CPU and mem).
2276 ;; The keys are interned strings (symbols) for faster lookup.
2277 ;; Should switch to hybrid alist/hashtable eventually.
2278 symbol-table ; an alist of (symbol . js2-symbol)
2279 parent-scope ; a `js2-scope'
2280 top) ; top-level `js2-scope' (script/function)
2282 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2283 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2285 (defun js2-scope-set-parent-scope (scope parent)
2286 (setf (js2-scope-parent-scope scope) parent
2287 (js2-scope-top scope) (if (null parent)
2289 (js2-scope-top parent))))
2291 (defun js2-node-get-enclosing-scope (node)
2292 "Return the innermost `js2-scope' node surrounding NODE.
2293 Returns nil if there is no enclosing scope node."
2294 (let ((parent (js2-node-parent node)))
2295 (while (not (js2-scope-p parent))
2296 (setq parent (js2-node-parent parent)))
2299 (defun js2-get-defining-scope (scope name)
2300 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2301 Returns `js2-scope' in which NAME is defined, or nil if not found."
2302 (let ((sym (if (symbolp name)
2308 (while (and scope continue)
2309 (if (and (setq table (js2-scope-symbol-table scope))
2313 (setq scope (js2-scope-parent-scope scope))))
2316 (defsubst js2-scope-get-symbol (scope name)
2317 "Return symbol table entry for NAME in SCOPE.
2318 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2319 (and (js2-scope-symbol-table scope)
2320 (cdr (assq (if (symbolp name)
2323 (js2-scope-symbol-table scope)))))
2325 (defsubst js2-scope-put-symbol (scope name symbol)
2326 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2327 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2328 (let* ((table (js2-scope-symbol-table scope))
2329 (sym (if (symbolp name) name (intern name)))
2330 (entry (assq sym table)))
2332 (setcdr entry symbol)
2333 (push (cons sym symbol)
2334 (js2-scope-symbol-table scope)))))
2336 (defstruct (js2-symbol
2338 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2339 "A symbol table entry."
2340 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2341 ;; js2-LET, or js2-CONST
2344 ast-node) ; a `js2-node'
2346 (defstruct (js2-error-node
2348 (:constructor nil) ; silence emacs21 byte-compiler
2349 (:constructor make-js2-error-node (&key (type js2-ERROR)
2352 "AST node representing a parse error.")
2354 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2355 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2357 (defstruct (js2-script-node
2358 (:include js2-scope)
2360 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2365 functions ; lisp list of nested functions
2366 regexps ; lisp list of (string . flags)
2367 symbols ; alist (every symbol gets unique index)
2369 var-names ; vector of string names
2370 consts ; bool-vector matching var-decls
2371 (temp-number 0)) ; for generating temp variables
2373 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2374 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2376 (defun js2-print-script (node indent)
2377 (dolist (kid (js2-block-node-kids node))
2378 (js2-print-ast kid indent)))
2380 (defstruct (js2-ast-root
2381 (:include js2-script-node)
2383 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2387 "The root node of a js2 AST."
2388 buffer ; the source buffer from which the code was parsed
2389 comments ; a lisp list of comments, ordered by start position
2390 errors ; a lisp list of errors found during parsing
2391 warnings ; a lisp list of warnings found during parsing
2392 node-count) ; number of nodes in the tree, including the root
2394 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2395 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2397 (defun js2-visit-ast-root (ast callback)
2398 (dolist (kid (js2-ast-root-kids ast))
2399 (js2-visit-ast kid callback))
2400 (dolist (comment (js2-ast-root-comments ast))
2401 (js2-visit-ast comment callback)))
2403 (defstruct (js2-comment-node
2406 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2409 (format js2-ts-comment-type))))
2410 format) ; 'line, 'block, 'jsdoc or 'html
2412 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2413 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2415 (defun js2-print-comment (n i)
2416 ;; We really ought to link end-of-line comments to their nodes.
2417 ;; Or maybe we could add a new comment type, 'endline.
2418 (insert (js2-make-pad i)
2419 (js2-node-string n)))
2421 (defstruct (js2-expr-stmt-node
2424 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2428 "An expression statement."
2431 (defsubst js2-expr-stmt-node-set-has-result (node)
2432 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2433 (setf (js2-node-type node) js2-EXPR_RESULT))
2435 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2436 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2438 (defun js2-visit-expr-stmt-node (n v)
2439 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2441 (defun js2-print-expr-stmt-node (n indent)
2442 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2445 (defstruct (js2-loop-node
2446 (:include js2-scope)
2448 "Abstract supertype of loop nodes."
2449 body ; a `js2-block-node'
2450 lp ; position of left-paren, nil if omitted
2451 rp) ; position of right-paren, nil if omitted
2453 (defstruct (js2-do-node
2454 (:include js2-loop-node)
2456 (:constructor make-js2-do-node (&key (type js2-DO)
2464 "AST node for do-loop."
2465 condition ; while (expression)
2466 while-pos) ; buffer position of 'while' keyword
2468 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2469 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2471 (defun js2-visit-do-node (n v)
2472 (js2-visit-ast (js2-do-node-body n) v)
2473 (js2-visit-ast (js2-do-node-condition n) v))
2475 (defun js2-print-do-node (n i)
2476 (let ((pad (js2-make-pad i)))
2477 (insert pad "do {\n")
2478 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2479 (js2-print-ast kid (1+ i)))
2480 (insert pad "} while (")
2481 (js2-print-ast (js2-do-node-condition n) 0)
2484 (defstruct (js2-while-node
2485 (:include js2-loop-node)
2487 (:constructor make-js2-while-node (&key (type js2-WHILE)
2494 "AST node for while-loop."
2495 condition) ; while-condition
2497 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2498 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2500 (defun js2-visit-while-node (n v)
2501 (js2-visit-ast (js2-while-node-condition n) v)
2502 (js2-visit-ast (js2-while-node-body n) v))
2504 (defun js2-print-while-node (n i)
2505 (let ((pad (js2-make-pad i)))
2506 (insert pad "while (")
2507 (js2-print-ast (js2-while-node-condition n) 0)
2509 (js2-print-body (js2-while-node-body n) (1+ i))
2510 (insert pad "}\n")))
2512 (defstruct (js2-for-node
2513 (:include js2-loop-node)
2515 (:constructor make-js2-for-node (&key (type js2-FOR)
2524 "AST node for a C-style for-loop."
2525 init ; initialization expression
2526 condition ; loop condition
2527 update) ; update clause
2529 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2530 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2532 (defun js2-visit-for-node (n v)
2533 (js2-visit-ast (js2-for-node-init n) v)
2534 (js2-visit-ast (js2-for-node-condition n) v)
2535 (js2-visit-ast (js2-for-node-update n) v)
2536 (js2-visit-ast (js2-for-node-body n) v))
2538 (defun js2-print-for-node (n i)
2539 (let ((pad (js2-make-pad i)))
2540 (insert pad "for (")
2541 (js2-print-ast (js2-for-node-init n) 0)
2543 (js2-print-ast (js2-for-node-condition n) 0)
2545 (js2-print-ast (js2-for-node-update n) 0)
2547 (js2-print-body (js2-for-node-body n) (1+ i))
2548 (insert pad "}\n")))
2550 (defstruct (js2-for-in-node
2551 (:include js2-loop-node)
2553 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2563 "AST node for a for..in loop."
2564 iterator ; [var] foo in ...
2565 object ; object over which we're iterating
2566 in-pos ; buffer position of 'in' keyword
2567 each-pos ; buffer position of 'each' keyword, if foreach-p
2568 foreach-p ; t if it's a for-each loop
2569 forof-p) ; t if it's a for-of loop
2571 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2572 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2574 (defun js2-visit-for-in-node (n v)
2575 (js2-visit-ast (js2-for-in-node-iterator n) v)
2576 (js2-visit-ast (js2-for-in-node-object n) v)
2577 (js2-visit-ast (js2-for-in-node-body n) v))
2579 (defun js2-print-for-in-node (n i)
2580 (let ((pad (js2-make-pad i))
2581 (foreach (js2-for-in-node-foreach-p n))
2582 (forof (js2-for-in-node-forof-p n)))
2587 (js2-print-ast (js2-for-in-node-iterator n) 0)
2591 (js2-print-ast (js2-for-in-node-object n) 0)
2593 (js2-print-body (js2-for-in-node-body n) (1+ i))
2594 (insert pad "}\n")))
2596 (defstruct (js2-return-node
2599 (:constructor make-js2-return-node (&key (type js2-RETURN)
2603 "AST node for a return statement."
2604 retval) ; expression to return, or 'undefined
2606 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2607 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2609 (defun js2-visit-return-node (n v)
2610 (js2-visit-ast (js2-return-node-retval n) v))
2612 (defun js2-print-return-node (n i)
2613 (insert (js2-make-pad i) "return")
2614 (when (js2-return-node-retval n)
2616 (js2-print-ast (js2-return-node-retval n) 0))
2619 (defstruct (js2-if-node
2622 (:constructor make-js2-if-node (&key (type js2-IF)
2631 "AST node for an if-statement."
2632 condition ; expression
2633 then-part ; statement or block
2634 else-pos ; optional buffer position of 'else' keyword
2635 else-part ; optional statement or block
2636 lp ; position of left-paren, nil if omitted
2637 rp) ; position of right-paren, nil if omitted
2639 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2640 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2642 (defun js2-visit-if-node (n v)
2643 (js2-visit-ast (js2-if-node-condition n) v)
2644 (js2-visit-ast (js2-if-node-then-part n) v)
2645 (js2-visit-ast (js2-if-node-else-part n) v))
2647 (defun js2-print-if-node (n i)
2648 (let ((pad (js2-make-pad i))
2649 (then-part (js2-if-node-then-part n))
2650 (else-part (js2-if-node-else-part n)))
2652 (js2-print-ast (js2-if-node-condition n) 0)
2654 (js2-print-body then-part (1+ i))
2659 ((js2-if-node-p else-part)
2661 (js2-print-body else-part i))
2663 (insert " else {\n")
2664 (js2-print-body else-part (1+ i))
2665 (insert pad "}\n")))))
2667 (defstruct (js2-try-node
2670 (:constructor make-js2-try-node (&key (type js2-TRY)
2676 "AST node for a try-statement."
2678 catch-clauses ; a lisp list of `js2-catch-node'
2679 finally-block) ; a `js2-finally-node'
2681 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2682 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2684 (defun js2-visit-try-node (n v)
2685 (js2-visit-ast (js2-try-node-try-block n) v)
2686 (dolist (clause (js2-try-node-catch-clauses n))
2687 (js2-visit-ast clause v))
2688 (js2-visit-ast (js2-try-node-finally-block n) v))
2690 (defun js2-print-try-node (n i)
2691 (let ((pad (js2-make-pad i))
2692 (catches (js2-try-node-catch-clauses n))
2693 (finally (js2-try-node-finally-block n)))
2694 (insert pad "try {\n")
2695 (js2-print-body (js2-try-node-try-block n) (1+ i))
2698 (dolist (catch catches)
2699 (js2-print-ast catch i)))
2701 (js2-print-ast finally i)
2704 (defstruct (js2-catch-node
2707 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2716 "AST node for a catch clause."
2717 param ; destructuring form or simple name node
2718 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2719 guard-expr ; catch condition, a `js2-node'
2720 block ; statements, a `js2-block-node'
2721 lp ; buffer position of left-paren, nil if omitted
2722 rp) ; buffer position of right-paren, nil if omitted
2724 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2725 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2727 (defun js2-visit-catch-node (n v)
2728 (js2-visit-ast (js2-catch-node-param n) v)
2729 (when (js2-catch-node-guard-kwd n)
2730 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2731 (js2-visit-ast (js2-catch-node-block n) v))
2733 (defun js2-print-catch-node (n i)
2734 (let ((pad (js2-make-pad i))
2735 (guard-kwd (js2-catch-node-guard-kwd n))
2736 (guard-expr (js2-catch-node-guard-expr n)))
2738 (js2-print-ast (js2-catch-node-param n) 0)
2741 (js2-print-ast guard-expr 0))
2743 (js2-print-body (js2-catch-node-block n) (1+ i))
2746 (defstruct (js2-finally-node
2749 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2753 "AST node for a finally clause."
2754 body) ; a `js2-node', often but not always a block node
2756 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2757 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2759 (defun js2-visit-finally-node (n v)
2760 (js2-visit-ast (js2-finally-node-body n) v))
2762 (defun js2-print-finally-node (n i)
2763 (let ((pad (js2-make-pad i)))
2764 (insert " finally {\n")
2765 (js2-print-body (js2-finally-node-body n) (1+ i))
2766 (insert pad "}\n")))
2768 (defstruct (js2-switch-node
2771 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2778 "AST node for a switch statement."
2779 discriminant ; a `js2-node' (switch expression)
2780 cases ; a lisp list of `js2-case-node'
2781 lp ; position of open-paren for discriminant, nil if omitted
2782 rp) ; position of close-paren for discriminant, nil if omitted
2784 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2785 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2787 (defun js2-visit-switch-node (n v)
2788 (js2-visit-ast (js2-switch-node-discriminant n) v)
2789 (dolist (c (js2-switch-node-cases n))
2790 (js2-visit-ast c v)))
2792 (defun js2-print-switch-node (n i)
2793 (let ((pad (js2-make-pad i))
2794 (cases (js2-switch-node-cases n)))
2795 (insert pad "switch (")
2796 (js2-print-ast (js2-switch-node-discriminant n) 0)
2798 (dolist (case cases)
2799 (js2-print-ast case i))
2800 (insert pad "}\n")))
2802 (defstruct (js2-case-node
2803 (:include js2-block-node)
2805 (:constructor make-js2-case-node (&key (type js2-CASE)
2810 "AST node for a case clause of a switch statement."
2811 expr) ; the case expression (nil for default)
2813 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2814 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2816 (defun js2-visit-case-node (n v)
2817 (js2-visit-ast (js2-case-node-expr n) v)
2818 (js2-visit-block n v))
2820 (defun js2-print-case-node (n i)
2821 (let ((pad (js2-make-pad i))
2822 (expr (js2-case-node-expr n)))
2825 (insert "default:\n")
2827 (js2-print-ast expr 0)
2829 (dolist (kid (js2-case-node-kids n))
2830 (js2-print-ast kid (1+ i)))))
2832 (defstruct (js2-throw-node
2835 (:constructor make-js2-throw-node (&key (type js2-THROW)
2839 "AST node for a throw statement."
2840 expr) ; the expression to throw
2842 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2843 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2845 (defun js2-visit-throw-node (n v)
2846 (js2-visit-ast (js2-throw-node-expr n) v))
2848 (defun js2-print-throw-node (n i)
2849 (insert (js2-make-pad i) "throw ")
2850 (js2-print-ast (js2-throw-node-expr n) 0)
2853 (defstruct (js2-with-node
2856 (:constructor make-js2-with-node (&key (type js2-WITH)
2863 "AST node for a with-statement."
2866 lp ; buffer position of left-paren around object, nil if omitted
2867 rp) ; buffer position of right-paren around object, nil if omitted
2869 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2870 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2872 (defun js2-visit-with-node (n v)
2873 (js2-visit-ast (js2-with-node-object n) v)
2874 (js2-visit-ast (js2-with-node-body n) v))
2876 (defun js2-print-with-node (n i)
2877 (let ((pad (js2-make-pad i)))
2878 (insert pad "with (")
2879 (js2-print-ast (js2-with-node-object n) 0)
2881 (js2-print-body (js2-with-node-body n) (1+ i))
2882 (insert pad "}\n")))
2884 (defstruct (js2-label-node
2887 (:constructor make-js2-label-node (&key (type js2-LABEL)
2891 "AST node for a statement label or case label."
2893 loop) ; for validating and code-generating continue-to-label
2895 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2896 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2898 (defun js2-print-label (n i)
2899 (insert (js2-make-pad i)
2900 (js2-label-node-name n)
2903 (defstruct (js2-labeled-stmt-node
2906 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2907 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2908 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2913 "AST node for a statement with one or more labels.
2914 Multiple labels for a statement are collapsed into the labels field."
2915 labels ; lisp list of `js2-label-node'
2916 stmt) ; the statement these labels are for
2918 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2919 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2921 (defun js2-get-label-by-name (lbl-stmt name)
2922 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2923 Returns nil if no such label is in the list."
2924 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2926 (while (and label-list (not result))
2927 (if (string= (js2-label-node-name (car label-list)) name)
2928 (setq result (car label-list))
2929 (setq label-list (cdr label-list))))
2932 (defun js2-visit-labeled-stmt (n v)
2933 (dolist (label (js2-labeled-stmt-node-labels n))
2934 (js2-visit-ast label v))
2935 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2937 (defun js2-print-labeled-stmt (n i)
2938 (dolist (label (js2-labeled-stmt-node-labels n))
2939 (js2-print-ast label i))
2940 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2942 (defun js2-labeled-stmt-node-contains (node label)
2943 "Return t if NODE contains LABEL in its label set.
2944 NODE is a `js2-labels-node'. LABEL is an identifier."
2945 (loop for nl in (js2-labeled-stmt-node-labels node)
2946 if (string= label (js2-label-node-name nl))
2948 finally return nil))
2950 (defsubst js2-labeled-stmt-node-add-label (node label)
2951 "Add a `js2-label-node' to the label set for this statement."
2952 (setf (js2-labeled-stmt-node-labels node)
2953 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2955 (defstruct (js2-jump-node
2958 "Abstract supertype of break and continue nodes."
2959 label ; `js2-name-node' for location of label identifier, if present
2960 target) ; target js2-labels-node or loop/switch statement
2962 (defun js2-visit-jump-node (n v)
2963 (js2-visit-ast (js2-jump-node-label n) v))
2965 (defstruct (js2-break-node
2966 (:include js2-jump-node)
2968 (:constructor make-js2-break-node (&key (type js2-BREAK)
2973 "AST node for a break statement.
2974 The label field is a `js2-name-node', possibly nil, for the named label
2975 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2976 is the target of the break - a label node or enclosing loop/switch statement.")
2978 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2979 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2981 (defun js2-print-break-node (n i)
2982 (insert (js2-make-pad i) "break")
2983 (when (js2-break-node-label n)
2985 (js2-print-ast (js2-break-node-label n) 0))
2988 (defstruct (js2-continue-node
2989 (:include js2-jump-node)
2991 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2996 "AST node for a continue statement.
2997 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2998 It is nil if continue specifies no label. The target field is the jump target:
2999 a `js2-label-node' or the innermost enclosing loop.")
3001 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3002 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3004 (defun js2-print-continue-node (n i)
3005 (insert (js2-make-pad i) "continue")
3006 (when (js2-continue-node-label n)
3008 (js2-print-ast (js2-continue-node-label n) 0))
3011 (defstruct (js2-function-node
3012 (:include js2-script-node)
3014 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3018 (form 'FUNCTION_STATEMENT)
3023 "AST node for a function declaration.
3024 The `params' field is a lisp list of nodes. Each node is either a simple
3025 `js2-name-node', or if it's a destructuring-assignment parameter, a
3026 `js2-array-node' or `js2-object-node'."
3027 ftype ; FUNCTION, GETTER or SETTER
3028 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3029 name ; function name (a `js2-name-node', or nil if anonymous)
3030 params ; a lisp list of destructuring forms or simple name nodes
3031 rest-p ; if t, the last parameter is rest parameter
3032 body ; a `js2-block-node' or expression node (1.8 only)
3033 lp ; position of arg-list open-paren, or nil if omitted
3034 rp ; position of arg-list close-paren, or nil if omitted
3035 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3036 needs-activation ; t if we need an activation object for this frame
3037 is-generator ; t if this function contains a yield
3038 member-expr) ; nonstandard Ecma extension from Rhino
3040 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3041 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3043 (defun js2-visit-function-node (n v)
3044 (js2-visit-ast (js2-function-node-name n) v)
3045 (dolist (p (js2-function-node-params n))
3046 (js2-visit-ast p v))
3047 (js2-visit-ast (js2-function-node-body n) v))
3049 (defun js2-print-function-node (n i)
3050 (let ((pad (js2-make-pad i))
3051 (getter (js2-node-get-prop n 'GETTER_SETTER))
3052 (name (js2-function-node-name n))
3053 (params (js2-function-node-params n))
3054 (rest-p (js2-function-node-rest-p n))
3055 (body (js2-function-node-body n))
3056 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3058 (insert pad "function"))
3061 (js2-print-ast name 0))
3063 (loop with len = (length params)
3067 (when (and rest-p (= count len))
3069 (js2-print-ast param 0)
3075 ;; TODO: fix this to be smarter about indenting, etc.
3076 (js2-print-body body (1+ i))
3081 (defsubst js2-function-name (node)
3082 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3083 (and (js2-function-node-name node)
3084 (js2-name-node-name (js2-function-node-name node))))
3086 ;; Having this be an expression node makes it more flexible.
3087 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3088 ;; that work better if you assume it's an expression. Whenever we have
3089 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3090 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3091 (defstruct (js2-var-decl-node
3094 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3099 "AST node for a variable declaration list (VAR, CONST or LET).
3100 The node bounds differ depending on the declaration type. For VAR or
3101 CONST declarations, the bounds include the var/const keyword. For LET
3102 declarations, the node begins at the position of the first child."
3103 kids ; a lisp list of `js2-var-init-node' structs.
3104 decl-type) ; js2-VAR, js2-CONST or js2-LET
3106 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3107 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3109 (defun js2-visit-var-decl (n v)
3110 (dolist (kid (js2-var-decl-node-kids n))
3111 (js2-visit-ast kid v)))
3113 (defun js2-print-var-decl (n i)
3114 (let ((pad (js2-make-pad i))
3115 (tt (js2-var-decl-node-decl-type n)))
3118 ((= tt js2-VAR) "var ")
3119 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3120 ((= tt js2-CONST) "const ")
3122 (error "malformed var-decl node"))))
3123 (loop with kids = (js2-var-decl-node-kids n)
3124 with len = (length kids)
3128 (js2-print-ast kid 0)
3132 (defstruct (js2-var-init-node
3135 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3140 "AST node for a variable declaration.
3141 The type field will be js2-CONST for a const decl."
3142 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3143 initializer) ; initializer expression, a `js2-node'
3145 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3146 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3148 (defun js2-visit-var-init-node (n v)
3149 (js2-visit-ast (js2-var-init-node-target n) v)
3150 (js2-visit-ast (js2-var-init-node-initializer n) v))
3152 (defun js2-print-var-init-node (n i)
3153 (let ((pad (js2-make-pad i))
3154 (name (js2-var-init-node-target n))
3155 (init (js2-var-init-node-initializer n)))
3157 (js2-print-ast name 0)
3160 (js2-print-ast init 0))))
3162 (defstruct (js2-cond-node
3165 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3173 "AST node for the ternary operator"
3177 q-pos ; buffer position of ?
3178 c-pos) ; buffer position of :
3180 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3181 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3183 (defun js2-visit-cond-node (n v)
3184 (js2-visit-ast (js2-cond-node-test-expr n) v)
3185 (js2-visit-ast (js2-cond-node-true-expr n) v)
3186 (js2-visit-ast (js2-cond-node-false-expr n) v))
3188 (defun js2-print-cond-node (n i)
3189 (let ((pad (js2-make-pad i)))
3191 (js2-print-ast (js2-cond-node-test-expr n) 0)
3193 (js2-print-ast (js2-cond-node-true-expr n) 0)
3195 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3197 (defstruct (js2-infix-node
3200 (:constructor make-js2-infix-node (&key type
3206 "Represents infix expressions.
3207 Includes assignment ops like `|=', and the comma operator.
3208 The type field inherited from `js2-node' holds the operator."
3209 op-pos ; buffer position where operator begins
3210 left ; any `js2-node'
3211 right) ; any `js2-node'
3213 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3214 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3216 (defun js2-visit-infix-node (n v)
3217 (js2-visit-ast (js2-infix-node-left n) v)
3218 (js2-visit-ast (js2-infix-node-right n) v))
3220 (defconst js2-operator-tokens
3221 (let ((table (make-hash-table :test 'eq))
3223 (list (cons js2-IN "in")
3224 (cons js2-TYPEOF "typeof")
3225 (cons js2-INSTANCEOF "instanceof")
3226 (cons js2-DELPROP "delete")
3227 (cons js2-COMMA ",")
3228 (cons js2-COLON ":")
3233 (cons js2-BITOR "|")
3234 (cons js2-BITXOR "^")
3235 (cons js2-BITAND "&")
3244 (cons js2-URSH ">>>")
3245 (cons js2-ADD "+") ; infix plus
3246 (cons js2-SUB "-") ; infix minus
3251 (cons js2-BITNOT "~")
3252 (cons js2-POS "+") ; unary plus
3253 (cons js2-NEG "-") ; unary minus
3254 (cons js2-SHEQ "===") ; shallow equality
3255 (cons js2-SHNE "!==") ; shallow inequality
3256 (cons js2-ASSIGN "=")
3257 (cons js2-ASSIGN_BITOR "|=")
3258 (cons js2-ASSIGN_BITXOR "^=")
3259 (cons js2-ASSIGN_BITAND "&=")
3260 (cons js2-ASSIGN_LSH "<<=")
3261 (cons js2-ASSIGN_RSH ">>=")
3262 (cons js2-ASSIGN_URSH ">>>=")
3263 (cons js2-ASSIGN_ADD "+=")
3264 (cons js2-ASSIGN_SUB "-=")
3265 (cons js2-ASSIGN_MUL "*=")
3266 (cons js2-ASSIGN_DIV "/=")
3267 (cons js2-ASSIGN_MOD "%="))))
3268 (loop for (k . v) in tokens do
3269 (puthash k v table))
3272 (defun js2-print-infix-node (n i)
3273 (let* ((tt (js2-node-type n))
3274 (op (gethash tt js2-operator-tokens)))
3276 (error "unrecognized infix operator %s" (js2-node-type n)))
3277 (insert (js2-make-pad i))
3278 (js2-print-ast (js2-infix-node-left n) 0)
3279 (unless (= tt js2-COMMA)
3283 (js2-print-ast (js2-infix-node-right n) 0)))
3285 (defstruct (js2-assign-node
3286 (:include js2-infix-node)
3288 (:constructor make-js2-assign-node (&key type
3294 "Represents any assignment.
3295 The type field holds the actual assignment operator.")
3297 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3298 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3300 (defstruct (js2-unary-node
3303 (:constructor make-js2-unary-node (&key type ; required
3307 "AST node type for unary operator nodes.
3308 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3309 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3310 property is added if the operator follows the operand."
3311 operand) ; a `js2-node' expression
3313 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3314 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3316 (defun js2-visit-unary-node (n v)
3317 (js2-visit-ast (js2-unary-node-operand n) v))
3319 (defun js2-print-unary-node (n i)
3320 (let* ((tt (js2-node-type n))
3321 (op (gethash tt js2-operator-tokens))
3322 (postfix (js2-node-get-prop n 'postfix)))
3324 (error "unrecognized unary operator %s" tt))
3325 (insert (js2-make-pad i))
3328 (if (or (= tt js2-TYPEOF)
3331 (js2-print-ast (js2-unary-node-operand n) 0)
3335 (defstruct (js2-let-node
3336 (:include js2-scope)
3338 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3345 "AST node for a let expression or a let statement.
3346 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3347 vars ; a `js2-var-decl-node'
3348 body ; a `js2-node' representing the expression or body block
3352 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3353 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3355 (defun js2-visit-let-node (n v)
3356 (js2-visit-ast (js2-let-node-vars n) v)
3357 (js2-visit-ast (js2-let-node-body n) v))
3359 (defun js2-print-let-node (n i)
3360 (insert (js2-make-pad i) "let (")
3361 (js2-print-ast (js2-let-node-vars n) 0)
3363 (js2-print-ast (js2-let-node-body n) i))
3365 (defstruct (js2-keyword-node
3368 (:constructor make-js2-keyword-node (&key type
3370 (len (- js2-ts-cursor pos)))))
3371 "AST node representing a literal keyword such as `null'.
3372 Used for `null', `this', `true', `false' and `debugger'.
3373 The node type is set to js2-NULL, js2-THIS, etc.")
3375 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3376 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3378 (defun js2-print-keyword-node (n i)
3379 (insert (js2-make-pad i)
3380 (let ((tt (js2-node-type n)))
3382 ((= tt js2-THIS) "this")
3383 ((= tt js2-NULL) "null")
3384 ((= tt js2-TRUE) "true")
3385 ((= tt js2-FALSE) "false")
3386 ((= tt js2-DEBUGGER) "debugger")
3387 (t (error "Invalid keyword literal type: %d" tt))))))
3389 (defsubst js2-this-node-p (node)
3390 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3391 (eq (js2-node-type node) js2-THIS))
3393 (defstruct (js2-new-node
3396 (:constructor make-js2-new-node (&key (type js2-NEW)
3404 "AST node for new-expression such as new Foo()."
3405 target ; an identifier or reference
3406 args ; a lisp list of argument nodes
3407 lp ; position of left-paren, nil if omitted
3408 rp ; position of right-paren, nil if omitted
3409 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3411 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3412 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3414 (defun js2-visit-new-node (n v)
3415 (js2-visit-ast (js2-new-node-target n) v)
3416 (dolist (arg (js2-new-node-args n))
3417 (js2-visit-ast arg v))
3418 (js2-visit-ast (js2-new-node-initializer n) v))
3420 (defun js2-print-new-node (n i)
3421 (insert (js2-make-pad i) "new ")
3422 (js2-print-ast (js2-new-node-target n))
3424 (js2-print-list (js2-new-node-args n))
3426 (when (js2-new-node-initializer n)
3428 (js2-print-ast (js2-new-node-initializer n))))
3430 (defstruct (js2-name-node
3433 (:constructor make-js2-name-node (&key (type js2-NAME)
3435 (len (- js2-ts-cursor
3437 (name js2-ts-string))))
3438 "AST node for a JavaScript identifier"
3440 scope) ; a `js2-scope' (optional, used for codegen)
3442 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3443 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3445 (defun js2-print-name-node (n i)
3446 (insert (js2-make-pad i)
3447 (js2-name-node-name n)))
3449 (defsubst js2-name-node-length (node)
3450 "Return identifier length of NODE, a `js2-name-node'.
3451 Returns 0 if NODE is nil or its identifier field is nil."
3453 (length (js2-name-node-name node))
3456 (defstruct (js2-number-node
3459 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3461 (len (- js2-ts-cursor
3463 (value js2-ts-string)
3464 (num-value js2-ts-number))))
3465 "AST node for a number literal."
3466 value ; the original string, e.g. "6.02e23"
3467 num-value) ; the parsed number value
3469 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3470 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3472 (defun js2-print-number-node (n i)
3473 (insert (js2-make-pad i)
3474 (number-to-string (js2-number-node-num-value n))))
3476 (defstruct (js2-regexp-node
3479 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3481 (len (- js2-ts-cursor
3485 "AST node for a regular expression literal."
3486 value ; the regexp string, without // delimiters
3487 flags) ; a string of flags, e.g. `mi'.
3489 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3490 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3492 (defun js2-print-regexp (n i)
3493 (insert (js2-make-pad i)
3495 (js2-regexp-node-value n)
3497 (if (js2-regexp-node-flags n)
3498 (insert (js2-regexp-node-flags n))))
3500 (defstruct (js2-string-node
3503 (:constructor make-js2-string-node (&key (type js2-STRING)
3505 (len (- js2-ts-cursor
3507 (value js2-ts-string))))
3509 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3510 You can tell the quote type by looking at the first character."
3511 value) ; the characters of the string, including the quotes
3513 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3514 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3516 (defun js2-print-string-node (n i)
3517 (insert (js2-make-pad i)
3518 (js2-node-string n)))
3520 (defstruct (js2-array-node
3523 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3527 "AST node for an array literal."
3528 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3530 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3531 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3533 (defun js2-visit-array-node (n v)
3534 (dolist (e (js2-array-node-elems n))
3535 (js2-visit-ast e v)))
3537 (defun js2-print-array-node (n i)
3538 (insert (js2-make-pad i) "[")
3539 (js2-print-list (js2-array-node-elems n))
3542 (defstruct (js2-object-node
3545 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3549 "AST node for an object literal expression.
3550 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3551 the latter represents abbreviation in destructuring expressions."
3554 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3555 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3557 (defun js2-visit-object-node (n v)
3558 (dolist (e (js2-object-node-elems n))
3559 (js2-visit-ast e v)))
3561 (defun js2-print-object-node (n i)
3562 (insert (js2-make-pad i) "{")
3563 (js2-print-list (js2-object-node-elems n))
3566 (defstruct (js2-object-prop-node
3567 (:include js2-infix-node)
3569 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3575 "AST node for an object literal prop:value entry.
3576 The `left' field is the property: a name node, string node or number node.
3577 The `right' field is a `js2-node' representing the initializer value.")
3579 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3580 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3582 (defun js2-print-object-prop-node (n i)
3583 (insert (js2-make-pad i))
3584 (js2-print-ast (js2-object-prop-node-left n) 0)
3586 (js2-print-ast (js2-object-prop-node-right n) 0))
3588 (defstruct (js2-getter-setter-node
3589 (:include js2-infix-node)
3591 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3596 "AST node for a getter/setter property in an object literal.
3597 The `left' field is the `js2-name-node' naming the getter/setter prop.
3598 The `right' field is always an anonymous `js2-function-node' with a node
3599 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3601 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3602 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3604 (defun js2-print-getter-setter (n i)
3605 (let ((pad (js2-make-pad i))
3606 (left (js2-getter-setter-node-left n))
3607 (right (js2-getter-setter-node-right n)))
3609 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3610 (js2-print-ast left 0)
3611 (js2-print-ast right 0)))
3613 (defstruct (js2-prop-get-node
3614 (:include js2-infix-node)
3616 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3621 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3623 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3624 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3626 (defun js2-visit-prop-get-node (n v)
3627 (js2-visit-ast (js2-prop-get-node-left n) v)
3628 (js2-visit-ast (js2-prop-get-node-right n) v))
3630 (defun js2-print-prop-get-node (n i)
3631 (insert (js2-make-pad i))
3632 (js2-print-ast (js2-prop-get-node-left n) 0)
3634 (js2-print-ast (js2-prop-get-node-right n) 0))
3636 (defstruct (js2-elem-get-node
3639 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3646 "AST node for an array index expression such as foo[bar]."
3647 target ; a `js2-node' - the expression preceding the "."
3648 element ; a `js2-node' - the expression in brackets
3649 lb ; position of left-bracket, nil if omitted
3650 rb) ; position of right-bracket, nil if omitted
3652 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3653 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3655 (defun js2-visit-elem-get-node (n v)
3656 (js2-visit-ast (js2-elem-get-node-target n) v)
3657 (js2-visit-ast (js2-elem-get-node-element n) v))
3659 (defun js2-print-elem-get-node (n i)
3660 (insert (js2-make-pad i))
3661 (js2-print-ast (js2-elem-get-node-target n) 0)
3663 (js2-print-ast (js2-elem-get-node-element n) 0)
3666 (defstruct (js2-call-node
3669 (:constructor make-js2-call-node (&key (type js2-CALL)
3676 "AST node for a JavaScript function call."
3677 target ; a `js2-node' evaluating to the function to call
3678 args ; a lisp list of `js2-node' arguments
3679 lp ; position of open-paren, or nil if missing
3680 rp) ; position of close-paren, or nil if missing
3682 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3683 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3685 (defun js2-visit-call-node (n v)
3686 (js2-visit-ast (js2-call-node-target n) v)
3687 (dolist (arg (js2-call-node-args n))
3688 (js2-visit-ast arg v)))
3690 (defun js2-print-call-node (n i)
3691 (insert (js2-make-pad i))
3692 (js2-print-ast (js2-call-node-target n) 0)
3694 (js2-print-list (js2-call-node-args n))
3697 (defstruct (js2-yield-node
3700 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3704 "AST node for yield statement or expression."
3705 value) ; optional: value to be yielded
3707 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3708 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3710 (defun js2-visit-yield-node (n v)
3711 (js2-visit-ast (js2-yield-node-value n) v))
3713 (defun js2-print-yield-node (n i)
3714 (insert (js2-make-pad i))
3716 (when (js2-yield-node-value n)
3718 (js2-print-ast (js2-yield-node-value n) 0)))
3720 (defstruct (js2-paren-node
3723 (:constructor make-js2-paren-node (&key (type js2-LP)
3727 "AST node for a parenthesized expression.
3728 In particular, used when the parens are syntactically optional,
3729 as opposed to required parens such as those enclosing an if-conditional."
3732 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3733 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3735 (defun js2-visit-paren-node (n v)
3736 (js2-visit-ast (js2-paren-node-expr n) v))
3738 (defun js2-print-paren-node (n i)
3739 (insert (js2-make-pad i))
3741 (js2-print-ast (js2-paren-node-expr n) 0)
3744 (defstruct (js2-array-comp-node
3745 (:include js2-scope)
3747 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3756 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3757 result ; result expression (just after left-bracket)
3758 loops ; a lisp list of `js2-array-comp-loop-node'
3759 filter ; guard/filter expression
3760 if-pos ; buffer pos of 'if' keyword, if present, else nil
3761 lp ; buffer position of if-guard left-paren, or nil if not present
3762 rp) ; buffer position of if-guard right-paren, or nil if not present
3764 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3765 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3767 (defun js2-visit-array-comp-node (n v)
3768 (js2-visit-ast (js2-array-comp-node-result n) v)
3769 (dolist (l (js2-array-comp-node-loops n))
3770 (js2-visit-ast l v))
3771 (js2-visit-ast (js2-array-comp-node-filter n) v))
3773 (defun js2-print-array-comp-node (n i)
3774 (let ((pad (js2-make-pad i))
3775 (result (js2-array-comp-node-result n))
3776 (loops (js2-array-comp-node-loops n))
3777 (filter (js2-array-comp-node-filter n)))
3779 (js2-print-ast result 0)
3782 (js2-print-ast l 0))
3785 (js2-print-ast filter 0)
3789 (defstruct (js2-array-comp-loop-node
3790 (:include js2-for-in-node)
3792 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3802 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3804 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3805 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3807 (defun js2-visit-array-comp-loop (n v)
3808 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3809 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3811 (defun js2-print-array-comp-loop (n i)
3813 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3814 (if (js2-array-comp-loop-node-forof-p n)
3817 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3820 (defstruct (js2-empty-expr-node
3823 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3826 "AST node for an empty expression.")
3828 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3829 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3831 (defstruct (js2-xml-node
3832 (:include js2-block-node)
3834 (:constructor make-js2-xml-node (&key (type js2-XML)
3838 "AST node for initial parse of E4X literals.
3839 The kids field is a list of XML fragments, each a `js2-string-node' or
3840 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3842 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3843 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3845 (defun js2-print-xml-node (n i)
3846 (dolist (kid (js2-xml-node-kids n))
3847 (js2-print-ast kid i)))
3849 (defstruct (js2-xml-js-expr-node
3850 (:include js2-xml-node)
3852 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3856 "AST node for an embedded JavaScript {expression} in an E4X literal.
3857 The start and end fields correspond to the curly-braces."
3858 expr) ; a `js2-expr-node' of some sort
3860 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3861 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3863 (defun js2-visit-xml-js-expr (n v)
3864 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3866 (defun js2-print-xml-js-expr (n i)
3867 (insert (js2-make-pad i))
3869 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3872 (defstruct (js2-xml-dot-query-node
3873 (:include js2-infix-node)
3875 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3882 "AST node for an E4X foo.(bar) filter expression.
3883 Note that the left-paren is automatically the character immediately
3884 following the dot (.) in the operator. No whitespace is permitted
3885 between the dot and the lp by the scanner."
3888 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3889 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3891 (defun js2-print-xml-dot-query (n i)
3892 (insert (js2-make-pad i))
3893 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3895 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3898 (defstruct (js2-xml-ref-node
3900 (:constructor nil)) ; abstract
3901 "Base type for E4X XML attribute-access or property-get expressions.
3902 Such expressions can take a variety of forms. The general syntax has
3905 - (optional) an @ (specifying an attribute access)
3906 - (optional) a namespace (a `js2-name-node') and double-colon
3907 - (required) either a `js2-name-node' or a bracketed [expression]
3909 The property-name expressions (examples: ns::name, @name) are
3910 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3911 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3913 This node type (or more specifically, its subclasses) will sometimes
3914 be the right-hand child of a `js2-prop-get-node' or a
3915 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3916 The `js2-xml-ref-node' may also be a standalone primary expression with
3917 no explicit target, which is valid in certain expression contexts such as
3919 company..employee.(@id < 100)
3921 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3922 expression whose parent is a `js2-xml-dot-query-node'."
3927 (defsubst js2-xml-ref-node-attr-access-p (node)
3928 "Return non-nil if this expression began with an @-token."
3929 (and (numberp (js2-xml-ref-node-at-pos node))
3930 (plusp (js2-xml-ref-node-at-pos node))))
3932 (defstruct (js2-xml-prop-ref-node
3933 (:include js2-xml-ref-node)
3935 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3942 "AST node for an E4X XML [expr] property-ref expression.
3943 The JavaScript syntax is an optional @, an optional ns::, and a name.
3945 [ '@' ] [ name '::' ] name
3947 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3948 @ns::*, @*::attr, @*::*, and @*.
3950 The node starts at the @ token, if present. Otherwise it starts at the
3951 namespace name. The node bounds extend through the closing right-bracket,
3952 or if it is missing due to a syntax error, through the end of the index
3956 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3957 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3959 (defun js2-visit-xml-prop-ref-node (n v)
3960 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3961 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3963 (defun js2-print-xml-prop-ref-node (n i)
3964 (insert (js2-make-pad i))
3965 (if (js2-xml-ref-node-attr-access-p n)
3967 (when (js2-xml-prop-ref-node-namespace n)
3968 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3970 (if (js2-xml-prop-ref-node-propname n)
3971 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3973 (defstruct (js2-xml-elem-ref-node
3974 (:include js2-xml-ref-node)
3976 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3985 "AST node for an E4X XML [expr] member-ref expression.
3988 [ '@' ] [ name '::' ] '[' expr ']'
3990 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3992 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3993 is not a legal E4X XML element-ref expression, since it's already used
3994 for standard JavaScript element-get array indexing. Hence, a
3995 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3996 non-nil namespace node, or both.
3998 The node starts at the @ token, if present. Otherwise it starts
3999 at the namespace name. The node bounds extend through the closing
4000 right-bracket, or if it is missing due to a syntax error, through the
4001 end of the index expression."
4002 expr ; the bracketed index expression
4006 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4007 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4009 (defun js2-visit-xml-elem-ref-node (n v)
4010 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4011 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4013 (defun js2-print-xml-elem-ref-node (n i)
4014 (insert (js2-make-pad i))
4015 (if (js2-xml-ref-node-attr-access-p n)
4017 (when (js2-xml-elem-ref-node-namespace n)
4018 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4021 (if (js2-xml-elem-ref-node-expr n)
4022 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4025 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4027 (defstruct (js2-xml-start-tag-node
4028 (:include js2-xml-node)
4030 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4037 "AST node for an XML start-tag. Not currently used.
4038 The `kids' field is a lisp list of child content nodes."
4039 name ; a `js2-xml-name-node'
4040 attrs ; a lisp list of `js2-xml-attr-node'
4041 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4043 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4044 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4046 (defun js2-visit-xml-start-tag (n v)
4047 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4048 (dolist (attr (js2-xml-start-tag-node-attrs n))
4049 (js2-visit-ast attr v))
4050 (js2-visit-block n v))
4052 (defun js2-print-xml-start-tag (n i)
4053 (insert (js2-make-pad i) "<")
4054 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4055 (when (js2-xml-start-tag-node-attrs n)
4057 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4060 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4061 ;; and add the end-tag to the kids list of the parent as well.
4062 (defstruct (js2-xml-end-tag-node
4063 (:include js2-xml-node)
4065 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4069 "AST node for an XML end-tag. Not currently used."
4070 name) ; a `js2-xml-name-node'
4072 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4073 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4075 (defun js2-visit-xml-end-tag (n v)
4076 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4078 (defun js2-print-xml-end-tag (n i)
4079 (insert (js2-make-pad i))
4081 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4084 (defstruct (js2-xml-name-node
4085 (:include js2-xml-node)
4087 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4092 "AST node for an E4X XML name. Not currently used.
4093 Any XML name can be qualified with a namespace, hence the namespace field.
4094 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4095 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4096 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4097 namespace) ; a `js2-string-node'
4099 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4100 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4102 (defun js2-visit-xml-name-node (n v)
4103 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4105 (defun js2-print-xml-name-node (n i)
4106 (insert (js2-make-pad i))
4107 (when (js2-xml-name-node-namespace n)
4108 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4110 (dolist (kid (js2-xml-name-node-kids n))
4111 (js2-print-ast kid 0)))
4113 (defstruct (js2-xml-pi-node
4114 (:include js2-xml-node)
4116 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4121 "AST node for an E4X XML processing instruction. Not currently used."
4122 name ; a `js2-xml-name-node'
4123 attrs) ; a list of `js2-xml-attr-node'
4125 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4126 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4128 (defun js2-visit-xml-pi-node (n v)
4129 (js2-visit-ast (js2-xml-pi-node-name n) v)
4130 (dolist (attr (js2-xml-pi-node-attrs n))
4131 (js2-visit-ast attr v)))
4133 (defun js2-print-xml-pi-node (n i)
4134 (insert (js2-make-pad i) "<?")
4135 (js2-print-ast (js2-xml-pi-node-name n))
4136 (when (js2-xml-pi-node-attrs n)
4138 (js2-print-list (js2-xml-pi-node-attrs n)))
4141 (defstruct (js2-xml-cdata-node
4142 (:include js2-xml-node)
4144 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4148 "AST node for a CDATA escape section. Not currently used."
4149 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4151 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4152 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4154 (defun js2-visit-xml-cdata-node (n v)
4155 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4157 (defun js2-print-xml-cdata-node (n i)
4158 (insert (js2-make-pad i))
4159 (js2-print-ast (js2-xml-cdata-node-content n)))
4161 (defstruct (js2-xml-attr-node
4162 (:include js2-xml-node)
4164 (:constructor make-js2-attr-node (&key (type js2-XML)
4171 "AST node representing a foo='bar' XML attribute value. Not yet used."
4172 name ; a `js2-xml-name-node'
4173 value ; a `js2-xml-name-node'
4174 eq-pos ; buffer position of "=" sign
4175 quote-type) ; 'single or 'double
4177 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4178 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4180 (defun js2-visit-xml-attr-node (n v)
4181 (js2-visit-ast (js2-xml-attr-node-name n) v)
4182 (js2-visit-ast (js2-xml-attr-node-value n) v))
4184 (defun js2-print-xml-attr-node (n i)
4185 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4188 (insert (js2-make-pad i))
4189 (js2-print-ast (js2-xml-attr-node-name n) 0)
4191 (js2-print-ast (js2-xml-attr-node-value n) 0)
4194 (defstruct (js2-xml-text-node
4195 (:include js2-xml-node)
4197 (:constructor make-js2-text-node (&key (type js2-XML)
4201 "AST node for an E4X XML text node. Not currently used."
4202 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4204 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4205 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4207 (defun js2-visit-xml-text-node (n v)
4208 (js2-visit-ast (js2-xml-text-node-content n) v))
4210 (defun js2-print-xml-text-node (n i)
4211 (insert (js2-make-pad i))
4212 (dolist (kid (js2-xml-text-node-content n))
4213 (js2-print-ast kid)))
4215 (defstruct (js2-xml-comment-node
4216 (:include js2-xml-node)
4218 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4221 "AST node for E4X XML comment. Not currently used.")
4223 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4224 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4226 (defun js2-print-xml-comment (n i)
4227 (insert (js2-make-pad i)
4228 (js2-node-string n)))
4232 (defsubst js2-node-line (n)
4233 "Fetch the source line number at the start of node N.
4234 This is O(n) in the length of the source buffer; use prudently."
4235 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4237 (defsubst js2-block-node-kid (n i)
4238 "Return child I of node N, or nil if there aren't that many."
4239 (nth i (js2-block-node-kids n)))
4241 (defsubst js2-block-node-first (n)
4242 "Return first child of block node N, or nil if there is none."
4243 (first (js2-block-node-kids n)))
4245 (defun js2-node-root (n)
4246 "Return the root of the AST containing N.
4247 If N has no parent pointer, returns N."
4248 (let ((parent (js2-node-parent n)))
4250 (js2-node-root parent)
4253 (defun js2-node-position-in-parent (node &optional parent)
4254 "Return the position of NODE in parent's block-kids list.
4255 PARENT can be supplied if known. Positioned returned is zero-indexed.
4256 Returns 0 if NODE is not a child of a block statement, or if NODE
4257 is not a statement node."
4258 (let ((p (or parent (js2-node-parent node)))
4260 (if (not (js2-block-node-p p))
4262 (or (js2-position node (js2-block-node-kids p))
4265 (defsubst js2-node-short-name (n)
4266 "Return the short name of node N as a string, e.g. `js2-if-node'."
4267 (substring (symbol-name (aref n 0))
4268 (length "cl-struct-")))
4270 (defsubst js2-node-child-list (node)
4271 "Return the child list for NODE, a lisp list of nodes.
4272 Works for block nodes, array nodes, obj literals, funarg lists,
4273 var decls and try nodes (for catch clauses). Note that you should call
4274 `js2-block-node-kids' on the function body for the body statements.
4275 Returns nil for zero-length child lists or unsupported nodes."
4277 ((js2-function-node-p node)
4278 (js2-function-node-params node))
4279 ((js2-block-node-p node)
4280 (js2-block-node-kids node))
4281 ((js2-try-node-p node)
4282 (js2-try-node-catch-clauses node))
4283 ((js2-array-node-p node)
4284 (js2-array-node-elems node))
4285 ((js2-object-node-p node)
4286 (js2-object-node-elems node))
4287 ((js2-call-node-p node)
4288 (js2-call-node-args node))
4289 ((js2-new-node-p node)
4290 (js2-new-node-args node))
4291 ((js2-var-decl-node-p node)
4292 (js2-var-decl-node-kids node))
4296 (defsubst js2-node-set-child-list (node kids)
4297 "Set the child list for NODE to KIDS."
4299 ((js2-function-node-p node)
4300 (setf (js2-function-node-params node) kids))
4301 ((js2-block-node-p node)
4302 (setf (js2-block-node-kids node) kids))
4303 ((js2-try-node-p node)
4304 (setf (js2-try-node-catch-clauses node) kids))
4305 ((js2-array-node-p node)
4306 (setf (js2-array-node-elems node) kids))
4307 ((js2-object-node-p node)
4308 (setf (js2-object-node-elems node) kids))
4309 ((js2-call-node-p node)
4310 (setf (js2-call-node-args node) kids))
4311 ((js2-new-node-p node)
4312 (setf (js2-new-node-args node) kids))
4313 ((js2-var-decl-node-p node)
4314 (setf (js2-var-decl-node-kids node) kids))
4316 (error "Unsupported node type: %s" (js2-node-short-name node))))
4319 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4320 (defconst js2-paren-expr-nodes
4321 '(cl-struct-js2-array-comp-loop-node
4322 cl-struct-js2-array-comp-node
4323 cl-struct-js2-call-node
4324 cl-struct-js2-catch-node
4325 cl-struct-js2-do-node
4326 cl-struct-js2-elem-get-node
4327 cl-struct-js2-for-in-node
4328 cl-struct-js2-for-node
4329 cl-struct-js2-function-node
4330 cl-struct-js2-if-node
4331 cl-struct-js2-let-node
4332 cl-struct-js2-new-node
4333 cl-struct-js2-paren-node
4334 cl-struct-js2-switch-node
4335 cl-struct-js2-while-node
4336 cl-struct-js2-with-node
4337 cl-struct-js2-xml-dot-query-node)
4338 "Node types that can have a parenthesized child expression.
4339 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4341 (defsubst js2-paren-expr-node-p (node)
4342 "Return t for nodes that typically have a parenthesized child expression.
4343 Useful for computing the indentation anchors for arg-lists and conditions.
4344 Note that it may return a false positive, for instance when NODE is
4345 a `js2-new-node' and there are no arguments or parentheses."
4346 (memq (aref node 0) js2-paren-expr-nodes))
4348 ;; Fake polymorphism... yech.
4349 (defsubst js2-node-lp (node)
4350 "Return relative left-paren position for NODE, if applicable.
4351 For `js2-elem-get-node' structs, returns left-bracket position.
4352 Note that the position may be nil in the case of a parse error."
4354 ((js2-elem-get-node-p node)
4355 (js2-elem-get-node-lb node))
4356 ((js2-loop-node-p node)
4357 (js2-loop-node-lp node))
4358 ((js2-function-node-p node)
4359 (js2-function-node-lp node))
4360 ((js2-if-node-p node)
4361 (js2-if-node-lp node))
4362 ((js2-new-node-p node)
4363 (js2-new-node-lp node))
4364 ((js2-call-node-p node)
4365 (js2-call-node-lp node))
4366 ((js2-paren-node-p node)
4367 (js2-node-pos node))
4368 ((js2-switch-node-p node)
4369 (js2-switch-node-lp node))
4370 ((js2-catch-node-p node)
4371 (js2-catch-node-lp node))
4372 ((js2-let-node-p node)
4373 (js2-let-node-lp node))
4374 ((js2-array-comp-node-p node)
4375 (js2-array-comp-node-lp node))
4376 ((js2-with-node-p node)
4377 (js2-with-node-lp node))
4378 ((js2-xml-dot-query-node-p node)
4379 (1+ (js2-infix-node-op-pos node)))
4381 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4383 ;; Fake polymorphism... blech.
4384 (defsubst js2-node-rp (node)
4385 "Return relative right-paren position for NODE, if applicable.
4386 For `js2-elem-get-node' structs, returns right-bracket position.
4387 Note that the position may be nil in the case of a parse error."
4389 ((js2-elem-get-node-p node)
4390 (js2-elem-get-node-rb node))
4391 ((js2-loop-node-p node)
4392 (js2-loop-node-rp node))
4393 ((js2-function-node-p node)
4394 (js2-function-node-rp node))
4395 ((js2-if-node-p node)
4396 (js2-if-node-rp node))
4397 ((js2-new-node-p node)
4398 (js2-new-node-rp node))
4399 ((js2-call-node-p node)
4400 (js2-call-node-rp node))
4401 ((js2-paren-node-p node)
4402 (+ (js2-node-pos node) (js2-node-len node)))
4403 ((js2-switch-node-p node)
4404 (js2-switch-node-rp node))
4405 ((js2-catch-node-p node)
4406 (js2-catch-node-rp node))
4407 ((js2-let-node-p node)
4408 (js2-let-node-rp node))
4409 ((js2-array-comp-node-p node)
4410 (js2-array-comp-node-rp node))
4411 ((js2-with-node-p node)
4412 (js2-with-node-rp node))
4413 ((js2-xml-dot-query-node-p node)
4414 (1+ (js2-xml-dot-query-node-rp node)))
4416 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4418 (defsubst js2-node-first-child (node)
4419 "Returns the first element of `js2-node-child-list' for NODE."
4420 (car (js2-node-child-list node)))
4422 (defsubst js2-node-last-child (node)
4423 "Returns the last element of `js2-node-last-child' for NODE."
4424 (car (last (js2-node-child-list node))))
4426 (defun js2-node-prev-sibling (node)
4427 "Return the previous statement in parent.
4428 Works for parents supported by `js2-node-child-list'.
4429 Returns nil if NODE is not in the parent, or PARENT is
4430 not a supported node, or if NODE is the first child."
4431 (let* ((p (js2-node-parent node))
4432 (kids (js2-node-child-list p))
4435 (not (eq node (cadr kids))))
4436 (setq kids (cdr kids)
4440 (defun js2-node-next-sibling (node)
4441 "Return the next statement in parent block.
4442 Returns nil if NODE is not in the block, or PARENT is not
4443 a block node, or if NODE is the last statement."
4444 (let* ((p (js2-node-parent node))
4445 (kids (js2-node-child-list p)))
4447 (not (eq node (car kids))))
4448 (setq kids (cdr kids)))
4451 (defun js2-node-find-child-before (pos parent &optional after)
4452 "Find the last child that starts before POS in parent.
4453 If AFTER is non-nil, returns first child starting after POS.
4454 POS is an absolute buffer position. PARENT is any node
4455 supported by `js2-node-child-list'.
4456 Returns nil if no applicable child is found."
4457 (let ((kids (if (js2-function-node-p parent)
4458 (js2-block-node-kids (js2-function-node-body parent))
4459 (js2-node-child-list parent)))
4460 (beg (if (js2-function-node-p parent)
4461 (js2-node-abs-pos (js2-function-node-body parent))
4462 (js2-node-abs-pos parent)))
4467 (setq fn (if after '>= '<))
4468 (while (and kids continue)
4469 (setq kid (car kids))
4470 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4472 continue (if after nil t))
4473 (setq continue (if after t nil)))
4474 (setq kids (cdr kids)))
4477 (defun js2-node-find-child-after (pos parent)
4478 "Find first child that starts after POS in parent.
4479 POS is an absolute buffer position. PARENT is any node
4480 supported by `js2-node-child-list'.
4481 Returns nil if no applicable child is found."
4482 (js2-node-find-child-before pos parent 'after))
4484 (defun js2-node-replace-child (pos parent new-node)
4485 "Replace node at index POS in PARENT with NEW-NODE.
4486 Only works for parents supported by `js2-node-child-list'."
4487 (let ((kids (js2-node-child-list parent))
4490 (setq kids (cdr kids)
4492 (setcar kids new-node)
4493 (js2-node-add-children parent new-node)))
4495 (defun js2-node-buffer (n)
4496 "Return the buffer associated with AST N.
4497 Returns nil if the buffer is not set as a property on the root
4498 node, or if parent links were not recorded during parsing."
4499 (let ((root (js2-node-root n)))
4501 (js2-ast-root-p root)
4502 (js2-ast-root-buffer root))))
4504 (defsubst js2-block-node-push (n kid)
4505 "Push js2-node KID onto the end of js2-block-node N's child list.
4506 KID is always added to the -end- of the kids list.
4507 Function also calls `js2-node-add-children' to add the parent link."
4508 (let ((kids (js2-node-child-list n)))
4510 (setcdr kids (nconc (cdr kids) (list kid)))
4511 (js2-node-set-child-list n (list kid)))
4512 (js2-node-add-children n kid)))
4514 (defun js2-node-string (node)
4515 (let ((buf (js2-node-buffer node))
4518 (error "No buffer available for node %s" node))
4519 (with-current-buffer buf
4520 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4521 (+ pos (js2-node-len node))))))
4523 ;; Container for storing the node we're looking for in a traversal.
4524 (js2-deflocal js2-discovered-node nil)
4526 ;; Keep track of absolute node position during traversals.
4527 (js2-deflocal js2-visitor-offset nil)
4529 (js2-deflocal js2-node-search-point nil)
4531 (when js2-mode-dev-mode-p
4532 (defun js2-find-node-at-point ()
4534 (let ((node (js2-node-at-point)))
4535 (message "%s" (or node "No node found at point"))))
4536 (defun js2-node-name-at-point ()
4538 (let ((node (js2-node-at-point)))
4539 (message "%s" (if node
4540 (js2-node-short-name node)
4541 "No node found at point.")))))
4543 (defun js2-node-at-point (&optional pos skip-comments)
4544 "Return AST node at POS, a buffer position, defaulting to current point.
4545 The `js2-mode-ast' variable must be set to the current parse tree.
4546 Signals an error if the AST (`js2-mode-ast') is nil.
4547 Always returns a node - if it can't find one, it returns the root.
4548 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4549 (let ((ast js2-mode-ast)
4552 (error "No JavaScript AST available"))
4553 ;; Look through comments first, since they may be inside nodes that
4554 ;; would otherwise report a match.
4555 (setq pos (or pos (point))
4556 result (if (> pos (js2-node-abs-end ast))
4558 (if (not skip-comments)
4559 (js2-comment-at-point pos))))
4561 (setq js2-discovered-node nil
4562 js2-visitor-offset 0
4563 js2-node-search-point pos)
4565 (catch 'js2-visit-done
4566 (js2-visit-ast ast #'js2-node-at-point-visitor))
4567 (setq js2-visitor-offset nil
4568 js2-node-search-point nil))
4569 (setq result js2-discovered-node))
4570 ;; may have found a comment beyond end of last child node,
4571 ;; since visiting the ast-root looks at the comment-list last.
4572 (if (and skip-comments
4573 (js2-comment-node-p result))
4575 (or result js2-mode-ast)))
4577 (defun js2-node-at-point-visitor (node end-p)
4578 (let ((rel-pos (js2-node-pos node))
4581 (point js2-node-search-point))
4584 ;; this evaluates to a non-nil return value, even if it's zero
4585 (decf js2-visitor-offset rel-pos))
4586 ;; we already looked for comments before visiting, and don't want them now
4587 ((js2-comment-node-p node)
4590 (setq abs-pos (incf js2-visitor-offset rel-pos)
4591 ;; we only want to use the node if the point is before
4592 ;; the last character position in the node, so we decrement
4593 ;; the absolute end by 1.
4594 abs-end (+ abs-pos (js2-node-len node) -1))
4596 ;; If this node starts after search-point, stop the search.
4598 (throw 'js2-visit-done nil))
4599 ;; If this node ends before the search-point, don't check kids.
4603 ;; Otherwise point is within this node, possibly in a child.
4604 (setq js2-discovered-node node)
4605 t)))))) ; keep processing kids to look for more specific match
4607 (defsubst js2-block-comment-p (node)
4608 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4609 (and (js2-comment-node-p node)
4610 (memq (js2-comment-node-format node) '(jsdoc block))))
4612 ;; TODO: put the comments in a vector and binary-search them instead
4613 (defun js2-comment-at-point (&optional pos)
4614 "Look through scanned comment nodes for one containing POS.
4615 POS is a buffer position that defaults to current point.
4616 Function returns nil if POS was not in any comment node."
4617 (let ((ast js2-mode-ast)
4618 (x (or pos (point)))
4622 (error "No JavaScript AST available"))
4624 ;; Comments are stored in lexical order.
4625 (dolist (comment (js2-ast-root-comments ast) nil)
4626 (setq beg (js2-node-abs-pos comment)
4627 end (+ beg (js2-node-len comment)))
4630 (throw 'done comment))))))
4632 (defun js2-mode-find-parent-fn (node)
4633 "Find function enclosing NODE.
4634 Returns nil if NODE is not inside a function."
4635 (setq node (js2-node-parent node))
4636 (while (and node (not (js2-function-node-p node)))
4637 (setq node (js2-node-parent node)))
4638 (and (js2-function-node-p node) node))
4640 (defun js2-mode-find-enclosing-fn (node)
4641 "Find function or root enclosing NODE."
4642 (if (js2-ast-root-p node)
4644 (setq node (js2-node-parent node))
4645 (while (not (or (js2-ast-root-p node)
4646 (js2-function-node-p node)))
4647 (setq node (js2-node-parent node)))
4650 (defun js2-mode-find-enclosing-node (beg end)
4651 "Find script or function fully enclosing BEG and END."
4652 (let ((node (js2-node-at-point beg))
4656 (if (or (js2-ast-root-p node)
4657 (and (js2-function-node-p node)
4658 (<= (setq pos (js2-node-abs-pos node)) beg)
4659 (>= (+ pos (js2-node-len node)) end)))
4661 (setq node (js2-node-parent node))))
4664 (defun js2-node-parent-script-or-fn (node)
4665 "Find script or function immediately enclosing NODE.
4666 If NODE is the ast-root, returns nil."
4667 (if (js2-ast-root-p node)
4669 (setq node (js2-node-parent node))
4670 (while (and node (not (or (js2-function-node-p node)
4671 (js2-script-node-p node))))
4672 (setq node (js2-node-parent node)))
4675 (defsubst js2-nested-function-p (node)
4676 "Return t if NODE is a nested function, or is inside a nested function."
4677 (unless (js2-ast-root-p node)
4678 (js2-function-node-p (if (js2-function-node-p node)
4679 (js2-node-parent-script-or-fn node)
4680 (js2-node-parent-script-or-fn
4681 (js2-node-parent-script-or-fn node))))))
4683 (defsubst js2-function-param-node-p (node)
4684 "Return non-nil if NODE is a param node of a `js2-function-node'."
4685 (let ((parent (js2-node-parent node)))
4687 (js2-function-node-p parent)
4688 (memq node (js2-function-node-params parent)))))
4690 (defsubst js2-mode-shift-kids (kids start offset)
4692 (if (> (js2-node-pos kid) start)
4693 (incf (js2-node-pos kid) offset))))
4695 (defsubst js2-mode-shift-children (parent start offset)
4696 "Update start-positions of all children of PARENT beyond START."
4697 (let ((root (js2-node-root parent)))
4698 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4699 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4701 (defsubst js2-node-is-descendant (node ancestor)
4702 "Return t if NODE is a descendant of ANCESTOR."
4704 (not (eq node ancestor)))
4705 (setq node (js2-node-parent node)))
4708 ;;; visitor infrastructure
4710 (defun js2-visit-none (node callback)
4711 "Visitor for AST node that have no node children."
4714 (defun js2-print-none (node indent)
4715 "Visitor for AST node with no printed representation.")
4717 (defun js2-print-body (node indent)
4718 "Print a statement, or a block without braces."
4719 (if (js2-block-node-p node)
4720 (dolist (kid (js2-block-node-kids node))
4721 (js2-print-ast kid indent))
4722 (js2-print-ast node indent)))
4724 (defun js2-print-list (args &optional delimiter)
4725 (loop with len = (length args)
4729 (js2-print-ast arg 0)
4731 (insert (or delimiter ", ")))))
4733 (defun js2-print-tree (ast)
4734 "Prints an AST to the current buffer.
4735 Makes `js2-ast-parent-nodes' available to the printer functions."
4736 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4737 (js2-print-ast ast)))
4739 (defun js2-print-ast (node &optional indent)
4740 "Helper function for printing AST nodes.
4741 Requires `js2-ast-parent-nodes' to be non-nil.
4742 You should use `js2-print-tree' instead of this function."
4743 (let ((printer (get (aref node 0) 'js2-printer))
4745 (pos (js2-node-abs-pos node)))
4746 ;; TODO: wedge comments in here somewhere
4748 (funcall printer node i))))
4750 (defconst js2-side-effecting-tokens
4751 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4752 (dolist (tt (list js2-ASSIGN
4821 (if js2-instanceof-has-side-effects
4822 (aset tokens js2-INSTANCEOF t))
4825 (defun js2-node-has-side-effects (node)
4826 "Return t if NODE has side effects."
4827 (when node ; makes it easier to handle malformed expressions
4828 (let ((tt (js2-node-type node)))
4830 ;; This doubtless needs some work, since EXPR_VOID is used
4831 ;; in several ways in Rhino, and I may not have caught them all.
4832 ;; I'll wait for people to notice incorrect warnings.
4833 ((and (= tt js2-EXPR_VOID)
4834 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4835 (let ((expr (js2-expr-stmt-node-expr node)))
4836 (or (js2-node-has-side-effects expr)
4837 (when (js2-string-node-p expr)
4838 (string= "use strict" (js2-string-node-value expr))))))
4840 (js2-node-has-side-effects (js2-infix-node-right node)))
4843 (or (js2-node-has-side-effects (js2-infix-node-right node))
4844 (js2-node-has-side-effects (js2-infix-node-left node))))
4846 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4847 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4848 ((js2-paren-node-p node)
4849 (js2-node-has-side-effects (js2-paren-node-expr node)))
4850 ((= tt js2-ERROR) ; avoid cascaded error messages
4853 (aref js2-side-effecting-tokens tt))))))
4855 (defun js2-member-expr-leftmost-name (node)
4856 "For an expr such as foo.bar.baz, return leftmost node foo.
4857 NODE is any `js2-node' object. If it represents a member expression,
4858 which is any sequence of property gets, element-gets, function calls,
4859 or xml descendants/filter operators, then we look at the lexically
4860 leftmost (first) node in the chain. If it is a name-node we return it.
4861 Note that NODE can be a raw name-node and it will be returned as well.
4862 If NODE is not a name-node or member expression, or if it is a member
4863 expression whose leftmost target is not a name node, returns nil."
4866 (while (and continue (not result))
4868 ((js2-name-node-p node)
4870 ((js2-prop-get-node-p node)
4871 (setq node (js2-prop-get-node-left node)))
4872 ;; TODO: handle call-nodes, xml-nodes, others?
4874 (setq continue nil))))
4877 (defconst js2-stmt-node-types
4881 js2-DEFAULT ; e4x "default xml namespace" statement
4893 "Node types that only appear in statement contexts.
4894 The list does not include nodes that always appear as the child
4895 of another specific statement type, such as switch-cases,
4896 catch and finally blocks, and else-clauses. The list also excludes
4897 nodes like yield, let and var, which may appear in either expression
4898 or statement context, and in the latter context always have a
4899 `js2-expr-stmt-node' parent. Finally, the list does not include
4900 functions or scripts, which are treated separately from statements
4901 by the JavaScript parser and runtime.")
4903 (defun js2-stmt-node-p (node)
4904 "Heuristic for figuring out if NODE is a statement.
4905 Some node types can appear in either an expression context or a
4906 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4907 For these node types in a statement context, the parent will be a
4908 `js2-expr-stmt-node'.
4909 Functions aren't included in the check."
4910 (memq (js2-node-type node) js2-stmt-node-types))
4912 (defsubst js2-mode-find-first-stmt (node)
4913 "Search upward starting from NODE looking for a statement.
4914 For purposes of this function, a `js2-function-node' counts."
4915 (while (not (or (js2-stmt-node-p node)
4916 (js2-function-node-p node)))
4917 (setq node (js2-node-parent node)))
4920 (defun js2-node-parent-stmt (node)
4921 "Return the node's first ancestor that is a statement.
4922 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4923 appearing in a statement context will have a parent that is a
4924 `js2-expr-stmt-node' that will be returned by this function."
4925 (let ((parent (js2-node-parent node)))
4926 (if (or (null parent)
4927 (js2-stmt-node-p parent)
4928 (and (js2-function-node-p parent)
4929 (not (eq (js2-function-node-form parent)
4930 'FUNCTION_EXPRESSION))))
4932 (js2-node-parent-stmt parent))))
4934 ;; In the Mozilla Rhino sources, Roshan James writes:
4935 ;; Does consistent-return analysis on the function body when strict mode is
4938 ;; function (x) { return (x+1) }
4942 ;; function (x) { if (x < 0) return (x+1); }
4944 ;; is not because the function can potentially return a value when the
4945 ;; condition is satisfied and if not, the function does not explicitly
4948 ;; This extends to checking mismatches such as "return" and "return <value>"
4949 ;; used in the same function. Warnings are not emitted if inconsistent
4950 ;; returns exist in code that can be statically shown to be unreachable.
4952 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4954 ;; emits no warning. However if the loop had a break statement, then a
4955 ;; warning would be emitted.
4957 ;; The consistency analysis looks at control structures such as loops, ifs,
4958 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4959 ;; warns the user about an inconsistent set of termination possibilities.
4961 ;; These flags enumerate the possible ways a statement/function can
4962 ;; terminate. These flags are used by endCheck() and by the Parser to
4963 ;; detect inconsistent return usage.
4965 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4966 ;; able to execute (example: throw, continue)
4968 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4969 ;; next one. Statement such as return dont. A compound statement may have
4970 ;; some branch that drops off control to the next statement.
4972 ;; END_RETURNS indicates that the statement can return with no value.
4973 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4975 ;; A compound statement such as
4979 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4981 (defconst js2-END_UNREACHED 0)
4982 (defconst js2-END_DROPS_OFF 1)
4983 (defconst js2-END_RETURNS 2)
4984 (defconst js2-END_RETURNS_VALUE 4)
4985 (defconst js2-END_YIELDS 8)
4987 (defun js2-has-consistent-return-usage (node)
4988 "Check that every return usage in a function body is consistent.
4989 Returns t if the function satisfies strict mode requirement."
4990 (let ((n (js2-end-check node)))
4991 ;; either it doesn't return a value in any branch...
4992 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4993 ;; or it returns a value (or is unreached) at every branch
4994 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4998 (defun js2-end-check-if (node)
4999 "Returns in the then and else blocks must be consistent with each other.
5000 If there is no else block, then the return statement can fall through.
5001 Returns logical OR of END_* flags"
5002 (let ((th (js2-if-node-then-part node))
5003 (el (js2-if-node-else-part node)))
5006 (logior (js2-end-check th) (if el
5008 js2-END_DROPS_OFF)))))
5010 (defun js2-end-check-switch (node)
5011 "Consistency of return statements is checked between the case statements.
5012 If there is no default, then the switch can fall through. If there is a
5013 default, we check to see if all code paths in the default return or if
5014 there is a code path that can fall through.
5015 Returns logical OR of END_* flags."
5016 (let ((rv js2-END_UNREACHED)
5018 ;; examine the cases
5020 (dolist (c (js2-switch-node-cases node))
5021 (if (js2-case-node-expr c)
5022 (js2-set-flag rv (js2-end-check-block c))
5023 (setq default-case c)
5024 (throw 'break nil))))
5025 ;; we don't care how the cases drop into each other
5026 (js2-clear-flag rv js2-END_DROPS_OFF)
5027 ;; examine the default
5028 (js2-set-flag rv (if default-case
5029 (js2-end-check default-case)
5033 (defun js2-end-check-try (node)
5034 "If the block has a finally, return consistency is checked in the
5035 finally block. If all code paths in the finally return, then the
5036 returns in the try-catch blocks don't matter. If there is a code path
5037 that does not return or if there is no finally block, the returns
5038 of the try and catch blocks are checked for mismatch.
5039 Returns logical OR of END_* flags."
5040 (let ((finally (js2-try-node-finally-block node))
5042 ;; check the finally if it exists
5043 (setq rv (if finally
5044 (js2-end-check (js2-finally-node-body finally))
5046 ;; If the finally block always returns, then none of the returns
5047 ;; in the try or catch blocks matter.
5048 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5049 (js2-clear-flag rv js2-END_DROPS_OFF)
5050 ;; examine the try block
5051 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5052 ;; check each catch block
5053 (dolist (cb (js2-try-node-catch-clauses node))
5054 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5057 (defun js2-end-check-loop (node)
5058 "Return statement in the loop body must be consistent. The default
5059 assumption for any kind of a loop is that it will eventually terminate.
5060 The only exception is a loop with a constant true condition. Code that
5061 follows such a loop is examined only if one can statically determine
5062 that there is a break out of the loop.
5064 for(... ; ... ; ...) {}
5069 Returns logical OR of END_* flags."
5070 (let ((rv (js2-end-check (js2-loop-node-body node)))
5072 ((js2-while-node-p node)
5073 (js2-while-node-condition node))
5074 ((js2-do-node-p node)
5075 (js2-do-node-condition node))
5076 ((js2-for-node-p node)
5077 (js2-for-node-condition node)))))
5079 ;; check to see if the loop condition is always true
5081 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5082 (js2-clear-flag rv js2-END_DROPS_OFF))
5084 ;; look for effect of breaks
5085 (js2-set-flag rv (js2-node-get-prop node
5090 (defun js2-end-check-block (node)
5091 "A general block of code is examined statement by statement.
5092 If any statement (even a compound one) returns in all branches, then
5093 subsequent statements are not examined.
5094 Returns logical OR of END_* flags."
5095 (let* ((rv js2-END_DROPS_OFF)
5096 (kids (js2-block-node-kids node))
5098 ;; Check each statment. If the statement can continue onto the next
5099 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5100 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5101 (js2-clear-flag rv js2-END_DROPS_OFF)
5102 (js2-set-flag rv (js2-end-check n))
5103 (setq kids (cdr kids)
5107 (defun js2-end-check-label (node)
5108 "A labeled statement implies that there may be a break to the label.
5109 The function processes the labeled statement and then checks the
5110 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5112 Returns logical OR of END_* flags."
5113 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5114 (logior rv (js2-node-get-prop node
5116 js2-END_UNREACHED))))
5118 (defun js2-end-check-break (node)
5119 "When a break is encountered annotate the statement being broken
5120 out of by setting its CONTROL_BLOCK_PROP property.
5121 Returns logical OR of END_* flags."
5122 (and (js2-break-node-target node)
5123 (js2-node-set-prop (js2-break-node-target node)
5128 (defun js2-end-check (node)
5129 "Examine the body of a function, doing a basic reachability analysis.
5130 Returns a combination of flags END_* flags that indicate
5131 how the function execution can terminate. These constitute only the
5132 pessimistic set of termination conditions. It is possible that at
5133 runtime certain code paths will never be actually taken. Hence this
5134 analysis will flag errors in cases where there may not be errors.
5135 Returns logical OR of END_* flags"
5138 ((js2-break-node-p node)
5139 (js2-end-check-break node))
5140 ((js2-expr-stmt-node-p node)
5141 (if (setq kid (js2-expr-stmt-node-expr node))
5144 ((or (js2-continue-node-p node)
5145 (js2-throw-node-p node))
5147 ((js2-return-node-p node)
5148 (if (setq kid (js2-return-node-retval node))
5149 js2-END_RETURNS_VALUE
5151 ((js2-loop-node-p node)
5152 (js2-end-check-loop node))
5153 ((js2-switch-node-p node)
5154 (js2-end-check-switch node))
5155 ((js2-labeled-stmt-node-p node)
5156 (js2-end-check-label node))
5157 ((js2-if-node-p node)
5158 (js2-end-check-if node))
5159 ((js2-try-node-p node)
5160 (js2-end-check-try node))
5161 ((js2-block-node-p node)
5162 (if (null (js2-block-node-kids node))
5164 (js2-end-check-block node)))
5165 ((js2-yield-node-p node)
5168 js2-END_DROPS_OFF))))
5170 (defun js2-always-defined-boolean-p (node)
5171 "Check if NODE always evaluates to true or false in boolean context.
5172 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5174 (let ((tt (js2-node-type node))
5177 ((or (= tt js2-FALSE) (= tt js2-NULL))
5182 (setq num (js2-number-node-num-value node))
5183 (if (and (not (eq num 0.0e+NaN))
5190 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5191 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5193 (defvar js2-tokens nil
5194 "List of all defined token names.") ; initialized in `js2-token-names'
5196 (defconst js2-token-names
5197 (let* ((names (make-vector js2-num-tokens -1))
5198 (case-fold-search nil) ; only match js2-UPPER_CASE
5199 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5200 (loop for sym in syms
5203 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5205 (aset names (symbol-value sym) ; code, e.g. 152
5207 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5208 (push sym js2-tokens)))
5210 "Vector mapping int values to token string names, sans `js2-' prefix.")
5212 (defun js2-token-name (tok)
5213 "Return a string name for TOK, a token symbol or code.
5214 Signals an error if it's not a recognized token."
5217 (setq code (symbol-value tok)))
5220 (if (and (numberp code)
5222 (< code js2-num-tokens))
5223 (aref js2-token-names code)
5224 (error "Invalid token: %s" code)))))
5226 (defsubst js2-token-sym (tok)
5227 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5228 (intern (js2-token-name tok)))
5230 (defconst js2-token-codes
5231 (let ((table (make-hash-table :test 'eq :size 256)))
5232 (loop for name across js2-token-names
5233 for sym = (intern (concat "js2-" (upcase name)))
5235 (puthash sym (symbol-value sym) table))
5236 ;; clean up a few that are "wrong" in Rhino's token codes
5237 (puthash 'js2-DELETE js2-DELPROP table)
5239 "Hashtable mapping token symbols to their bytecodes.")
5241 (defsubst js2-token-code (sym)
5242 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5243 (or (gethash sym js2-token-codes)
5244 (error "Invalid token symbol: %s " sym))) ; signal code bug
5246 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5247 (setq js2-token-end js2-ts-cursor)
5248 (js2-report-error msg nil
5249 (or beg js2-token-beg)
5250 (or len (- js2-token-end js2-token-beg)))
5252 (throw 'return js2-ERROR)))
5254 (defsubst js2-get-string-from-buffer ()
5255 "Reverse the char accumulator and return it as a string."
5256 (setq js2-token-end js2-ts-cursor)
5257 (if js2-ts-string-buffer
5258 (apply #'string (nreverse js2-ts-string-buffer))
5261 ;; TODO: could potentially avoid a lot of consing by allocating a
5262 ;; char buffer the way Rhino does.
5263 (defsubst js2-add-to-string (c)
5264 (push c js2-ts-string-buffer))
5266 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5267 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5268 ;; any other character: when it's not part of the current token, we
5269 ;; unget it, allowing it to be read again by the following call.
5270 (defsubst js2-unget-char ()
5271 (decf js2-ts-cursor))
5273 ;; Rhino distinguishes \r and \n line endings. We don't need to
5274 ;; because we only scan from Emacs buffers, which always use \n.
5275 (defsubst js2-get-char ()
5276 "Read and return the next character from the input buffer.
5277 Increments `js2-ts-lineno' if the return value is a newline char.
5278 Updates `js2-ts-cursor' to the point after the returned char.
5279 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5280 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5282 ;; check for end of buffer
5283 (if (>= js2-ts-cursor (point-max))
5284 (setq js2-ts-hit-eof t
5285 js2-ts-cursor (1+ js2-ts-cursor)
5286 c js2-EOF_CHAR) ; return value
5287 ;; otherwise read next char
5288 (setq c (char-before (incf js2-ts-cursor)))
5289 ;; if we read a newline, update counters
5291 (setq js2-ts-line-start js2-ts-cursor
5292 js2-ts-lineno (1+ js2-ts-lineno)))
5293 ;; TODO: skip over format characters
5296 (defsubst js2-read-unicode-escape ()
5297 "Read a \\uNNNN sequence from the input.
5298 Assumes the ?\ and ?u have already been read.
5299 Returns the unicode character, or nil if it wasn't a valid character.
5300 Doesn't change the values of any scanner variables."
5301 ;; I really wish I knew a better way to do this, but I can't
5302 ;; find the Emacs function that takes a 16-bit int and converts
5303 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5304 ;; Have to first check that it's 4 hex characters or it may stop
5307 (let ((s (buffer-substring-no-properties js2-ts-cursor
5308 (+ 4 js2-ts-cursor))))
5309 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5310 (read (concat "?\\u" s))))))
5312 (defsubst js2-match-char (test)
5313 "Consume and return next character if it matches TEST, a character.
5314 Returns nil and consumes nothing if TEST is not the next character."
5315 (let ((c (js2-get-char)))
5321 (defsubst js2-peek-char ()
5326 (defsubst js2-java-identifier-start-p (c)
5329 (js2-char-uppercase-p c)
5330 (js2-char-lowercase-p c)))
5332 (defsubst js2-java-identifier-part-p (c)
5333 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5334 ;; TODO: make me Unicode-friendly. See comments above.
5337 (js2-char-uppercase-p c)
5338 (js2-char-lowercase-p c)
5339 (and (>= c ?0) (<= c ?9))))
5341 (defsubst js2-alpha-p (c)
5342 (cond ((and (<= ?A c) (<= c ?Z)) t)
5343 ((and (<= ?a c) (<= c ?z)) t)
5346 (defsubst js2-digit-p (c)
5347 (and (<= ?0 c) (<= c ?9)))
5349 (defsubst js2-js-space-p (c)
5351 (memq c '(#x20 #x9 #xB #xC #xD))
5354 ;; TODO: change this nil to check for Unicode space character
5357 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5359 (defsubst js2-skip-line ()
5360 "Skip to end of line"
5362 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5364 (setq js2-token-end js2-ts-cursor)))
5366 (defun js2-init-scanner (&optional buf line)
5367 "Create token stream for BUF starting on LINE.
5368 BUF defaults to current-buffer and line defaults to 1.
5370 A buffer can only have one scanner active at a time, which yields
5371 dramatically simpler code than using a defstruct. If you need to
5372 have simultaneous scanners in a buffer, copy the regions to scan
5377 (setq js2-ts-dirty-line nil
5378 js2-ts-regexp-flags nil
5383 js2-ts-lineno (or line 1)
5384 js2-ts-line-end-char -1
5385 js2-ts-cursor (point-min)
5386 js2-ts-is-xml-attribute nil
5387 js2-ts-xml-is-tag-content nil
5388 js2-ts-xml-open-tags-count 0
5389 js2-ts-string-buffer nil)))
5391 ;; This function uses the cached op, string and number fields in
5392 ;; TokenStream; if getToken has been called since the passed token
5393 ;; was scanned, the op or string printed may be incorrect.
5394 (defun js2-token-to-string (token)
5395 ;; Not sure where this function is used in Rhino. Not tested.
5396 (if (not js2-debug-print-trees)
5398 (let ((name (js2-token-name token)))
5400 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5401 (concat name " `" js2-ts-string "'"))
5402 ((eq token js2-NUMBER)
5403 (format "NUMBER %g" js2-ts-number))
5407 (defconst js2-keywords
5409 case catch const continue
5410 debugger default delete do
5412 false finally for function
5413 if in instanceof import
5418 this throw true try typeof
5423 ;; Token names aren't exactly the same as the keywords, unfortunately.
5424 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5425 (defconst js2-kwd-tokens
5426 (let ((table (make-vector js2-num-tokens nil))
5429 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5430 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5432 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5433 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5438 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5443 (aset table i 'font-lock-keyword-face))
5444 (aset table js2-STRING 'font-lock-string-face)
5445 (aset table js2-REGEXP 'font-lock-string-face)
5446 (aset table js2-COMMENT 'font-lock-comment-face)
5447 (aset table js2-THIS 'font-lock-builtin-face)
5448 (aset table js2-VOID 'font-lock-constant-face)
5449 (aset table js2-NULL 'font-lock-constant-face)
5450 (aset table js2-TRUE 'font-lock-constant-face)
5451 (aset table js2-FALSE 'font-lock-constant-face)
5453 "Vector whose values are non-nil for tokens that are keywords.
5454 The values are default faces to use for highlighting the keywords.")
5456 (defconst js2-reserved-words
5464 implements import int interface
5467 package private protected public
5468 short static super synchronized
5472 (defconst js2-keyword-names
5473 (let ((table (make-hash-table :test 'equal)))
5474 (loop for k in js2-keywords
5476 (symbol-name k) ; instanceof
5477 (intern (concat "js2-"
5478 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5481 "JavaScript keywords by name, mapped to their symbols.")
5483 (defconst js2-reserved-word-names
5484 (let ((table (make-hash-table :test 'equal)))
5485 (loop for k in js2-reserved-words
5487 (puthash (symbol-name k) 'js2-RESERVED table))
5489 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5491 (defsubst js2-collect-string (buf)
5492 "Convert BUF, a list of chars, to a string.
5493 Reverses BUF before converting."
5497 ((null buf) ; for emacs21 compat
5501 (apply #'string (nreverse buf))
5504 (defun js2-string-to-keyword (s)
5505 "Return token for S, a string, if S is a keyword or reserved word.
5506 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5507 (or (gethash s js2-keyword-names)
5508 (gethash s js2-reserved-word-names)))
5510 (defsubst js2-ts-set-char-token-bounds ()
5511 "Used when next token is one character."
5512 (setq js2-token-beg (1- js2-ts-cursor)
5513 js2-token-end js2-ts-cursor))
5515 (defsubst js2-ts-return (token)
5516 "Return an N-character TOKEN from `js2-get-token'.
5517 Updates `js2-token-end' accordingly."
5518 (setq js2-token-end js2-ts-cursor)
5519 (throw 'return token))
5521 (defsubst js2-x-digit-to-int (c accumulator)
5522 "Build up a hex number.
5523 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5524 corresponding number. Otherwise return -1."
5527 ;; Use 0..9 < A..Z < a..z
5532 (throw 'check nil)))
5536 (throw 'check nil)))
5540 (throw 'check nil))))
5542 (logior c (lsh accumulator 4))))
5544 (defun js2-get-token ()
5545 "Return next JavaScript token, an int such as js2-RETURN."
5549 is-unicode-escape-start
5563 ;; Eat whitespace, possibly sensitive to newlines.
5566 (setq c (js2-get-char))
5568 ((eq c js2-EOF_CHAR)
5569 (js2-ts-set-char-token-bounds)
5570 (throw 'return js2-EOF))
5572 (js2-ts-set-char-token-bounds)
5573 (setq js2-ts-dirty-line nil)
5574 (throw 'return js2-EOL))
5575 ((not (js2-js-space-p c))
5576 (if (/= c ?-) ; in case end of HTML comment
5577 (setq js2-ts-dirty-line t))
5578 (setq continue nil))))
5579 ;; Assume the token will be 1 char - fixed up below.
5580 (js2-ts-set-char-token-bounds)
5582 (throw 'return js2-XMLATTR))
5583 ;; identifier/keyword/instanceof?
5584 ;; watch out for starting with a <backslash>
5587 (setq c (js2-get-char))
5589 (setq identifier-start t
5590 is-unicode-escape-start t
5591 js2-ts-string-buffer nil)
5592 (setq identifier-start nil)
5596 (when (setq identifier-start (js2-java-identifier-start-p c))
5597 (setq js2-ts-string-buffer nil)
5598 (js2-add-to-string c))))
5599 (when identifier-start
5600 (setq contains-escape is-unicode-escape-start)
5603 (if is-unicode-escape-start
5604 ;; strictly speaking we should probably push-back
5605 ;; all the bad characters if the <backslash>uXXXX
5606 ;; sequence is malformed. But since there isn't a
5607 ;; correct context(is there?) for a bad Unicode
5608 ;; escape sequence in an identifier, we can report
5613 (setq c (js2-get-char)
5614 escape-val (js2-x-digit-to-int c escape-val))
5615 ;; Next check takes care of c < 0 and bad escape
5616 (if (minusp escape-val)
5617 (throw 'break nil)))
5618 (if (minusp escape-val)
5619 (js2-report-scan-error "msg.invalid.escape" t))
5620 (js2-add-to-string escape-val)
5621 (setq is-unicode-escape-start nil))
5622 (setq c (js2-get-char))
5625 (setq c (js2-get-char))
5627 (setq is-unicode-escape-start t
5629 (js2-report-scan-error "msg.illegal.character" t)))
5631 (if (or (eq c js2-EOF_CHAR)
5632 (not (js2-java-identifier-part-p c)))
5634 (js2-add-to-string c))))))
5636 (setq str (js2-get-string-from-buffer))
5637 (unless contains-escape
5638 ;; OPT we shouldn't have to make a string (object!) to
5639 ;; check if it's a keyword.
5640 ;; Return the corresponding token if it's a keyword
5641 (when (setq result (js2-string-to-keyword str))
5642 (if (and (< js2-language-version 170)
5643 (memq result '(js2-LET js2-YIELD)))
5644 ;; LET and YIELD are tokens only in 1.7 and later
5645 (setq result 'js2-NAME))
5646 (if (not (eq result 'js2-RESERVED))
5647 (throw 'return (js2-token-code result)))
5648 (js2-report-warning "msg.reserved.keyword" str)))
5649 ;; If we want to intern these as Rhino does, just use (intern str)
5650 (setq js2-ts-string str)
5651 (throw 'return js2-NAME)) ; end identifier/kwd check
5653 (when (or (js2-digit-p c)
5654 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5655 (setq js2-ts-string-buffer nil
5658 (setq c (js2-get-char))
5660 ((or (eq c ?x) (eq c ?X))
5662 (setq c (js2-get-char)))
5666 (js2-add-to-string ?0))))
5668 (while (<= 0 (js2-x-digit-to-int c 0))
5669 (js2-add-to-string c)
5670 (setq c (js2-get-char)))
5671 (while (and (<= ?0 c) (<= c ?9))
5672 ;; We permit 08 and 09 as decimal numbers, which
5673 ;; makes our behavior a superset of the ECMA
5674 ;; numeric grammar. We might not always be so
5675 ;; permissive, so we warn about it.
5676 (when (and (eq base 8) (>= c ?8))
5677 (js2-report-warning "msg.bad.octal.literal"
5678 (if (eq c ?8) "8" "9"))
5680 (js2-add-to-string c)
5681 (setq c (js2-get-char))))
5683 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5684 (setq is-integer nil)
5687 (js2-add-to-string c)
5688 (setq c (js2-get-char))
5689 while (js2-digit-p c)))
5690 (when (memq c '(?e ?E))
5691 (js2-add-to-string c)
5692 (setq c (js2-get-char))
5693 (when (memq c '(?+ ?-))
5694 (js2-add-to-string c)
5695 (setq c (js2-get-char)))
5696 (unless (js2-digit-p c)
5697 (js2-report-scan-error "msg.missing.exponent" t))
5699 (js2-add-to-string c)
5700 (setq c (js2-get-char))
5701 while (js2-digit-p c))))
5703 (setq js2-ts-string (js2-get-string-from-buffer)
5705 (if (and (eq base 10) (not is-integer))
5706 (string-to-number js2-ts-string)
5707 ;; TODO: call runtime number-parser. Some of it is in
5708 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5709 (string-to-number js2-ts-string)))
5710 (throw 'return js2-NUMBER))
5712 (when (memq c '(?\" ?\'))
5713 ;; We attempt to accumulate a string the fast way, by
5714 ;; building it directly out of the reader. But if there
5715 ;; are any escaped characters in the string, we revert to
5716 ;; building it out of a string buffer.
5718 js2-ts-string-buffer nil
5721 (while (/= c quote-char)
5723 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5725 (setq js2-token-end js2-ts-cursor)
5726 (js2-report-error "msg.unterminated.string.lit")
5727 (throw 'return js2-STRING))
5729 ;; We've hit an escaped character
5730 (setq c (js2-get-char))
5739 (setq c1 (js2-read-unicode-escape))
5740 (if js2-parse-ide-mode
5743 ;; just copy the string in IDE-mode
5744 (js2-add-to-string ?\\)
5745 (js2-add-to-string ?u)
5747 (js2-add-to-string (js2-get-char)))
5748 (setq c (js2-get-char))) ; added at end of loop
5749 ;; flag it as an invalid escape
5750 (js2-report-warning "msg.invalid.escape"
5751 nil (- js2-ts-cursor 2) 6))
5752 ;; Get 4 hex digits; if the u escape is not
5753 ;; followed by 4 hex digits, use 'u' + the
5754 ;; literal character sequence that follows.
5755 (js2-add-to-string ?u)
5758 (setq c (js2-get-char)
5759 escape-val (js2-x-digit-to-int c escape-val))
5760 (if (minusp escape-val)
5761 (throw 'continue nil))
5762 (js2-add-to-string c))
5763 ;; prepare for replace of stored 'u' sequence by escape value
5764 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5767 ;; Get 2 hex digits, defaulting to 'x'+literal
5768 ;; sequence, as above.
5769 (setq c (js2-get-char)
5770 escape-val (js2-x-digit-to-int c 0))
5771 (if (minusp escape-val)
5773 (js2-add-to-string ?x)
5774 (throw 'continue nil))
5777 escape-val (js2-x-digit-to-int c escape-val))
5778 (if (minusp escape-val)
5780 (js2-add-to-string ?x)
5781 (js2-add-to-string c1)
5782 (throw 'continue nil))
5784 (setq c escape-val))))
5786 ;; Remove line terminator after escape to follow
5787 ;; SpiderMonkey and C/C++
5788 (setq c (js2-get-char))
5789 (throw 'continue nil))
5791 (when (and (<= ?0 c) (< c ?8))
5794 (when (and (<= ?0 c) (< c ?8))
5795 (setq val (- (+ (* 8 val) c) ?0)
5797 (when (and (<= ?0 c)
5800 ;; c is 3rd char of octal sequence only
5801 ;; if the resulting val <= 0377
5802 (setq val (- (+ (* 8 val) c) ?0)
5806 (js2-add-to-string c)
5807 (setq c (js2-get-char)))))
5808 (setq js2-ts-string (js2-get-string-from-buffer))
5809 (throw 'return js2-STRING))
5812 (throw 'return js2-SEMI))
5814 (throw 'return js2-LB))
5816 (throw 'return js2-RB))
5818 (throw 'return js2-LC))
5820 (throw 'return js2-RC))
5822 (throw 'return js2-LP))
5824 (throw 'return js2-RP))
5826 (throw 'return js2-COMMA))
5828 (throw 'return js2-HOOK))
5830 (if (js2-match-char ?:)
5831 (js2-ts-return js2-COLONCOLON)
5832 (throw 'return js2-COLON)))
5834 (if (js2-match-char ?.)
5835 (if (js2-match-char ?.)
5836 (js2-ts-return js2-TRIPLEDOT)
5837 (js2-ts-return js2-DOTDOT))
5838 (if (js2-match-char ?\()
5839 (js2-ts-return js2-DOTQUERY)
5840 (throw 'return js2-DOT))))
5842 (if (js2-match-char ?|)
5843 (throw 'return js2-OR)
5844 (if (js2-match-char ?=)
5845 (js2-ts-return js2-ASSIGN_BITOR)
5846 (throw 'return js2-BITOR))))
5848 (if (js2-match-char ?=)
5849 (js2-ts-return js2-ASSIGN_BITOR)
5850 (throw 'return js2-BITXOR)))
5852 (if (js2-match-char ?&)
5853 (throw 'return js2-AND)
5854 (if (js2-match-char ?=)
5855 (js2-ts-return js2-ASSIGN_BITAND)
5856 (throw 'return js2-BITAND))))
5858 (if (js2-match-char ?=)
5859 (if (js2-match-char ?=)
5860 (js2-ts-return js2-SHEQ)
5861 (throw 'return js2-EQ))
5862 (throw 'return js2-ASSIGN)))
5864 (if (js2-match-char ?=)
5865 (if (js2-match-char ?=)
5866 (js2-ts-return js2-SHNE)
5867 (js2-ts-return js2-NE))
5868 (throw 'return js2-NOT)))
5870 ;; NB:treat HTML begin-comment as comment-till-eol
5871 (when (js2-match-char ?!)
5872 (when (js2-match-char ?-)
5873 (when (js2-match-char ?-)
5875 (setq js2-ts-comment-type 'html)
5876 (throw 'return js2-COMMENT)))
5878 (if (js2-match-char ?<)
5879 (if (js2-match-char ?=)
5880 (js2-ts-return js2-ASSIGN_LSH)
5881 (js2-ts-return js2-LSH))
5882 (if (js2-match-char ?=)
5883 (js2-ts-return js2-LE)
5884 (throw 'return js2-LT))))
5886 (if (js2-match-char ?>)
5887 (if (js2-match-char ?>)
5888 (if (js2-match-char ?=)
5889 (js2-ts-return js2-ASSIGN_URSH)
5890 (js2-ts-return js2-URSH))
5891 (if (js2-match-char ?=)
5892 (js2-ts-return js2-ASSIGN_RSH)
5893 (js2-ts-return js2-RSH)))
5894 (if (js2-match-char ?=)
5895 (js2-ts-return js2-GE)
5896 (throw 'return js2-GT))))
5898 (if (js2-match-char ?=)
5899 (js2-ts-return js2-ASSIGN_MUL)
5900 (throw 'return js2-MUL)))
5902 ;; is it a // comment?
5903 (when (js2-match-char ?/)
5904 (setq js2-token-beg (- js2-ts-cursor 2))
5906 (setq js2-ts-comment-type 'line)
5907 ;; include newline so highlighting goes to end of window
5908 (incf js2-token-end)
5909 (throw 'return js2-COMMENT))
5910 ;; is it a /* comment?
5911 (when (js2-match-char ?*)
5912 (setq look-for-slash nil
5913 js2-token-beg (- js2-ts-cursor 2)
5915 (if (js2-match-char ?*)
5917 (setq look-for-slash t)
5921 (setq c (js2-get-char))
5923 ((eq c js2-EOF_CHAR)
5924 (setq js2-token-end (1- js2-ts-cursor))
5925 (js2-report-error "msg.unterminated.comment")
5926 (throw 'return js2-COMMENT))
5928 (setq look-for-slash t))
5931 (js2-ts-return js2-COMMENT)))
5933 (setq look-for-slash nil
5934 js2-token-end js2-ts-cursor)))))
5935 (if (js2-match-char ?=)
5936 (js2-ts-return js2-ASSIGN_DIV)
5937 (throw 'return js2-DIV)))
5939 (when js2-skip-preprocessor-directives
5941 (setq js2-ts-comment-type 'preprocessor
5942 js2-token-end js2-ts-cursor)
5943 (throw 'return js2-COMMENT))
5944 (throw 'return js2-ERROR))
5946 (if (js2-match-char ?=)
5947 (js2-ts-return js2-ASSIGN_MOD)
5948 (throw 'return js2-MOD)))
5950 (throw 'return js2-BITNOT))
5952 (if (js2-match-char ?=)
5953 (js2-ts-return js2-ASSIGN_ADD)
5954 (if (js2-match-char ?+)
5955 (js2-ts-return js2-INC)
5956 (throw 'return js2-ADD))))
5959 ((js2-match-char ?=)
5960 (setq c js2-ASSIGN_SUB))
5961 ((js2-match-char ?-)
5962 (unless js2-ts-dirty-line
5963 ;; treat HTML end-comment after possible whitespace
5964 ;; after line start as comment-until-eol
5965 (when (js2-match-char ?>)
5967 (setq js2-ts-comment-type 'html)
5968 (throw 'return js2-COMMENT)))
5972 (setq js2-ts-dirty-line t)
5975 (js2-report-scan-error "msg.illegal.character")))))))
5977 (defun js2-read-regexp (start-token)
5978 "Called by parser when it gets / or /= in literal context."
5981 in-class ; inside a '[' .. ']' character-class
5984 (setq js2-token-beg js2-ts-cursor
5985 js2-ts-string-buffer nil
5986 js2-ts-regexp-flags nil)
5987 (if (eq start-token js2-ASSIGN_DIV)
5989 (js2-add-to-string ?=)
5990 (if (not (eq start-token js2-DIV))
5991 (error "failed assertion")))
5992 (while (and (not err)
5993 (or (/= (setq c (js2-get-char)) ?/)
5998 (setq js2-token-end (1- js2-ts-cursor)
6000 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6001 (js2-report-error "msg.unterminated.re.lit"))
6004 (js2-add-to-string c)
6005 (setq c (js2-get-char)))
6009 (setq in-class nil)))
6010 (js2-add-to-string c))))
6014 ((js2-match-char ?g)
6016 ((js2-match-char ?i)
6018 ((js2-match-char ?m)
6021 (setq continue nil))))
6022 (if (js2-alpha-p (js2-peek-char))
6023 (js2-report-scan-error "msg.invalid.re.flag" t
6025 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6026 js2-ts-regexp-flags (js2-collect-string flags)
6027 js2-token-end js2-ts-cursor)
6028 ;; tell `parse-partial-sexp' to ignore this range of chars
6029 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6031 (defun js2-get-first-xml-token ()
6032 (setq js2-ts-xml-open-tags-count 0
6033 js2-ts-is-xml-attribute nil
6034 js2-ts-xml-is-tag-content nil)
6036 (js2-get-next-xml-token))
6038 (defsubst js2-xml-discard-string ()
6039 "Throw away the string in progress and flag an XML parse error."
6040 (setq js2-ts-string-buffer nil
6042 (js2-report-scan-error "msg.XML.bad.form" t))
6044 (defun js2-get-next-xml-token ()
6045 (setq js2-ts-string-buffer nil ; for recording the XML
6046 js2-token-beg js2-ts-cursor)
6051 (setq c (js2-get-char))
6054 (throw 'return js2-ERROR))
6055 (js2-ts-xml-is-tag-content
6058 (js2-add-to-string c)
6059 (setq js2-ts-xml-is-tag-content nil
6060 js2-ts-is-xml-attribute nil))
6062 (js2-add-to-string c)
6063 (when (eq ?> (js2-peek-char))
6064 (setq c (js2-get-char))
6065 (js2-add-to-string c)
6066 (setq js2-ts-xml-is-tag-content nil)
6067 (decf js2-ts-xml-open-tags-count)))
6070 (setq js2-ts-string (js2-get-string-from-buffer))
6071 (throw 'return js2-XML))
6073 (js2-add-to-string c)
6074 (unless (js2-read-quoted-string c)
6075 (throw 'return js2-ERROR)))
6077 (js2-add-to-string c)
6078 (setq js2-ts-is-xml-attribute t))
6080 (js2-add-to-string c))
6082 (js2-add-to-string c)
6083 (setq js2-ts-is-xml-attribute nil)))
6084 (when (and (not js2-ts-xml-is-tag-content)
6085 (zerop js2-ts-xml-open-tags-count))
6086 (setq js2-ts-string (js2-get-string-from-buffer))
6087 (throw 'return js2-XMLEND)))
6089 ;; else not tag content
6092 (js2-add-to-string c)
6093 (setq c (js2-peek-char))
6096 (setq c (js2-get-char)) ;; skip !
6097 (js2-add-to-string c)
6098 (setq c (js2-peek-char))
6101 (setq c (js2-get-char)) ;; skip -
6102 (js2-add-to-string c)
6105 (js2-add-to-string c)
6106 (unless (js2-read-xml-comment)
6107 (throw 'return js2-ERROR)))
6108 (js2-xml-discard-string)
6109 (throw 'return js2-ERROR)))
6111 (setq c (js2-get-char)) ;; skip [
6112 (js2-add-to-string c)
6113 (if (and (= (js2-get-char) ?C)
6114 (= (js2-get-char) ?D)
6115 (= (js2-get-char) ?A)
6116 (= (js2-get-char) ?T)
6117 (= (js2-get-char) ?A)
6118 (= (js2-get-char) ?\[))
6120 (js2-add-to-string ?C)
6121 (js2-add-to-string ?D)
6122 (js2-add-to-string ?A)
6123 (js2-add-to-string ?T)
6124 (js2-add-to-string ?A)
6125 (js2-add-to-string ?\[)
6126 (unless (js2-read-cdata)
6127 (throw 'return js2-ERROR)))
6128 (js2-xml-discard-string)
6129 (throw 'return js2-ERROR)))
6131 (unless (js2-read-entity)
6132 (throw 'return js2-ERROR))))
6133 ;; allow bare CDATA section
6134 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6135 (when (zerop js2-ts-xml-open-tags-count)
6136 (throw 'return js2-XMLEND)))
6138 (setq c (js2-get-char)) ;; skip ?
6139 (js2-add-to-string c)
6140 (unless (js2-read-PI)
6141 (throw 'return js2-ERROR)))
6144 (setq c (js2-get-char)) ;; skip /
6145 (js2-add-to-string c)
6146 (when (zerop js2-ts-xml-open-tags-count)
6147 (js2-xml-discard-string)
6148 (throw 'return js2-ERROR))
6149 (setq js2-ts-xml-is-tag-content t)
6150 (decf js2-ts-xml-open-tags-count))
6153 (setq js2-ts-xml-is-tag-content t)
6154 (incf js2-ts-xml-open-tags-count))))
6157 (setq js2-ts-string (js2-get-string-from-buffer))
6158 (throw 'return js2-XML))
6160 (js2-add-to-string c))))))))
6161 (setq js2-token-end js2-ts-cursor)
6164 (defun js2-read-quoted-string (quote)
6167 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6168 (js2-add-to-string c)
6171 (js2-xml-discard-string) ;; throw away string in progress
6174 (defun js2-read-xml-comment ()
6175 (let ((c (js2-get-char)))
6177 (while (/= c js2-EOF_CHAR)
6179 (js2-add-to-string c)
6180 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6181 (setq c (js2-get-char))
6182 (js2-add-to-string c)
6183 (if (eq (js2-peek-char) ?>)
6185 (setq c (js2-get-char)) ;; skip >
6186 (js2-add-to-string c)
6188 (throw 'continue nil)))
6189 (setq c (js2-get-char))))
6190 (js2-xml-discard-string)
6193 (defun js2-read-cdata ()
6194 (let ((c (js2-get-char)))
6196 (while (/= c js2-EOF_CHAR)
6198 (js2-add-to-string c)
6199 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6200 (setq c (js2-get-char))
6201 (js2-add-to-string c)
6202 (if (eq (js2-peek-char) ?>)
6204 (setq c (js2-get-char)) ;; Skip >
6205 (js2-add-to-string c)
6207 (throw 'continue nil)))
6208 (setq c (js2-get-char))))
6209 (js2-xml-discard-string)
6212 (defun js2-read-entity ()
6216 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6217 (js2-add-to-string c)
6223 (if (zerop decl-tags)
6224 (throw 'return t)))))
6225 (js2-xml-discard-string)
6228 (defun js2-read-PI ()
6229 "Scan an XML processing instruction."
6232 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6233 (js2-add-to-string c)
6234 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6235 (setq c (js2-get-char)) ;; Skip >
6236 (js2-add-to-string c)
6238 (js2-xml-discard-string)
6241 (defun js2-scanner-get-line ()
6242 "Return the text of the current scan line."
6243 (buffer-substring (point-at-bol) (point-at-eol)))
6247 (defsubst js2-set-face (beg end face &optional record)
6248 "Fontify a region. If RECORD is non-nil, record for later."
6249 (when (plusp js2-highlight-level)
6250 (setq beg (min (point-max) beg)
6251 beg (max (point-min) beg)
6252 end (min (point-max) end)
6253 end (max (point-min) end))
6255 (push (list beg end face) js2-mode-fontifications)
6256 (put-text-property beg end 'font-lock-face face))))
6258 (defsubst js2-set-kid-face (pos kid len face)
6259 "Set-face on a child node.
6260 POS is absolute buffer position of parent.
6261 KID is the child node.
6262 LEN is the length to fontify.
6263 FACE is the face to fontify with."
6264 (js2-set-face (+ pos (js2-node-pos kid))
6265 (+ pos (js2-node-pos kid) (js2-node-len kid))
6268 (defsubst js2-fontify-kwd (start length)
6269 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6271 (defsubst js2-clear-face (beg end)
6272 (remove-text-properties beg end '(font-lock-face nil
6277 (defconst js2-ecma-global-props
6280 '("Infinity" "NaN" "undefined" "arguments") t)
6282 "Value properties of the Ecma-262 Global Object.
6283 Shown at or above `js2-highlight-level' 2.")
6285 ;; might want to add the name "arguments" to this list?
6286 (defconst js2-ecma-object-props
6289 '("prototype" "__proto__" "__parent__") t)
6291 "Value properties of the Ecma-262 Object constructor.
6292 Shown at or above `js2-highlight-level' 2.")
6294 (defconst js2-ecma-global-funcs
6298 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6299 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6301 "Function properties of the Ecma-262 Global object.
6302 Shown at or above `js2-highlight-level' 2.")
6304 (defconst js2-ecma-number-props
6306 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6308 "POSITIVE_INFINITY") t)
6310 "Properties of the Ecma-262 Number constructor.
6311 Shown at or above `js2-highlight-level' 2.")
6313 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6314 "Properties of the Ecma-262 Date constructor.
6315 Shown at or above `js2-highlight-level' 2.")
6317 (defconst js2-ecma-math-props
6320 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6323 "Properties of the Ecma-262 Math object.
6324 Shown at or above `js2-highlight-level' 2.")
6326 (defconst js2-ecma-math-funcs
6329 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6330 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6332 "Function properties of the Ecma-262 Math object.
6333 Shown at or above `js2-highlight-level' 2.")
6335 (defconst js2-ecma-function-props
6339 '(;; properties of the Object prototype object
6340 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6341 "toLocaleString" "toString" "valueOf"
6342 ;; properties of the Function prototype object
6344 ;; properties of the Array prototype object
6345 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6347 ;; properties of the String prototype object
6348 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6349 "localeCompare" "match" "replace" "search" "split" "substring"
6350 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6352 ;; properties of the Number prototype object
6353 "toExponential" "toFixed" "toPrecision"
6354 ;; properties of the Date prototype object
6355 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6356 "getMinutes" "getMonth" "getSeconds" "getTime"
6357 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6358 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6359 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6360 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6361 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6362 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6363 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6364 "toTimeString" "toUTCString"
6365 ;; properties of the RegExp prototype object
6367 ;; properties of the JSON prototype object
6369 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6370 "toSource" "__defineGetter__" "__defineSetter__"
6371 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6372 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6375 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6376 Shown at or above `js2-highlight-level' 3.")
6378 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6379 (let ((target-name (and target
6380 (js2-name-node-p target)
6381 (js2-name-node-name target)))
6382 (prop-name (if prop (js2-name-node-name prop)))
6383 (level1 (>= js2-highlight-level 1))
6384 (level2 (>= js2-highlight-level 2))
6385 (level3 (>= js2-highlight-level 3))
6393 ((and level3 (string-match js2-ecma-function-props prop-name))
6394 (setq face 'font-lock-builtin-face))
6395 ((and target-name prop)
6397 ((string= target-name "Date")
6398 (if (string-match js2-ecma-date-props prop-name)
6399 (setq face 'font-lock-builtin-face)))
6400 ((string= target-name "Math")
6401 (if (string-match js2-ecma-math-funcs prop-name)
6402 (setq face 'font-lock-builtin-face)))))))
6404 (if (string-match js2-ecma-global-funcs prop-name)
6405 (setq face 'font-lock-builtin-face))))
6409 ((string= target-name "Number")
6410 (if (string-match js2-ecma-number-props prop-name)
6411 (setq face 'font-lock-constant-face)))
6412 ((string= target-name "Math")
6413 (if (string-match js2-ecma-math-props prop-name)
6414 (setq face 'font-lock-constant-face)))))
6416 (if (string-match js2-ecma-object-props prop-name)
6417 (setq face 'font-lock-constant-face)))))
6419 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6420 (js2-node-pos prop))) ; relative
6421 (+ pos (js2-node-len prop))
6424 (defun js2-parse-highlight-member-expr-node (node)
6425 "Perform syntax highlighting of EcmaScript built-in properties.
6426 The variable `js2-highlight-level' governs this highighting."
6427 (let (face target prop name pos end parent call-p callee)
6429 ;; case 1: simple name, e.g. foo
6430 ((js2-name-node-p node)
6431 (setq name (js2-name-node-name node))
6432 ;; possible for name to be nil in rare cases - saw it when
6433 ;; running js2-mode on an elisp buffer. Might as well try to
6434 ;; make it so js2-mode never barfs.
6436 (setq face (if (string-match js2-ecma-global-props name)
6437 'font-lock-constant-face))
6439 (setq pos (js2-node-pos node)
6440 end (+ pos (js2-node-len node)))
6441 (js2-set-face pos end face 'record))))
6442 ;; case 2: property access or function call
6443 ((or (js2-prop-get-node-p node)
6444 ;; highlight function call if expr is a prop-get node
6445 ;; or a plain name (i.e. unqualified function call)
6446 (and (setq call-p (js2-call-node-p node))
6447 (setq callee (js2-call-node-target node)) ; separate setq!
6448 (or (js2-prop-get-node-p callee)
6449 (js2-name-node-p callee))))
6451 node (if call-p callee node))
6452 (if (and call-p (js2-name-node-p callee))
6454 (setq target (js2-prop-get-node-left node)
6455 prop (js2-prop-get-node-right node)))
6457 ((js2-name-node-p target)
6458 (if (js2-name-node-p prop)
6459 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6460 (js2-parse-highlight-prop-get parent target prop call-p)
6461 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6462 (js2-parse-highlight-prop-get parent target nil call-p)))
6463 ((js2-name-node-p prop)
6464 ;; case 2c: complex target, simple name, e.g. x[y].bar
6465 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6467 (defun js2-parse-highlight-member-expr-fn-name (expr)
6468 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6469 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6470 We currently only handle the case where the last component is a prop-get
6471 of a simple name. Called before EXPR has a parent node."
6473 (name (and (js2-prop-get-node-p expr)
6474 (js2-prop-get-node-right expr))))
6475 (when (js2-name-node-p name)
6476 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6477 (js2-node-pos name)))
6478 (+ pos (js2-node-len name))
6479 'font-lock-function-name-face
6482 ;; source: http://jsdoc.sourceforge.net/
6483 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6484 ;; allows type specifications, and needs work before entering the wild.
6486 (defconst js2-jsdoc-param-tag-regexp
6487 (concat "^\\s-*\\*+\\s-*\\(@"
6488 "\\(?:param\\|argument\\)"
6490 "\\s-*\\({[^}]+}\\)?" ; optional type
6491 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6493 "Matches jsdoc tags with optional type and optional param name.")
6495 (defconst js2-jsdoc-typed-tag-regexp
6496 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6510 "\\)\\)\\s-*\\({[^}]+}\\)?")
6511 "Matches jsdoc tags with optional type.")
6513 (defconst js2-jsdoc-arg-tag-regexp
6514 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6537 "\\)\\)\\s-+\\([^ \t]+\\)")
6538 "Matches jsdoc tags with a single argument.")
6540 (defconst js2-jsdoc-empty-tag-regexp
6541 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6581 "Matches empty jsdoc tags.")
6583 (defconst js2-jsdoc-link-tag-regexp
6584 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6585 "Matches a jsdoc link or code tag.")
6587 (defconst js2-jsdoc-see-tag-regexp
6588 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6589 "Matches a jsdoc @see tag.")
6591 (defconst js2-jsdoc-html-tag-regexp
6592 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6593 "Matches a simple (no attributes) html start- or end-tag.")
6595 (defsubst js2-jsdoc-highlight-helper ()
6596 (js2-set-face (match-beginning 1)
6598 'js2-jsdoc-tag-face)
6599 (if (match-beginning 2)
6601 (goto-char (match-beginning 2))
6602 (= (char-after) ?{))
6603 (js2-set-face (1+ (match-beginning 2))
6605 'js2-jsdoc-type-face)
6606 (js2-set-face (match-beginning 2)
6608 'js2-jsdoc-value-face)))
6609 (if (match-beginning 3)
6610 (js2-set-face (match-beginning 3)
6612 'js2-jsdoc-value-face)))
6614 (defun js2-highlight-jsdoc (ast)
6615 "Highlight doc comment tags."
6616 (let ((comments (js2-ast-root-comments ast))
6619 (dolist (node comments)
6620 (when (eq (js2-comment-node-format node) 'jsdoc)
6621 (setq beg (js2-node-abs-pos node)
6622 end (+ beg (js2-node-len node)))
6624 (narrow-to-region beg end)
6625 (dolist (re (list js2-jsdoc-param-tag-regexp
6626 js2-jsdoc-typed-tag-regexp
6627 js2-jsdoc-arg-tag-regexp
6628 js2-jsdoc-link-tag-regexp
6629 js2-jsdoc-see-tag-regexp
6630 js2-jsdoc-empty-tag-regexp))
6632 (while (re-search-forward re nil t)
6633 (js2-jsdoc-highlight-helper)))
6634 ;; simple highlighting for html tags
6636 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6637 (js2-set-face (match-beginning 1)
6639 'js2-jsdoc-html-tag-delimiter-face)
6640 (js2-set-face (match-beginning 2)
6642 'js2-jsdoc-html-tag-name-face)
6643 (js2-set-face (match-beginning 3)
6645 'js2-jsdoc-html-tag-delimiter-face))))))))
6647 (defun js2-highlight-assign-targets (node left right)
6648 "Highlight function properties and external variables."
6649 (let (leftpos end name)
6650 ;; highlight vars and props assigned function values
6651 (when (js2-function-node-p right)
6653 ;; var foo = function() {...}
6654 ((js2-name-node-p left)
6656 ;; foo.bar.baz = function() {...}
6657 ((and (js2-prop-get-node-p left)
6658 (js2-name-node-p (js2-prop-get-node-right left)))
6659 (setq name (js2-prop-get-node-right left))))
6661 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6662 (+ leftpos (js2-node-len name))
6663 'font-lock-function-name-face
6666 (defun js2-record-name-node (node)
6667 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6668 later. NODE must be a name node."
6670 (push (list node js2-current-scope
6671 (setq leftpos (js2-node-abs-pos node))
6672 (setq end (+ leftpos (js2-node-len node))))
6673 js2-recorded-identifiers)))
6675 (defun js2-highlight-undeclared-vars ()
6676 "After entire parse is finished, look for undeclared variable references.
6677 We have to wait until entire buffer is parsed, since JavaScript permits var
6678 decls to occur after they're used.
6680 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6681 it is considered declared."
6683 (dolist (entry js2-recorded-identifiers)
6684 (destructuring-bind (name-node scope pos end) entry
6685 (setq name (js2-name-node-name name-node))
6686 (unless (or (member name js2-global-externs)
6687 (member name js2-default-externs)
6688 (member name js2-additional-externs)
6689 (js2-get-defining-scope scope name))
6690 (js2-set-face pos end 'js2-external-variable-face 'record)
6691 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6692 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6693 (setq js2-recorded-identifiers nil)))
6697 ;; We currently only support imenu, but eventually should support speedbar and
6698 ;; possibly other browsing mechanisms.
6700 ;; The basic strategy is to identify function assignment targets of the form
6701 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6702 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6703 ;; for imenu after parsing is finished.
6705 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6706 ;; JavaScript, and the general problem is undecidable. However, several forms
6707 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6710 ;; function foo() -- function declaration
6711 ;; foo = function() -- function expression assigned to variable
6712 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6713 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6714 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6715 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6716 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6717 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6718 ;; function foo() {function bar() {...}} -- nested function
6719 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6721 ;; This list boils down to a few forms that can be combined recursively.
6722 ;; Top-level named function declarations include both the left-hand (name)
6723 ;; and the right-hand (function value) expressions needed to produce an imenu
6724 ;; entry. The other "right-hand" forms we need to look for are:
6725 ;; - functions declared as props/getters/setters in object literals
6726 ;; - nested named function declarations
6727 ;; The "left-hand" expressions that functions can be assigned to include:
6728 ;; - local/global variables
6729 ;; - nested property-get expressions like a.b.c.d
6730 ;; - element gets like foo[10] or foo['bar'] where the index
6731 ;; expression can be trivially converted to a property name. They
6732 ;; effectively then become property gets.
6734 ;; All the different definition types are canonicalized into the form
6735 ;; foo.bar.baz = position-of-function-keyword
6737 ;; We need to build a trie-like structure for imenu. As an example,
6738 ;; consider the following JavaScript code:
6740 ;; a = function() {...} // function at position 5
6741 ;; b = function() {...} // function at position 25
6742 ;; foo = function() {...} // function at position 100
6743 ;; foo.bar = function() {...} // function at position 200
6744 ;; foo.bar.baz = function() {...} // function at position 300
6745 ;; foo.bar.zab = function() {...} // function at position 400
6747 ;; During parsing we accumulate an entry for each definition in
6748 ;; the variable `js2-imenu-recorder', like so:
6754 ;; (fn foo bar baz 300)
6755 ;; (fn foo bar zab 400))
6757 ;; Where 'fn' is the respective function node.
6758 ;; After parsing these entries are merged into this alist-trie:
6762 ;; (foo (<definition> . 3)
6763 ;; (bar (<definition> . 6)
6767 ;; Note the wacky need for a <definition> name. The token can be anything
6768 ;; that isn't a valid JavaScript identifier, because you might make foo
6769 ;; a function and then start setting properties on it that are also functions.
6771 (defsubst js2-prop-node-name (node)
6772 "Return the name of a node that may be a property-get/property-name.
6773 If NODE is not a valid name-node, string-node or integral number-node,
6774 returns nil. Otherwise returns the string name/value of the node."
6776 ((js2-name-node-p node)
6777 (js2-name-node-name node))
6778 ((js2-string-node-p node)
6779 (js2-string-node-value node))
6780 ((and (js2-number-node-p node)
6781 (string-match "^[0-9]+$" (js2-number-node-value node)))
6782 (js2-number-node-value node))
6783 ((js2-this-node-p node)
6786 (defsubst js2-node-qname-component (node)
6787 "Return the name of this node, if it contributes to a qname.
6788 Returns nil if the node doesn't contribute."
6790 (or (js2-prop-node-name node)
6791 (if (and (js2-function-node-p node)
6792 (js2-function-node-name node))
6793 (js2-name-node-name (js2-function-node-name node))))))
6795 (defsubst js2-record-imenu-entry (fn-node qname pos)
6796 "Add an entry to `js2-imenu-recorder'.
6797 FN-NODE should be the current item's function node.
6799 Associate FN-NODE with its QNAME for later lookup.
6800 This is used in postprocessing the chain list. For each chain, we find
6801 the parent function, look up its qname, then prepend a copy of it to the chain."
6802 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6803 (unless js2-imenu-function-map
6804 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6805 (puthash fn-node qname js2-imenu-function-map))
6807 (defun js2-record-imenu-functions (node &optional var)
6808 "Record function definitions for imenu.
6809 NODE is a function node or an object literal.
6810 VAR, if non-nil, is the expression that NODE is being assigned to.
6811 When passed arguments of wrong type, does nothing."
6812 (when js2-parse-ide-mode
6813 (let ((fun-p (js2-function-node-p node))
6814 qname left fname-node pos)
6816 ;; non-anonymous function declaration?
6819 (setq fname-node (js2-function-node-name node)))
6820 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6821 ;; for remaining forms, compute left-side tree branch first
6822 ((and var (setq qname (js2-compute-nested-prop-get var)))
6824 ;; foo.bar.baz = function
6826 (js2-record-imenu-entry node qname (js2-node-pos node)))
6827 ;; foo.bar.baz = object-literal
6828 ;; look for nested functions: {a: {b: function() {...} }}
6829 ((js2-object-node-p node)
6830 ;; Node position here is still absolute, since the parser
6831 ;; passes the assignment target and value expressions
6832 ;; to us before they are added as children of the assignment node.
6833 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6835 (defun js2-compute-nested-prop-get (node)
6836 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6837 component nodes as a list. Otherwise return nil. Element-gets are treated
6838 as property-gets if the index expression is a string, or a positive integer."
6839 (let (left right head)
6841 ((or (js2-name-node-p node)
6842 (js2-this-node-p node))
6844 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6845 ((js2-prop-get-node-p node) ; foo.bar
6846 (setq left (js2-prop-get-node-left node)
6847 right (js2-prop-get-node-right node))
6848 (if (setq head (js2-compute-nested-prop-get left))
6849 (nconc head (list right))))
6850 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6851 (setq left (js2-elem-get-node-target node)
6852 right (js2-elem-get-node-element node))
6853 (if (or (js2-string-node-p right) ; ['bar']
6854 (and (js2-number-node-p right) ; [10]
6855 (string-match "^[0-9]+$"
6856 (js2-number-node-value right))))
6857 (if (setq head (js2-compute-nested-prop-get left))
6858 (nconc head (list right))))))))
6860 (defun js2-record-object-literal (node qname pos)
6861 "Recursively process an object literal looking for functions.
6862 NODE is an object literal that is the right-hand child of an assignment
6863 expression. QNAME is a list of nodes representing the assignment target,
6864 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6865 POS is the absolute position of the node.
6866 We do a depth-first traversal of NODE. For any functions we find,
6867 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6868 (let (left right prop-qname)
6869 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6870 (let ((left (js2-infix-node-left e))
6871 ;; Element positions are relative to the parent position.
6872 (pos (+ pos (js2-node-pos e))))
6874 ;; foo: function() {...}
6875 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6876 (when (js2-prop-node-name left)
6877 ;; As a policy decision, we record the position of the property,
6878 ;; not the position of the `function' keyword, since the property
6879 ;; is effectively the name of the function.
6880 (js2-record-imenu-entry right (append qname (list left)) pos)))
6881 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6882 ((js2-object-node-p right)
6883 (js2-record-object-literal right
6884 (append qname (list (js2-infix-node-left e)))
6885 (+ pos (js2-node-pos right)))))))))
6887 (defsubst js2-node-top-level-decl-p (node)
6888 "Return t if NODE's name is defined in the top-level scope.
6889 Also returns t if NODE's name is not defined in any scope, since it implies
6890 that it's an external variable, which must also be in the top-level scope."
6891 (let* ((name (js2-prop-node-name node))
6892 (this-scope (js2-node-get-enclosing-scope node))
6895 ((js2-this-node-p node)
6899 ((setq defining-scope (js2-get-defining-scope this-scope name))
6900 (js2-ast-root-p defining-scope))
6903 (defsubst js2-wrapper-function-p (node)
6904 "Returns t if NODE is a function expression that's immediately invoked.
6905 NODE must be `js2-function-node'."
6906 (let ((parent (js2-node-parent node)))
6908 ;; function(){...}();
6909 (js2-call-node-p parent)
6910 (and (js2-paren-node-p parent)
6911 ;; (function(){...})();
6912 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6913 ;; (function(){...}).call(this);
6914 (and (js2-prop-get-node-p parent)
6915 (member (js2-name-node-name (js2-prop-get-node-right parent))
6917 (js2-call-node-p (js2-node-parent parent))))))))
6919 (defun js2-browse-postprocess-chains (entries)
6920 "Modify function-declaration name chains after parsing finishes.
6921 Some of the information is only available after the parse tree is complete.
6922 For instance, processing a nested scope requires a parent function node."
6923 (let (result head fn current-fn parent-qname qname p elem)
6924 (dolist (entry entries)
6925 ;; function node goes first
6926 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6927 ;; Examine head's defining scope:
6928 ;; Pre-processed chain, or top-level/external, keep as-is.
6929 (if (or (stringp head) (js2-node-top-level-decl-p head))
6931 (when (js2-this-node-p head)
6932 (setq chain (cdr chain))) ; discard this-node
6933 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6934 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6935 (when (eq parent-qname 'not-found)
6936 ;; anonymous function expressions are not recorded
6937 ;; during the parse, so we need to handle this case here
6939 (if (js2-wrapper-function-p fn)
6940 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6941 (if (js2-ast-root-p grandparent)
6943 (gethash grandparent js2-imenu-function-map 'skip)))
6945 (puthash fn parent-qname js2-imenu-function-map))
6946 (unless (eq parent-qname 'skip)
6947 ;; prefix parent fn qname to this chain.
6948 (let ((qname (append parent-qname chain)))
6949 (puthash current-fn (butlast qname) js2-imenu-function-map)
6950 (push qname result)))))))
6951 ;; finally replace each node in each chain with its name.
6952 (dolist (chain result)
6955 (if (js2-node-p (setq elem (car p)))
6956 (setcar p (js2-node-qname-component elem)))
6960 ;; Merge name chains into a trie-like tree structure of nested lists.
6961 ;; To simplify construction of the trie, we first build it out using the rule
6962 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6963 ;; [key, num-or-list]. The second element can be a number; if so, this key
6964 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6965 ;; associated with the key at this level.) Otherwise the second element is
6966 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6967 ;; a simple recursive formulation.
6969 ;; js2-mode is building the data structure for imenu. The imenu documentation
6970 ;; claims that it's the structure above, but in practice it wants the children
6971 ;; at the same list level as the key for that level, which is how I've drawn
6972 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6973 ;; list wrapper around the children at each level.
6975 ;; A completed nested imenu-alist entry looks like this:
6977 ;; ("<definition>" . 7)
6982 ;; In particular, the documentation for `imenu--index-alist' says that
6983 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6984 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6986 (defun js2-treeify (lst)
6987 "Convert (a b c d) to (a ((b ((c d)))))"
6988 (if (null (cddr lst)) ; list length <= 2
6990 (list (car lst) (list (js2-treeify (cdr lst))))))
6992 (defun js2-build-alist-trie (chains trie)
6993 "Merge declaration name chains into a trie-like alist structure for imenu.
6994 CHAINS is the qname chain list produced during parsing. TRIE is a
6995 list of elements built up so far."
6996 (let (head tail pos branch kids)
6997 (dolist (chain chains)
6998 (setq head (car chain)
7000 pos (if (numberp (car tail)) (car tail))
7001 branch (js2-find-if (lambda (n)
7002 (string= (car n) head))
7004 kids (second branch))
7006 ;; case 1: this key isn't in the trie yet
7009 (setcdr (last trie) (list (js2-treeify chain)))
7010 (setq trie (list (js2-treeify chain)))))
7011 ;; case 2: key is present with a single number entry: replace w/ list
7012 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7013 ;; ("<definition>" 20)))
7015 (setcar (cdr branch)
7016 (list (list "<definition-1>" kids)
7018 (list "<definition-2>" pos)
7019 (js2-treeify tail)))))
7020 ;; case 3: key is there (with kids), and we're a number entry
7024 (list (format "<definition-%d>"
7025 (1+ (loop for kid in kids
7026 count (eq ?< (aref (car kid) 0)))))
7028 ;; case 4: key is there with kids, need to merge in our chain
7030 (js2-build-alist-trie (list tail) kids))))
7033 (defun js2-flatten-trie (trie)
7034 "Convert TRIE to imenu-format.
7035 Recurses through nodes, and for each one whose second element is a list,
7036 appends the list's flattened elements to the current element. Also
7037 changes the tails into conses. For instance, this pre-flattened trie
7049 Note that the root of the trie has no key, just a list of chains.
7050 This is also true for the value of any key with multiple children,
7051 e.g. key 'c' in the example above."
7054 (mapcar #'js2-flatten-trie trie))
7056 (if (numberp (second trie))
7057 (cons (car trie) (second trie))
7058 ;; else pop list and append its kids
7059 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7061 (defun js2-build-imenu-index ()
7062 "Turn `js2-imenu-recorder' into an imenu data structure."
7063 (unless (eq js2-imenu-recorder 'empty)
7064 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7065 (result (js2-build-alist-trie chains nil)))
7066 (js2-flatten-trie result))))
7068 (defun js2-test-print-chains (chains)
7069 "Print a list of qname chains.
7070 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7071 i.e. one or more nodes, and an integer position as the list tail."
7072 (mapconcat (lambda (chain)
7074 (mapconcat (lambda (elem)
7075 (if (js2-node-p elem)
7076 (or (js2-node-qname-component elem)
7078 (number-to-string elem)))
7087 (defconst js2-version "1.8.0"
7088 "Version of JavaScript supported, plus minor js2 version.")
7090 (defmacro js2-record-face (face)
7091 "Record a style run of FACE for the current token."
7092 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7094 (defsubst js2-node-end (n)
7095 "Computes the absolute end of node N.
7096 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7097 is only true until the node is added to its parent; i.e., while parsing."
7101 (defsubst js2-record-comment ()
7102 "Record a comment in `js2-scanned-comments'."
7103 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7104 :format js2-ts-comment-type)
7105 js2-scanned-comments)
7106 (when js2-parse-ide-mode
7107 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7109 'font-lock-comment-face))
7110 (when (memq js2-ts-comment-type '(html preprocessor))
7111 ;; Tell cc-engine the bounds of the comment.
7112 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7114 ;; This function is called depressingly often, so it should be fast.
7115 ;; Most of the time it's looking at the same token it peeked before.
7116 (defsubst js2-peek-token ()
7117 "Returns the next token without consuming it.
7118 If previous token was consumed, calls scanner to get new token.
7119 If previous token was -not- consumed, returns it (idempotent).
7121 This function will not return a newline (js2-EOL) - instead, it
7122 gobbles newlines until it finds a non-newline token, and flags
7123 that token as appearing just after a newline.
7125 This function will also not return a js2-COMMENT. Instead, it
7126 records comments found in `js2-scanned-comments'. If the token
7127 returned by this function immediately follows a jsdoc comment,
7128 the token is flagged as such.
7130 Note that this function always returned the un-flagged token!
7131 The flags, if any, are saved in `js2-current-flagged-token'."
7132 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7133 js2-current-token ; most common case - return already-peeked token
7134 (let ((tt (js2-get-token)) ; call scanner
7137 ;; process comments and whitespace
7138 (while (or (= tt js2-EOL)
7143 (if js2-record-comments
7144 (js2-record-comment)))
7145 (setq tt (js2-get-token))) ; call scanner
7146 (setq js2-current-token tt
7147 js2-current-flagged-token (if saw-eol
7148 (logior tt js2-ti-after-eol)
7150 ;; perform lexical fontification as soon as token is scanned
7151 (when js2-parse-ide-mode
7154 (js2-record-face 'js2-error-face))
7155 ((setq face (aref js2-kwd-tokens tt))
7156 (js2-record-face face))
7157 ((and (= tt js2-NAME)
7158 (equal js2-ts-string "undefined"))
7159 (js2-record-face 'font-lock-constant-face))))
7160 tt))) ; return unflagged token
7162 (defsubst js2-peek-flagged-token ()
7163 "Returns the current token along with any flags set for it."
7165 js2-current-flagged-token)
7167 (defsubst js2-consume-token ()
7168 (setq js2-current-flagged-token js2-EOF))
7170 (defsubst js2-next-token ()
7173 (js2-consume-token)))
7175 (defsubst js2-next-flagged-token ()
7177 (prog1 js2-current-flagged-token
7178 (js2-consume-token)))
7180 (defsubst js2-match-token (match)
7181 "Consume and return t if next token matches MATCH, a bytecode.
7182 Returns nil and consumes nothing if MATCH is not the next token."
7183 (if (/= (js2-peek-token) match)
7188 (defun js2-match-contextual-kwd (name)
7189 "Consume and return t if next token is `js2-NAME', and its
7190 string is NAME. Returns nil and does nothing otherwise."
7191 (if (or (/= (js2-peek-token) js2-NAME)
7192 (not (string= js2-ts-string name)))
7195 (js2-record-face 'font-lock-keyword-face)
7198 (defsubst js2-valid-prop-name-token (tt)
7200 (when (and js2-allow-keywords-as-property-names
7202 (aref js2-kwd-tokens tt))
7203 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7206 (defsubst js2-match-prop-name ()
7207 "Consume token and return t if next token is a valid property name.
7208 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7209 is non-nil and it's a keyword token."
7210 (if (js2-valid-prop-name-token (js2-peek-token))
7216 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7217 (if (js2-match-prop-name)
7219 (js2-report-error msg-id nil pos len)
7222 (defsubst js2-peek-token-or-eol ()
7223 "Return js2-EOL if the current token immediately follows a newline.
7224 Else returns the current token. Used in situations where we don't
7225 consider certain token types valid if they are preceded by a newline.
7226 One example is the postfix ++ or -- operator, which has to be on the
7227 same line as its operand."
7228 (let ((tt (js2-peek-token)))
7229 ;; Check for last peeked token flags
7230 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7234 (defsubst js2-set-check-for-label ()
7235 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7236 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7238 (defsubst js2-must-match (token msg-id &optional pos len)
7239 "Match next token to token code TOKEN, or record a syntax error.
7240 MSG-ID is the error message to report if the match fails.
7241 Returns t on match, nil if no match."
7242 (if (js2-match-token token)
7244 (js2-report-error msg-id nil pos len)
7247 (defsubst js2-inside-function ()
7248 (plusp js2-nesting-of-function))
7250 (defsubst js2-set-requires-activation ()
7251 (if (js2-function-node-p js2-current-script-or-fn)
7252 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7254 (defsubst js2-check-activation-name (name token)
7255 (when (js2-inside-function)
7256 ;; skip language-version 1.2 check from Rhino
7257 (if (or (string= "arguments" name)
7258 (and js2-compiler-activation-names ; only used in codegen
7259 (gethash name js2-compiler-activation-names)))
7260 (js2-set-requires-activation))))
7262 (defsubst js2-set-is-generator ()
7263 (if (js2-function-node-p js2-current-script-or-fn)
7264 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7266 (defsubst js2-must-have-xml ()
7267 (unless js2-compiler-xml-available
7268 (js2-report-error "msg.XML.not.available")))
7270 (defsubst js2-push-scope (scope)
7271 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7272 (assert (js2-scope-p scope))
7273 (assert (null (js2-scope-parent-scope scope)))
7274 (assert (not (eq js2-current-scope scope)))
7275 (setf (js2-scope-parent-scope scope) js2-current-scope
7276 js2-current-scope scope))
7278 (defsubst js2-pop-scope ()
7279 (setq js2-current-scope
7280 (js2-scope-parent-scope js2-current-scope)))
7282 (defsubst js2-enter-loop (loop-node)
7283 (push loop-node js2-loop-set)
7284 (push loop-node js2-loop-and-switch-set)
7285 (js2-push-scope loop-node)
7286 ;; Tell the current labeled statement (if any) its statement,
7287 ;; and set the jump target of the first label to the loop.
7288 ;; These are used in `js2-parse-continue' to verify that the
7289 ;; continue target is an actual labeled loop. (And for codegen.)
7290 (when js2-labeled-stmt
7291 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7292 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7293 js2-labeled-stmt))) loop-node)))
7295 (defsubst js2-exit-loop ()
7297 (pop js2-loop-and-switch-set)
7300 (defsubst js2-enter-switch (switch-node)
7301 (push switch-node js2-loop-and-switch-set))
7303 (defsubst js2-exit-switch ()
7304 (pop js2-loop-and-switch-set))
7306 (defun js2-parse (&optional buf cb)
7307 "Tells the js2 parser to parse a region of JavaScript.
7309 BUF is a buffer or buffer name containing the code to parse.
7310 Call `narrow-to-region' first to parse only part of the buffer.
7312 The returned AST root node is given some additional properties:
7313 `node-count' - total number of nodes in the AST
7314 `buffer' - BUF. The buffer it refers to may change or be killed,
7315 so the value is not necessarily reliable.
7317 An optional callback CB can be specified to report parsing
7318 progress. If `(functionp CB)' returns t, it will be called with
7319 the current line number once before parsing begins, then again
7320 each time the lexer reaches a new line number.
7322 CB can also be a list of the form `(symbol cb ...)' to specify
7323 multiple callbacks with different criteria. Each symbol is a
7324 criterion keyword, and the following element is the callback to
7327 :line - called whenever the line number changes
7328 :token - called for each new token consumed
7330 The list of criteria could be extended to include entering or
7331 leaving a statement, an expression, or a function definition."
7332 (if (and cb (not (functionp cb)))
7333 (error "criteria callbacks not yet implemented"))
7334 (let ((inhibit-point-motion-hooks t)
7335 (js2-compiler-xml-available (>= js2-language-version 160))
7336 ;; This is a recursive-descent parser, so give it a big stack.
7337 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7338 (max-specpdl-size (max max-specpdl-size 3000))
7339 (case-fold-search nil)
7341 (message nil) ; clear any error message from previous parse
7343 (when buf (set-buffer buf))
7344 (setq js2-scanned-comments nil
7345 js2-parsed-errors nil
7346 js2-parsed-warnings nil
7347 js2-imenu-recorder nil
7348 js2-imenu-function-map nil
7351 (setq ast (js2-with-unmodifying-text-property-changes
7353 (unless js2-ts-hit-eof
7354 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7355 (setf (js2-ast-root-errors ast) js2-parsed-errors
7356 (js2-ast-root-warnings ast) js2-parsed-warnings)
7357 ;; if we didn't find any declarations, put a dummy in this list so we
7358 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7359 (unless js2-imenu-recorder
7360 (setq js2-imenu-recorder 'empty))
7361 (run-hooks 'js2-parse-finished-hook)
7364 ;; Corresponds to Rhino's Parser.parse() method.
7365 (defun js2-do-parse ()
7366 "Parse current buffer starting from current point.
7367 Scanner should be initialized."
7368 (let ((pos js2-ts-cursor)
7369 (end js2-ts-cursor) ; in case file is empty
7371 ;; initialize buffer-local parsing vars
7372 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7373 js2-current-script-or-fn root
7374 js2-current-scope root
7375 js2-current-flagged-token js2-EOF
7376 js2-nesting-of-function 0
7377 js2-labeled-stmt nil
7378 js2-recorded-identifiers nil) ; for js2-highlight
7379 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7380 (if (= tt js2-FUNCTION)
7383 (setq n (js2-parse-function (if js2-called-by-compile-function
7384 'FUNCTION_EXPRESSION
7385 'FUNCTION_STATEMENT))))
7386 ;; not a function - parse a statement
7387 (setq n (js2-parse-statement)))
7388 ;; add function or statement to script
7389 (setq end (js2-node-end n))
7390 (js2-block-node-push root n))
7391 ;; add comments to root in lexical order
7392 (when js2-scanned-comments
7393 ;; if we find a comment beyond end of normal kids, use its end
7394 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7395 (dolist (comment js2-scanned-comments)
7396 (push comment (js2-ast-root-comments root))
7397 (js2-node-add-children root comment)))
7398 (setf (js2-node-len root) (- end pos))
7399 ;; Give extensions a chance to muck with things before highlighting starts.
7400 (let ((js2-additional-externs js2-additional-externs))
7401 (dolist (callback js2-post-parse-callbacks)
7403 (js2-highlight-undeclared-vars))
7406 (defun js2-function-parser ()
7408 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7410 (defun js2-parse-function-closure-body (fn-node)
7411 "Parse a JavaScript 1.8 function closure body."
7412 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7414 (js2-report-error "msg.no.brace.body" nil
7415 (js2-node-pos fn-node)
7416 (- js2-ts-cursor (js2-node-pos fn-node)))
7417 (js2-node-add-children fn-node
7418 (setf (js2-function-node-body fn-node)
7419 (js2-parse-expr t))))))
7421 (defun js2-parse-function-body (fn-node)
7422 (js2-must-match js2-LC "msg.no.brace.body"
7423 (js2-node-pos fn-node)
7424 (- js2-ts-cursor (js2-node-pos fn-node)))
7425 (let ((pos js2-token-beg) ; LC position
7426 (pn (make-js2-block-node)) ; starts at LC position
7429 (incf js2-nesting-of-function)
7431 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7434 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7435 (js2-parse-statement)
7437 (js2-parse-function 'FUNCTION_STATEMENT))))
7438 (decf js2-nesting-of-function))
7439 (setq end js2-token-end) ; assume no curly and leave at current token
7440 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7441 (setq end js2-token-end))
7442 (setf (js2-node-pos pn) pos
7443 (js2-node-len pn) (- end pos))
7444 (setf (js2-function-node-body fn-node) pn)
7445 (js2-node-add-children fn-node pn)
7448 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7449 "Declare and fontify destructuring parameters inside NODE.
7450 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7452 ((js2-name-node-p node)
7454 (js2-define-symbol decl-type (js2-name-node-name node)
7455 node ignore-not-in-block)
7457 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7458 (+ leftpos (js2-node-len node))
7460 ((js2-object-node-p node)
7461 (dolist (elem (js2-object-node-elems node))
7462 (js2-define-destruct-symbols
7463 (if (js2-object-prop-node-p elem)
7464 (js2-object-prop-node-right elem)
7465 ;; abbreviated destructuring {a, b}
7467 decl-type face ignore-not-in-block)))
7468 ((js2-array-node-p node)
7469 (dolist (elem (js2-array-node-elems node))
7471 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7472 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7473 (js2-node-len node)))))
7475 (defun js2-parse-function-params (fn-node pos)
7476 (if (js2-match-token js2-RP)
7477 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7478 (let (params len param default-found rest-param-at)
7479 (loop for tt = (js2-peek-token)
7482 ;; destructuring param
7483 ((or (= tt js2-LB) (= tt js2-LC))
7485 (js2-report-error "msg.no.default.after.default.param"))
7486 (setq param (js2-parse-destruct-primary-expr))
7487 (js2-define-destruct-symbols param
7489 'js2-function-param-face)
7490 (push param params))
7493 (when (and (>= js2-language-version 200)
7494 (js2-match-token js2-TRIPLEDOT)
7495 (not rest-param-at))
7496 ;; to report errors if there are more parameters
7497 (setq rest-param-at (length params)))
7498 (js2-must-match js2-NAME "msg.no.parm")
7499 (js2-record-face 'js2-function-param-face)
7500 (setq param (js2-create-name-node))
7501 (js2-define-symbol js2-LP js2-ts-string param)
7502 ;; default parameter value
7503 (when (or (and default-found
7505 (js2-must-match js2-ASSIGN
7506 "msg.no.default.after.default.param"
7507 (js2-node-pos param)
7508 (js2-node-len param)))
7509 (and (>= js2-language-version 200)
7510 (js2-match-token js2-ASSIGN)))
7511 (let* ((pos (js2-node-pos param))
7512 (tt js2-current-token)
7513 (op-pos (- js2-token-beg pos))
7515 (right (js2-parse-assign-expr))
7516 (len (- (js2-node-end right) pos)))
7517 (setq param (make-js2-assign-node
7518 :type tt :pos pos :len len :op-pos op-pos
7519 :left left :right right)
7521 (js2-node-add-children param left right)))
7522 (push param params)))
7523 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7524 (js2-report-error "msg.param.after.rest" nil
7525 (js2-node-pos param) (js2-node-len param)))
7527 (js2-match-token js2-COMMA))
7528 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7529 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7531 (setf (js2-function-node-rest-p fn-node) t))
7533 (js2-node-add-children fn-node p)
7534 (push p (js2-function-node-params fn-node))))))
7536 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7537 "Possibly show inconsistent-return warning.
7538 Last token scanned is the close-curly for the function body."
7539 (when (and js2-mode-show-strict-warnings
7540 js2-strict-inconsistent-return-warning
7541 (not (js2-has-consistent-return-usage
7542 (js2-function-node-body fn-node))))
7543 ;; Have it extend from close-curly to bol or beginning of block.
7544 (let ((pos (save-excursion
7545 (goto-char js2-token-end)
7546 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7548 (end js2-token-end))
7549 (if (plusp (js2-name-node-length name))
7550 (js2-add-strict-warning "msg.no.return.value"
7551 (js2-name-node-name name) pos end)
7552 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7554 (defun js2-parse-function (function-type)
7555 "Function parser. FUNCTION-TYPE is a symbol."
7556 (let ((pos js2-token-beg) ; start of 'function' keyword
7562 (synthetic-type function-type)
7564 ;; parse function name, expression, or non-name (anonymous)
7566 ;; function foo(...)
7567 ((js2-match-token js2-NAME)
7568 (setq name (js2-create-name-node t)
7569 name-beg js2-token-beg
7570 name-end js2-token-end)
7571 (unless (js2-match-token js2-LP)
7572 (when js2-allow-member-expr-as-function-name
7573 ;; function foo.bar(...)
7574 (setq member-expr-node name
7576 member-expr-node (js2-parse-member-expr-tail
7577 nil member-expr-node)))
7578 (js2-must-match js2-LP "msg.no.paren.parms")))
7579 ((js2-match-token js2-LP)
7580 nil) ; anonymous function: leave name as null
7582 ;; function random-member-expr(...)
7583 (when js2-allow-member-expr-as-function-name
7584 ;; Note that memberExpr can not start with '(' like
7585 ;; in function (1+2).toString(), because 'function (' already
7586 ;; processed as anonymous function
7587 (setq member-expr-node (js2-parse-member-expr)))
7588 (js2-must-match js2-LP "msg.no.paren.parms")))
7589 (if (= js2-current-token js2-LP) ; eventually matched LP?
7590 (setq lp js2-token-beg))
7591 (if member-expr-node
7593 (setq synthetic-type 'FUNCTION_EXPRESSION)
7594 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7596 (js2-set-face name-beg name-end
7597 'font-lock-function-name-face 'record)))
7598 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7599 (plusp (js2-name-node-length name)))
7600 ;; Function statements define a symbol in the enclosing scope
7601 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7602 (setf fn-node (make-js2-function-node :pos pos
7605 :lp (if lp (- lp pos))))
7606 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7607 ;; 1. Nested functions are not affected by the dynamic scope flag
7608 ;; as dynamic scope is already a parent of their scope.
7609 ;; 2. Functions defined under the with statement also immune to
7610 ;; this setup, in which case dynamic scope is ignored in favor
7611 ;; of the with object.
7612 (setf (js2-function-node-ignore-dynamic fn-node) t))
7613 ;; dynamically bind all the per-function variables
7614 (let ((js2-current-script-or-fn fn-node)
7615 (js2-current-scope fn-node)
7616 (js2-nesting-of-with 0)
7620 js2-loop-and-switch-set)
7621 (js2-parse-function-params fn-node pos)
7622 (if (and (>= js2-language-version 180)
7623 (/= (js2-peek-token) js2-LC))
7624 (js2-parse-function-closure-body fn-node)
7625 (js2-parse-function-body fn-node))
7627 (js2-node-add-children fn-node name))
7628 (js2-check-inconsistent-return-warning fn-node name)
7629 ;; Function expressions define a name only in the body of the
7630 ;; function, and only if not hidden by a parameter name
7632 (eq synthetic-type 'FUNCTION_EXPRESSION)
7633 (null (js2-scope-get-symbol js2-current-scope
7634 (js2-name-node-name name))))
7635 (js2-define-symbol js2-FUNCTION
7636 (js2-name-node-name name)
7639 (not (eq function-type 'FUNCTION_EXPRESSION)))
7640 (js2-record-imenu-functions fn-node)))
7641 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7642 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7643 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7644 ;; We wait until after parsing the function to set its parent scope,
7645 ;; since `js2-define-symbol' needs the defining-scope check to stop
7646 ;; at the function boundary when checking for redeclarations.
7647 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7650 (defun js2-parse-statements (&optional parent)
7651 "Parse a statement list. Last token consumed must be js2-LC.
7653 PARENT can be a `js2-block-node', in which case the statements are
7654 appended to PARENT. Otherwise a new `js2-block-node' is created
7657 This function does not match the closing js2-RC: the caller
7658 matches the RC so it can provide a suitable error message if not
7659 matched. This means it's up to the caller to set the length of
7660 the node to include the closing RC. The node start pos is set to
7661 the absolute buffer start position, and the caller should fix it
7662 up to be relative to the parent node. All children of this block
7663 node are given relative start positions and correct lengths."
7664 (let ((pn (or parent (make-js2-block-node)))
7666 (setf (js2-node-pos pn) js2-token-beg)
7667 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7669 (js2-block-node-push pn (js2-parse-statement)))
7672 (defun js2-parse-statement ()
7673 (let (tt pn beg end)
7674 ;; coarse-grained user-interrupt check - needs work
7675 (and js2-parse-interruptable-p
7676 (zerop (% (incf js2-parse-stmt-count)
7677 js2-statements-per-pause))
7679 (throw 'interrupted t))
7680 (setq pn (js2-statement-helper))
7681 ;; no-side-effects warning check
7682 (unless (js2-node-has-side-effects pn)
7683 (setq end (js2-node-end pn))
7686 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7687 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7690 ;; These correspond to the switch cases in Parser.statementHelper
7691 (defconst js2-parsers
7692 (let ((parsers (make-vector js2-num-tokens
7693 #'js2-parse-expr-stmt)))
7694 (aset parsers js2-BREAK #'js2-parse-break)
7695 (aset parsers js2-CONST #'js2-parse-const-var)
7696 (aset parsers js2-CONTINUE #'js2-parse-continue)
7697 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7698 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7699 (aset parsers js2-DO #'js2-parse-do)
7700 (aset parsers js2-FOR #'js2-parse-for)
7701 (aset parsers js2-FUNCTION #'js2-function-parser)
7702 (aset parsers js2-IF #'js2-parse-if)
7703 (aset parsers js2-LC #'js2-parse-block)
7704 (aset parsers js2-LET #'js2-parse-let-stmt)
7705 (aset parsers js2-NAME #'js2-parse-name-or-label)
7706 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7707 (aset parsers js2-SEMI #'js2-parse-semi)
7708 (aset parsers js2-SWITCH #'js2-parse-switch)
7709 (aset parsers js2-THROW #'js2-parse-throw)
7710 (aset parsers js2-TRY #'js2-parse-try)
7711 (aset parsers js2-VAR #'js2-parse-const-var)
7712 (aset parsers js2-WHILE #'js2-parse-while)
7713 (aset parsers js2-WITH #'js2-parse-with)
7714 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7716 "A vector mapping token types to parser functions.")
7718 (defsubst js2-parse-warn-missing-semi (beg end)
7719 (and js2-mode-show-strict-warnings
7720 js2-strict-missing-semi-warning
7721 (js2-add-strict-warning
7722 "msg.missing.semi" nil
7723 ;; back up to beginning of statement or line
7724 (max beg (save-excursion
7729 (defconst js2-no-semi-insertion
7741 "List of tokens that don't do automatic semicolon insertion.")
7743 (defconst js2-autoinsert-semi-and-warn
7744 (list js2-ERROR js2-EOF js2-RC))
7746 (defun js2-statement-helper ()
7747 (let* ((tt (js2-peek-token))
7750 (parser (if (= tt js2-ERROR)
7752 (aref js2-parsers tt)))
7755 ;; If the statement is set, then it's been told its label by now.
7756 (and js2-labeled-stmt
7757 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7758 (setq js2-labeled-stmt nil))
7759 (setq pn (funcall parser))
7760 ;; Don't do auto semi insertion for certain statement types.
7761 (unless (or (memq first-tt js2-no-semi-insertion)
7762 (js2-labeled-stmt-node-p pn))
7763 (js2-auto-insert-semicolon pn))
7766 (defun js2-auto-insert-semicolon (pn)
7767 (let* ((tt-flagged (js2-peek-flagged-token))
7768 (tt (logand tt-flagged js2-clear-ti-mask))
7769 (pos (js2-node-pos pn)))
7772 ;; Consume ';' as a part of expression
7774 ;; extend the node bounds to include the semicolon.
7775 (setf (js2-node-len pn) (- js2-token-end pos)))
7776 ((memq tt js2-autoinsert-semi-and-warn)
7778 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7780 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7781 ;; Report error if no EOL or autoinsert ';' otherwise
7782 (js2-report-error "msg.no.semi.stmt")
7783 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7785 (defun js2-parse-condition ()
7786 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7787 The parens are discarded and the expression node is returned.
7788 The `pos' field of the return value is set to an absolute position
7789 that must be fixed up by the caller.
7790 Return value is a list (EXPR LP RP), with absolute paren positions."
7792 (if (js2-must-match js2-LP "msg.no.paren.cond")
7793 (setq lp js2-token-beg))
7794 (setq pn (js2-parse-expr))
7795 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7796 (setq rp js2-token-beg))
7797 ;; Report strict warning on code like "if (a = 7) ..."
7798 (if (and js2-strict-cond-assign-warning
7799 (js2-assign-node-p pn))
7800 (js2-add-strict-warning "msg.equal.as.assign" nil
7802 (+ (js2-node-pos pn)
7803 (js2-node-len pn))))
7806 (defun js2-parse-if ()
7807 "Parser for if-statement. Last matched token must be js2-IF."
7808 (let ((pos js2-token-beg)
7816 (setq cond (js2-parse-condition)
7817 if-true (js2-parse-statement)
7818 if-false (if (js2-match-token js2-ELSE)
7820 (setq else-pos (- js2-token-beg pos))
7821 (js2-parse-statement)))
7822 end (js2-node-end (or if-false if-true))
7823 pn (make-js2-if-node :pos pos
7825 :condition (car cond)
7829 :lp (js2-relpos (second cond) pos)
7830 :rp (js2-relpos (third cond) pos)))
7831 (js2-node-add-children pn (car cond) if-true if-false)
7834 (defun js2-parse-switch ()
7835 "Parser for if-statement. Last matched token must be js2-SWITCH."
7836 (let ((pos js2-token-beg)
7849 (if (js2-must-match js2-LP "msg.no.paren.switch")
7850 (setq lp js2-token-beg))
7851 (setq discriminant (js2-parse-expr)
7852 pn (make-js2-switch-node :discriminant discriminant
7854 :lp (js2-relpos lp pos)))
7855 (js2-node-add-children pn discriminant)
7856 (js2-enter-switch pn)
7859 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7860 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7861 (js2-must-match js2-LC "msg.no.brace.switch")
7864 (setq tt (js2-next-token)
7865 case-pos js2-token-beg)
7868 (setf (js2-node-len pn) (- js2-token-end pos))
7869 (throw 'break nil)) ; done
7871 (setq case-expr (js2-parse-expr))
7872 (js2-must-match js2-COLON "msg.no.colon.case"))
7875 (js2-report-error "msg.double.switch.default"))
7878 (js2-must-match js2-COLON "msg.no.colon.case"))
7880 (js2-report-error "msg.bad.switch")
7881 (throw 'break nil)))
7882 (setq case-node (make-js2-case-node :pos case-pos
7883 :len (- js2-token-end case-pos)
7885 (js2-node-add-children case-node case-expr)
7886 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7890 (setf stmt (js2-parse-statement)
7891 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7892 (js2-block-node-push case-node stmt))
7893 (push case-node cases)))
7894 ;; add cases last, as pushing reverses the order to be correct
7896 (js2-node-add-children pn kid)
7897 (push kid (js2-switch-node-cases pn)))
7899 (js2-exit-switch))))
7901 (defun js2-parse-while ()
7902 "Parser for while-statement. Last matched token must be js2-WHILE."
7903 (let ((pos js2-token-beg)
7904 (pn (make-js2-while-node))
7911 (setf cond (js2-parse-condition)
7912 (js2-while-node-condition pn) (car cond)
7913 body (js2-parse-statement)
7914 (js2-while-node-body pn) body
7915 (js2-node-len pn) (- (js2-node-end body) pos)
7916 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7917 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7918 (js2-node-add-children pn body (car cond)))
7922 (defun js2-parse-do ()
7923 "Parser for do-statement. Last matched token must be js2-DO."
7924 (let ((pos js2-token-beg)
7925 (pn (make-js2-do-node))
7933 (setq body (js2-parse-statement))
7934 (js2-must-match js2-WHILE "msg.no.while.do")
7935 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7936 cond (js2-parse-condition)
7937 (js2-do-node-condition pn) (car cond)
7938 (js2-do-node-body pn) body
7940 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7941 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7942 (js2-node-add-children pn (car cond) body))
7944 ;; Always auto-insert semicolon to follow SpiderMonkey:
7945 ;; It is required by ECMAScript but is ignored by the rest of
7946 ;; world; see bug 238945
7947 (if (js2-match-token js2-SEMI)
7948 (setq end js2-ts-cursor))
7949 (setf (js2-node-len pn) (- end pos))
7952 (defun js2-parse-for ()
7953 "Parser for for-statement. Last matched token must be js2-FOR.
7954 Parses for, for-in, and for each-in statements."
7955 (let ((for-pos js2-token-beg)
7956 pn is-for-each is-for-in-or-of is-for-of
7957 in-pos each-pos tmp-pos
7958 init ; Node init is also foo in 'foo in object'
7959 cond ; Node cond is also object in 'foo in object'
7960 incr ; 3rd section of for-loop initializer
7963 ;; See if this is a for each () instead of just a for ()
7964 (when (js2-match-token js2-NAME)
7965 (if (string= "each" js2-ts-string)
7968 each-pos (- js2-token-beg for-pos)) ; relative
7969 (js2-record-face 'font-lock-keyword-face))
7970 (js2-report-error "msg.no.paren.for")))
7971 (if (js2-must-match js2-LP "msg.no.paren.for")
7972 (setq lp (- js2-token-beg for-pos)))
7973 (setq tt (js2-peek-token))
7974 ;; 'for' makes local scope
7975 (js2-push-scope (make-js2-scope))
7977 ;; parse init clause
7978 (let ((js2-in-for-init t)) ; set as dynamic variable
7981 (setq init (make-js2-empty-expr-node)))
7982 ((or (= tt js2-VAR) (= tt js2-LET))
7984 (setq init (js2-parse-variables tt js2-token-beg)))
7986 (setq init (js2-parse-expr)))))
7987 (if (or (js2-match-token js2-IN)
7988 (and (>= js2-language-version 200)
7989 (js2-match-contextual-kwd "of")
7990 (setq is-for-of t)))
7991 (setq is-for-in-or-of t
7992 in-pos (- js2-token-beg for-pos)
7993 ;; scope of iteration target object is not the scope we've created above.
7994 ;; stash current scope temporary.
7995 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7996 (js2-parse-expr))) ; object over which we're iterating
7997 ;; else ordinary for loop - parse cond and incr
7998 (js2-must-match js2-SEMI "msg.no.semi.for")
7999 (setq cond (if (= (js2-peek-token) js2-SEMI)
8000 (make-js2-empty-expr-node) ; no loop condition
8002 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8003 (setq tmp-pos js2-token-end
8004 incr (if (= (js2-peek-token) js2-RP)
8005 (make-js2-empty-expr-node :pos tmp-pos)
8007 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8008 (setq rp (- js2-token-beg for-pos)))
8009 (if (not is-for-in-or-of)
8010 (setq pn (make-js2-for-node :init init
8015 ;; cond could be null if 'in obj' got eaten by the init node.
8016 (if (js2-infix-node-p init)
8017 ;; it was (foo in bar) instead of (var foo in bar)
8018 (setq cond (js2-infix-node-right init)
8019 init (js2-infix-node-left init))
8020 (if (and (js2-var-decl-node-p init)
8021 (> (length (js2-var-decl-node-kids init)) 1))
8022 (js2-report-error "msg.mult.index")))
8023 (setq pn (make-js2-for-in-node :iterator init
8026 :foreach-p is-for-each
8034 ;; We have to parse the body -after- creating the loop node,
8035 ;; so that the loop node appears in the js2-loop-set, allowing
8036 ;; break/continue statements to find the enclosing loop.
8037 (setf body (js2-parse-statement)
8038 (js2-loop-node-body pn) body
8039 (js2-node-pos pn) for-pos
8040 (js2-node-len pn) (- (js2-node-end body) for-pos))
8041 (js2-node-add-children pn init cond incr body))
8047 (defun js2-parse-try ()
8048 "Parser for try-statement. Last matched token must be js2-TRY."
8049 (let ((try-pos js2-token-beg)
8067 (if (/= (js2-peek-token) js2-LC)
8068 (js2-report-error "msg.no.brace.try"))
8069 (setq try-block (js2-parse-statement)
8070 try-end (js2-node-end try-block)
8071 peek (js2-peek-token))
8074 (while (js2-match-token js2-CATCH)
8075 (setq catch-pos js2-token-beg
8080 (if saw-default-catch
8081 (js2-report-error "msg.catch.unreachable"))
8082 (if (js2-must-match js2-LP "msg.no.paren.catch")
8083 (setq lp (- js2-token-beg catch-pos)))
8084 (js2-push-scope (make-js2-scope))
8085 (let ((tt (js2-peek-token)))
8087 ;; destructuring pattern
8088 ;; catch ({ message, file }) { ... }
8089 ((or (= tt js2-LB) (= tt js2-LC))
8090 (setq param (js2-parse-destruct-primary-expr))
8091 (js2-define-destruct-symbols param js2-LET nil))
8094 (js2-must-match js2-NAME "msg.bad.catchcond")
8095 (setq param (js2-create-name-node))
8096 (js2-define-symbol js2-LET js2-ts-string param))))
8098 (if (js2-match-token js2-IF)
8099 (setq guard-kwd (- js2-token-beg catch-pos)
8100 catch-cond (js2-parse-expr))
8101 (setq saw-default-catch t))
8102 (if (js2-must-match js2-RP "msg.bad.catchcond")
8103 (setq rp (- js2-token-beg catch-pos)))
8104 (js2-must-match js2-LC "msg.no.brace.catchblock")
8105 (setq block (js2-parse-statements)
8106 try-end (js2-node-end block)
8107 catch-node (make-js2-catch-node :pos catch-pos
8109 :guard-expr catch-cond
8110 :guard-kwd guard-kwd
8115 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8116 (setq try-end js2-token-beg))
8117 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8118 (js2-node-len catch-node) (- try-end catch-pos))
8119 (js2-node-add-children catch-node param catch-cond block)
8120 (push catch-node catch-blocks)))
8121 ((/= peek js2-FINALLY)
8122 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8123 (js2-node-pos try-block)
8124 (- (setq try-end (js2-node-end try-block))
8125 (js2-node-pos try-block)))))
8126 (when (js2-match-token js2-FINALLY)
8127 (setq finally-pos js2-token-beg
8128 block (js2-parse-statement)
8129 try-end (js2-node-end block)
8130 finally-block (make-js2-finally-node :pos finally-pos
8131 :len (- try-end finally-pos)
8133 (js2-node-add-children finally-block block))
8134 (setq pn (make-js2-try-node :pos try-pos
8135 :len (- try-end try-pos)
8136 :try-block try-block
8137 :finally-block finally-block))
8138 (js2-node-add-children pn try-block finally-block)
8139 ;; push them onto the try-node, which reverses and corrects their order
8140 (dolist (cb catch-blocks)
8141 (js2-node-add-children pn cb)
8142 (push cb (js2-try-node-catch-clauses pn)))
8145 (defun js2-parse-throw ()
8146 "Parser for throw-statement. Last matched token must be js2-THROW."
8147 (let ((pos js2-token-beg)
8151 (if (= (js2-peek-token-or-eol) js2-EOL)
8152 ;; ECMAScript does not allow new lines before throw expression,
8154 (js2-report-error "msg.bad.throw.eol"))
8155 (setq expr (js2-parse-expr)
8156 pn (make-js2-throw-node :pos pos
8157 :len (- (js2-node-end expr) pos)
8159 (js2-node-add-children pn expr)
8162 (defsubst js2-match-jump-label-name (label-name)
8163 "If break/continue specified a label, return that label's labeled stmt.
8164 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8165 does not match an existing label, reports an error and returns nil."
8166 (let ((bundle (cdr (assoc label-name js2-label-set))))
8168 (js2-report-error "msg.undef.label"))
8171 (defun js2-parse-break ()
8172 "Parser for break-statement. Last matched token must be js2-BREAK."
8173 (let ((pos js2-token-beg)
8175 break-target ; statement to break from
8176 break-label ; in "break foo", name-node representing the foo
8177 labels ; matching labeled statement to break to
8179 (js2-consume-token) ; `break'
8180 (when (eq (js2-peek-token-or-eol) js2-NAME)
8182 (setq break-label (js2-create-name-node)
8183 end (js2-node-end break-label)
8184 ;; matchJumpLabelName only matches if there is one
8185 labels (js2-match-jump-label-name js2-ts-string)
8186 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8187 (unless (or break-target break-label)
8188 ;; no break target specified - try for innermost enclosing loop/switch
8189 (if (null js2-loop-and-switch-set)
8191 (js2-report-error "msg.bad.break" nil pos (length "break")))
8192 (setq break-target (car js2-loop-and-switch-set))))
8193 (setq pn (make-js2-break-node :pos pos
8196 :target break-target))
8197 (js2-node-add-children pn break-label) ; but not break-target
8200 (defun js2-parse-continue ()
8201 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8202 (let ((pos js2-token-beg)
8204 label ; optional user-specified label, a `js2-name-node'
8205 labels ; current matching labeled stmt, if any
8206 target ; the `js2-loop-node' target of this continue stmt
8208 (js2-consume-token) ; `continue'
8209 (when (= (js2-peek-token-or-eol) js2-NAME)
8211 (setq label (js2-create-name-node)
8212 end (js2-node-end label)
8213 ;; matchJumpLabelName only matches if there is one
8214 labels (js2-match-jump-label-name js2-ts-string)))
8216 ((null labels) ; no current label to go to
8217 (if (null js2-loop-set) ; no loop to continue to
8218 (js2-report-error "msg.continue.outside" nil pos
8219 (length "continue"))
8220 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8222 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8223 (setq target (js2-labeled-stmt-node-stmt labels))
8224 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8225 (setq pn (make-js2-continue-node :pos pos
8229 (js2-node-add-children pn label) ; but not target - it's not our child
8232 (defun js2-parse-with ()
8233 "Parser for with-statement. Last matched token must be js2-WITH."
8235 (let ((pos js2-token-beg)
8237 (if (js2-must-match js2-LP "msg.no.paren.with")
8238 (setq lp js2-token-beg))
8239 (setq obj (js2-parse-expr))
8240 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8241 (setq rp js2-token-beg))
8242 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8243 (setq body (js2-parse-statement)))
8244 (setq pn (make-js2-with-node :pos pos
8245 :len (- (js2-node-end body) pos)
8248 :lp (js2-relpos lp pos)
8249 :rp (js2-relpos rp pos)))
8250 (js2-node-add-children pn obj body)
8253 (defun js2-parse-const-var ()
8254 "Parser for var- or const-statement.
8255 Last matched token must be js2-CONST or js2-VAR."
8256 (let ((tt (js2-peek-token))
8261 (setq expr (js2-parse-variables tt js2-token-beg)
8262 pn (make-js2-expr-stmt-node :pos pos
8263 :len (- (js2-node-end expr) pos)
8265 (js2-node-add-children pn expr)
8268 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8269 (let ((pn (make-js2-expr-stmt-node :pos pos
8270 :len (js2-node-len expr)
8271 :type (if (js2-inside-function)
8276 (js2-node-add-children pn expr))
8279 (defun js2-parse-let-stmt ()
8280 "Parser for let-statement. Last matched token must be js2-LET."
8282 (let ((pos js2-token-beg)
8285 (if (= (js2-peek-token) js2-LP)
8286 ;; let expression in statement context
8287 (setq expr (js2-parse-let pos 'statement)
8288 pn (js2-wrap-with-expr-stmt pos expr t))
8289 ;; else we're looking at a statement like let x=6, y=7;
8290 (setf expr (js2-parse-variables js2-LET pos)
8291 pn (js2-wrap-with-expr-stmt pos expr t)
8292 (js2-node-type pn) js2-EXPR_RESULT))
8295 (defun js2-parse-ret-yield ()
8296 (js2-parse-return-or-yield (js2-peek-token) nil))
8298 (defconst js2-parse-return-stmt-enders
8299 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8301 (defsubst js2-now-all-set (before after mask)
8302 "Return whether or not the bits in the mask have changed to all set.
8303 BEFORE is bits before change, AFTER is bits after change, and MASK is
8304 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8306 (and (/= (logand before mask) mask)
8307 (= (logand after mask) mask)))
8309 (defun js2-parse-return-or-yield (tt expr-context)
8310 (let ((pos js2-token-beg)
8312 (before js2-end-flags)
8313 (inside-function (js2-inside-function))
8317 (unless inside-function
8318 (js2-report-error (if (eq tt js2-RETURN)
8322 ;; This is ugly, but we don't want to require a semicolon.
8323 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8324 (setq e (js2-parse-expr)
8325 end (js2-node-end e)))
8328 (js2-set-flag js2-end-flags (if (null e)
8330 js2-end-returns-value))
8331 (setq ret (make-js2-return-node :pos pos
8334 (js2-node-add-children ret e)
8335 ;; See if we need a strict mode warning.
8336 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8337 ;; more thorough and accurate than this before/after flag check.
8338 ;; E.g. if there's a finally-block that always returns, we shouldn't
8339 ;; show a warning generated by inconsistent returns in the catch blocks.
8340 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8341 ;; so we know which returns/yields to highlight, and we should get rid of
8342 ;; all the checking in `js2-parse-return-or-yield'.
8343 (if (and js2-strict-inconsistent-return-warning
8344 (js2-now-all-set before js2-end-flags
8345 (logior js2-end-returns js2-end-returns-value)))
8346 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8348 (unless (js2-inside-function)
8349 (js2-report-error "msg.bad.yield"))
8350 (js2-set-flag js2-end-flags js2-end-yields)
8351 (setq ret (make-js2-yield-node :pos pos
8354 (js2-node-add-children ret e)
8355 (unless expr-context
8357 ret (js2-wrap-with-expr-stmt pos e t))
8358 (js2-set-requires-activation)
8359 (js2-set-is-generator))))
8360 ;; see if we are mixing yields and value returns.
8361 (when (and inside-function
8362 (js2-now-all-set before js2-end-flags
8363 (logior js2-end-yields js2-end-returns-value)))
8364 (setq name (js2-function-name js2-current-script-or-fn))
8365 (if (zerop (length name))
8366 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8367 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8370 (defun js2-parse-debugger ()
8372 (make-js2-keyword-node :type js2-DEBUGGER))
8374 (defun js2-parse-block ()
8375 "Parser for a curly-delimited statement block.
8376 Last token matched must be js2-LC."
8377 (let ((pos js2-token-beg)
8378 (pn (make-js2-scope)))
8383 (js2-parse-statements pn)
8384 (js2-must-match js2-RC "msg.no.brace.block")
8385 (setf (js2-node-len pn) (- js2-token-end pos)))
8389 ;; for js2-ERROR too, to have a node for error recovery to work on
8390 (defun js2-parse-semi ()
8391 "Parse a statement or handle an error.
8392 Last matched token is js2-SEMI or js2-ERROR."
8393 (let ((tt (js2-peek-token)) pos len)
8395 (if (eq tt js2-SEMI)
8396 (make-js2-empty-expr-node :len 1)
8397 (setq pos js2-token-beg
8398 len (- js2-token-beg pos))
8399 (js2-report-error "msg.syntax" nil pos len)
8400 (make-js2-error-node :pos pos :len len))))
8402 (defun js2-parse-default-xml-namespace ()
8403 "Parse a `default xml namespace = <expr>' e4x statement."
8404 (let ((pos js2-token-beg)
8405 end len expr unary es)
8408 (js2-set-requires-activation)
8409 (setq len (- js2-ts-cursor pos))
8410 (unless (and (js2-match-token js2-NAME)
8411 (string= js2-ts-string "xml"))
8412 (js2-report-error "msg.bad.namespace" nil pos len))
8413 (unless (and (js2-match-token js2-NAME)
8414 (string= js2-ts-string "namespace"))
8415 (js2-report-error "msg.bad.namespace" nil pos len))
8416 (unless (js2-match-token js2-ASSIGN)
8417 (js2-report-error "msg.bad.namespace" nil pos len))
8418 (setq expr (js2-parse-expr)
8419 end (js2-node-end expr)
8420 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8424 (js2-node-add-children unary expr)
8425 (make-js2-expr-stmt-node :pos pos
8429 (defun js2-record-label (label bundle)
8430 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8432 (let ((name (js2-label-node-name label))
8435 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8436 ;; flag both labels if possible when used in editing mode
8437 (if (and js2-parse-ide-mode
8438 (setq dup (js2-get-label-by-name labeled-stmt name)))
8439 (js2-report-error "msg.dup.label" nil
8440 (js2-node-abs-pos dup) (js2-node-len dup)))
8441 (js2-report-error "msg.dup.label" nil
8442 (js2-node-pos label) (js2-node-len label)))
8443 (js2-labeled-stmt-node-add-label bundle label)
8444 (js2-node-add-children bundle label)
8445 ;; Add one reference to the bundle per label in `js2-label-set'
8446 (push (cons name bundle) js2-label-set)))
8448 (defun js2-parse-name-or-label ()
8449 "Parser for identifier or label. Last token matched must be js2-NAME.
8450 Called when we found a name in a statement context. If it's a label, we gather
8451 up any following labels and the next non-label statement into a
8452 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8453 expression and return it wrapped in a `js2-expr-stmt-node'."
8454 (let ((pos js2-token-beg)
8461 ;; set check for label and call down to `js2-parse-primary-expr'
8462 (js2-set-check-for-label)
8463 (setq expr (js2-parse-expr))
8464 (if (/= (js2-node-type expr) js2-LABEL)
8465 ;; Parsed non-label expression - wrap with expression stmt.
8466 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8467 ;; else parsed a label
8468 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8469 (js2-record-label expr bundle)
8470 ;; look for more labels
8471 (while (and continue (= (js2-peek-token) js2-NAME))
8472 (js2-set-check-for-label)
8473 (setq expr (js2-parse-expr))
8474 (if (/= (js2-node-type expr) js2-LABEL)
8476 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8478 (js2-auto-insert-semicolon stmt))
8479 (js2-record-label expr bundle)))
8480 ;; no more labels; now parse the labeled statement
8483 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8484 (setq stmt (js2-statement-helper))))
8485 ;; remove the labels for this statement from the global set
8486 (dolist (label (js2-labeled-stmt-node-labels bundle))
8487 (setq js2-label-set (remove label js2-label-set))))
8488 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8489 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8490 (js2-node-add-children bundle stmt)
8493 (defun js2-parse-expr-stmt ()
8494 "Default parser in statement context, if no recognized statement found."
8495 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8497 (defun js2-parse-variables (decl-type pos)
8498 "Parse a comma-separated list of variable declarations.
8499 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8501 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8502 For 'var' or 'const', the keyword should be the token last scanned.
8504 POS is the position where the node should start. It's sometimes the
8505 var/const/let keyword, and other times the beginning of the first token
8506 in the first variable declaration.
8508 Returns the parsed `js2-var-decl-node' expression node."
8509 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8521 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8522 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8523 ;; var {a, b} = baz;
8525 (setq destructuring nil
8528 kid-pos js2-token-beg
8531 (if (or (= tt js2-LB) (= tt js2-LC))
8532 ;; Destructuring assignment, e.g., var [a, b] = ...
8533 (setq destructuring (js2-parse-destruct-primary-expr)
8534 end (js2-node-end destructuring))
8535 ;; Simple variable name
8536 (when (js2-must-match js2-NAME "msg.bad.var")
8537 (setq name (js2-create-name-node)
8541 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8542 (when (js2-match-token js2-ASSIGN)
8543 (setq init (js2-parse-assign-expr)
8544 end (js2-node-end init))
8545 (js2-record-imenu-functions init name))
8547 (js2-set-face nbeg nend (if (js2-function-node-p init)
8548 'font-lock-function-name-face
8549 'font-lock-variable-name-face)
8551 (setq vi (make-js2-var-init-node :pos kid-pos
8552 :len (- end kid-pos)
8556 (if (and (null init) (not js2-in-for-init))
8557 (js2-report-error "msg.destruct.assign.no.init"))
8558 (js2-define-destruct-symbols destructuring
8560 'font-lock-variable-name-face)
8561 (setf (js2-var-init-node-target vi) destructuring))
8562 (setf (js2-var-init-node-target vi) name))
8563 (setf (js2-var-init-node-initializer vi) init)
8564 (js2-node-add-children vi name destructuring init)
8565 (js2-block-node-push result vi)
8566 (unless (js2-match-token js2-COMMA)
8567 (setq continue nil)))
8568 (setf (js2-node-len result) (- end pos))
8571 (defun js2-parse-let (pos &optional stmt-p)
8572 "Parse a let expression or statement.
8573 A let-expression is of the form `let (vars) expr'.
8574 A let-statment is of the form `let (vars) {statements}'.
8575 The third form of let is a variable declaration list, handled
8576 by `js2-parse-variables'."
8577 (let ((pn (make-js2-let-node :pos pos))
8579 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8580 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8584 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8585 (if (js2-must-match js2-RP "msg.no.paren.let")
8586 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8587 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8591 (setf beg js2-token-beg ; position stmt at LC
8592 body (js2-parse-statements))
8593 (js2-must-match js2-RC "msg.no.curly.let")
8594 (setf (js2-node-len body) (- js2-token-end beg)
8595 (js2-node-len pn) (- js2-token-end pos)
8596 (js2-let-node-body pn) body
8597 (js2-node-type pn) js2-LET))
8599 (setf body (js2-parse-expr)
8600 (js2-node-len pn) (- (js2-node-end body) pos)
8601 (js2-let-node-body pn) body))
8602 (js2-node-add-children pn vars body))
8606 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8607 (js2-scope-put-symbol (or scope js2-current-scope)
8609 (make-js2-symbol decl-type name node)))
8611 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8612 "Define a symbol in the current scope.
8613 If NODE is non-nil, it is the AST node associated with the symbol."
8614 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8615 (symbol (if defining-scope
8616 (js2-scope-get-symbol defining-scope name)))
8617 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8619 ((and symbol ; already defined
8620 (or (= sdt js2-CONST) ; old version is const
8621 (= decl-type js2-CONST) ; new version is const
8622 ;; two let-bound vars in this block have same name
8623 (and (= sdt js2-LET)
8624 (eq defining-scope js2-current-scope))))
8627 ((= sdt js2-CONST) "msg.const.redecl")
8628 ((= sdt js2-LET) "msg.let.redecl")
8629 ((= sdt js2-VAR) "msg.var.redecl")
8630 ((= sdt js2-FUNCTION) "msg.function.redecl")
8631 (t "msg.parm.redecl"))
8633 ((= decl-type js2-LET)
8634 (if (and (not ignore-not-in-block)
8635 (or (= (js2-node-type js2-current-scope) js2-IF)
8636 (js2-loop-node-p js2-current-scope)))
8637 (js2-report-error "msg.let.decl.not.in.block")
8638 (js2-define-new-symbol decl-type name node)))
8639 ((or (= decl-type js2-VAR)
8640 (= decl-type js2-CONST)
8641 (= decl-type js2-FUNCTION))
8643 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8644 (js2-add-strict-warning "msg.var.redecl" name)
8645 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8646 (js2-add-strict-warning "msg.var.hides.arg" name)))
8647 (js2-define-new-symbol decl-type name node
8648 js2-current-script-or-fn)))
8649 ((= decl-type js2-LP)
8651 ;; must be duplicate parameter. Second parameter hides the
8652 ;; first, so go ahead and add the second pararameter
8653 (js2-report-warning "msg.dup.parms" name))
8654 (js2-define-new-symbol decl-type name node))
8655 (t (js2-code-bug)))))
8657 (defun js2-parse-expr (&optional oneshot)
8658 (let* ((pn (js2-parse-assign-expr))
8659 (pos (js2-node-pos pn))
8663 (while (and (not oneshot)
8664 (js2-match-token js2-COMMA))
8665 (setq op-pos (- js2-token-beg pos)) ; relative
8666 (if (= (js2-peek-token) js2-YIELD)
8667 (js2-report-error "msg.yield.parenthesized"))
8668 (setq right (js2-parse-assign-expr)
8670 pn (make-js2-infix-node :type js2-COMMA
8672 :len (- js2-ts-cursor pos)
8676 (js2-node-add-children pn left right))
8679 (defun js2-parse-assign-expr ()
8680 (let ((tt (js2-peek-token))
8686 (if (= tt js2-YIELD)
8687 (js2-parse-return-or-yield tt t)
8688 ;; not yield - parse assignment expression
8689 (setq pn (js2-parse-cond-expr)
8690 tt (js2-peek-token))
8691 (when (and (<= js2-first-assign tt)
8692 (<= tt js2-last-assign))
8693 ;; tt express assignment (=, |=, ^=, ..., %=)
8695 (setq op-pos (- js2-token-beg pos) ; relative
8697 right (js2-parse-assign-expr)
8698 pn (make-js2-assign-node :type tt
8700 :len (- (js2-node-end right) pos)
8704 (when js2-parse-ide-mode
8705 (js2-highlight-assign-targets pn left right)
8706 (js2-record-imenu-functions right left))
8707 ;; do this last so ide checks above can use absolute positions
8708 (js2-node-add-children pn left right))
8711 (defun js2-parse-cond-expr ()
8712 (let ((pos js2-token-beg)
8713 (pn (js2-parse-or-expr))
8719 (when (js2-match-token js2-HOOK)
8720 (setq q-pos (- js2-token-beg pos)
8721 if-true (js2-parse-assign-expr))
8722 (js2-must-match js2-COLON "msg.no.colon.cond")
8723 (setq c-pos (- js2-token-beg pos)
8724 if-false (js2-parse-assign-expr)
8726 pn (make-js2-cond-node :pos pos
8727 :len (- (js2-node-end if-false) pos)
8728 :test-expr test-expr
8730 :false-expr if-false
8733 (js2-node-add-children pn test-expr if-true if-false))
8736 (defun js2-make-binary (type left parser)
8737 "Helper for constructing a binary-operator AST node.
8738 LEFT is the left-side-expression, already parsed, and the
8739 binary operator should have just been matched.
8740 PARSER is a function to call to parse the right operand,
8741 or a `js2-node' struct if it has already been parsed."
8742 (let* ((pos (js2-node-pos left))
8743 (op-pos (- js2-token-beg pos))
8744 (right (if (js2-node-p parser)
8747 (pn (make-js2-infix-node :type type
8749 :len (- (js2-node-end right) pos)
8753 (js2-node-add-children pn left right)
8756 (defun js2-parse-or-expr ()
8757 (let ((pn (js2-parse-and-expr)))
8758 (when (js2-match-token js2-OR)
8759 (setq pn (js2-make-binary js2-OR
8761 'js2-parse-or-expr)))
8764 (defun js2-parse-and-expr ()
8765 (let ((pn (js2-parse-bit-or-expr)))
8766 (when (js2-match-token js2-AND)
8767 (setq pn (js2-make-binary js2-AND
8769 'js2-parse-and-expr)))
8772 (defun js2-parse-bit-or-expr ()
8773 (let ((pn (js2-parse-bit-xor-expr)))
8774 (while (js2-match-token js2-BITOR)
8775 (setq pn (js2-make-binary js2-BITOR
8777 'js2-parse-bit-xor-expr)))
8780 (defun js2-parse-bit-xor-expr ()
8781 (let ((pn (js2-parse-bit-and-expr)))
8782 (while (js2-match-token js2-BITXOR)
8783 (setq pn (js2-make-binary js2-BITXOR
8785 'js2-parse-bit-and-expr)))
8788 (defun js2-parse-bit-and-expr ()
8789 (let ((pn (js2-parse-eq-expr)))
8790 (while (js2-match-token js2-BITAND)
8791 (setq pn (js2-make-binary js2-BITAND
8793 'js2-parse-eq-expr)))
8796 (defconst js2-parse-eq-ops
8797 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8799 (defun js2-parse-eq-expr ()
8800 (let ((pn (js2-parse-rel-expr))
8802 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8804 (setq pn (js2-make-binary tt
8806 'js2-parse-rel-expr)))
8809 (defconst js2-parse-rel-ops
8810 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8812 (defun js2-parse-rel-expr ()
8813 (let ((pn (js2-parse-shift-expr))
8817 (setq tt (js2-peek-token))
8819 ((and js2-in-for-init (= tt js2-IN))
8820 (setq continue nil))
8821 ((memq tt js2-parse-rel-ops)
8823 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8825 (setq continue nil))))
8828 (defconst js2-parse-shift-ops
8829 (list js2-LSH js2-URSH js2-RSH))
8831 (defun js2-parse-shift-expr ()
8832 (let ((pn (js2-parse-add-expr))
8836 (setq tt (js2-peek-token))
8837 (if (memq tt js2-parse-shift-ops)
8840 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8841 (setq continue nil)))
8844 (defun js2-parse-add-expr ()
8845 (let ((pn (js2-parse-mul-expr))
8849 (setq tt (js2-peek-token))
8850 (if (or (= tt js2-ADD) (= tt js2-SUB))
8853 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8854 (setq continue nil)))
8857 (defconst js2-parse-mul-ops
8858 (list js2-MUL js2-DIV js2-MOD))
8860 (defun js2-parse-mul-expr ()
8861 (let ((pn (js2-parse-unary-expr))
8865 (setq tt (js2-peek-token))
8866 (if (memq tt js2-parse-mul-ops)
8869 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8870 (setq continue nil)))
8873 (defsubst js2-make-unary (type parser &rest args)
8874 "Make a unary node of type TYPE.
8875 PARSER is either a node (for postfix operators) or a function to call
8876 to parse the operand (for prefix operators)."
8877 (let* ((pos js2-token-beg)
8878 (postfix (js2-node-p parser))
8881 (apply parser args)))
8884 (if postfix ; e.g. i++
8885 (setq pos (js2-node-pos expr)
8887 (setq end (js2-node-end expr)))
8888 (setq pn (make-js2-unary-node :type type
8892 (js2-node-add-children pn expr)
8895 (defconst js2-incrementable-node-types
8896 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8897 "Node types that can be the operand of a ++ or -- operator.")
8899 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8900 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8901 js2-incrementable-node-types)
8902 (js2-report-error (if (= tt js2-INC)
8905 nil beg (- end beg))))
8907 (defun js2-parse-unary-expr ()
8908 (let ((tt (js2-peek-token))
8911 ((or (= tt js2-VOID)
8916 (js2-make-unary tt 'js2-parse-unary-expr))
8919 ;; Convert to special POS token in decompiler and parse tree
8920 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8923 ;; Convert to special NEG token in decompiler and parse tree
8924 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8929 (setq beg js2-token-beg
8931 expr (js2-make-unary tt 'js2-parse-member-expr t))
8932 (js2-check-bad-inc-dec tt beg end expr)))
8935 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8938 (make-js2-error-node)) ; try to continue
8940 js2-compiler-xml-available)
8941 ;; XML stream encountered in expression.
8943 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8945 (setq pn (js2-parse-member-expr t)
8946 ;; Don't look across a newline boundary for a postfix incop.
8947 tt (js2-peek-token-or-eol))
8948 (when (or (= tt js2-INC) (= tt js2-DEC))
8951 pn (js2-make-unary tt expr))
8952 (js2-node-set-prop pn 'postfix t)
8953 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8956 (defun js2-parse-xml-initializer ()
8957 "Parse an E4X XML initializer.
8958 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8959 Then I'll postprocess the result, depending on whether we're in IDE
8960 mode or codegen mode, and generate the appropriate rewritten AST.
8961 IDE mode uses a rich AST that models the XML structure. Codegen mode
8962 just concatenates everything and makes a new XML or XMLList out of it."
8963 (let ((tt (js2-get-first-xml-token))
8971 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8972 (js2-report-error "msg.syntax"))
8973 (setq pn-xml (make-js2-xml-node))
8976 (setq first-token nil)
8977 (setq tt (js2-get-next-xml-token)))
8979 ;; js2-XML means we found a {expr} in the XML stream.
8980 ;; The js2-ts-string is the XML up to the left-curly.
8982 (push (make-js2-string-node :pos js2-token-beg
8983 :len (- js2-ts-cursor js2-token-beg))
8985 (js2-must-match js2-LC "msg.syntax")
8986 (setq expr-pos js2-ts-cursor
8987 expr (if (eq (js2-peek-token) js2-RC)
8988 (make-js2-empty-expr-node :pos expr-pos)
8990 (js2-must-match js2-RC "msg.syntax")
8991 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8992 :len (js2-node-len expr)
8994 (js2-node-add-children pn expr)
8996 ;; a js2-XMLEND token means we hit the final close-tag.
8998 (push (make-js2-string-node :pos js2-token-beg
8999 :len (- js2-ts-cursor js2-token-beg))
9001 (dolist (kid (nreverse kids))
9002 (js2-block-node-push pn-xml kid))
9003 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9004 (js2-node-pos pn-xml))
9007 (js2-report-error "msg.syntax")
9008 (setq continue nil))))
9012 (defun js2-parse-argument-list ()
9013 "Parse an argument list and return it as a lisp list of nodes.
9014 Returns the list in reverse order. Consumes the right-paren token."
9016 (unless (js2-match-token js2-RP)
9018 (if (= (js2-peek-token) js2-YIELD)
9019 (js2-report-error "msg.yield.parenthesized"))
9020 (push (js2-parse-assign-expr) result)
9022 (js2-match-token js2-COMMA))
9023 (js2-must-match js2-RP "msg.no.paren.arg")
9026 (defun js2-parse-member-expr (&optional allow-call-syntax)
9027 (let ((tt (js2-peek-token))
9037 (setq pn (js2-parse-primary-expr))
9038 ;; parse a 'new' expression
9040 (setq pos js2-token-beg
9042 target (js2-parse-member-expr)
9043 end (js2-node-end target)
9044 pn (make-js2-new-node :pos pos
9047 (js2-node-add-children pn target)
9048 (when (js2-match-token js2-LP)
9049 ;; Add the arguments to pn, if any are supplied.
9050 (setf beg pos ; start of "new" keyword
9052 args (nreverse (js2-parse-argument-list))
9053 (js2-new-node-args pn) args
9055 (js2-new-node-lp pn) (- pos beg)
9056 (js2-new-node-rp pn) (- end 1 beg))
9057 (apply #'js2-node-add-children pn args))
9058 (when (and js2-allow-rhino-new-expr-initializer
9059 (js2-match-token js2-LC))
9060 (setf init (js2-parse-object-literal)
9061 end (js2-node-end init)
9062 (js2-new-node-initializer pn) init)
9063 (js2-node-add-children pn init))
9064 (setf (js2-node-len pn) (- end beg))) ; end outer if
9065 (js2-parse-member-expr-tail allow-call-syntax pn)))
9067 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9068 "Parse a chain of property/array accesses or function calls.
9069 Includes parsing for E4X operators like `..' and `.@'.
9070 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9071 Returns an expression tree that includes PN, the parent node."
9072 (let ((beg (js2-node-pos pn))
9076 (setq tt (js2-peek-token))
9078 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9079 (setq pn (js2-parse-property-access tt pn)))
9080 ((= tt js2-DOTQUERY)
9081 (setq pn (js2-parse-dot-query pn)))
9083 (setq pn (js2-parse-element-get pn)))
9085 (if allow-call-syntax
9086 (setq pn (js2-parse-function-call pn))
9087 (setq continue nil)))
9089 (setq continue nil))))
9090 (if (>= js2-highlight-level 2)
9091 (js2-parse-highlight-member-expr-node pn))
9094 (defun js2-parse-dot-query (pn)
9095 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9096 Last token parsed must be `js2-DOTQUERY'."
9097 (let ((pos (js2-node-pos pn))
9103 (js2-set-requires-activation)
9104 (setq op-pos js2-token-beg
9105 expr (js2-parse-expr)
9106 end (js2-node-end expr)
9107 pn (make-js2-xml-dot-query-node :left pn
9111 (js2-node-add-children pn
9112 (js2-xml-dot-query-node-left pn)
9113 (js2-xml-dot-query-node-right pn))
9114 (if (js2-must-match js2-RP "msg.no.paren")
9115 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9117 (setf (js2-node-len pn) (- end pos))
9120 (defun js2-parse-element-get (pn)
9121 "Parse an element-get expression, e.g. foo[bar].
9122 Last token parsed must be `js2-RB'."
9123 (let ((lb js2-token-beg)
9124 (pos (js2-node-pos pn))
9128 (setq expr (js2-parse-expr))
9129 (if (js2-must-match js2-RB "msg.no.bracket.index")
9130 (setq rb js2-token-beg))
9131 (setq pn (make-js2-elem-get-node :target pn
9134 :lb (js2-relpos lb pos)
9135 :rb (js2-relpos rb pos)
9136 :len (- js2-token-end pos)))
9137 (js2-node-add-children pn
9138 (js2-elem-get-node-target pn)
9139 (js2-elem-get-node-element pn))
9142 (defun js2-parse-function-call (pn)
9144 (pos (js2-node-pos pn)))
9146 (setq pn (make-js2-call-node :pos pos
9148 :lp (- js2-token-beg pos)))
9149 (js2-node-add-children pn (js2-call-node-target pn))
9150 ;; Add the arguments to pn, if any are supplied.
9151 (setf args (nreverse (js2-parse-argument-list))
9152 (js2-call-node-rp pn) (- js2-token-beg pos)
9153 (js2-call-node-args pn) args)
9154 (apply #'js2-node-add-children pn args)
9155 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9158 (defun js2-parse-property-access (tt pn)
9159 "Parse a property access, XML descendants access, or XML attr access."
9160 (let ((member-type-flags 0)
9161 (dot-pos js2-token-beg)
9162 (dot-len (if (= tt js2-DOTDOT) 2 1))
9164 ref ; right side of . or .. operator
9167 (when (= tt js2-DOTDOT)
9169 (setq member-type-flags js2-descendants-flag))
9170 (if (not js2-compiler-xml-available)
9172 (js2-must-match-prop-name "msg.no.name.after.dot")
9173 (setq name (js2-create-name-node t js2-GETPROP)
9174 result (make-js2-prop-get-node :left pn
9177 :len (- js2-token-end
9179 (js2-node-add-children result pn name)
9181 ;; otherwise look for XML operators
9182 (setf result (if (= tt js2-DOT)
9183 (make-js2-prop-get-node)
9184 (make-js2-infix-node :type js2-DOTDOT))
9185 (js2-node-pos result) (js2-node-pos pn)
9186 (js2-infix-node-op-pos result) dot-pos
9187 (js2-infix-node-left result) pn ; do this after setting position
9188 tt (js2-next-token))
9190 ;; needed for generator.throw()
9192 (js2-save-name-token-data js2-token-beg "throw")
9193 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9194 ;; handles: name, ns::name, ns::*, ns::[expr]
9195 ((js2-valid-prop-name-token tt)
9196 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9197 ;; handles: *, *::name, *::*, *::[expr]
9199 (js2-save-name-token-data js2-token-beg "*")
9200 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9201 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9203 (setq result (js2-parse-attribute-access)))
9205 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9207 (setf (js2-node-len result) (- (js2-node-end ref)
9208 (js2-node-pos result))
9209 (js2-infix-node-right result) ref))
9210 (if (js2-infix-node-p result)
9211 (js2-node-add-children result
9212 (js2-infix-node-left result)
9213 (js2-infix-node-right result)))
9216 (defun js2-parse-attribute-access ()
9217 "Parse an E4X XML attribute expression.
9218 This includes expressions of the forms:
9220 @attr @ns::attr @ns::*
9222 @[expr] @*::[expr] @ns::[expr]
9224 Called if we peeked an '@' token."
9225 (let ((tt (js2-next-token))
9226 (at-pos js2-token-beg))
9228 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9229 ((js2-valid-prop-name-token tt)
9230 (js2-parse-property-name at-pos js2-ts-string 0))
9231 ;; handles: @*, @*::name, @*::*, @*::[expr]
9233 (js2-save-name-token-data js2-token-beg "*")
9234 (js2-parse-property-name js2-token-beg "*" 0))
9237 (js2-parse-xml-elem-ref at-pos))
9239 (js2-report-error "msg.no.name.after.xmlAttr")
9240 ;; Avoid cascaded errors that happen if we make an error node here.
9241 (js2-save-name-token-data js2-token-beg "")
9242 (js2-parse-property-name js2-token-beg "" 0)))))
9244 (defun js2-parse-property-name (at-pos s member-type-flags)
9245 "Check if :: follows name in which case it becomes qualified name.
9247 AT-POS is a natural number if we just read an '@' token, else nil.
9248 S is the name or string that was matched: an identifier, 'throw' or '*'.
9249 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9251 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9252 operator, or the name is followed by ::. For a plain name, returns a
9253 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9254 (let ((pos (or at-pos js2-token-beg))
9256 (name (js2-create-name-node t js2-current-token))
9262 (when (js2-match-token js2-COLONCOLON)
9264 colon-pos js2-token-beg
9265 tt (js2-next-token))
9267 ;; handles name::name
9268 ((js2-valid-prop-name-token tt)
9269 (setq name (js2-create-name-node)))
9272 (js2-save-name-token-data js2-token-beg "*")
9273 (setq name (js2-create-name-node)))
9274 ;; handles name::[expr]
9276 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9278 (js2-report-error "msg.no.name.after.coloncolon"))))
9279 (if (and (null ns) (zerop member-type-flags))
9283 (make-js2-xml-prop-ref-node :pos pos
9284 :len (- (js2-node-end name) pos)
9286 :colon-pos colon-pos
9288 (js2-node-add-children pn name))))))
9290 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9291 "Parse the [expr] portion of an xml element reference.
9292 For instance, @[expr], @*::[expr], or ns::[expr]."
9293 (let* ((lb js2-token-beg)
9294 (pos (or at-pos lb))
9296 (expr (js2-parse-expr))
9297 (end (js2-node-end expr))
9299 (if (js2-must-match js2-RB "msg.no.bracket.index")
9300 (setq rb js2-token-beg
9304 (make-js2-xml-elem-ref-node :pos pos
9306 :namespace namespace
9307 :colon-pos colon-pos
9310 :lb (js2-relpos lb pos)
9311 :rb (js2-relpos rb pos)))
9312 (js2-node-add-children pn namespace expr))))
9314 (defun js2-parse-destruct-primary-expr ()
9315 (let ((js2-is-in-destructuring t))
9316 (js2-parse-primary-expr)))
9318 (defun js2-parse-primary-expr ()
9319 "Parses a literal (leaf) expression of some sort.
9320 Includes complex literals such as functions, object-literals,
9321 array-literals, array comprehensions and regular expressions."
9322 (let ((tt-flagged (js2-next-flagged-token))
9323 pn ; parent node (usually return value)
9325 px-pos ; paren-expr pos
9327 flags ; regexp flags
9329 (setq tt js2-current-token)
9331 ((= tt js2-FUNCTION)
9332 (js2-parse-function 'FUNCTION_EXPRESSION))
9334 (js2-parse-array-literal))
9336 (js2-parse-object-literal))
9338 (js2-parse-let js2-token-beg))
9340 (setq px-pos js2-token-beg
9341 expr (js2-parse-expr))
9342 (js2-must-match js2-RP "msg.no.paren")
9343 (setq pn (make-js2-paren-node :pos px-pos
9345 :len (- js2-token-end px-pos)))
9346 (js2-node-add-children pn (js2-paren-node-expr pn))
9350 (js2-parse-attribute-access))
9352 (js2-parse-name tt-flagged tt))
9354 (make-js2-number-node))
9357 (make-js2-string-node)
9358 (js2-record-face 'font-lock-string-face)))
9359 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9360 ;; Got / or /= which in this context means a regexp literal
9361 (setq px-pos js2-token-beg)
9362 (js2-read-regexp tt)
9363 (setq flags js2-ts-regexp-flags
9364 js2-ts-regexp-flags nil)
9366 (make-js2-regexp-node :pos px-pos
9367 :len (- js2-ts-cursor px-pos)
9368 :value js2-ts-string
9370 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9371 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9372 ((or (= tt js2-NULL)
9376 (make-js2-keyword-node :type tt))
9377 ((= tt js2-RESERVED)
9378 (js2-report-error "msg.reserved.id")
9379 (make-js2-name-node))
9381 ;; the scanner or one of its subroutines reported the error.
9382 (make-js2-error-node))
9384 (setq px-pos (point-at-bol)
9385 len (- js2-ts-cursor px-pos))
9386 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9387 (make-js2-error-node :pos px-pos :len len))
9389 (js2-report-error "msg.syntax")
9390 (make-js2-error-node)))))
9392 (defun js2-parse-name (tt-flagged tt)
9393 (let ((name js2-ts-string)
9394 (name-pos js2-token-beg)
9396 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9397 (= (js2-peek-token) js2-COLON))
9399 ;; Do not consume colon, it is used as unwind indicator
9400 ;; to return to statementHelper.
9401 (make-js2-label-node :pos name-pos
9402 :len (- js2-token-end name-pos)
9404 (js2-set-face name-pos
9406 'font-lock-variable-name-face 'record))
9407 ;; Otherwise not a label, just a name. Unfortunately peeking
9408 ;; the next token to check for a colon has biffed js2-token-beg
9409 ;; and js2-token-end. We store the name's bounds in buffer vars
9410 ;; and `js2-create-name-node' uses them.
9411 (js2-save-name-token-data name-pos name)
9412 (setq node (if js2-compiler-xml-available
9413 (js2-parse-property-name nil name 0)
9414 (js2-create-name-node 'check-activation)))
9415 (if js2-highlight-external-variables
9416 (js2-record-name-node node))
9419 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9420 (js2-add-strict-warning
9422 ;; back up from comma to beginning of line or array/objlit
9424 (js2-node-pos (car elems))
9427 (goto-char comma-pos)
9428 (back-to-indentation)
9432 (defun js2-parse-array-literal ()
9433 (let ((pos js2-token-beg)
9435 (after-lb-or-comma t)
9441 (unless js2-is-in-destructuring
9442 (js2-push-scope (make-js2-scope))) ; for array comp
9444 (setq tt (js2-peek-token))
9449 (setq after-comma js2-token-end)
9450 (if (not after-lb-or-comma)
9451 (setq after-lb-or-comma t)
9455 (= tt js2-EOF)) ; prevent infinite loop
9457 (js2-report-error "msg.no.bracket.arg" nil pos)
9458 (js2-consume-token))
9461 pn (make-js2-array-node :pos pos
9462 :len (- js2-ts-cursor pos)
9463 :elems (nreverse elems)))
9464 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9465 (when (and after-comma (not js2-is-in-destructuring))
9466 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9467 pos elems after-comma)))
9468 ;; destructuring binding
9469 (js2-is-in-destructuring
9470 (push (if (or (= tt js2-LC)
9473 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9474 (js2-parse-destruct-primary-expr)
9477 (js2-report-error "msg.bad.var")
9478 (make-js2-error-node))
9480 (setq after-lb-or-comma nil
9483 ((and (>= js2-language-version 170)
9484 (= tt js2-FOR) ; check for array comprehension
9485 (not after-lb-or-comma) ; "for" can't follow a comma
9486 elems ; must have at least 1 element
9487 (not (cdr elems))) ; but no 2nd element
9489 pn (js2-parse-array-comprehension (car elems) pos)))
9493 (unless after-lb-or-comma
9494 (js2-report-error "msg.no.bracket.arg"))
9495 (push (js2-parse-assign-expr) elems)
9496 (setq after-lb-or-comma nil
9498 (unless js2-is-in-destructuring
9502 (defun js2-parse-array-comprehension (expr pos)
9503 "Parse a JavaScript 1.7 Array Comprehension.
9504 EXPR is the first expression after the opening left-bracket.
9505 POS is the beginning of the LB token preceding EXPR.
9506 We should have just parsed the 'for' keyword before calling this function."
9514 (while (= (js2-peek-token) js2-FOR)
9515 (let ((prev (car loops))) ; rearrange scope chain
9516 (push (setq loop (js2-parse-array-comp-loop)) loops)
9517 (if prev ; each loop is parent scope to the next one
9518 (setf (js2-scope-parent-scope loop) prev)
9519 ; first loop takes expr scope's parent
9520 (setf (js2-scope-parent-scope (setq first loop))
9521 (js2-scope-parent-scope js2-current-scope)))))
9522 ;; set expr scope's parent to the last loop
9523 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9524 (when (= (js2-peek-token) js2-IF)
9526 (setq if-pos (- js2-token-beg pos) ; relative
9527 filter (js2-parse-condition)))
9528 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9529 (setq result (make-js2-array-comp-node :pos pos
9530 :len (- js2-ts-cursor pos)
9532 :loops (nreverse loops)
9533 :filter (car filter)
9534 :lp (js2-relpos (second filter) pos)
9535 :rp (js2-relpos (third filter) pos)
9537 (apply #'js2-node-add-children result expr (car filter)
9538 (js2-array-comp-node-loops result))
9539 (setq js2-current-scope first) ; pop to the first loop
9542 (defun js2-parse-array-comp-loop ()
9543 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9544 Last token peeked should be the initial FOR."
9545 (let ((pos js2-token-beg)
9546 (pn (make-js2-array-comp-loop-node))
9547 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9548 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9552 (when (js2-match-token js2-NAME)
9553 (if (string= js2-ts-string "each")
9556 each-pos (- js2-token-beg pos)) ; relative
9557 (js2-record-face 'font-lock-keyword-face))
9558 (js2-report-error "msg.no.paren.for")))
9559 (if (js2-must-match js2-LP "msg.no.paren.for")
9560 (setq lp (- js2-token-beg pos)))
9561 (setq tt (js2-peek-token))
9565 (setq iter (js2-parse-destruct-primary-expr))
9566 (js2-define-destruct-symbols iter js2-LET
9567 'font-lock-variable-name-face t))
9568 ((js2-match-token js2-NAME)
9569 (setq iter (js2-create-name-node)))
9571 (js2-report-error "msg.bad.var")))
9572 ;; Define as a let since we want the scope of the variable to
9573 ;; be restricted to the array comprehension
9574 (if (js2-name-node-p iter)
9575 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9576 (if (or (js2-match-token js2-IN)
9577 (and (>= js2-language-version 200)
9578 (js2-match-contextual-kwd "of")
9580 (setq in-pos (- js2-token-beg pos))
9581 (js2-report-error "msg.in.after.for.name"))
9582 (setq obj (js2-parse-expr))
9583 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9584 (setq rp (- js2-token-beg pos)))
9585 (setf (js2-node-pos pn) pos
9586 (js2-node-len pn) (- js2-ts-cursor pos)
9587 (js2-array-comp-loop-node-iterator pn) iter
9588 (js2-array-comp-loop-node-object pn) obj
9589 (js2-array-comp-loop-node-in-pos pn) in-pos
9590 (js2-array-comp-loop-node-each-pos pn) each-pos
9591 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9592 (js2-array-comp-loop-node-forof-p pn) forof-p
9593 (js2-array-comp-loop-node-lp pn) lp
9594 (js2-array-comp-loop-node-rp pn) rp)
9595 (js2-node-add-children pn iter obj))
9599 (defun js2-parse-object-literal ()
9600 (let ((pos js2-token-beg)
9607 (setq tt (js2-peek-token))
9609 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9610 ((or (js2-valid-prop-name-token tt)
9612 (setq after-comma nil
9613 result (js2-parse-named-prop tt))
9614 (if (and (null result)
9615 (not js2-recover-from-parse-errors))
9617 (push result elems)))
9618 ;; {12: x} or {10.7: x}
9621 (setq after-comma nil)
9622 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9627 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9628 pos elems after-comma)))
9630 (js2-report-error "msg.bad.prop")
9631 (unless js2-recover-from-parse-errors
9632 (setq continue nil)))) ; end switch
9633 (if (js2-match-token js2-COMMA)
9634 (setq after-comma js2-token-end)
9635 (setq continue nil))) ; end loop
9636 (js2-must-match js2-RC "msg.no.brace.prop")
9637 (setq result (make-js2-object-node :pos pos
9638 :len (- js2-ts-cursor pos)
9639 :elems (nreverse elems)))
9640 (apply #'js2-node-add-children result (js2-object-node-elems result))
9643 (defun js2-parse-named-prop (tt)
9644 "Parse a name, string, or getter/setter object property.
9645 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9647 (let ((string-prop (and (= tt js2-STRING)
9648 (make-js2-string-node)))
9650 (ppos js2-token-beg)
9651 (pend js2-token-end)
9652 (name (js2-create-name-node))
9653 (prop js2-ts-string))
9655 ;; getter/setter prop
9656 ((and (= tt js2-NAME)
9657 (= (js2-peek-token) js2-NAME)
9658 (or (string= prop "get")
9659 (string= prop "set")))
9661 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9662 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9663 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9664 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9665 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9666 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9667 ;; when patterns are used in variable declarations, function parameters,
9668 ;; catch-clause, and iterators.
9669 ;; We have to set `js2-is-in-destructuring' to t when the current
9670 ;; expressions are on the left side of any assignment, but it's difficult
9671 ;; because it requires looking ahead of expression.
9672 ((and js2-is-in-destructuring
9674 (let ((ctk (js2-peek-token)))
9675 (or (= ctk js2-COMMA)
9677 (js2-valid-prop-name-token ctk))))
9682 (setq expr (js2-parse-plain-property (or string-prop name)))
9683 (js2-set-face ppos pend
9684 (if (js2-function-node-p
9685 (js2-object-prop-node-right expr))
9686 'font-lock-function-name-face
9687 'font-lock-variable-name-face)
9690 (defun js2-parse-plain-property (prop)
9691 "Parse a non-getter/setter property in an object literal.
9692 PROP is the node representing the property: a number, name or string."
9693 (js2-must-match js2-COLON "msg.no.colon.prop")
9694 (let* ((pos (js2-node-pos prop))
9695 (colon (- js2-token-beg pos))
9696 (expr (js2-parse-assign-expr))
9697 (result (make-js2-object-prop-node
9699 ;; don't include last consumed token in length
9700 :len (- (+ (js2-node-pos expr)
9701 (js2-node-len expr))
9706 (js2-node-add-children result prop expr)
9709 (defun js2-parse-getter-setter-prop (pos prop get-p)
9710 "Parse getter or setter property in an object literal.
9711 JavaScript syntax is:
9713 { get foo() {...}, set foo(x) {...} }
9715 and expression closure style is also supported
9717 { get foo() x, set foo(x) _x = x }
9719 POS is the start position of the `get' or `set' keyword.
9720 PROP is the `js2-name-node' representing the property name.
9721 GET-P is non-nil if the keyword was `get'."
9722 (let ((type (if get-p js2-GET js2-SET))
9725 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9726 ;; it has to be an anonymous function, as we already parsed the name
9727 (if (/= (js2-node-type fn) js2-FUNCTION)
9728 (js2-report-error "msg.bad.prop")
9729 (if (plusp (length (js2-function-name fn)))
9730 (js2-report-error "msg.bad.prop")))
9731 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9732 (setq end (js2-node-end fn)
9733 result (make-js2-getter-setter-node :type type
9738 (js2-node-add-children result prop fn)
9741 (defun js2-create-name-node (&optional check-activation-p token)
9742 "Create a name node using the token info from last scanned name.
9743 In some cases we need to either synthesize a name node, or we lost
9744 the name token information by peeking. If the TOKEN parameter is
9745 not `js2-NAME', then we use the token info saved in instance vars."
9746 (let ((beg js2-token-beg)
9749 (when (/= js2-current-token js2-NAME)
9750 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9751 s js2-prev-name-token-string
9752 js2-prev-name-token-start nil
9753 js2-prev-name-token-string nil))
9754 (setq name (make-js2-name-node :pos beg
9757 (if check-activation-p
9758 (js2-check-activation-name s (or token js2-NAME)))
9761 ;;; Indentation support
9763 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9764 ;; Karl cleverly deduces that the desired indentation level is often a
9765 ;; function of paren/bracket/brace nesting depth, which can be determined
9766 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9767 ;; then does some equally clever checks to see if we're in the context of a
9768 ;; substatement of a possibly braceless statement keyword such as if, while,
9769 ;; or finally. This approach yields pretty good results.
9771 ;; The indenter is often "wrong", however, and needs to be overridden.
9772 ;; The right long-term solution is probably to emulate (or integrate
9773 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9774 ;; parse tree from `js2-parse' is present, which is not true at the
9775 ;; moment the user is typing, computing indentation is still thousands
9776 ;; of lines of code to handle every possible syntactic edge case.
9778 ;; In the meantime, the compromise solution is that we offer a "bounce
9779 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9780 ;; current line indent among various likely guess points. This approach
9781 ;; is far from perfect, but should at least make it slightly easier to
9782 ;; move the line towards its desired indentation when manually
9783 ;; overriding Karl's heuristic nesting guesser.
9785 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9786 ;; extensions such as `let' and Array comprehensions. Major kudos to
9787 ;; Karl for coming up with the initial approach, which packs a lot of
9788 ;; punch for so little code.
9790 (defconst js2-possibly-braceless-keywords-re
9791 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9792 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9793 "try" "while" "with" "let")))
9794 "Regular expression matching keywords that are optionally
9795 followed by an opening brace.")
9797 (defconst js2-indent-operator-re
9798 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9799 (regexp-opt '("in" "instanceof") 'words))
9800 "Regular expression matching operators that affect indentation
9801 of continued expressions.")
9803 (defconst js2-declaration-keyword-re
9804 (regexp-opt '("var" "let" "const") 'words)
9805 "Regular expression matching variable declaration keywords.")
9807 ;; This function has horrible results if you're typing an array
9808 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9809 ;; in conjunction with electric-indent, so just disabling it.
9810 (defsubst js2-code-at-bol-p ()
9811 "Return t if the first character on line is non-whitespace."
9814 (defun js2-insert-and-indent (key)
9815 "Run command bound to key and indent current line. Runs the command
9816 bound to KEY in the global keymap and indents the current line."
9817 (interactive (list (this-command-keys)))
9818 (let ((cmd (lookup-key (current-global-map) key)))
9820 (call-interactively cmd)))
9821 ;; don't do the electric keys inside comments or strings,
9822 ;; and don't do bounce-indent with them.
9823 (let ((parse-state (syntax-ppss (point)))
9824 (js2-bounce-indent-p (js2-code-at-bol-p)))
9825 (unless (or (nth 3 parse-state)
9826 (nth 4 parse-state))
9827 (indent-according-to-mode))))
9829 (defun js2-re-search-forward-inner (regexp &optional bound count)
9830 "Auxiliary function for `js2-re-search-forward'."
9831 (let (parse saved-point)
9833 (re-search-forward regexp bound)
9834 (setq parse (if saved-point
9835 (parse-partial-sexp saved-point (point))
9836 (syntax-ppss (point))))
9837 (cond ((nth 3 parse)
9839 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9840 (save-excursion (end-of-line) (point)) t))
9844 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9845 (re-search-forward "\\*/"))
9847 (setq count (1- count))))
9848 (setq saved-point (point))))
9851 (defun js2-re-search-forward (regexp &optional bound noerror count)
9852 "Search forward but ignore strings and comments. Invokes
9853 `re-search-forward' but treats the buffer as if strings and
9854 comments have been removed."
9855 (let ((saved-point (point))
9858 '(js2-re-search-forward-inner regexp bound 1))
9860 '(js2-re-search-backward-inner regexp bound (- count)))
9862 '(js2-re-search-forward-inner regexp bound count)))))
9866 (goto-char saved-point)
9868 (error (error-message-string err)))))))
9870 (defun js2-re-search-backward-inner (regexp &optional bound count)
9871 "Auxiliary function for `js2-re-search-backward'."
9872 (let (parse saved-point)
9874 (re-search-backward regexp bound)
9875 (setq parse (if saved-point
9876 (parse-partial-sexp saved-point (point))
9877 (syntax-ppss (point))))
9878 (cond ((nth 3 parse)
9880 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9881 (save-excursion (beginning-of-line) (point)) t))
9883 (goto-char (nth 8 parse)))
9885 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9886 (re-search-backward "/\\*"))
9888 (setq count (1- count))))))
9891 (defun js2-re-search-backward (regexp &optional bound noerror count)
9892 "Search backward but ignore strings and comments. Invokes
9893 `re-search-backward' but treats the buffer as if strings and
9894 comments have been removed."
9895 (let ((saved-point (point))
9898 '(js2-re-search-backward-inner regexp bound 1))
9900 '(js2-re-search-forward-inner regexp bound (- count)))
9902 '(js2-re-search-backward-inner regexp bound count)))))
9906 (goto-char saved-point)
9908 (error (error-message-string err)))))))
9910 (defun js2-looking-at-operator-p ()
9911 "Return non-nil if text after point is an operator (that is not
9914 (and (looking-at js2-indent-operator-re)
9915 (or (not (looking-at ":"))
9917 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9918 (looking-at "?")))))))
9920 (defun js2-continued-expression-p ()
9921 "Returns non-nil if the current line continues an expression."
9923 (back-to-indentation)
9924 (or (js2-looking-at-operator-p)
9926 (and (js2-re-search-backward "\n" nil t)
9928 (skip-chars-backward " \t")
9931 (and (js2-looking-at-operator-p)
9934 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9936 (defun js2-end-of-do-while-loop-p ()
9937 "Returns non-nil if word after point is `while' of a do-while
9938 statement, else returns nil. A braceless do-while statement
9939 spanning several lines requires that the start of the loop is
9940 indented to the same column as the current line."
9944 (when (looking-at "\\s-*\\<while\\>")
9946 (skip-chars-backward "[ \t\n]*}")
9947 (looking-at "[ \t\n]*}"))
9949 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9950 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9951 (or (looking-at "\\<do\\>")
9952 (let ((saved-indent (current-indentation)))
9953 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9954 (/= (current-indentation) saved-indent)))
9955 (and (looking-at "[ \t]*\\<do\\>")
9956 (not (js2-re-search-forward
9957 "\\<while\\>" (point-at-eol) t))
9958 (= (current-indentation) saved-indent)))))))))
9960 (defun js2-multiline-decl-indentation ()
9961 "Returns the declaration indentation column if the current line belongs
9962 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9963 (let (forward-sexp-function ; use Lisp version
9966 (back-to-indentation)
9967 (when (not (looking-at js2-declaration-keyword-re))
9968 (when (looking-at js2-indent-operator-re)
9969 (goto-char (match-end 0))) ; continued expressions are ok
9970 (while (and (not at-opening-bracket)
9972 (let ((pos (point)))
9975 (or (eq (char-before) ?,)
9976 (and (not (eq (char-before) ?\;))
9978 (prog2 (skip-chars-backward "[[:punct:]]")
9979 (looking-at js2-indent-operator-re)
9981 (not (eq (char-before) ?\;))))
9982 (js2-same-line pos)))))
9985 (scan-error (setq at-opening-bracket t))))
9986 (when (looking-at js2-declaration-keyword-re)
9987 (goto-char (match-end 0))
9988 (1+ (current-column)))))))
9990 (defun js2-ctrl-statement-indentation ()
9991 "Returns the proper indentation of the current line if it
9992 starts the body of a control statement without braces, else
9994 (let (forward-sexp-function) ; temporarily unbind it
9996 (back-to-indentation)
9997 (when (and (not (js2-same-line (point-min)))
9998 (not (looking-at "{"))
9999 (js2-re-search-backward "[[:graph:]]" nil t)
10000 (not (looking-at "[{([]"))
10003 (when (= (char-before) ?\))
10004 ;; scan-sexps sometimes throws an error
10005 (ignore-errors (backward-sexp))
10006 (skip-chars-backward " \t" (point-at-bol)))
10007 (let ((pt (point)))
10008 (back-to-indentation)
10009 (and (looking-at js2-possibly-braceless-keywords-re)
10010 (= (match-end 0) pt)
10011 (not (js2-end-of-do-while-loop-p))))))
10012 (+ (current-indentation) js2-basic-offset)))))
10014 (defun js2-indent-in-array-comp (parse-status)
10015 "Return non-nil if we think we're in an array comprehension.
10016 In particular, return the buffer position of the first `for' kwd."
10017 (let ((bracket (nth 1 parse-status))
10021 (goto-char bracket)
10022 (when (looking-at "\\[")
10025 (if (looking-at "[[{]")
10026 (let (forward-sexp-function) ; use lisp version
10027 (forward-sexp) ; skip destructuring form
10029 (if (and (/= (char-after) ?,) ; regular array
10030 (looking-at "for"))
10031 (match-beginning 0)))
10032 ;; to skip arbitrary expressions we need the parser,
10033 ;; so we'll just guess at it.
10034 (if (and (> end (point)) ; not empty literal
10035 (re-search-forward "[^,]]* \\(for\\) " end t)
10036 ;; not inside comment or string literal
10037 (let ((state (parse-partial-sexp bracket (point))))
10038 (not (or (nth 3 state) (nth 4 state)))))
10039 (match-beginning 1))))))))
10041 (defun js2-array-comp-indentation (parse-status for-kwd)
10042 (if (js2-same-line for-kwd)
10043 ;; first continuation line
10045 (goto-char (nth 1 parse-status))
10047 (skip-chars-forward " \t")
10050 (goto-char for-kwd)
10051 (current-column))))
10053 (defun js2-proper-indentation (parse-status)
10054 "Return the proper indentation for the current line."
10056 (back-to-indentation)
10057 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10058 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10059 (continued-expr-p (js2-continued-expression-p))
10060 (declaration-indent (and js2-pretty-multiline-declarations
10061 (js2-multiline-decl-indentation)))
10062 (bracket (nth 1 parse-status))
10065 ;; indent array comprehension continuation lines specially
10067 (>= js2-language-version 170)
10068 (not (js2-same-line bracket))
10069 (setq beg (js2-indent-in-array-comp parse-status))
10070 (>= (point) (save-excursion
10072 (point-at-bol)))) ; at or after first loop?
10073 (js2-array-comp-indentation parse-status beg))
10077 ((and declaration-indent continued-expr-p)
10078 (+ declaration-indent js2-basic-offset))
10080 (declaration-indent)
10083 (goto-char bracket)
10085 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10086 (when (save-excursion (skip-chars-backward " \t)")
10089 (back-to-indentation)
10090 (and (eq js2-pretty-multiline-declarations 'all)
10091 (looking-at js2-declaration-keyword-re)
10092 (goto-char (1+ (match-end 0))))
10093 (cond (same-indent-p
10096 (+ (current-column) (* 2 js2-basic-offset)))
10098 (+ (current-column) js2-basic-offset))))
10100 (unless same-indent-p
10102 (skip-chars-forward " \t"))
10103 (current-column))))
10105 (continued-expr-p js2-basic-offset)
10109 (defun js2-lineup-comment (parse-status)
10110 "Indent a multi-line block comment continuation line."
10111 (let* ((beg (nth 8 parse-status))
10112 (first-line (js2-same-line beg))
10113 (offset (save-excursion
10115 (if (looking-at "/\\*")
10116 (+ 1 (current-column))
10119 (indent-line-to offset))))
10121 (defun js2-backward-sws ()
10122 "Move backward through whitespace and comments."
10124 (while (forward-comment -1)))
10126 (defun js2-forward-sws ()
10127 "Move forward through whitespace and comments."
10129 (while (forward-comment 1)))
10131 (defsubst js2-current-indent (&optional pos)
10132 "Return column of indentation on current line.
10133 If POS is non-nil, go to that point and return indentation for that line."
10137 (back-to-indentation)
10140 (defsubst js2-arglist-close ()
10141 "Return non-nil if we're on a line beginning with a close-paren/brace."
10144 (goto-char (point-at-bol))
10146 (looking-at "[])}]"))))
10148 (defsubst js2-indent-looks-like-label-p ()
10149 (goto-char (point-at-bol))
10151 (looking-at (concat js2-mode-identifier-re ":")))
10153 (defun js2-indent-in-objlit-p (parse-status)
10154 "Return non-nil if this looks like an object-literal entry."
10155 (let ((start (nth 1 parse-status)))
10159 (and (zerop (forward-line -1))
10160 (not (< (point) start)) ; crossed a {} boundary
10161 (js2-indent-looks-like-label-p)))
10163 (js2-indent-looks-like-label-p)))))
10165 ;; if prev line looks like foobar({ then we're passing an object
10166 ;; literal to a function call, and people pretty much always want to
10167 ;; de-dent back to the previous line, so move the 'basic-offset'
10168 ;; position to the front.
10169 (defsubst js2-indent-objlit-arg-p (parse-status)
10171 (back-to-indentation)
10173 (and (eq (1- (point)) (nth 1 parse-status))
10174 (eq (char-before) ?{)
10177 (skip-chars-backward " \t")
10178 (eq (char-before) ?\()))))
10180 (defsubst js2-indent-case-block-p ()
10182 (back-to-indentation)
10184 (goto-char (point-at-bol))
10185 (skip-chars-forward " \t")
10187 (looking-at "case\\s-.+:"))))
10189 (defsubst js2-syntax-bol ()
10190 "Return the point at the first non-whitespace char on the line.
10191 Returns `point-at-bol' if the line is empty."
10193 (beginning-of-line)
10194 (skip-chars-forward " \t")
10197 (defun js2-bounce-indent (normal-col parse-status backwards)
10198 "Cycle among alternate computed indentation positions.
10199 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10200 of the buffer to the current point. NORMAL-COL is the indentation
10201 column computed by the heuristic guesser based on current paren,
10202 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10204 (let ((cur-indent (js2-current-indent))
10205 (old-buffer-undo-list buffer-undo-list)
10206 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10207 (current-line (save-excursion
10208 (forward-line 0) ; move to bol
10209 (1+ (count-lines (point-min) (point)))))
10219 ;; temporarily don't record undo info, if user requested this
10220 (if js2-mode-indent-inhibit-undo
10221 (setq buffer-undo-list t))
10224 ;; first likely point: indent from beginning of previous code line
10225 (push (setq basic-offset
10227 (back-to-indentation)
10229 (back-to-indentation)
10230 (setq prev-line-col (current-column)))
10234 ;; (first + epsilon) likely point: indent 2x from beginning of
10235 ;; previous code line. Some companies like this approach. Ahem.
10236 ;; Seriously, though -- 4-space indent for expression continuation
10237 ;; lines isn't a bad idea. We should eventually implement it
10239 (push (setq basic-offset
10241 (back-to-indentation)
10243 (back-to-indentation)
10244 (setq prev-line-col (current-column)))
10245 (* 2 js2-basic-offset)))
10248 ;; second likely point: indent from assign-expr RHS. This
10249 ;; is just a crude guess based on finding " = " on the previous
10250 ;; line containing actual code.
10251 (setq pos (save-excursion
10254 (goto-char (point-at-bol))
10255 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10257 (goto-char (match-end 1))
10258 (skip-chars-forward " \t\r\n")
10259 (current-column)))))
10261 (incf pos js2-basic-offset)
10262 (push pos positions))
10264 ;; third likely point: same indent as previous line of code.
10265 ;; Make it the first likely point if we're not on an
10266 ;; arglist-close line and previous line ends in a comma, or
10267 ;; both this line and prev line look like object-literal
10269 (setq pos (save-excursion
10270 (goto-char (point-at-bol))
10272 (back-to-indentation)
10275 ;; while we're here, look for trailing comma
10276 (if (save-excursion
10277 (goto-char (point-at-eol))
10279 (eq (char-before) ?,))
10280 (setq arglist-cont (1- (point)))))))
10282 (if (and (or arglist-cont
10283 (js2-indent-in-objlit-p parse-status))
10284 (not (js2-arglist-close)))
10285 (setq same-indent pos))
10286 (push pos positions))
10288 ;; fourth likely point: first preceding code with less indentation
10289 ;; than the immediately preceding code line.
10290 (setq pos (save-excursion
10291 (back-to-indentation)
10293 (back-to-indentation)
10294 (setq anchor (current-column))
10295 (while (and (zerop (forward-line -1))
10297 (back-to-indentation)
10300 (setq pos (current-column))))
10301 (push pos positions)
10303 ;; nesting-heuristic position, main by default
10304 (push (setq main-pos normal-col) positions)
10306 ;; delete duplicates and sort positions list
10307 (setq positions (sort (delete-dups positions) '<))
10309 ;; comma-list continuation lines: prev line indent takes precedence
10311 (setq main-pos same-indent))
10313 ;; common special cases where we want to indent in from previous line
10314 (if (or (js2-indent-case-block-p)
10315 (js2-indent-objlit-arg-p parse-status))
10316 (setq main-pos basic-offset))
10318 ;; if bouncing backwards, reverse positions list
10320 (setq positions (reverse positions)))
10322 ;; record whether we're already sitting on one of the alternatives
10323 (setq pos (member cur-indent positions))
10326 ;; case 0: we're one one of the alternatives and this is the
10327 ;; first time they've pressed TAB on this line (best-guess).
10328 ((and js2-mode-indent-ignore-first-tab
10330 ;; first time pressing TAB on this line?
10331 (not (eq js2-mode-last-indented-line current-line)))
10333 (setq computed-pos nil))
10334 ;; case 1: only one computed position => use it
10335 ((null (cdr positions))
10336 (setq computed-pos 0))
10337 ;; case 2: not on any of the computed spots => use main spot
10339 (setq computed-pos (js2-position main-pos positions)))
10340 ;; case 3: on last position: cycle to first position
10342 (setq computed-pos 0))
10343 ;; case 4: on intermediate position: cycle to next position
10345 (setq computed-pos (js2-position (second pos) positions))))
10347 ;; see if any hooks want to indent; otherwise we do it
10348 (loop with result = nil
10349 for hook in js2-indent-hook
10350 while (null result)
10352 (setq result (funcall hook positions computed-pos))
10354 (unless (or result (null computed-pos))
10355 (indent-line-to (nth computed-pos positions)))))
10358 (if js2-mode-indent-inhibit-undo
10359 (setq buffer-undo-list old-buffer-undo-list))
10360 ;; see commentary for `js2-mode-last-indented-line'
10361 (setq js2-mode-last-indented-line current-line))))
10363 (defun js2-indent-bounce-backwards ()
10364 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10365 cycles between the computed indentation positions in reverse order."
10367 (js2-indent-line t))
10369 (defsubst js2-1-line-comment-continuation-p ()
10370 "Return t if we're in a 1-line comment continuation.
10371 If so, we don't ever want to use bounce-indent."
10376 (looking-at "\\s-*//"))
10380 (when (looking-at "\\s-*$")
10383 (looking-at "\\s-*//"))))))
10385 (defun js2-indent-line (&optional bounce-backwards)
10386 "Indent the current line as JavaScript source text."
10392 ;; don't whine about errors/warnings when we're indenting.
10393 ;; This has to be set before calling parse-partial-sexp below.
10394 (inhibit-point-motion-hooks t))
10395 (setq parse-status (save-excursion
10396 (syntax-ppss (point-at-bol)))
10397 offset (- (point) (save-excursion
10398 (back-to-indentation)
10400 (js2-with-underscore-as-word-syntax
10401 (if (nth 4 parse-status)
10402 (js2-lineup-comment parse-status)
10403 (setq indent-col (js2-proper-indentation parse-status))
10404 ;; see comments below about js2-mode-last-indented-line
10406 ;; bounce-indenting is disabled during electric-key indent.
10407 ;; It doesn't work well on first line of buffer.
10408 ((and js2-bounce-indent-p
10409 (not (js2-same-line (point-min)))
10410 (not (js2-1-line-comment-continuation-p)))
10411 (js2-bounce-indent indent-col parse-status bounce-backwards))
10412 ;; just indent to the guesser's likely spot
10413 (t (indent-line-to indent-col)))
10414 (when (plusp offset)
10415 (forward-char offset))))))
10417 (defun js2-indent-region (start end)
10418 "Indent the region, but don't use bounce indenting."
10419 (let ((js2-bounce-indent-p nil)
10420 (indent-region-function nil)
10421 (after-change-functions (remq 'js2-mode-edit
10422 after-change-functions)))
10423 (indent-region start end nil) ; nil for byte-compiler
10424 (js2-mode-edit start end (- end start))))
10426 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10430 "Major mode for editing JavaScript code."
10432 (kill-all-local-variables)
10433 (set-syntax-table js2-mode-syntax-table)
10434 (use-local-map js2-mode-map)
10435 (make-local-variable 'comment-start)
10436 (make-local-variable 'comment-end)
10437 (make-local-variable 'comment-start-skip)
10438 (setq major-mode 'js2-mode
10439 mode-name "JavaScript-IDE"
10440 comment-start "//" ; used by comment-region; don't change it
10442 (setq local-abbrev-table js2-mode-abbrev-table)
10443 (set (make-local-variable 'max-lisp-eval-depth)
10444 (max max-lisp-eval-depth 3000))
10445 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10446 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10448 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10449 ;; on most platforms other than the one I originally wrote it on.
10450 ;; So it's back to `c-fill-paragraph'.
10451 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10453 (add-hook 'before-save-hook #'js2-before-save nil t)
10454 (set (make-local-variable 'next-error-function) #'js2-next-error)
10455 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10456 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10457 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10458 ;; for characters inside regexp literals.
10459 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10460 ;; this is necessary to make `show-paren-function' work properly
10461 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10462 ;; needed for M-x rgrep, among other things
10463 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10465 ;; some variables needed by cc-engine for paragraph-fill, etc.
10466 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10467 c-comment-start-regexp "/[*/]\\|\\s|"
10468 c-line-comment-starter "//"
10469 c-paragraph-start js2-paragraph-start
10470 c-paragraph-separate "$"
10471 comment-start-skip js2-comment-start-skip
10472 c-syntactic-ws-start js2-syntactic-ws-start
10473 c-syntactic-ws-end js2-syntactic-ws-end
10474 c-syntactic-eol js2-syntactic-eol)
10476 (let ((c-buffer-is-cc-mode t))
10477 ;; Copied from `js-mode'. Also see Bug#6071.
10478 (make-local-variable 'paragraph-start)
10479 (make-local-variable 'paragraph-separate)
10480 (make-local-variable 'paragraph-ignore-fill-prefix)
10481 (make-local-variable 'adaptive-fill-mode)
10482 (make-local-variable 'adaptive-fill-regexp)
10483 (c-setup-paragraph-variables))
10485 (setq js2-default-externs
10486 (append js2-ecma-262-externs
10487 (if js2-include-browser-externs
10488 js2-browser-externs)
10489 (if js2-include-gears-externs
10491 (if js2-include-rhino-externs
10492 js2-rhino-externs)))
10494 ;; We do our own syntax highlighting based on the parse tree.
10495 ;; However, we want minor modes that add keywords to highlight properly
10496 ;; (examples: doxymacs, column-marker).
10497 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10498 (setq font-lock-defaults '(nil t))
10500 ;; Experiment: make reparse-delay longer for longer files.
10501 (if (plusp js2-dynamic-idle-timer-adjust)
10502 (setq js2-idle-timer-delay
10503 (* js2-idle-timer-delay
10504 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10506 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10507 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10508 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10509 (imenu-add-to-menubar (concat "IM-" mode-name))
10510 (when js2-mirror-mode
10511 (js2-enter-mirror-mode))
10512 (add-to-invisibility-spec '(js2-outline . t))
10513 (set (make-local-variable 'line-move-ignore-invisible) t)
10514 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10516 (if (fboundp 'run-mode-hooks)
10517 (run-mode-hooks 'js2-mode-hook)
10518 (run-hooks 'js2-mode-hook))
10520 (setq js2-mode-functions-hidden nil
10521 js2-mode-comments-hidden nil
10522 js2-mode-buffer-dirty-p t
10523 js2-mode-parsing nil)
10526 (defun js2-mode-exit ()
10527 "Exit `js2-mode' and clean up."
10529 (when js2-mode-node-overlay
10530 (delete-overlay js2-mode-node-overlay)
10531 (setq js2-mode-node-overlay nil))
10532 (js2-remove-overlays)
10533 (setq js2-mode-ast nil)
10534 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10535 (remove-from-invisibility-spec '(js2-outline . t))
10536 (js2-mode-show-all)
10537 (js2-with-unmodifying-text-property-changes
10538 (js2-clear-face (point-min) (point-max))))
10540 (defun js2-before-save ()
10541 "Clean up whitespace before saving file.
10542 You can disable this by customizing `js2-cleanup-whitespace'."
10543 (when js2-cleanup-whitespace
10544 (let ((col (current-column)))
10545 (delete-trailing-whitespace)
10546 ;; don't change trailing whitespace on current line
10547 (unless (eq (current-column) col)
10548 (indent-to col)))))
10550 (defsubst js2-mode-reset-timer ()
10551 "Cancel any existing parse timer and schedule a new one."
10552 (if js2-mode-parse-timer
10553 (cancel-timer js2-mode-parse-timer))
10554 (setq js2-mode-parsing nil)
10555 (let ((timer (timer-create)))
10556 (setq js2-mode-parse-timer timer)
10557 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10558 (timer-set-idle-time timer js2-idle-timer-delay)
10559 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10560 (timer-activate-when-idle timer nil)))
10562 (defun js2-mode-idle-reparse (buffer)
10563 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10564 it to be reparsed when the buffer is selected."
10565 (if (eq buffer (current-buffer))
10567 ;; reparse when the buffer is selected again
10568 (with-current-buffer buffer
10569 (add-hook 'window-configuration-change-hook
10570 #'js2-mode-idle-reparse-inner
10573 (defun js2-mode-idle-reparse-inner ()
10574 (remove-hook 'window-configuration-change-hook
10575 #'js2-mode-idle-reparse-inner
10579 (defun js2-mode-edit (beg end len)
10580 "Schedule a new parse after buffer is edited.
10581 Buffer edit spans from BEG to END and is of length LEN.
10582 Also clears the `js2-magic' bit on autoinserted parens/brackets
10583 if the edit occurred on a line different from the magic paren."
10584 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10585 (line (if magic-pos (line-number-at-pos magic-pos))))
10587 (or (/= (line-number-at-pos beg) line)
10589 (/= (line-number-at-pos end) line)))
10590 (js2-mode-mundanify-parens)))
10591 (setq js2-mode-buffer-dirty-p t)
10592 (js2-mode-hide-overlay)
10593 (js2-mode-reset-timer))
10595 (defun js2-reparse (&optional force)
10596 "Re-parse current buffer after user finishes some data entry.
10597 If we get any user input while parsing, including cursor motion,
10598 we discard the parse and reschedule it. If FORCE is nil, then the
10599 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10602 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10603 (unless js2-mode-parsing
10604 (setq js2-mode-parsing t)
10606 (when (or js2-mode-buffer-dirty-p force)
10607 (js2-remove-overlays)
10608 (js2-with-unmodifying-text-property-changes
10609 (setq js2-mode-buffer-dirty-p nil
10610 js2-mode-fontifications nil
10611 js2-mode-deferred-properties nil)
10612 (if js2-mode-verbose-parse-p
10613 (message "parsing..."))
10616 (setq interrupted-p
10617 (catch 'interrupted
10618 (setq js2-mode-ast (js2-parse))
10619 ;; if parsing is interrupted, comments and regex
10620 ;; literals stay ignored by `parse-partial-sexp'
10621 (remove-text-properties (point-min) (point-max)
10623 (js2-mode-apply-deferred-properties)
10624 (js2-mode-remove-suppressed-warnings)
10625 (js2-mode-show-warnings)
10626 (js2-mode-show-errors)
10627 (js2-mode-highlight-magic-parens)
10628 (if (>= js2-highlight-level 1)
10629 (js2-highlight-jsdoc js2-mode-ast))
10633 ;; unfinished parse => try again
10634 (setq js2-mode-buffer-dirty-p t)
10635 (js2-mode-reset-timer))
10636 (if js2-mode-verbose-parse-p
10637 (message "Parse time: %s" time)))))
10638 (setq js2-mode-parsing nil)
10639 (unless interrupted-p
10640 (setq js2-mode-parse-timer nil))))))
10642 (defun js2-mode-show-node (event)
10643 "Debugging aid: highlight selected AST node on mouse click."
10645 (mouse-set-point event)
10646 (let ((node (js2-node-at-point))
10649 (when js2-mode-show-overlay
10651 (message "No node found at location %s" (point))
10652 (setq beg (js2-node-abs-pos node)
10653 end (+ beg (js2-node-len node)))
10654 (if js2-mode-node-overlay
10655 (move-overlay js2-mode-node-overlay beg end)
10656 (setq js2-mode-node-overlay (make-overlay beg end))
10657 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10658 (js2-with-unmodifying-text-property-changes
10659 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10660 (message "%s, parent: %s"
10661 (js2-node-short-name node)
10662 (if (js2-node-parent node)
10663 (js2-node-short-name (js2-node-parent node))
10666 (put 'js2-mode-show-node 'CUA 'move)
10668 (defun js2-mode-hide-overlay (&optional p1 p2)
10669 "Remove the debugging overlay when the point moves.
10670 P1 and P2 are the old and new values of point, respectively."
10671 (when js2-mode-node-overlay
10672 (let ((beg (overlay-start js2-mode-node-overlay))
10673 (end (overlay-end js2-mode-node-overlay)))
10674 ;; Sometimes we're called spuriously.
10678 (js2-with-unmodifying-text-property-changes
10679 (remove-text-properties beg end '(point-left nil)))
10680 (delete-overlay js2-mode-node-overlay)
10681 (setq js2-mode-node-overlay nil)))))
10683 (defun js2-mode-reset ()
10684 "Debugging helper: reset everything."
10689 (defsubst js2-mode-show-warn-or-err (e face)
10690 "Highlight a warning or error E with FACE.
10691 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10692 (let* ((key (first e))
10694 (end (+ beg (third e)))
10695 ;; Don't inadvertently go out of bounds.
10696 (beg (max (point-min) (min beg (point-max))))
10697 (end (max (point-min) (min end (point-max))))
10698 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10699 (ovl (make-overlay beg end)))
10700 (overlay-put ovl 'font-lock-face face)
10701 (overlay-put ovl 'js2-error t)
10702 (put-text-property beg end 'help-echo (js2-get-msg key))
10703 (put-text-property beg end 'point-entered #'js2-echo-error)))
10705 (defun js2-remove-overlays ()
10706 "Remove overlays from buffer that have a `js2-error' property."
10707 (let ((beg (point-min))
10710 (dolist (o (overlays-in beg end))
10711 (when (overlay-get o 'js2-error)
10712 (delete-overlay o))))))
10714 (defun js2-error-at-point (&optional pos)
10715 "Return non-nil if there's an error overlay at POS.
10716 Defaults to point."
10717 (loop with pos = (or pos (point))
10718 for o in (overlays-at pos)
10719 thereis (overlay-get o 'js2-error)))
10721 (defun js2-mode-apply-deferred-properties ()
10722 "Apply fontifications and other text properties recorded during parsing."
10723 (when (plusp js2-highlight-level)
10724 ;; We defer clearing faces as long as possible to eliminate flashing.
10725 (js2-clear-face (point-min) (point-max))
10726 ;; Have to reverse the recorded fontifications list so that errors
10727 ;; and warnings overwrite the normal fontifications.
10728 (dolist (f (nreverse js2-mode-fontifications))
10729 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10730 (setq js2-mode-fontifications nil))
10731 (dolist (p js2-mode-deferred-properties)
10732 (apply #'put-text-property p))
10733 (setq js2-mode-deferred-properties nil))
10735 (defun js2-mode-show-errors ()
10736 "Highlight syntax errors."
10737 (when js2-mode-show-parse-errors
10738 (dolist (e (js2-ast-root-errors js2-mode-ast))
10739 (js2-mode-show-warn-or-err e 'js2-error-face))))
10741 (defun js2-mode-remove-suppressed-warnings ()
10742 "Take suppressed warnings out of the AST warnings list.
10743 This ensures that the counts and `next-error' are correct."
10744 (setf (js2-ast-root-warnings js2-mode-ast)
10747 (let ((key (caar e)))
10749 (and (not js2-strict-trailing-comma-warning)
10750 (string-match "trailing\\.comma" key))
10751 (and (not js2-strict-cond-assign-warning)
10752 (string= key "msg.equal.as.assign"))
10753 (and js2-missing-semi-one-line-override
10754 (string= key "msg.missing.semi")
10755 (let* ((beg (second e))
10756 (node (js2-node-at-point beg))
10757 (fn (js2-mode-find-parent-fn node))
10758 (body (and fn (js2-function-node-body fn)))
10759 (lc (and body (js2-node-abs-pos body)))
10760 (rc (and lc (+ lc (js2-node-len body)))))
10765 (and (js2-same-line lc)
10766 (js2-same-line rc))))))))))
10767 (js2-ast-root-warnings js2-mode-ast))))
10769 (defun js2-mode-show-warnings ()
10770 "Highlight strict-mode warnings."
10771 (when js2-mode-show-strict-warnings
10772 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10773 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10775 (defun js2-echo-error (old-point new-point)
10776 "Called by point-motion hooks."
10777 (let ((msg (get-text-property new-point 'help-echo)))
10778 (if (and msg (or (not (current-message))
10779 (string= (current-message) "Quit")))
10782 (defalias #'js2-echo-help #'js2-echo-error)
10784 (defun js2-enter-key ()
10785 "Handle user pressing the Enter key."
10787 (let ((parse-status (save-excursion
10788 (syntax-ppss (point))))
10789 (js2-bounce-indent-p nil))
10791 ;; check if we're inside a string
10792 ((nth 3 parse-status)
10793 (if js2-concat-multiline-strings
10794 (js2-mode-split-string parse-status)
10796 ;; check if inside a block comment
10797 ((nth 4 parse-status)
10798 (js2-mode-extend-comment))
10800 ;; should probably figure out what the mode-map says we should do
10801 (if js2-indent-on-enter-key
10804 (if js2-enter-indents-newline
10805 (js2-indent-line))))))
10807 (defun js2-mode-split-string (parse-status)
10808 "Turn a newline in mid-string into a string concatenation.
10809 PARSE-STATUS is as documented in `parse-partial-sexp'."
10810 (let* ((col (current-column))
10811 (quote-char (nth 3 parse-status))
10812 (quote-string (string quote-char))
10813 (string-beg (nth 8 parse-status))
10814 (at-eol (eq js2-concat-multiline-strings 'eol))
10815 (indent (save-match-data
10818 (back-to-indentation)
10819 (if (looking-at "\\+")
10822 (goto-char string-beg)
10823 (if (looking-back "\\+\\s-+")
10824 (goto-char (match-beginning 0)))
10825 (current-column))))))
10826 (insert quote-char)
10830 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10834 (insert quote-string)
10836 (insert quote-string)
10837 (backward-char 1))))
10839 (defun js2-mode-extend-comment ()
10840 "Indent the line and, when inside a comment block, add comment prefix."
10841 (let (star single col first-line needs-close)
10843 (back-to-indentation)
10845 ((looking-at "\\*[^/]")
10847 col (current-column)))
10848 ((looking-at "/\\*")
10851 col (1+ (current-column))))
10854 col (current-column)))))
10855 ;; Heuristic for whether we need to close the comment:
10856 ;; if we've got a parse error here, assume it's an unterminated
10860 (eq (get-text-property (1- (point)) 'point-entered)
10862 ;; The heuristic above doesn't work well when we're
10863 ;; creating a comment and there's another one downstream,
10864 ;; as our parser thinks this one ends at the end of the
10865 ;; next one. (You can have a /* inside a js block comment.)
10866 ;; So just close it if the next non-ws char isn't a *.
10870 (skip-chars-forward " \t\r\n")
10871 (not (eq (char-after) ?*))))))
10877 (if (and first-line needs-close)
10884 (and (zerop (forward-line 1))
10885 (looking-at "\\s-*//"))))
10888 ;; don't need to extend the comment after all
10889 (js2-enter-indents-newline
10890 (js2-indent-line)))))
10892 (defun js2-beginning-of-line ()
10893 "Toggles point between bol and first non-whitespace char in line.
10894 Also moves past comment delimiters when inside comments."
10899 (back-to-indentation))
10901 (skip-chars-forward "/ \t"))
10902 ((and (eq (char-after) ?*)
10903 (setq node (js2-comment-at-point))
10904 (memq (js2-comment-node-format node) '(jsdoc block))
10906 (skip-chars-backward " \t")
10908 (skip-chars-forward "\* \t"))
10910 (goto-char (point-at-bol))))))
10912 (defun js2-end-of-line ()
10913 "Toggles point between eol and last non-whitespace char in line."
10916 (skip-chars-backward " \t")
10917 (goto-char (point-at-eol))))
10919 (defun js2-enter-mirror-mode()
10920 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10923 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10924 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10925 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10926 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10927 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10928 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10929 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10930 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10932 (defun js2-leave-mirror-mode()
10933 "Turns off mirror mode."
10935 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10936 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10938 (defsubst js2-mode-inside-string ()
10939 "Return non-nil if inside a string.
10940 Actually returns the quote character that begins the string."
10941 (let ((parse-state (save-excursion
10942 (syntax-ppss (point)))))
10943 (nth 3 parse-state)))
10945 (defsubst js2-mode-inside-comment-or-string ()
10946 "Return non-nil if inside a comment or string."
10948 (let ((comment-start
10950 (goto-char (point-at-bol))
10951 (if (re-search-forward "//" (point-at-eol) t)
10952 (match-beginning 0)))))
10954 (<= comment-start (point))))
10955 (let ((parse-state (save-excursion
10956 (syntax-ppss (point)))))
10957 (or (nth 3 parse-state)
10958 (nth 4 parse-state)))))
10960 (defsubst js2-make-magic-delimiter (delim &optional pos)
10961 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10962 Sets value of `js2-magic' text property to line number at POS."
10964 'js2-magic (line-number-at-pos pos)
10965 'font-lock-face 'js2-magic-paren-face))
10967 (defun js2-mode-match-delimiter (open close)
10968 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10969 The rule we use, which as far as we can tell is how Eclipse works,
10970 is that we insert the match if we're not in a comment or string,
10971 and the next non-whitespace character is either punctuation or
10972 occurs on another line."
10974 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10975 (not (js2-mode-inside-comment-or-string)))
10977 (insert (js2-make-magic-delimiter close)))
10978 (when js2-auto-indent-p
10979 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10980 (js2-indent-line)))))
10982 (defun js2-mode-match-bracket ()
10983 "Insert matching bracket."
10985 (js2-mode-match-delimiter "[" "]"))
10987 (defun js2-mode-match-paren ()
10988 "Insert matching paren unless already inserted."
10990 (js2-mode-match-delimiter "(" ")"))
10992 (defun js2-mode-match-curly (arg)
10993 "Insert matching curly-brace.
10994 With prefix arg, no formatting or indentation will occur -- the close-brace
10995 is simply inserted directly at the point."
10999 (current-prefix-arg
11000 (js2-mode-match-delimiter "{" "}"))
11001 ((and js2-auto-insert-catch-block
11002 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
11004 (match-beginning 1))))
11005 (js2-insert-catch-skel try-pos))
11007 ;; Otherwise try to do something smarter.
11009 (unless (or (not (looking-at "\\s-*$"))
11011 (skip-chars-forward " \t\r\n")
11012 (and (looking-at "}")
11013 (js2-error-at-point)))
11014 (js2-mode-inside-comment-or-string))
11016 ;; absolutely mystifying bug: when inserting the next "\n",
11017 ;; the buffer-undo-list is given two new entries: the inserted range,
11018 ;; and the incorrect position of the point. It's recorded incorrectly
11019 ;; as being before the opening "{", not after it. But it's recorded
11020 ;; as the correct value if you're debugging `js2-mode-match-curly'
11021 ;; in edebug. I have no idea why it's doing this, but incrementing
11022 ;; the inserted position fixes the problem, so that the undo takes us
11023 ;; back to just after the user-inserted "{".
11026 (incf (cadr buffer-undo-list)))
11030 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11031 (js2-indent-line))))))))
11033 (defun js2-insert-catch-skel (try-pos)
11034 "Complete a try/catch block after inserting a { following a try keyword.
11035 Rationale is that a try always needs a catch or a finally, and the catch is
11036 the more likely of the two.
11038 TRY-POS is the buffer position of the try keyword. The open-curly should
11039 already have been inserted."
11041 (let ((try-col (save-excursion
11042 (goto-char try-pos)
11043 (current-column))))
11046 (js2-indent-line) ;; indent the blank line where cursor will end up
11049 (indent-to try-col)
11050 (insert "} catch (x) {\n\n")
11051 (indent-to try-col)
11054 (defun js2-mode-highlight-magic-parens ()
11055 "Re-highlight magic parens after parsing nukes the 'face prop."
11056 (let ((beg (point-min))
11058 (while (setq beg (next-single-property-change beg 'js2-magic))
11059 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11060 (if (get-text-property beg 'js2-magic)
11061 (js2-with-unmodifying-text-property-changes
11062 (put-text-property beg (or end (1+ beg))
11063 'font-lock-face 'js2-magic-paren-face))))))
11065 (defun js2-mode-mundanify-parens ()
11066 "Clear all magic parens and brackets."
11067 (let ((beg (point-min))
11069 (while (setq beg (next-single-property-change beg 'js2-magic))
11070 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11071 (remove-text-properties beg (or end (1+ beg))
11072 '(js2-magic face)))))
11074 (defsubst js2-match-quote (quote-string)
11075 (let ((start-quote (js2-mode-inside-string)))
11077 ;; inside a comment - don't do quote-matching, since we can't
11078 ;; reliably figure out if we're in a string inside the comment
11079 ((js2-comment-at-point)
11080 (insert quote-string))
11082 ;; not in string => insert matched quotes
11083 (insert quote-string)
11084 ;; exception: if we're just before a word, don't double it.
11085 (unless (looking-at "[^ \t\r\n]")
11087 (insert quote-string))))
11088 ((looking-at quote-string)
11089 (if (looking-back "[^\\]\\\\")
11090 (insert quote-string)
11092 ((and js2-mode-escape-quotes
11095 (re-search-forward quote-string (point-at-eol) t))))
11096 ;; inside terminated string, escape quote (unless already escaped)
11097 (insert (if (looking-back "[^\\]\\\\")
11099 (concat "\\" quote-string))))
11101 (insert quote-string))))) ; else terminate the string
11103 (defun js2-mode-match-single-quote ()
11104 "Insert matching single-quote."
11106 (let ((parse-status (syntax-ppss (point))))
11107 ;; don't match inside comments, since apostrophe is more common
11108 (if (nth 4 parse-status)
11110 (js2-match-quote "'"))))
11112 (defun js2-mode-match-double-quote ()
11113 "Insert matching double-quote."
11115 (js2-match-quote "\""))
11117 ;; Eclipse works as follows:
11118 ;; * type an open-paren and it auto-inserts close-paren
11119 ;; - auto-inserted paren gets a green bracket
11120 ;; - green bracket means typing close-paren there will skip it
11121 ;; * if you insert any text on a different line, it turns off
11122 (defun js2-mode-magic-close-paren ()
11123 "Skip over close-paren rather than inserting, where appropriate."
11125 (let* ((here (point))
11126 (parse-status (syntax-ppss here))
11127 (open-pos (nth 1 parse-status))
11128 (close last-input-event)
11137 (if (and (eq (char-after) close)
11138 (eq open (char-after open-pos))
11139 (js2-same-line open-pos)
11140 (get-text-property here 'js2-magic))
11142 (remove-text-properties here (1+ here) '(js2-magic face))
11144 (insert-char close 1))
11145 (blink-matching-open)))
11147 (defun js2-mode-wait-for-parse (callback)
11148 "Invoke CALLBACK when parsing is finished.
11149 If parsing is already finished, calls CALLBACK immediately."
11150 (if (not js2-mode-buffer-dirty-p)
11152 (push callback js2-mode-pending-parse-callbacks)
11153 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11155 (defun js2-mode-parse-finished ()
11156 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11157 ;; We can't let errors propagate up, since it prevents the
11158 ;; `js2-parse' method from completing normally and returning
11159 ;; the ast, which makes things mysteriously not work right.
11161 (dolist (cb js2-mode-pending-parse-callbacks)
11162 (condition-case err
11164 (error (message "%s" err))))
11165 (setq js2-mode-pending-parse-callbacks nil)))
11167 (defun js2-mode-flag-region (from to flag)
11168 "Hide or show text from FROM to TO, according to FLAG.
11169 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11170 Returns the created overlay if FLAG is non-nil."
11171 (remove-overlays from to 'invisible 'js2-outline)
11173 (let ((o (make-overlay from to)))
11174 (overlay-put o 'invisible 'js2-outline)
11175 (overlay-put o 'isearch-open-invisible
11176 'js2-isearch-open-invisible)
11179 ;; Function to be set as an outline-isearch-open-invisible' property
11180 ;; to the overlay that makes the outline invisible (see
11181 ;; `js2-mode-flag-region').
11182 (defun js2-isearch-open-invisible (overlay)
11183 ;; We rely on the fact that isearch places point on the matched text.
11184 (js2-mode-show-element))
11186 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11187 "Return cons cell of bounds of folding overlay at POS.
11188 Returns nil if not found."
11189 (let ((overlays (overlays-at (or pos (point))))
11191 (while (and overlays
11193 (if (overlay-get (car overlays) 'invisible)
11194 (setq o (car overlays))
11195 (setq overlays (cdr overlays))))
11197 (cons (overlay-start o) (overlay-end o)))))
11199 (defun js2-mode-function-at-point (&optional pos)
11200 "Return the innermost function node enclosing current point.
11201 Returns nil if point is not in a function."
11202 (let ((node (js2-node-at-point pos)))
11203 (while (and node (not (js2-function-node-p node)))
11204 (setq node (js2-node-parent node)))
11205 (if (js2-function-node-p node)
11208 (defun js2-mode-toggle-element ()
11209 "Hide or show the foldable element at the point."
11211 (let (comment fn pos)
11215 ;; /* ... */ comment?
11216 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11217 (if (js2-mode-invisible-overlay-bounds
11218 (setq pos (+ 3 (js2-node-abs-pos comment))))
11221 (js2-mode-show-element))
11222 (js2-mode-hide-element)))
11225 (back-to-indentation)
11226 (looking-at js2-mode-//-comment-re))
11227 (js2-mode-toggle-//-comment))
11229 ((setq fn (js2-mode-function-at-point))
11230 (setq pos (and (js2-function-node-body fn)
11231 (js2-node-abs-pos (js2-function-node-body fn))))
11232 (goto-char (1+ pos))
11233 (if (js2-mode-invisible-overlay-bounds)
11234 (js2-mode-show-element)
11235 (js2-mode-hide-element)))
11237 (message "Nothing at point to hide or show")))))))
11239 (defun js2-mode-hide-element ()
11240 "Fold/hide contents of a block, showing ellipses.
11241 Show the hidden text with \\[js2-mode-show-element]."
11243 (if js2-mode-buffer-dirty-p
11244 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11245 (let (node body beg end)
11247 ((js2-mode-invisible-overlay-bounds)
11248 (message "already hidden"))
11250 (setq node (js2-node-at-point))
11252 ((js2-block-comment-p node)
11253 (js2-mode-hide-comment node))
11255 (while (and node (not (js2-function-node-p node)))
11256 (setq node (js2-node-parent node)))
11258 (setq body (js2-function-node-body node)))
11260 (setq beg (js2-node-abs-pos body)
11261 end (+ beg (js2-node-len body)))
11262 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11263 (message "No collapsable element found at point"))))))))
11265 (defun js2-mode-show-element ()
11266 "Show the hidden element at current point."
11268 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11270 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11271 (message "Nothing to un-hide"))))
11273 (defun js2-mode-show-all ()
11274 "Show all of the text in the buffer."
11276 (js2-mode-flag-region (point-min) (point-max) nil))
11278 (defun js2-mode-toggle-hide-functions ()
11280 (if js2-mode-functions-hidden
11281 (js2-mode-show-functions)
11282 (js2-mode-hide-functions)))
11284 (defun js2-mode-hide-functions ()
11285 "Hides all non-nested function bodies in the buffer.
11286 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11287 to open an individual entry."
11289 (if js2-mode-buffer-dirty-p
11290 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11291 (if (null js2-mode-ast)
11292 (message "Oops - parsing failed")
11293 (setq js2-mode-functions-hidden t)
11294 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11296 (defun js2-mode-function-hider (n endp)
11298 (let ((tt (js2-node-type n))
11301 ((and (= tt js2-FUNCTION)
11302 (setq body (js2-function-node-body n)))
11303 (setq beg (js2-node-abs-pos body)
11304 end (+ beg (js2-node-len body)))
11305 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11306 nil) ; don't process children of function
11308 t))))) ; keep processing other AST nodes
11310 (defun js2-mode-show-functions ()
11311 "Un-hide any folded function bodies in the buffer."
11313 (setq js2-mode-functions-hidden nil)
11315 (goto-char (point-min))
11316 (while (/= (goto-char (next-overlay-change (point)))
11318 (dolist (o (overlays-at (point)))
11319 (when (and (overlay-get o 'invisible)
11320 (not (overlay-get o 'comment)))
11321 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11323 (defun js2-mode-hide-comment (n)
11324 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11327 (beg (+ (js2-node-abs-pos n) head))
11328 (end (- (+ beg (js2-node-len n)) head 2))
11329 (o (js2-mode-flag-region beg end 'hide)))
11330 (overlay-put o 'comment t)))
11332 (defun js2-mode-toggle-hide-comments ()
11333 "Folds all block comments in the buffer.
11334 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11335 to open an individual entry."
11337 (if js2-mode-comments-hidden
11338 (js2-mode-show-comments)
11339 (js2-mode-hide-comments)))
11341 (defun js2-mode-hide-comments ()
11343 (if js2-mode-buffer-dirty-p
11344 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11345 (if (null js2-mode-ast)
11346 (message "Oops - parsing failed")
11347 (setq js2-mode-comments-hidden t)
11348 (dolist (n (js2-ast-root-comments js2-mode-ast))
11349 (let ((format (js2-comment-node-format n)))
11350 (when (js2-block-comment-p n)
11351 (js2-mode-hide-comment n))))
11352 (js2-mode-hide-//-comments)))
11354 (defsubst js2-mode-extend-//-comment (direction)
11355 "Find start or end of a block of similar //-comment lines.
11356 DIRECTION is -1 to look back, 1 to look forward.
11357 INDENT is the indentation level to match.
11358 Returns the end-of-line position of the furthest adjacent
11359 //-comment line with the same indentation as the current line.
11360 If there is no such matching line, returns current end of line."
11361 (let ((pos (point-at-eol))
11362 (indent (current-indentation)))
11365 (while (and (zerop (forward-line direction))
11366 (looking-at js2-mode-//-comment-re)
11367 (eq indent (length (match-string 1))))
11368 (setq pos (point-at-eol)))
11371 (defun js2-mode-hide-//-comments ()
11372 "Fold adjacent 1-line comments, showing only snippet of first one."
11376 (goto-char (point-min))
11377 (while (re-search-forward js2-mode-//-comment-re nil t)
11379 end (js2-mode-extend-//-comment 1))
11380 (unless (eq beg end)
11381 (overlay-put (js2-mode-flag-region beg end 'hide)
11384 (forward-char 1))))))
11386 (defun js2-mode-toggle-//-comment ()
11387 "Fold or un-fold any multi-line //-comment at point.
11388 Caller should have determined that this line starts with a //-comment."
11389 (let* ((beg (point-at-eol))
11393 (if (js2-mode-invisible-overlay-bounds)
11394 (js2-mode-show-element)
11395 ;; else hide the comment
11396 (setq beg (js2-mode-extend-//-comment -1)
11397 end (js2-mode-extend-//-comment 1))
11398 (unless (eq beg end)
11399 (overlay-put (js2-mode-flag-region beg end 'hide)
11402 (defun js2-mode-show-comments ()
11403 "Un-hide any hidden comments, leaving other hidden elements alone."
11405 (setq js2-mode-comments-hidden nil)
11407 (goto-char (point-min))
11408 (while (/= (goto-char (next-overlay-change (point)))
11410 (dolist (o (overlays-at (point)))
11411 (when (overlay-get o 'comment)
11412 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11414 (defun js2-mode-display-warnings-and-errors ()
11415 "Turn on display of warnings and errors."
11417 (setq js2-mode-show-parse-errors t
11418 js2-mode-show-strict-warnings t)
11419 (js2-reparse 'force))
11421 (defun js2-mode-hide-warnings-and-errors ()
11422 "Turn off display of warnings and errors."
11424 (setq js2-mode-show-parse-errors nil
11425 js2-mode-show-strict-warnings nil)
11426 (js2-reparse 'force))
11428 (defun js2-mode-toggle-warnings-and-errors ()
11429 "Toggle the display of warnings and errors.
11430 Some users don't like having warnings/errors reported while they type."
11432 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11433 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11434 (if (interactive-p)
11435 (message "warnings and errors %s"
11436 (if js2-mode-show-parse-errors
11439 (js2-reparse 'force))
11441 (defun js2-mode-customize ()
11443 (customize-group 'js2-mode))
11445 (defun js2-mode-forward-sexp (&optional arg)
11446 "Move forward across one statement or balanced expression.
11447 With ARG, do it that many times. Negative arg -N means
11448 move backward across N balanced expressions."
11450 (setq arg (or arg 1))
11451 (when js2-mode-buffer-dirty-p
11453 (let ((scan-msg "Containing expression ends prematurely")
11454 node (start (point)) pos lp rp child)
11457 ;; could probably make this better for some cases:
11458 ;; - if in statement block (e.g. function body), go to parent
11459 ;; - infix exprs like (foo in bar) - maybe go to beginning
11460 ;; of infix expr if in the right-side expression?
11461 ((and arg (minusp arg))
11462 (dotimes (i (- arg))
11464 (forward-char -1) ; enter the node we backed up to
11465 (when (setq node (js2-node-at-point (point) t))
11466 (setq pos (js2-node-abs-pos node))
11467 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11468 (setq lp (car parens)
11471 (or (when (and lp (> start lp))
11472 (if (and rp (<= start rp))
11473 (if (setq child (js2-node-closest-child node (point) lp t))
11474 (js2-node-abs-pos child)
11476 (signal 'scan-error (list scan-msg lp lp)))
11485 (when (setq node (js2-node-at-point (point) t))
11486 (setq pos (js2-node-abs-pos node))
11487 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11488 (setq lp (car parens)
11491 (or (when (and rp (<= start rp))
11493 (if (setq child (js2-node-closest-child node (point) rp))
11494 (js2-node-abs-end child)
11496 (signal 'scan-error (list scan-msg rp (1+ rp))))
11501 (if (js2-expr-stmt-node-p (js2-node-parent node))
11502 ;; stop after the semicolon
11503 (js2-node-parent node)
11507 (defun js2-mode-forward-sexp-parens (node abs-pos)
11509 ((or (js2-array-node-p node)
11510 (js2-object-node-p node)
11511 (js2-array-comp-node-p node)
11512 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11513 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11514 ((js2-paren-expr-node-p node)
11515 (let ((lp (js2-node-lp node))
11516 (rp (js2-node-rp node)))
11517 (cons (when lp (+ abs-pos lp))
11518 (when rp (+ abs-pos rp)))))))
11520 (defun js2-node-closest-child (parent point limit &optional before)
11521 (let* ((parent-pos (js2-node-abs-pos parent))
11522 (rpoint (- point parent-pos))
11523 (rlimit (- limit parent-pos))
11524 (min (min rpoint rlimit))
11525 (max (max rpoint rlimit))
11530 (lambda (node end-p)
11531 (if (eq node parent)
11533 (let ((pos (js2-node-pos node)) ;; Both relative values.
11534 (end (+ (js2-node-pos node) (js2-node-len node))))
11535 (when (and (>= pos min) (<= end max)
11536 (if before (< pos rpoint) (> end rpoint)))
11538 (when (> end rpoint)
11539 (throw 'done nil)))
11543 (defun js2-next-error (&optional arg reset)
11544 "Move to next parse error.
11545 Typically invoked via \\[next-error].
11546 ARG is the number of errors, forward or backward, to move.
11547 RESET means start over from the beginning."
11549 (if (or (null js2-mode-ast)
11550 (and (null (js2-ast-root-errors js2-mode-ast))
11551 (null (js2-ast-root-warnings js2-mode-ast))))
11552 (message "No errors")
11554 (goto-char (point-min)))
11555 (let* ((errs (copy-sequence
11556 (append (js2-ast-root-errors js2-mode-ast)
11557 (js2-ast-root-warnings js2-mode-ast))))
11561 (backward (minusp count))
11562 (sorter (if backward '> '<))
11563 (stopper (if backward '< '>))
11564 (count (abs count))
11567 ;; sort by start position
11568 (setq errs (sort errs (lambda (e1 e2)
11569 (funcall sorter (second e1) (second e2))))
11571 ;; find nth error with pos > start
11572 (while (and errs continue)
11573 (when (funcall stopper (cadar errs) start)
11574 (setq err (car errs))
11575 (if (zerop (decf count))
11576 (setq continue nil)))
11577 (setq errs (cdr errs)))
11579 (goto-char (second err))
11580 ;; wrap around to first error
11581 (goto-char (second (car all-errs)))
11582 ;; if we were already on it, echo msg again
11583 (if (= (point) start)
11584 (js2-echo-error (point) (point)))))))
11586 (defun js2-down-mouse-3 ()
11587 "Make right-click move the point to the click location.
11588 This makes right-click context menu operations a bit more intuitive.
11589 The point will not move if the region is active, however, to avoid
11590 destroying the region selection."
11592 (when (and js2-move-point-on-right-click
11594 (let ((e last-input-event))
11596 (goto-char (cadadr e))))))
11598 (defun js2-mode-create-imenu-index ()
11599 "Return an alist for `imenu--index-alist'."
11600 ;; This is built up in `js2-parse-record-imenu' during parsing.
11602 ;; if we have an ast but no recorder, they're requesting a rescan
11603 (unless js2-imenu-recorder
11604 (js2-reparse 'force))
11606 (js2-build-imenu-index)
11607 (setq js2-imenu-recorder nil
11608 js2-imenu-function-map nil))))
11610 (defun js2-mode-find-tag ()
11611 "Replacement for `find-tag-default'.
11612 `find-tag-default' returns a ridiculous answer inside comments."
11614 (js2-with-underscore-as-word-syntax
11616 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11617 (looking-back "[A-Za-z0-9_$]"))
11618 (setq beg (progn (forward-word -1) (point))
11619 end (progn (forward-word 1) (point)))
11620 (setq beg (progn (forward-word 1) (point))
11621 end (progn (forward-word -1) (point))))
11622 (replace-regexp-in-string
11624 (buffer-substring-no-properties beg end))))))
11626 (defun js2-mode-forward-sibling ()
11627 "Move to the end of the sibling following point in parent.
11628 Returns non-nil if successful, or nil if there was no following sibling."
11629 (let* ((node (js2-node-at-point))
11630 (parent (js2-mode-find-enclosing-fn node))
11632 (when (setq sib (js2-node-find-child-after (point) parent))
11633 (goto-char (+ (js2-node-abs-pos sib)
11634 (js2-node-len sib))))))
11636 (defun js2-mode-backward-sibling ()
11637 "Move to the beginning of the sibling node preceding point in parent.
11638 Parent is defined as the enclosing script or function."
11639 (let* ((node (js2-node-at-point))
11640 (parent (js2-mode-find-enclosing-fn node))
11642 (when (setq sib (js2-node-find-child-before (point) parent))
11643 (goto-char (js2-node-abs-pos sib)))))
11645 (defun js2-beginning-of-defun (&optional arg)
11646 "Go to line on which current function starts, and return t on success.
11647 If we're not in a function or already at the beginning of one, go
11648 to beginning of previous script-level element.
11649 With ARG N, do that N times. If N is negative, move forward."
11650 (setq arg (or arg 1))
11652 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11654 ((js2-function-node-p parent)
11655 (goto-char (js2-node-abs-pos parent)))
11657 (js2-mode-backward-sibling)))
11659 (js2-beginning-of-defun (1- arg))
11661 (when (js2-end-of-defun)
11663 (js2-beginning-of-defun 1)
11664 (js2-beginning-of-defun (1+ arg))))))
11666 (defun js2-end-of-defun ()
11667 "Go to the char after the last position of the current function
11668 or script-level element."
11669 (let* ((node (js2-node-at-point))
11670 (parent (or (and (js2-function-node-p node) node)
11671 (js2-node-parent-script-or-fn node)))
11673 (unless (js2-function-node-p parent)
11674 ;; use current script-level node, or, if none, the next one
11675 (setq script (or parent node))
11676 (setq parent (js2-node-find-child-before (point) script))
11677 (when (or (null parent)
11678 (>= (point) (+ (js2-node-abs-pos parent)
11679 (js2-node-len parent))))
11680 (setq parent (js2-node-find-child-after (point) script))))
11682 (goto-char (+ (js2-node-abs-pos parent)
11683 (js2-node-len parent))))))
11685 (defun js2-mark-defun (&optional allow-extend)
11686 "Put mark at end of this function, point at beginning.
11687 The function marked is the one that contains point.
11689 Interactively, if this command is repeated,
11690 or (in Transient Mark mode) if the mark is active,
11691 it marks the next defun after the ones already marked."
11694 (when (and allow-extend
11695 (or (and (eq last-command this-command) (mark t))
11696 (and transient-mark-mode mark-active)))
11697 (let ((sib (save-excursion
11699 (if (js2-mode-forward-sibling)
11706 ;; no more siblings - try extending to enclosing node
11707 (goto-char (mark t)))))
11708 (when (not extended)
11709 (let ((node (js2-node-at-point (point) t)) ; skip comments
11710 ast fn stmt parent beg end)
11711 (when (js2-ast-root-p node)
11713 node (or (js2-node-find-child-after (point) node)
11714 (js2-node-find-child-before (point) node))))
11715 ;; only mark whole buffer if we can't find any children
11718 (if (js2-function-node-p node)
11720 (setq fn (js2-mode-find-enclosing-fn node)
11721 stmt (if (or (null fn)
11722 (js2-ast-root-p fn))
11723 (js2-mode-find-first-stmt node))
11724 parent (or stmt fn)))
11725 (setq beg (js2-node-abs-pos parent)
11726 end (+ beg (js2-node-len parent)))
11729 (exchange-point-and-mark)))))
11731 (defun js2-narrow-to-defun ()
11732 "Narrow to the function enclosing point."
11734 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11735 (fn (if (js2-script-node-p node)
11737 (js2-mode-find-enclosing-fn node)))
11738 (beg (js2-node-abs-pos fn)))
11739 (unless (js2-ast-root-p fn)
11740 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11742 (provide 'js2-mode)
11744 ;;; js2-mode.el ends here