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)
2565 "AST node for a for..in loop."
2566 iterator ; [var] foo in ...
2567 object ; object over which we're iterating
2568 in-pos ; buffer position of 'in' keyword
2569 each-pos ; buffer position of 'each' keyword, if foreach-p
2570 foreach-p ; t if it's a for-each loop
2571 forof-p) ; t if it's a for-of loop
2573 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2574 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2576 (defun js2-visit-for-in-node (n v)
2577 (js2-visit-ast (js2-for-in-node-iterator n) v)
2578 (js2-visit-ast (js2-for-in-node-object n) v)
2579 (js2-visit-ast (js2-for-in-node-body n) v))
2581 (defun js2-print-for-in-node (n i)
2582 (let ((pad (js2-make-pad i))
2583 (foreach (js2-for-in-node-foreach-p n))
2584 (forof (js2-for-in-node-forof-p n)))
2589 (js2-print-ast (js2-for-in-node-iterator n) 0)
2593 (js2-print-ast (js2-for-in-node-object n) 0)
2595 (js2-print-body (js2-for-in-node-body n) (1+ i))
2596 (insert pad "}\n")))
2598 (defstruct (js2-return-node
2601 (:constructor make-js2-return-node (&key (type js2-RETURN)
2605 "AST node for a return statement."
2606 retval) ; expression to return, or 'undefined
2608 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2609 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2611 (defun js2-visit-return-node (n v)
2612 (js2-visit-ast (js2-return-node-retval n) v))
2614 (defun js2-print-return-node (n i)
2615 (insert (js2-make-pad i) "return")
2616 (when (js2-return-node-retval n)
2618 (js2-print-ast (js2-return-node-retval n) 0))
2621 (defstruct (js2-if-node
2624 (:constructor make-js2-if-node (&key (type js2-IF)
2633 "AST node for an if-statement."
2634 condition ; expression
2635 then-part ; statement or block
2636 else-pos ; optional buffer position of 'else' keyword
2637 else-part ; optional statement or block
2638 lp ; position of left-paren, nil if omitted
2639 rp) ; position of right-paren, nil if omitted
2641 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2642 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2644 (defun js2-visit-if-node (n v)
2645 (js2-visit-ast (js2-if-node-condition n) v)
2646 (js2-visit-ast (js2-if-node-then-part n) v)
2647 (js2-visit-ast (js2-if-node-else-part n) v))
2649 (defun js2-print-if-node (n i)
2650 (let ((pad (js2-make-pad i))
2651 (then-part (js2-if-node-then-part n))
2652 (else-part (js2-if-node-else-part n)))
2654 (js2-print-ast (js2-if-node-condition n) 0)
2656 (js2-print-body then-part (1+ i))
2661 ((js2-if-node-p else-part)
2663 (js2-print-body else-part i))
2665 (insert " else {\n")
2666 (js2-print-body else-part (1+ i))
2667 (insert pad "}\n")))))
2669 (defstruct (js2-try-node
2672 (:constructor make-js2-try-node (&key (type js2-TRY)
2678 "AST node for a try-statement."
2680 catch-clauses ; a lisp list of `js2-catch-node'
2681 finally-block) ; a `js2-finally-node'
2683 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2684 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2686 (defun js2-visit-try-node (n v)
2687 (js2-visit-ast (js2-try-node-try-block n) v)
2688 (dolist (clause (js2-try-node-catch-clauses n))
2689 (js2-visit-ast clause v))
2690 (js2-visit-ast (js2-try-node-finally-block n) v))
2692 (defun js2-print-try-node (n i)
2693 (let ((pad (js2-make-pad i))
2694 (catches (js2-try-node-catch-clauses n))
2695 (finally (js2-try-node-finally-block n)))
2696 (insert pad "try {\n")
2697 (js2-print-body (js2-try-node-try-block n) (1+ i))
2700 (dolist (catch catches)
2701 (js2-print-ast catch i)))
2703 (js2-print-ast finally i)
2706 (defstruct (js2-catch-node
2709 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2718 "AST node for a catch clause."
2719 param ; destructuring form or simple name node
2720 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2721 guard-expr ; catch condition, a `js2-node'
2722 block ; statements, a `js2-block-node'
2723 lp ; buffer position of left-paren, nil if omitted
2724 rp) ; buffer position of right-paren, nil if omitted
2726 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2727 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2729 (defun js2-visit-catch-node (n v)
2730 (js2-visit-ast (js2-catch-node-param n) v)
2731 (when (js2-catch-node-guard-kwd n)
2732 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2733 (js2-visit-ast (js2-catch-node-block n) v))
2735 (defun js2-print-catch-node (n i)
2736 (let ((pad (js2-make-pad i))
2737 (guard-kwd (js2-catch-node-guard-kwd n))
2738 (guard-expr (js2-catch-node-guard-expr n)))
2740 (js2-print-ast (js2-catch-node-param n) 0)
2743 (js2-print-ast guard-expr 0))
2745 (js2-print-body (js2-catch-node-block n) (1+ i))
2748 (defstruct (js2-finally-node
2751 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2755 "AST node for a finally clause."
2756 body) ; a `js2-node', often but not always a block node
2758 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2759 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2761 (defun js2-visit-finally-node (n v)
2762 (js2-visit-ast (js2-finally-node-body n) v))
2764 (defun js2-print-finally-node (n i)
2765 (let ((pad (js2-make-pad i)))
2766 (insert " finally {\n")
2767 (js2-print-body (js2-finally-node-body n) (1+ i))
2768 (insert pad "}\n")))
2770 (defstruct (js2-switch-node
2773 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2780 "AST node for a switch statement."
2781 discriminant ; a `js2-node' (switch expression)
2782 cases ; a lisp list of `js2-case-node'
2783 lp ; position of open-paren for discriminant, nil if omitted
2784 rp) ; position of close-paren for discriminant, nil if omitted
2786 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2787 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2789 (defun js2-visit-switch-node (n v)
2790 (js2-visit-ast (js2-switch-node-discriminant n) v)
2791 (dolist (c (js2-switch-node-cases n))
2792 (js2-visit-ast c v)))
2794 (defun js2-print-switch-node (n i)
2795 (let ((pad (js2-make-pad i))
2796 (cases (js2-switch-node-cases n)))
2797 (insert pad "switch (")
2798 (js2-print-ast (js2-switch-node-discriminant n) 0)
2800 (dolist (case cases)
2801 (js2-print-ast case i))
2802 (insert pad "}\n")))
2804 (defstruct (js2-case-node
2805 (:include js2-block-node)
2807 (:constructor make-js2-case-node (&key (type js2-CASE)
2812 "AST node for a case clause of a switch statement."
2813 expr) ; the case expression (nil for default)
2815 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2816 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2818 (defun js2-visit-case-node (n v)
2819 (js2-visit-ast (js2-case-node-expr n) v)
2820 (js2-visit-block n v))
2822 (defun js2-print-case-node (n i)
2823 (let ((pad (js2-make-pad i))
2824 (expr (js2-case-node-expr n)))
2827 (insert "default:\n")
2829 (js2-print-ast expr 0)
2831 (dolist (kid (js2-case-node-kids n))
2832 (js2-print-ast kid (1+ i)))))
2834 (defstruct (js2-throw-node
2837 (:constructor make-js2-throw-node (&key (type js2-THROW)
2841 "AST node for a throw statement."
2842 expr) ; the expression to throw
2844 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2845 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2847 (defun js2-visit-throw-node (n v)
2848 (js2-visit-ast (js2-throw-node-expr n) v))
2850 (defun js2-print-throw-node (n i)
2851 (insert (js2-make-pad i) "throw ")
2852 (js2-print-ast (js2-throw-node-expr n) 0)
2855 (defstruct (js2-with-node
2858 (:constructor make-js2-with-node (&key (type js2-WITH)
2865 "AST node for a with-statement."
2868 lp ; buffer position of left-paren around object, nil if omitted
2869 rp) ; buffer position of right-paren around object, nil if omitted
2871 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2872 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2874 (defun js2-visit-with-node (n v)
2875 (js2-visit-ast (js2-with-node-object n) v)
2876 (js2-visit-ast (js2-with-node-body n) v))
2878 (defun js2-print-with-node (n i)
2879 (let ((pad (js2-make-pad i)))
2880 (insert pad "with (")
2881 (js2-print-ast (js2-with-node-object n) 0)
2883 (js2-print-body (js2-with-node-body n) (1+ i))
2884 (insert pad "}\n")))
2886 (defstruct (js2-label-node
2889 (:constructor make-js2-label-node (&key (type js2-LABEL)
2893 "AST node for a statement label or case label."
2895 loop) ; for validating and code-generating continue-to-label
2897 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2898 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2900 (defun js2-print-label (n i)
2901 (insert (js2-make-pad i)
2902 (js2-label-node-name n)
2905 (defstruct (js2-labeled-stmt-node
2908 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2909 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2910 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2915 "AST node for a statement with one or more labels.
2916 Multiple labels for a statement are collapsed into the labels field."
2917 labels ; lisp list of `js2-label-node'
2918 stmt) ; the statement these labels are for
2920 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2921 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2923 (defun js2-get-label-by-name (lbl-stmt name)
2924 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2925 Returns nil if no such label is in the list."
2926 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2928 (while (and label-list (not result))
2929 (if (string= (js2-label-node-name (car label-list)) name)
2930 (setq result (car label-list))
2931 (setq label-list (cdr label-list))))
2934 (defun js2-visit-labeled-stmt (n v)
2935 (dolist (label (js2-labeled-stmt-node-labels n))
2936 (js2-visit-ast label v))
2937 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2939 (defun js2-print-labeled-stmt (n i)
2940 (dolist (label (js2-labeled-stmt-node-labels n))
2941 (js2-print-ast label i))
2942 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2944 (defun js2-labeled-stmt-node-contains (node label)
2945 "Return t if NODE contains LABEL in its label set.
2946 NODE is a `js2-labels-node'. LABEL is an identifier."
2947 (loop for nl in (js2-labeled-stmt-node-labels node)
2948 if (string= label (js2-label-node-name nl))
2950 finally return nil))
2952 (defsubst js2-labeled-stmt-node-add-label (node label)
2953 "Add a `js2-label-node' to the label set for this statement."
2954 (setf (js2-labeled-stmt-node-labels node)
2955 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2957 (defstruct (js2-jump-node
2960 "Abstract supertype of break and continue nodes."
2961 label ; `js2-name-node' for location of label identifier, if present
2962 target) ; target js2-labels-node or loop/switch statement
2964 (defun js2-visit-jump-node (n v)
2965 (js2-visit-ast (js2-jump-node-label n) v))
2967 (defstruct (js2-break-node
2968 (:include js2-jump-node)
2970 (:constructor make-js2-break-node (&key (type js2-BREAK)
2975 "AST node for a break statement.
2976 The label field is a `js2-name-node', possibly nil, for the named label
2977 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2978 is the target of the break - a label node or enclosing loop/switch statement.")
2980 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2981 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2983 (defun js2-print-break-node (n i)
2984 (insert (js2-make-pad i) "break")
2985 (when (js2-break-node-label n)
2987 (js2-print-ast (js2-break-node-label n) 0))
2990 (defstruct (js2-continue-node
2991 (:include js2-jump-node)
2993 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2998 "AST node for a continue statement.
2999 The label field is the user-supplied enclosing label name, a `js2-name-node'.
3000 It is nil if continue specifies no label. The target field is the jump target:
3001 a `js2-label-node' or the innermost enclosing loop.")
3003 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
3004 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
3006 (defun js2-print-continue-node (n i)
3007 (insert (js2-make-pad i) "continue")
3008 (when (js2-continue-node-label n)
3010 (js2-print-ast (js2-continue-node-label n) 0))
3013 (defstruct (js2-function-node
3014 (:include js2-script-node)
3016 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
3020 (form 'FUNCTION_STATEMENT)
3027 "AST node for a function declaration.
3028 The `params' field is a lisp list of nodes. Each node is either a simple
3029 `js2-name-node', or if it's a destructuring-assignment parameter, a
3030 `js2-array-node' or `js2-object-node'."
3031 ftype ; FUNCTION, GETTER or SETTER
3032 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
3033 name ; function name (a `js2-name-node', or nil if anonymous)
3034 params ; a lisp list of destructuring forms or simple name nodes
3035 rest-p ; if t, the last parameter is rest parameter
3036 body ; a `js2-block-node' or expression node (1.8 only)
3037 lp ; position of arg-list open-paren, or nil if omitted
3038 rp ; position of arg-list close-paren, or nil if omitted
3039 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3040 needs-activation ; t if we need an activation object for this frame
3041 is-generator ; t if this function contains a yield
3042 member-expr) ; nonstandard Ecma extension from Rhino
3044 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3045 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3047 (defun js2-visit-function-node (n v)
3048 (js2-visit-ast (js2-function-node-name n) v)
3049 (dolist (p (js2-function-node-params n))
3050 (js2-visit-ast p v))
3051 (js2-visit-ast (js2-function-node-body n) v))
3053 (defun js2-print-function-node (n i)
3054 (let ((pad (js2-make-pad i))
3055 (getter (js2-node-get-prop n 'GETTER_SETTER))
3056 (name (js2-function-node-name n))
3057 (params (js2-function-node-params n))
3058 (rest-p (js2-function-node-rest-p n))
3059 (body (js2-function-node-body n))
3060 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3062 (insert pad "function"))
3065 (js2-print-ast name 0))
3067 (loop with len = (length params)
3071 (when (and rest-p (= count len))
3073 (js2-print-ast param 0)
3079 ;; TODO: fix this to be smarter about indenting, etc.
3080 (js2-print-body body (1+ i))
3085 (defsubst js2-function-name (node)
3086 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3087 (and (js2-function-node-name node)
3088 (js2-name-node-name (js2-function-node-name node))))
3090 ;; Having this be an expression node makes it more flexible.
3091 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3092 ;; that work better if you assume it's an expression. Whenever we have
3093 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3094 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3095 (defstruct (js2-var-decl-node
3098 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3103 "AST node for a variable declaration list (VAR, CONST or LET).
3104 The node bounds differ depending on the declaration type. For VAR or
3105 CONST declarations, the bounds include the var/const keyword. For LET
3106 declarations, the node begins at the position of the first child."
3107 kids ; a lisp list of `js2-var-init-node' structs.
3108 decl-type) ; js2-VAR, js2-CONST or js2-LET
3110 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3111 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3113 (defun js2-visit-var-decl (n v)
3114 (dolist (kid (js2-var-decl-node-kids n))
3115 (js2-visit-ast kid v)))
3117 (defun js2-print-var-decl (n i)
3118 (let ((pad (js2-make-pad i))
3119 (tt (js2-var-decl-node-decl-type n)))
3122 ((= tt js2-VAR) "var ")
3123 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3124 ((= tt js2-CONST) "const ")
3126 (error "malformed var-decl node"))))
3127 (loop with kids = (js2-var-decl-node-kids n)
3128 with len = (length kids)
3132 (js2-print-ast kid 0)
3136 (defstruct (js2-var-init-node
3139 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3144 "AST node for a variable declaration.
3145 The type field will be js2-CONST for a const decl."
3146 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3147 initializer) ; initializer expression, a `js2-node'
3149 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3150 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3152 (defun js2-visit-var-init-node (n v)
3153 (js2-visit-ast (js2-var-init-node-target n) v)
3154 (js2-visit-ast (js2-var-init-node-initializer n) v))
3156 (defun js2-print-var-init-node (n i)
3157 (let ((pad (js2-make-pad i))
3158 (name (js2-var-init-node-target n))
3159 (init (js2-var-init-node-initializer n)))
3161 (js2-print-ast name 0)
3164 (js2-print-ast init 0))))
3166 (defstruct (js2-cond-node
3169 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3177 "AST node for the ternary operator"
3181 q-pos ; buffer position of ?
3182 c-pos) ; buffer position of :
3184 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3185 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3187 (defun js2-visit-cond-node (n v)
3188 (js2-visit-ast (js2-cond-node-test-expr n) v)
3189 (js2-visit-ast (js2-cond-node-true-expr n) v)
3190 (js2-visit-ast (js2-cond-node-false-expr n) v))
3192 (defun js2-print-cond-node (n i)
3193 (let ((pad (js2-make-pad i)))
3195 (js2-print-ast (js2-cond-node-test-expr n) 0)
3197 (js2-print-ast (js2-cond-node-true-expr n) 0)
3199 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3201 (defstruct (js2-infix-node
3204 (:constructor make-js2-infix-node (&key type
3210 "Represents infix expressions.
3211 Includes assignment ops like `|=', and the comma operator.
3212 The type field inherited from `js2-node' holds the operator."
3213 op-pos ; buffer position where operator begins
3214 left ; any `js2-node'
3215 right) ; any `js2-node'
3217 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3218 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3220 (defun js2-visit-infix-node (n v)
3221 (js2-visit-ast (js2-infix-node-left n) v)
3222 (js2-visit-ast (js2-infix-node-right n) v))
3224 (defconst js2-operator-tokens
3225 (let ((table (make-hash-table :test 'eq))
3227 (list (cons js2-IN "in")
3228 (cons js2-TYPEOF "typeof")
3229 (cons js2-INSTANCEOF "instanceof")
3230 (cons js2-DELPROP "delete")
3231 (cons js2-COMMA ",")
3232 (cons js2-COLON ":")
3237 (cons js2-BITOR "|")
3238 (cons js2-BITXOR "^")
3239 (cons js2-BITAND "&")
3248 (cons js2-URSH ">>>")
3249 (cons js2-ADD "+") ; infix plus
3250 (cons js2-SUB "-") ; infix minus
3255 (cons js2-BITNOT "~")
3256 (cons js2-POS "+") ; unary plus
3257 (cons js2-NEG "-") ; unary minus
3258 (cons js2-SHEQ "===") ; shallow equality
3259 (cons js2-SHNE "!==") ; shallow inequality
3260 (cons js2-ASSIGN "=")
3261 (cons js2-ASSIGN_BITOR "|=")
3262 (cons js2-ASSIGN_BITXOR "^=")
3263 (cons js2-ASSIGN_BITAND "&=")
3264 (cons js2-ASSIGN_LSH "<<=")
3265 (cons js2-ASSIGN_RSH ">>=")
3266 (cons js2-ASSIGN_URSH ">>>=")
3267 (cons js2-ASSIGN_ADD "+=")
3268 (cons js2-ASSIGN_SUB "-=")
3269 (cons js2-ASSIGN_MUL "*=")
3270 (cons js2-ASSIGN_DIV "/=")
3271 (cons js2-ASSIGN_MOD "%="))))
3272 (loop for (k . v) in tokens do
3273 (puthash k v table))
3276 (defun js2-print-infix-node (n i)
3277 (let* ((tt (js2-node-type n))
3278 (op (gethash tt js2-operator-tokens)))
3280 (error "unrecognized infix operator %s" (js2-node-type n)))
3281 (insert (js2-make-pad i))
3282 (js2-print-ast (js2-infix-node-left n) 0)
3283 (unless (= tt js2-COMMA)
3287 (js2-print-ast (js2-infix-node-right n) 0)))
3289 (defstruct (js2-assign-node
3290 (:include js2-infix-node)
3292 (:constructor make-js2-assign-node (&key type
3298 "Represents any assignment.
3299 The type field holds the actual assignment operator.")
3301 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3302 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3304 (defstruct (js2-unary-node
3307 (:constructor make-js2-unary-node (&key type ; required
3311 "AST node type for unary operator nodes.
3312 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3313 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3314 property is added if the operator follows the operand."
3315 operand) ; a `js2-node' expression
3317 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3318 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3320 (defun js2-visit-unary-node (n v)
3321 (js2-visit-ast (js2-unary-node-operand n) v))
3323 (defun js2-print-unary-node (n i)
3324 (let* ((tt (js2-node-type n))
3325 (op (gethash tt js2-operator-tokens))
3326 (postfix (js2-node-get-prop n 'postfix)))
3328 (error "unrecognized unary operator %s" tt))
3329 (insert (js2-make-pad i))
3332 (if (or (= tt js2-TYPEOF)
3335 (js2-print-ast (js2-unary-node-operand n) 0)
3339 (defstruct (js2-let-node
3340 (:include js2-scope)
3342 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3349 "AST node for a let expression or a let statement.
3350 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3351 vars ; a `js2-var-decl-node'
3352 body ; a `js2-node' representing the expression or body block
3356 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3357 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3359 (defun js2-visit-let-node (n v)
3360 (js2-visit-ast (js2-let-node-vars n) v)
3361 (js2-visit-ast (js2-let-node-body n) v))
3363 (defun js2-print-let-node (n i)
3364 (insert (js2-make-pad i) "let (")
3365 (js2-print-ast (js2-let-node-vars n) 0)
3367 (js2-print-ast (js2-let-node-body n) i))
3369 (defstruct (js2-keyword-node
3372 (:constructor make-js2-keyword-node (&key type
3374 (len (- js2-ts-cursor pos)))))
3375 "AST node representing a literal keyword such as `null'.
3376 Used for `null', `this', `true', `false' and `debugger'.
3377 The node type is set to js2-NULL, js2-THIS, etc.")
3379 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3380 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3382 (defun js2-print-keyword-node (n i)
3383 (insert (js2-make-pad i)
3384 (let ((tt (js2-node-type n)))
3386 ((= tt js2-THIS) "this")
3387 ((= tt js2-NULL) "null")
3388 ((= tt js2-TRUE) "true")
3389 ((= tt js2-FALSE) "false")
3390 ((= tt js2-DEBUGGER) "debugger")
3391 (t (error "Invalid keyword literal type: %d" tt))))))
3393 (defsubst js2-this-node-p (node)
3394 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3395 (eq (js2-node-type node) js2-THIS))
3397 (defstruct (js2-new-node
3400 (:constructor make-js2-new-node (&key (type js2-NEW)
3408 "AST node for new-expression such as new Foo()."
3409 target ; an identifier or reference
3410 args ; a lisp list of argument nodes
3411 lp ; position of left-paren, nil if omitted
3412 rp ; position of right-paren, nil if omitted
3413 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3415 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3416 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3418 (defun js2-visit-new-node (n v)
3419 (js2-visit-ast (js2-new-node-target n) v)
3420 (dolist (arg (js2-new-node-args n))
3421 (js2-visit-ast arg v))
3422 (js2-visit-ast (js2-new-node-initializer n) v))
3424 (defun js2-print-new-node (n i)
3425 (insert (js2-make-pad i) "new ")
3426 (js2-print-ast (js2-new-node-target n))
3428 (js2-print-list (js2-new-node-args n))
3430 (when (js2-new-node-initializer n)
3432 (js2-print-ast (js2-new-node-initializer n))))
3434 (defstruct (js2-name-node
3437 (:constructor make-js2-name-node (&key (type js2-NAME)
3439 (len (- js2-ts-cursor
3441 (name js2-ts-string))))
3442 "AST node for a JavaScript identifier"
3444 scope) ; a `js2-scope' (optional, used for codegen)
3446 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3447 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3449 (defun js2-print-name-node (n i)
3450 (insert (js2-make-pad i)
3451 (js2-name-node-name n)))
3453 (defsubst js2-name-node-length (node)
3454 "Return identifier length of NODE, a `js2-name-node'.
3455 Returns 0 if NODE is nil or its identifier field is nil."
3457 (length (js2-name-node-name node))
3460 (defstruct (js2-number-node
3463 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3465 (len (- js2-ts-cursor
3467 (value js2-ts-string)
3468 (num-value js2-ts-number))))
3469 "AST node for a number literal."
3470 value ; the original string, e.g. "6.02e23"
3471 num-value) ; the parsed number value
3473 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3474 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3476 (defun js2-print-number-node (n i)
3477 (insert (js2-make-pad i)
3478 (number-to-string (js2-number-node-num-value n))))
3480 (defstruct (js2-regexp-node
3483 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3485 (len (- js2-ts-cursor
3489 "AST node for a regular expression literal."
3490 value ; the regexp string, without // delimiters
3491 flags) ; a string of flags, e.g. `mi'.
3493 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3494 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3496 (defun js2-print-regexp (n i)
3497 (insert (js2-make-pad i)
3499 (js2-regexp-node-value n)
3501 (if (js2-regexp-node-flags n)
3502 (insert (js2-regexp-node-flags n))))
3504 (defstruct (js2-string-node
3507 (:constructor make-js2-string-node (&key (type js2-STRING)
3509 (len (- js2-ts-cursor
3511 (value js2-ts-string))))
3513 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3514 You can tell the quote type by looking at the first character."
3515 value) ; the characters of the string, including the quotes
3517 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3518 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3520 (defun js2-print-string-node (n i)
3521 (insert (js2-make-pad i)
3522 (js2-node-string n)))
3524 (defstruct (js2-array-node
3527 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3531 "AST node for an array literal."
3532 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3534 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3535 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3537 (defun js2-visit-array-node (n v)
3538 (dolist (e (js2-array-node-elems n))
3539 (js2-visit-ast e v)))
3541 (defun js2-print-array-node (n i)
3542 (insert (js2-make-pad i) "[")
3543 (js2-print-list (js2-array-node-elems n))
3546 (defstruct (js2-object-node
3549 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3553 "AST node for an object literal expression.
3554 `elems' is a list of either `js2-object-prop-node' or `js2-name-node',
3555 the latter represents abbreviation in destructuring expressions."
3558 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3559 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3561 (defun js2-visit-object-node (n v)
3562 (dolist (e (js2-object-node-elems n))
3563 (js2-visit-ast e v)))
3565 (defun js2-print-object-node (n i)
3566 (insert (js2-make-pad i) "{")
3567 (js2-print-list (js2-object-node-elems n))
3570 (defstruct (js2-object-prop-node
3571 (:include js2-infix-node)
3573 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3579 "AST node for an object literal prop:value entry.
3580 The `left' field is the property: a name node, string node or number node.
3581 The `right' field is a `js2-node' representing the initializer value.")
3583 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3584 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3586 (defun js2-print-object-prop-node (n i)
3587 (insert (js2-make-pad i))
3588 (js2-print-ast (js2-object-prop-node-left n) 0)
3590 (js2-print-ast (js2-object-prop-node-right n) 0))
3592 (defstruct (js2-getter-setter-node
3593 (:include js2-infix-node)
3595 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3600 "AST node for a getter/setter property in an object literal.
3601 The `left' field is the `js2-name-node' naming the getter/setter prop.
3602 The `right' field is always an anonymous `js2-function-node' with a node
3603 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3605 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3606 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3608 (defun js2-print-getter-setter (n i)
3609 (let ((pad (js2-make-pad i))
3610 (left (js2-getter-setter-node-left n))
3611 (right (js2-getter-setter-node-right n)))
3613 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3614 (js2-print-ast left 0)
3615 (js2-print-ast right 0)))
3617 (defstruct (js2-prop-get-node
3618 (:include js2-infix-node)
3620 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3625 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3627 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3628 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3630 (defun js2-visit-prop-get-node (n v)
3631 (js2-visit-ast (js2-prop-get-node-left n) v)
3632 (js2-visit-ast (js2-prop-get-node-right n) v))
3634 (defun js2-print-prop-get-node (n i)
3635 (insert (js2-make-pad i))
3636 (js2-print-ast (js2-prop-get-node-left n) 0)
3638 (js2-print-ast (js2-prop-get-node-right n) 0))
3640 (defstruct (js2-elem-get-node
3643 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3650 "AST node for an array index expression such as foo[bar]."
3651 target ; a `js2-node' - the expression preceding the "."
3652 element ; a `js2-node' - the expression in brackets
3653 lb ; position of left-bracket, nil if omitted
3654 rb) ; position of right-bracket, nil if omitted
3656 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3657 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3659 (defun js2-visit-elem-get-node (n v)
3660 (js2-visit-ast (js2-elem-get-node-target n) v)
3661 (js2-visit-ast (js2-elem-get-node-element n) v))
3663 (defun js2-print-elem-get-node (n i)
3664 (insert (js2-make-pad i))
3665 (js2-print-ast (js2-elem-get-node-target n) 0)
3667 (js2-print-ast (js2-elem-get-node-element n) 0)
3670 (defstruct (js2-call-node
3673 (:constructor make-js2-call-node (&key (type js2-CALL)
3680 "AST node for a JavaScript function call."
3681 target ; a `js2-node' evaluating to the function to call
3682 args ; a lisp list of `js2-node' arguments
3683 lp ; position of open-paren, or nil if missing
3684 rp) ; position of close-paren, or nil if missing
3686 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3687 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3689 (defun js2-visit-call-node (n v)
3690 (js2-visit-ast (js2-call-node-target n) v)
3691 (dolist (arg (js2-call-node-args n))
3692 (js2-visit-ast arg v)))
3694 (defun js2-print-call-node (n i)
3695 (insert (js2-make-pad i))
3696 (js2-print-ast (js2-call-node-target n) 0)
3698 (js2-print-list (js2-call-node-args n))
3701 (defstruct (js2-yield-node
3704 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3708 "AST node for yield statement or expression."
3709 value) ; optional: value to be yielded
3711 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3712 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3714 (defun js2-visit-yield-node (n v)
3715 (js2-visit-ast (js2-yield-node-value n) v))
3717 (defun js2-print-yield-node (n i)
3718 (insert (js2-make-pad i))
3720 (when (js2-yield-node-value n)
3722 (js2-print-ast (js2-yield-node-value n) 0)))
3724 (defstruct (js2-paren-node
3727 (:constructor make-js2-paren-node (&key (type js2-LP)
3731 "AST node for a parenthesized expression.
3732 In particular, used when the parens are syntactically optional,
3733 as opposed to required parens such as those enclosing an if-conditional."
3736 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3737 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3739 (defun js2-visit-paren-node (n v)
3740 (js2-visit-ast (js2-paren-node-expr n) v))
3742 (defun js2-print-paren-node (n i)
3743 (insert (js2-make-pad i))
3745 (js2-print-ast (js2-paren-node-expr n) 0)
3748 (defstruct (js2-array-comp-node
3749 (:include js2-scope)
3751 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3760 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3761 result ; result expression (just after left-bracket)
3762 loops ; a lisp list of `js2-array-comp-loop-node'
3763 filter ; guard/filter expression
3764 if-pos ; buffer pos of 'if' keyword, if present, else nil
3765 lp ; buffer position of if-guard left-paren, or nil if not present
3766 rp) ; buffer position of if-guard right-paren, or nil if not present
3768 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3769 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3771 (defun js2-visit-array-comp-node (n v)
3772 (js2-visit-ast (js2-array-comp-node-result n) v)
3773 (dolist (l (js2-array-comp-node-loops n))
3774 (js2-visit-ast l v))
3775 (js2-visit-ast (js2-array-comp-node-filter n) v))
3777 (defun js2-print-array-comp-node (n i)
3778 (let ((pad (js2-make-pad i))
3779 (result (js2-array-comp-node-result n))
3780 (loops (js2-array-comp-node-loops n))
3781 (filter (js2-array-comp-node-filter n)))
3783 (js2-print-ast result 0)
3786 (js2-print-ast l 0))
3789 (js2-print-ast filter 0)
3793 (defstruct (js2-array-comp-loop-node
3794 (:include js2-for-in-node)
3796 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3807 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3809 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3810 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3812 (defun js2-visit-array-comp-loop (n v)
3813 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3814 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3816 (defun js2-print-array-comp-loop (n i)
3818 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3819 (if (js2-array-comp-loop-node-forof-p n)
3822 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3825 (defstruct (js2-empty-expr-node
3828 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3831 "AST node for an empty expression.")
3833 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3834 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3836 (defstruct (js2-xml-node
3837 (:include js2-block-node)
3839 (:constructor make-js2-xml-node (&key (type js2-XML)
3843 "AST node for initial parse of E4X literals.
3844 The kids field is a list of XML fragments, each a `js2-string-node' or
3845 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3847 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3848 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3850 (defun js2-print-xml-node (n i)
3851 (dolist (kid (js2-xml-node-kids n))
3852 (js2-print-ast kid i)))
3854 (defstruct (js2-xml-js-expr-node
3855 (:include js2-xml-node)
3857 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3861 "AST node for an embedded JavaScript {expression} in an E4X literal.
3862 The start and end fields correspond to the curly-braces."
3863 expr) ; a `js2-expr-node' of some sort
3865 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3866 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3868 (defun js2-visit-xml-js-expr (n v)
3869 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3871 (defun js2-print-xml-js-expr (n i)
3872 (insert (js2-make-pad i))
3874 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3877 (defstruct (js2-xml-dot-query-node
3878 (:include js2-infix-node)
3880 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3887 "AST node for an E4X foo.(bar) filter expression.
3888 Note that the left-paren is automatically the character immediately
3889 following the dot (.) in the operator. No whitespace is permitted
3890 between the dot and the lp by the scanner."
3893 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3894 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3896 (defun js2-print-xml-dot-query (n i)
3897 (insert (js2-make-pad i))
3898 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3900 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3903 (defstruct (js2-xml-ref-node
3905 (:constructor nil)) ; abstract
3906 "Base type for E4X XML attribute-access or property-get expressions.
3907 Such expressions can take a variety of forms. The general syntax has
3910 - (optional) an @ (specifying an attribute access)
3911 - (optional) a namespace (a `js2-name-node') and double-colon
3912 - (required) either a `js2-name-node' or a bracketed [expression]
3914 The property-name expressions (examples: ns::name, @name) are
3915 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3916 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3918 This node type (or more specifically, its subclasses) will sometimes
3919 be the right-hand child of a `js2-prop-get-node' or a
3920 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3921 The `js2-xml-ref-node' may also be a standalone primary expression with
3922 no explicit target, which is valid in certain expression contexts such as
3924 company..employee.(@id < 100)
3926 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3927 expression whose parent is a `js2-xml-dot-query-node'."
3932 (defsubst js2-xml-ref-node-attr-access-p (node)
3933 "Return non-nil if this expression began with an @-token."
3934 (and (numberp (js2-xml-ref-node-at-pos node))
3935 (plusp (js2-xml-ref-node-at-pos node))))
3937 (defstruct (js2-xml-prop-ref-node
3938 (:include js2-xml-ref-node)
3940 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3947 "AST node for an E4X XML [expr] property-ref expression.
3948 The JavaScript syntax is an optional @, an optional ns::, and a name.
3950 [ '@' ] [ name '::' ] name
3952 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3953 @ns::*, @*::attr, @*::*, and @*.
3955 The node starts at the @ token, if present. Otherwise it starts at the
3956 namespace name. The node bounds extend through the closing right-bracket,
3957 or if it is missing due to a syntax error, through the end of the index
3961 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3962 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3964 (defun js2-visit-xml-prop-ref-node (n v)
3965 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3966 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3968 (defun js2-print-xml-prop-ref-node (n i)
3969 (insert (js2-make-pad i))
3970 (if (js2-xml-ref-node-attr-access-p n)
3972 (when (js2-xml-prop-ref-node-namespace n)
3973 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3975 (if (js2-xml-prop-ref-node-propname n)
3976 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3978 (defstruct (js2-xml-elem-ref-node
3979 (:include js2-xml-ref-node)
3981 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3990 "AST node for an E4X XML [expr] member-ref expression.
3993 [ '@' ] [ name '::' ] '[' expr ']'
3995 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3997 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3998 is not a legal E4X XML element-ref expression, since it's already used
3999 for standard JavaScript element-get array indexing. Hence, a
4000 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
4001 non-nil namespace node, or both.
4003 The node starts at the @ token, if present. Otherwise it starts
4004 at the namespace name. The node bounds extend through the closing
4005 right-bracket, or if it is missing due to a syntax error, through the
4006 end of the index expression."
4007 expr ; the bracketed index expression
4011 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
4012 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
4014 (defun js2-visit-xml-elem-ref-node (n v)
4015 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
4016 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
4018 (defun js2-print-xml-elem-ref-node (n i)
4019 (insert (js2-make-pad i))
4020 (if (js2-xml-ref-node-attr-access-p n)
4022 (when (js2-xml-elem-ref-node-namespace n)
4023 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
4026 (if (js2-xml-elem-ref-node-expr n)
4027 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
4030 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4032 (defstruct (js2-xml-start-tag-node
4033 (:include js2-xml-node)
4035 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4042 "AST node for an XML start-tag. Not currently used.
4043 The `kids' field is a lisp list of child content nodes."
4044 name ; a `js2-xml-name-node'
4045 attrs ; a lisp list of `js2-xml-attr-node'
4046 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4048 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4049 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4051 (defun js2-visit-xml-start-tag (n v)
4052 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4053 (dolist (attr (js2-xml-start-tag-node-attrs n))
4054 (js2-visit-ast attr v))
4055 (js2-visit-block n v))
4057 (defun js2-print-xml-start-tag (n i)
4058 (insert (js2-make-pad i) "<")
4059 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4060 (when (js2-xml-start-tag-node-attrs n)
4062 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4065 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4066 ;; and add the end-tag to the kids list of the parent as well.
4067 (defstruct (js2-xml-end-tag-node
4068 (:include js2-xml-node)
4070 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4074 "AST node for an XML end-tag. Not currently used."
4075 name) ; a `js2-xml-name-node'
4077 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4078 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4080 (defun js2-visit-xml-end-tag (n v)
4081 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4083 (defun js2-print-xml-end-tag (n i)
4084 (insert (js2-make-pad i))
4086 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4089 (defstruct (js2-xml-name-node
4090 (:include js2-xml-node)
4092 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4097 "AST node for an E4X XML name. Not currently used.
4098 Any XML name can be qualified with a namespace, hence the namespace field.
4099 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4100 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4101 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4102 namespace) ; a `js2-string-node'
4104 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4105 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4107 (defun js2-visit-xml-name-node (n v)
4108 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4110 (defun js2-print-xml-name-node (n i)
4111 (insert (js2-make-pad i))
4112 (when (js2-xml-name-node-namespace n)
4113 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4115 (dolist (kid (js2-xml-name-node-kids n))
4116 (js2-print-ast kid 0)))
4118 (defstruct (js2-xml-pi-node
4119 (:include js2-xml-node)
4121 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4126 "AST node for an E4X XML processing instruction. Not currently used."
4127 name ; a `js2-xml-name-node'
4128 attrs) ; a list of `js2-xml-attr-node'
4130 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4131 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4133 (defun js2-visit-xml-pi-node (n v)
4134 (js2-visit-ast (js2-xml-pi-node-name n) v)
4135 (dolist (attr (js2-xml-pi-node-attrs n))
4136 (js2-visit-ast attr v)))
4138 (defun js2-print-xml-pi-node (n i)
4139 (insert (js2-make-pad i) "<?")
4140 (js2-print-ast (js2-xml-pi-node-name n))
4141 (when (js2-xml-pi-node-attrs n)
4143 (js2-print-list (js2-xml-pi-node-attrs n)))
4146 (defstruct (js2-xml-cdata-node
4147 (:include js2-xml-node)
4149 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4153 "AST node for a CDATA escape section. Not currently used."
4154 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4156 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4157 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4159 (defun js2-visit-xml-cdata-node (n v)
4160 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4162 (defun js2-print-xml-cdata-node (n i)
4163 (insert (js2-make-pad i))
4164 (js2-print-ast (js2-xml-cdata-node-content n)))
4166 (defstruct (js2-xml-attr-node
4167 (:include js2-xml-node)
4169 (:constructor make-js2-attr-node (&key (type js2-XML)
4176 "AST node representing a foo='bar' XML attribute value. Not yet used."
4177 name ; a `js2-xml-name-node'
4178 value ; a `js2-xml-name-node'
4179 eq-pos ; buffer position of "=" sign
4180 quote-type) ; 'single or 'double
4182 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4183 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4185 (defun js2-visit-xml-attr-node (n v)
4186 (js2-visit-ast (js2-xml-attr-node-name n) v)
4187 (js2-visit-ast (js2-xml-attr-node-value n) v))
4189 (defun js2-print-xml-attr-node (n i)
4190 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4193 (insert (js2-make-pad i))
4194 (js2-print-ast (js2-xml-attr-node-name n) 0)
4196 (js2-print-ast (js2-xml-attr-node-value n) 0)
4199 (defstruct (js2-xml-text-node
4200 (:include js2-xml-node)
4202 (:constructor make-js2-text-node (&key (type js2-XML)
4206 "AST node for an E4X XML text node. Not currently used."
4207 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4209 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4210 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4212 (defun js2-visit-xml-text-node (n v)
4213 (js2-visit-ast (js2-xml-text-node-content n) v))
4215 (defun js2-print-xml-text-node (n i)
4216 (insert (js2-make-pad i))
4217 (dolist (kid (js2-xml-text-node-content n))
4218 (js2-print-ast kid)))
4220 (defstruct (js2-xml-comment-node
4221 (:include js2-xml-node)
4223 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4226 "AST node for E4X XML comment. Not currently used.")
4228 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4229 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4231 (defun js2-print-xml-comment (n i)
4232 (insert (js2-make-pad i)
4233 (js2-node-string n)))
4237 (defsubst js2-node-line (n)
4238 "Fetch the source line number at the start of node N.
4239 This is O(n) in the length of the source buffer; use prudently."
4240 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4242 (defsubst js2-block-node-kid (n i)
4243 "Return child I of node N, or nil if there aren't that many."
4244 (nth i (js2-block-node-kids n)))
4246 (defsubst js2-block-node-first (n)
4247 "Return first child of block node N, or nil if there is none."
4248 (first (js2-block-node-kids n)))
4250 (defun js2-node-root (n)
4251 "Return the root of the AST containing N.
4252 If N has no parent pointer, returns N."
4253 (let ((parent (js2-node-parent n)))
4255 (js2-node-root parent)
4258 (defun js2-node-position-in-parent (node &optional parent)
4259 "Return the position of NODE in parent's block-kids list.
4260 PARENT can be supplied if known. Positioned returned is zero-indexed.
4261 Returns 0 if NODE is not a child of a block statement, or if NODE
4262 is not a statement node."
4263 (let ((p (or parent (js2-node-parent node)))
4265 (if (not (js2-block-node-p p))
4267 (or (js2-position node (js2-block-node-kids p))
4270 (defsubst js2-node-short-name (n)
4271 "Return the short name of node N as a string, e.g. `js2-if-node'."
4272 (substring (symbol-name (aref n 0))
4273 (length "cl-struct-")))
4275 (defsubst js2-node-child-list (node)
4276 "Return the child list for NODE, a lisp list of nodes.
4277 Works for block nodes, array nodes, obj literals, funarg lists,
4278 var decls and try nodes (for catch clauses). Note that you should call
4279 `js2-block-node-kids' on the function body for the body statements.
4280 Returns nil for zero-length child lists or unsupported nodes."
4282 ((js2-function-node-p node)
4283 (js2-function-node-params node))
4284 ((js2-block-node-p node)
4285 (js2-block-node-kids node))
4286 ((js2-try-node-p node)
4287 (js2-try-node-catch-clauses node))
4288 ((js2-array-node-p node)
4289 (js2-array-node-elems node))
4290 ((js2-object-node-p node)
4291 (js2-object-node-elems node))
4292 ((js2-call-node-p node)
4293 (js2-call-node-args node))
4294 ((js2-new-node-p node)
4295 (js2-new-node-args node))
4296 ((js2-var-decl-node-p node)
4297 (js2-var-decl-node-kids node))
4301 (defsubst js2-node-set-child-list (node kids)
4302 "Set the child list for NODE to KIDS."
4304 ((js2-function-node-p node)
4305 (setf (js2-function-node-params node) kids))
4306 ((js2-block-node-p node)
4307 (setf (js2-block-node-kids node) kids))
4308 ((js2-try-node-p node)
4309 (setf (js2-try-node-catch-clauses node) kids))
4310 ((js2-array-node-p node)
4311 (setf (js2-array-node-elems node) kids))
4312 ((js2-object-node-p node)
4313 (setf (js2-object-node-elems node) kids))
4314 ((js2-call-node-p node)
4315 (setf (js2-call-node-args node) kids))
4316 ((js2-new-node-p node)
4317 (setf (js2-new-node-args node) kids))
4318 ((js2-var-decl-node-p node)
4319 (setf (js2-var-decl-node-kids node) kids))
4321 (error "Unsupported node type: %s" (js2-node-short-name node))))
4324 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4325 (defconst js2-paren-expr-nodes
4326 '(cl-struct-js2-array-comp-loop-node
4327 cl-struct-js2-array-comp-node
4328 cl-struct-js2-call-node
4329 cl-struct-js2-catch-node
4330 cl-struct-js2-do-node
4331 cl-struct-js2-elem-get-node
4332 cl-struct-js2-for-in-node
4333 cl-struct-js2-for-node
4334 cl-struct-js2-function-node
4335 cl-struct-js2-if-node
4336 cl-struct-js2-let-node
4337 cl-struct-js2-new-node
4338 cl-struct-js2-paren-node
4339 cl-struct-js2-switch-node
4340 cl-struct-js2-while-node
4341 cl-struct-js2-with-node
4342 cl-struct-js2-xml-dot-query-node)
4343 "Node types that can have a parenthesized child expression.
4344 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4346 (defsubst js2-paren-expr-node-p (node)
4347 "Return t for nodes that typically have a parenthesized child expression.
4348 Useful for computing the indentation anchors for arg-lists and conditions.
4349 Note that it may return a false positive, for instance when NODE is
4350 a `js2-new-node' and there are no arguments or parentheses."
4351 (memq (aref node 0) js2-paren-expr-nodes))
4353 ;; Fake polymorphism... yech.
4354 (defsubst js2-node-lp (node)
4355 "Return relative left-paren position for NODE, if applicable.
4356 For `js2-elem-get-node' structs, returns left-bracket position.
4357 Note that the position may be nil in the case of a parse error."
4359 ((js2-elem-get-node-p node)
4360 (js2-elem-get-node-lb node))
4361 ((js2-loop-node-p node)
4362 (js2-loop-node-lp node))
4363 ((js2-function-node-p node)
4364 (js2-function-node-lp node))
4365 ((js2-if-node-p node)
4366 (js2-if-node-lp node))
4367 ((js2-new-node-p node)
4368 (js2-new-node-lp node))
4369 ((js2-call-node-p node)
4370 (js2-call-node-lp node))
4371 ((js2-paren-node-p node)
4372 (js2-node-pos node))
4373 ((js2-switch-node-p node)
4374 (js2-switch-node-lp node))
4375 ((js2-catch-node-p node)
4376 (js2-catch-node-lp node))
4377 ((js2-let-node-p node)
4378 (js2-let-node-lp node))
4379 ((js2-array-comp-node-p node)
4380 (js2-array-comp-node-lp node))
4381 ((js2-with-node-p node)
4382 (js2-with-node-lp node))
4383 ((js2-xml-dot-query-node-p node)
4384 (1+ (js2-infix-node-op-pos node)))
4386 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4388 ;; Fake polymorphism... blech.
4389 (defsubst js2-node-rp (node)
4390 "Return relative right-paren position for NODE, if applicable.
4391 For `js2-elem-get-node' structs, returns right-bracket position.
4392 Note that the position may be nil in the case of a parse error."
4394 ((js2-elem-get-node-p node)
4395 (js2-elem-get-node-lb node))
4396 ((js2-loop-node-p node)
4397 (js2-loop-node-rp node))
4398 ((js2-function-node-p node)
4399 (js2-function-node-rp node))
4400 ((js2-if-node-p node)
4401 (js2-if-node-rp node))
4402 ((js2-new-node-p node)
4403 (js2-new-node-rp node))
4404 ((js2-call-node-p node)
4405 (js2-call-node-rp node))
4406 ((js2-paren-node-p node)
4407 (+ (js2-node-pos node) (js2-node-len node)))
4408 ((js2-switch-node-p node)
4409 (js2-switch-node-rp node))
4410 ((js2-catch-node-p node)
4411 (js2-catch-node-rp node))
4412 ((js2-let-node-p node)
4413 (js2-let-node-rp node))
4414 ((js2-array-comp-node-p node)
4415 (js2-array-comp-node-rp node))
4416 ((js2-with-node-p node)
4417 (js2-with-node-rp node))
4418 ((js2-xml-dot-query-node-p node)
4419 (1+ (js2-xml-dot-query-node-rp node)))
4421 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4423 (defsubst js2-node-first-child (node)
4424 "Returns the first element of `js2-node-child-list' for NODE."
4425 (car (js2-node-child-list node)))
4427 (defsubst js2-node-last-child (node)
4428 "Returns the last element of `js2-node-last-child' for NODE."
4429 (car (last (js2-node-child-list node))))
4431 (defun js2-node-prev-sibling (node)
4432 "Return the previous statement in parent.
4433 Works for parents supported by `js2-node-child-list'.
4434 Returns nil if NODE is not in the parent, or PARENT is
4435 not a supported node, or if NODE is the first child."
4436 (let* ((p (js2-node-parent node))
4437 (kids (js2-node-child-list p))
4440 (not (eq node (cadr kids))))
4441 (setq kids (cdr kids)
4445 (defun js2-node-next-sibling (node)
4446 "Return the next statement in parent block.
4447 Returns nil if NODE is not in the block, or PARENT is not
4448 a block node, or if NODE is the last statement."
4449 (let* ((p (js2-node-parent node))
4450 (kids (js2-node-child-list p)))
4452 (not (eq node (car kids))))
4453 (setq kids (cdr kids)))
4456 (defun js2-node-find-child-before (pos parent &optional after)
4457 "Find the last child that starts before POS in parent.
4458 If AFTER is non-nil, returns first child starting after POS.
4459 POS is an absolute buffer position. PARENT is any node
4460 supported by `js2-node-child-list'.
4461 Returns nil if no applicable child is found."
4462 (let ((kids (if (js2-function-node-p parent)
4463 (js2-block-node-kids (js2-function-node-body parent))
4464 (js2-node-child-list parent)))
4465 (beg (if (js2-function-node-p parent)
4466 (js2-node-abs-pos (js2-function-node-body parent))
4467 (js2-node-abs-pos parent)))
4472 (setq fn (if after '>= '<))
4473 (while (and kids continue)
4474 (setq kid (car kids))
4475 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4477 continue (if after nil t))
4478 (setq continue (if after t nil)))
4479 (setq kids (cdr kids)))
4482 (defun js2-node-find-child-after (pos parent)
4483 "Find first child that starts after POS in parent.
4484 POS is an absolute buffer position. PARENT is any node
4485 supported by `js2-node-child-list'.
4486 Returns nil if no applicable child is found."
4487 (js2-node-find-child-before pos parent 'after))
4489 (defun js2-node-replace-child (pos parent new-node)
4490 "Replace node at index POS in PARENT with NEW-NODE.
4491 Only works for parents supported by `js2-node-child-list'."
4492 (let ((kids (js2-node-child-list parent))
4495 (setq kids (cdr kids)
4497 (setcar kids new-node)
4498 (js2-node-add-children parent new-node)))
4500 (defun js2-node-buffer (n)
4501 "Return the buffer associated with AST N.
4502 Returns nil if the buffer is not set as a property on the root
4503 node, or if parent links were not recorded during parsing."
4504 (let ((root (js2-node-root n)))
4506 (js2-ast-root-p root)
4507 (js2-ast-root-buffer root))))
4509 (defsubst js2-block-node-push (n kid)
4510 "Push js2-node KID onto the end of js2-block-node N's child list.
4511 KID is always added to the -end- of the kids list.
4512 Function also calls `js2-node-add-children' to add the parent link."
4513 (let ((kids (js2-node-child-list n)))
4515 (setcdr kids (nconc (cdr kids) (list kid)))
4516 (js2-node-set-child-list n (list kid)))
4517 (js2-node-add-children n kid)))
4519 (defun js2-node-string (node)
4520 (let ((buf (js2-node-buffer node))
4523 (error "No buffer available for node %s" node))
4524 (with-current-buffer buf
4525 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4526 (+ pos (js2-node-len node))))))
4528 ;; Container for storing the node we're looking for in a traversal.
4529 (js2-deflocal js2-discovered-node nil)
4531 ;; Keep track of absolute node position during traversals.
4532 (js2-deflocal js2-visitor-offset nil)
4534 (js2-deflocal js2-node-search-point nil)
4536 (when js2-mode-dev-mode-p
4537 (defun js2-find-node-at-point ()
4539 (let ((node (js2-node-at-point)))
4540 (message "%s" (or node "No node found at point"))))
4541 (defun js2-node-name-at-point ()
4543 (let ((node (js2-node-at-point)))
4544 (message "%s" (if node
4545 (js2-node-short-name node)
4546 "No node found at point.")))))
4548 (defun js2-node-at-point (&optional pos skip-comments)
4549 "Return AST node at POS, a buffer position, defaulting to current point.
4550 The `js2-mode-ast' variable must be set to the current parse tree.
4551 Signals an error if the AST (`js2-mode-ast') is nil.
4552 Always returns a node - if it can't find one, it returns the root.
4553 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4554 (let ((ast js2-mode-ast)
4557 (error "No JavaScript AST available"))
4558 ;; Look through comments first, since they may be inside nodes that
4559 ;; would otherwise report a match.
4560 (setq pos (or pos (point))
4561 result (if (> pos (js2-node-abs-end ast))
4563 (if (not skip-comments)
4564 (js2-comment-at-point pos))))
4566 (setq js2-discovered-node nil
4567 js2-visitor-offset 0
4568 js2-node-search-point pos)
4570 (catch 'js2-visit-done
4571 (js2-visit-ast ast #'js2-node-at-point-visitor))
4572 (setq js2-visitor-offset nil
4573 js2-node-search-point nil))
4574 (setq result js2-discovered-node))
4575 ;; may have found a comment beyond end of last child node,
4576 ;; since visiting the ast-root looks at the comment-list last.
4577 (if (and skip-comments
4578 (js2-comment-node-p result))
4580 (or result js2-mode-ast)))
4582 (defun js2-node-at-point-visitor (node end-p)
4583 (let ((rel-pos (js2-node-pos node))
4586 (point js2-node-search-point))
4589 ;; this evaluates to a non-nil return value, even if it's zero
4590 (decf js2-visitor-offset rel-pos))
4591 ;; we already looked for comments before visiting, and don't want them now
4592 ((js2-comment-node-p node)
4595 (setq abs-pos (incf js2-visitor-offset rel-pos)
4596 ;; we only want to use the node if the point is before
4597 ;; the last character position in the node, so we decrement
4598 ;; the absolute end by 1.
4599 abs-end (+ abs-pos (js2-node-len node) -1))
4601 ;; If this node starts after search-point, stop the search.
4603 (throw 'js2-visit-done nil))
4604 ;; If this node ends before the search-point, don't check kids.
4608 ;; Otherwise point is within this node, possibly in a child.
4609 (setq js2-discovered-node node)
4610 t)))))) ; keep processing kids to look for more specific match
4612 (defsubst js2-block-comment-p (node)
4613 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4614 (and (js2-comment-node-p node)
4615 (memq (js2-comment-node-format node) '(jsdoc block))))
4617 ;; TODO: put the comments in a vector and binary-search them instead
4618 (defun js2-comment-at-point (&optional pos)
4619 "Look through scanned comment nodes for one containing POS.
4620 POS is a buffer position that defaults to current point.
4621 Function returns nil if POS was not in any comment node."
4622 (let ((ast js2-mode-ast)
4623 (x (or pos (point)))
4627 (error "No JavaScript AST available"))
4629 ;; Comments are stored in lexical order.
4630 (dolist (comment (js2-ast-root-comments ast) nil)
4631 (setq beg (js2-node-abs-pos comment)
4632 end (+ beg (js2-node-len comment)))
4635 (throw 'done comment))))))
4637 (defun js2-mode-find-parent-fn (node)
4638 "Find function enclosing NODE.
4639 Returns nil if NODE is not inside a function."
4640 (setq node (js2-node-parent node))
4641 (while (and node (not (js2-function-node-p node)))
4642 (setq node (js2-node-parent node)))
4643 (and (js2-function-node-p node) node))
4645 (defun js2-mode-find-enclosing-fn (node)
4646 "Find function or root enclosing NODE."
4647 (if (js2-ast-root-p node)
4649 (setq node (js2-node-parent node))
4650 (while (not (or (js2-ast-root-p node)
4651 (js2-function-node-p node)))
4652 (setq node (js2-node-parent node)))
4655 (defun js2-mode-find-enclosing-node (beg end)
4656 "Find script or function fully enclosing BEG and END."
4657 (let ((node (js2-node-at-point beg))
4661 (if (or (js2-ast-root-p node)
4662 (and (js2-function-node-p node)
4663 (<= (setq pos (js2-node-abs-pos node)) beg)
4664 (>= (+ pos (js2-node-len node)) end)))
4666 (setq node (js2-node-parent node))))
4669 (defun js2-node-parent-script-or-fn (node)
4670 "Find script or function immediately enclosing NODE.
4671 If NODE is the ast-root, returns nil."
4672 (if (js2-ast-root-p node)
4674 (setq node (js2-node-parent node))
4675 (while (and node (not (or (js2-function-node-p node)
4676 (js2-script-node-p node))))
4677 (setq node (js2-node-parent node)))
4680 (defsubst js2-nested-function-p (node)
4681 "Return t if NODE is a nested function, or is inside a nested function."
4682 (unless (js2-ast-root-p node)
4683 (js2-function-node-p (if (js2-function-node-p node)
4684 (js2-node-parent-script-or-fn node)
4685 (js2-node-parent-script-or-fn
4686 (js2-node-parent-script-or-fn node))))))
4688 (defsubst js2-function-param-node-p (node)
4689 "Return non-nil if NODE is a param node of a `js2-function-node'."
4690 (let ((parent (js2-node-parent node)))
4692 (js2-function-node-p parent)
4693 (memq node (js2-function-node-params parent)))))
4695 (defsubst js2-mode-shift-kids (kids start offset)
4697 (if (> (js2-node-pos kid) start)
4698 (incf (js2-node-pos kid) offset))))
4700 (defsubst js2-mode-shift-children (parent start offset)
4701 "Update start-positions of all children of PARENT beyond START."
4702 (let ((root (js2-node-root parent)))
4703 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4704 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4706 (defsubst js2-node-is-descendant (node ancestor)
4707 "Return t if NODE is a descendant of ANCESTOR."
4709 (not (eq node ancestor)))
4710 (setq node (js2-node-parent node)))
4713 ;;; visitor infrastructure
4715 (defun js2-visit-none (node callback)
4716 "Visitor for AST node that have no node children."
4719 (defun js2-print-none (node indent)
4720 "Visitor for AST node with no printed representation.")
4722 (defun js2-print-body (node indent)
4723 "Print a statement, or a block without braces."
4724 (if (js2-block-node-p node)
4725 (dolist (kid (js2-block-node-kids node))
4726 (js2-print-ast kid indent))
4727 (js2-print-ast node indent)))
4729 (defun js2-print-list (args &optional delimiter)
4730 (loop with len = (length args)
4734 (js2-print-ast arg 0)
4736 (insert (or delimiter ", ")))))
4738 (defun js2-print-tree (ast)
4739 "Prints an AST to the current buffer.
4740 Makes `js2-ast-parent-nodes' available to the printer functions."
4741 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4742 (js2-print-ast ast)))
4744 (defun js2-print-ast (node &optional indent)
4745 "Helper function for printing AST nodes.
4746 Requires `js2-ast-parent-nodes' to be non-nil.
4747 You should use `js2-print-tree' instead of this function."
4748 (let ((printer (get (aref node 0) 'js2-printer))
4750 (pos (js2-node-abs-pos node)))
4751 ;; TODO: wedge comments in here somewhere
4753 (funcall printer node i))))
4755 (defconst js2-side-effecting-tokens
4756 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4757 (dolist (tt (list js2-ASSIGN
4826 (if js2-instanceof-has-side-effects
4827 (aset tokens js2-INSTANCEOF t))
4830 (defun js2-node-has-side-effects (node)
4831 "Return t if NODE has side effects."
4832 (when node ; makes it easier to handle malformed expressions
4833 (let ((tt (js2-node-type node)))
4835 ;; This doubtless needs some work, since EXPR_VOID is used
4836 ;; in several ways in Rhino, and I may not have caught them all.
4837 ;; I'll wait for people to notice incorrect warnings.
4838 ((and (= tt js2-EXPR_VOID)
4839 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4840 (let ((expr (js2-expr-stmt-node-expr node)))
4841 (or (js2-node-has-side-effects expr)
4842 (when (js2-string-node-p expr)
4843 (string= "use strict" (js2-string-node-value expr))))))
4845 (js2-node-has-side-effects (js2-infix-node-right node)))
4848 (or (js2-node-has-side-effects (js2-infix-node-right node))
4849 (js2-node-has-side-effects (js2-infix-node-left node))))
4851 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4852 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4853 ((js2-paren-node-p node)
4854 (js2-node-has-side-effects (js2-paren-node-expr node)))
4855 ((= tt js2-ERROR) ; avoid cascaded error messages
4858 (aref js2-side-effecting-tokens tt))))))
4860 (defun js2-member-expr-leftmost-name (node)
4861 "For an expr such as foo.bar.baz, return leftmost node foo.
4862 NODE is any `js2-node' object. If it represents a member expression,
4863 which is any sequence of property gets, element-gets, function calls,
4864 or xml descendants/filter operators, then we look at the lexically
4865 leftmost (first) node in the chain. If it is a name-node we return it.
4866 Note that NODE can be a raw name-node and it will be returned as well.
4867 If NODE is not a name-node or member expression, or if it is a member
4868 expression whose leftmost target is not a name node, returns nil."
4871 (while (and continue (not result))
4873 ((js2-name-node-p node)
4875 ((js2-prop-get-node-p node)
4876 (setq node (js2-prop-get-node-left node)))
4877 ;; TODO: handle call-nodes, xml-nodes, others?
4879 (setq continue nil))))
4882 (defconst js2-stmt-node-types
4886 js2-DEFAULT ; e4x "default xml namespace" statement
4898 "Node types that only appear in statement contexts.
4899 The list does not include nodes that always appear as the child
4900 of another specific statement type, such as switch-cases,
4901 catch and finally blocks, and else-clauses. The list also excludes
4902 nodes like yield, let and var, which may appear in either expression
4903 or statement context, and in the latter context always have a
4904 `js2-expr-stmt-node' parent. Finally, the list does not include
4905 functions or scripts, which are treated separately from statements
4906 by the JavaScript parser and runtime.")
4908 (defun js2-stmt-node-p (node)
4909 "Heuristic for figuring out if NODE is a statement.
4910 Some node types can appear in either an expression context or a
4911 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4912 For these node types in a statement context, the parent will be a
4913 `js2-expr-stmt-node'.
4914 Functions aren't included in the check."
4915 (memq (js2-node-type node) js2-stmt-node-types))
4917 (defsubst js2-mode-find-first-stmt (node)
4918 "Search upward starting from NODE looking for a statement.
4919 For purposes of this function, a `js2-function-node' counts."
4920 (while (not (or (js2-stmt-node-p node)
4921 (js2-function-node-p node)))
4922 (setq node (js2-node-parent node)))
4925 (defun js2-node-parent-stmt (node)
4926 "Return the node's first ancestor that is a statement.
4927 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4928 appearing in a statement context will have a parent that is a
4929 `js2-expr-stmt-node' that will be returned by this function."
4930 (let ((parent (js2-node-parent node)))
4931 (if (or (null parent)
4932 (js2-stmt-node-p parent)
4933 (and (js2-function-node-p parent)
4934 (not (eq (js2-function-node-form parent)
4935 'FUNCTION_EXPRESSION))))
4937 (js2-node-parent-stmt parent))))
4939 ;; In the Mozilla Rhino sources, Roshan James writes:
4940 ;; Does consistent-return analysis on the function body when strict mode is
4943 ;; function (x) { return (x+1) }
4947 ;; function (x) { if (x < 0) return (x+1); }
4949 ;; is not because the function can potentially return a value when the
4950 ;; condition is satisfied and if not, the function does not explicitly
4953 ;; This extends to checking mismatches such as "return" and "return <value>"
4954 ;; used in the same function. Warnings are not emitted if inconsistent
4955 ;; returns exist in code that can be statically shown to be unreachable.
4957 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4959 ;; emits no warning. However if the loop had a break statement, then a
4960 ;; warning would be emitted.
4962 ;; The consistency analysis looks at control structures such as loops, ifs,
4963 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4964 ;; warns the user about an inconsistent set of termination possibilities.
4966 ;; These flags enumerate the possible ways a statement/function can
4967 ;; terminate. These flags are used by endCheck() and by the Parser to
4968 ;; detect inconsistent return usage.
4970 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4971 ;; able to execute (example: throw, continue)
4973 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4974 ;; next one. Statement such as return dont. A compound statement may have
4975 ;; some branch that drops off control to the next statement.
4977 ;; END_RETURNS indicates that the statement can return with no value.
4978 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4980 ;; A compound statement such as
4984 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4986 (defconst js2-END_UNREACHED 0)
4987 (defconst js2-END_DROPS_OFF 1)
4988 (defconst js2-END_RETURNS 2)
4989 (defconst js2-END_RETURNS_VALUE 4)
4990 (defconst js2-END_YIELDS 8)
4992 (defun js2-has-consistent-return-usage (node)
4993 "Check that every return usage in a function body is consistent.
4994 Returns t if the function satisfies strict mode requirement."
4995 (let ((n (js2-end-check node)))
4996 ;; either it doesn't return a value in any branch...
4997 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4998 ;; or it returns a value (or is unreached) at every branch
4999 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
5003 (defun js2-end-check-if (node)
5004 "Returns in the then and else blocks must be consistent with each other.
5005 If there is no else block, then the return statement can fall through.
5006 Returns logical OR of END_* flags"
5007 (let ((th (js2-if-node-then-part node))
5008 (el (js2-if-node-else-part node)))
5011 (logior (js2-end-check th) (if el
5013 js2-END_DROPS_OFF)))))
5015 (defun js2-end-check-switch (node)
5016 "Consistency of return statements is checked between the case statements.
5017 If there is no default, then the switch can fall through. If there is a
5018 default, we check to see if all code paths in the default return or if
5019 there is a code path that can fall through.
5020 Returns logical OR of END_* flags."
5021 (let ((rv js2-END_UNREACHED)
5023 ;; examine the cases
5025 (dolist (c (js2-switch-node-cases node))
5026 (if (js2-case-node-expr c)
5027 (js2-set-flag rv (js2-end-check-block c))
5028 (setq default-case c)
5029 (throw 'break nil))))
5030 ;; we don't care how the cases drop into each other
5031 (js2-clear-flag rv js2-END_DROPS_OFF)
5032 ;; examine the default
5033 (js2-set-flag rv (if default-case
5034 (js2-end-check default-case)
5038 (defun js2-end-check-try (node)
5039 "If the block has a finally, return consistency is checked in the
5040 finally block. If all code paths in the finally return, then the
5041 returns in the try-catch blocks don't matter. If there is a code path
5042 that does not return or if there is no finally block, the returns
5043 of the try and catch blocks are checked for mismatch.
5044 Returns logical OR of END_* flags."
5045 (let ((finally (js2-try-node-finally-block node))
5047 ;; check the finally if it exists
5048 (setq rv (if finally
5049 (js2-end-check (js2-finally-node-body finally))
5051 ;; If the finally block always returns, then none of the returns
5052 ;; in the try or catch blocks matter.
5053 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5054 (js2-clear-flag rv js2-END_DROPS_OFF)
5055 ;; examine the try block
5056 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5057 ;; check each catch block
5058 (dolist (cb (js2-try-node-catch-clauses node))
5059 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5062 (defun js2-end-check-loop (node)
5063 "Return statement in the loop body must be consistent. The default
5064 assumption for any kind of a loop is that it will eventually terminate.
5065 The only exception is a loop with a constant true condition. Code that
5066 follows such a loop is examined only if one can statically determine
5067 that there is a break out of the loop.
5069 for(... ; ... ; ...) {}
5074 Returns logical OR of END_* flags."
5075 (let ((rv (js2-end-check (js2-loop-node-body node)))
5077 ((js2-while-node-p node)
5078 (js2-while-node-condition node))
5079 ((js2-do-node-p node)
5080 (js2-do-node-condition node))
5081 ((js2-for-node-p node)
5082 (js2-for-node-condition node)))))
5084 ;; check to see if the loop condition is always true
5086 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5087 (js2-clear-flag rv js2-END_DROPS_OFF))
5089 ;; look for effect of breaks
5090 (js2-set-flag rv (js2-node-get-prop node
5095 (defun js2-end-check-block (node)
5096 "A general block of code is examined statement by statement.
5097 If any statement (even a compound one) returns in all branches, then
5098 subsequent statements are not examined.
5099 Returns logical OR of END_* flags."
5100 (let* ((rv js2-END_DROPS_OFF)
5101 (kids (js2-block-node-kids node))
5103 ;; Check each statment. If the statement can continue onto the next
5104 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5105 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5106 (js2-clear-flag rv js2-END_DROPS_OFF)
5107 (js2-set-flag rv (js2-end-check n))
5108 (setq kids (cdr kids)
5112 (defun js2-end-check-label (node)
5113 "A labeled statement implies that there may be a break to the label.
5114 The function processes the labeled statement and then checks the
5115 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5117 Returns logical OR of END_* flags."
5118 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5119 (logior rv (js2-node-get-prop node
5121 js2-END_UNREACHED))))
5123 (defun js2-end-check-break (node)
5124 "When a break is encountered annotate the statement being broken
5125 out of by setting its CONTROL_BLOCK_PROP property.
5126 Returns logical OR of END_* flags."
5127 (and (js2-break-node-target node)
5128 (js2-node-set-prop (js2-break-node-target node)
5133 (defun js2-end-check (node)
5134 "Examine the body of a function, doing a basic reachability analysis.
5135 Returns a combination of flags END_* flags that indicate
5136 how the function execution can terminate. These constitute only the
5137 pessimistic set of termination conditions. It is possible that at
5138 runtime certain code paths will never be actually taken. Hence this
5139 analysis will flag errors in cases where there may not be errors.
5140 Returns logical OR of END_* flags"
5143 ((js2-break-node-p node)
5144 (js2-end-check-break node))
5145 ((js2-expr-stmt-node-p node)
5146 (if (setq kid (js2-expr-stmt-node-expr node))
5149 ((or (js2-continue-node-p node)
5150 (js2-throw-node-p node))
5152 ((js2-return-node-p node)
5153 (if (setq kid (js2-return-node-retval node))
5154 js2-END_RETURNS_VALUE
5156 ((js2-loop-node-p node)
5157 (js2-end-check-loop node))
5158 ((js2-switch-node-p node)
5159 (js2-end-check-switch node))
5160 ((js2-labeled-stmt-node-p node)
5161 (js2-end-check-label node))
5162 ((js2-if-node-p node)
5163 (js2-end-check-if node))
5164 ((js2-try-node-p node)
5165 (js2-end-check-try node))
5166 ((js2-block-node-p node)
5167 (if (null (js2-block-node-kids node))
5169 (js2-end-check-block node)))
5170 ((js2-yield-node-p node)
5173 js2-END_DROPS_OFF))))
5175 (defun js2-always-defined-boolean-p (node)
5176 "Check if NODE always evaluates to true or false in boolean context.
5177 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5179 (let ((tt (js2-node-type node))
5182 ((or (= tt js2-FALSE) (= tt js2-NULL))
5187 (setq num (js2-number-node-num-value node))
5188 (if (and (not (eq num 0.0e+NaN))
5195 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5196 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5198 (defvar js2-tokens nil
5199 "List of all defined token names.") ; initialized in `js2-token-names'
5201 (defconst js2-token-names
5202 (let* ((names (make-vector js2-num-tokens -1))
5203 (case-fold-search nil) ; only match js2-UPPER_CASE
5204 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5205 (loop for sym in syms
5208 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5210 (aset names (symbol-value sym) ; code, e.g. 152
5212 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5213 (push sym js2-tokens)))
5215 "Vector mapping int values to token string names, sans `js2-' prefix.")
5217 (defun js2-token-name (tok)
5218 "Return a string name for TOK, a token symbol or code.
5219 Signals an error if it's not a recognized token."
5222 (setq code (symbol-value tok)))
5225 (if (and (numberp code)
5227 (< code js2-num-tokens))
5228 (aref js2-token-names code)
5229 (error "Invalid token: %s" code)))))
5231 (defsubst js2-token-sym (tok)
5232 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5233 (intern (js2-token-name tok)))
5235 (defconst js2-token-codes
5236 (let ((table (make-hash-table :test 'eq :size 256)))
5237 (loop for name across js2-token-names
5238 for sym = (intern (concat "js2-" (upcase name)))
5240 (puthash sym (symbol-value sym) table))
5241 ;; clean up a few that are "wrong" in Rhino's token codes
5242 (puthash 'js2-DELETE js2-DELPROP table)
5244 "Hashtable mapping token symbols to their bytecodes.")
5246 (defsubst js2-token-code (sym)
5247 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5248 (or (gethash sym js2-token-codes)
5249 (error "Invalid token symbol: %s " sym))) ; signal code bug
5251 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5252 (setq js2-token-end js2-ts-cursor)
5253 (js2-report-error msg nil
5254 (or beg js2-token-beg)
5255 (or len (- js2-token-end js2-token-beg)))
5257 (throw 'return js2-ERROR)))
5259 (defsubst js2-get-string-from-buffer ()
5260 "Reverse the char accumulator and return it as a string."
5261 (setq js2-token-end js2-ts-cursor)
5262 (if js2-ts-string-buffer
5263 (apply #'string (nreverse js2-ts-string-buffer))
5266 ;; TODO: could potentially avoid a lot of consing by allocating a
5267 ;; char buffer the way Rhino does.
5268 (defsubst js2-add-to-string (c)
5269 (push c js2-ts-string-buffer))
5271 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5272 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5273 ;; any other character: when it's not part of the current token, we
5274 ;; unget it, allowing it to be read again by the following call.
5275 (defsubst js2-unget-char ()
5276 (decf js2-ts-cursor))
5278 ;; Rhino distinguishes \r and \n line endings. We don't need to
5279 ;; because we only scan from Emacs buffers, which always use \n.
5280 (defsubst js2-get-char ()
5281 "Read and return the next character from the input buffer.
5282 Increments `js2-ts-lineno' if the return value is a newline char.
5283 Updates `js2-ts-cursor' to the point after the returned char.
5284 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5285 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5287 ;; check for end of buffer
5288 (if (>= js2-ts-cursor (point-max))
5289 (setq js2-ts-hit-eof t
5290 js2-ts-cursor (1+ js2-ts-cursor)
5291 c js2-EOF_CHAR) ; return value
5292 ;; otherwise read next char
5293 (setq c (char-before (incf js2-ts-cursor)))
5294 ;; if we read a newline, update counters
5296 (setq js2-ts-line-start js2-ts-cursor
5297 js2-ts-lineno (1+ js2-ts-lineno)))
5298 ;; TODO: skip over format characters
5301 (defsubst js2-read-unicode-escape ()
5302 "Read a \\uNNNN sequence from the input.
5303 Assumes the ?\ and ?u have already been read.
5304 Returns the unicode character, or nil if it wasn't a valid character.
5305 Doesn't change the values of any scanner variables."
5306 ;; I really wish I knew a better way to do this, but I can't
5307 ;; find the Emacs function that takes a 16-bit int and converts
5308 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5309 ;; Have to first check that it's 4 hex characters or it may stop
5312 (let ((s (buffer-substring-no-properties js2-ts-cursor
5313 (+ 4 js2-ts-cursor))))
5314 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5315 (read (concat "?\\u" s))))))
5317 (defsubst js2-match-char (test)
5318 "Consume and return next character if it matches TEST, a character.
5319 Returns nil and consumes nothing if TEST is not the next character."
5320 (let ((c (js2-get-char)))
5326 (defsubst js2-peek-char ()
5331 (defsubst js2-java-identifier-start-p (c)
5334 (js2-char-uppercase-p c)
5335 (js2-char-lowercase-p c)))
5337 (defsubst js2-java-identifier-part-p (c)
5338 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5339 ;; TODO: make me Unicode-friendly. See comments above.
5342 (js2-char-uppercase-p c)
5343 (js2-char-lowercase-p c)
5344 (and (>= c ?0) (<= c ?9))))
5346 (defsubst js2-alpha-p (c)
5347 (cond ((and (<= ?A c) (<= c ?Z)) t)
5348 ((and (<= ?a c) (<= c ?z)) t)
5351 (defsubst js2-digit-p (c)
5352 (and (<= ?0 c) (<= c ?9)))
5354 (defsubst js2-js-space-p (c)
5356 (memq c '(#x20 #x9 #xB #xC #xD))
5359 ;; TODO: change this nil to check for Unicode space character
5362 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5364 (defsubst js2-skip-line ()
5365 "Skip to end of line"
5367 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5369 (setq js2-token-end js2-ts-cursor)))
5371 (defun js2-init-scanner (&optional buf line)
5372 "Create token stream for BUF starting on LINE.
5373 BUF defaults to current-buffer and line defaults to 1.
5375 A buffer can only have one scanner active at a time, which yields
5376 dramatically simpler code than using a defstruct. If you need to
5377 have simultaneous scanners in a buffer, copy the regions to scan
5382 (setq js2-ts-dirty-line nil
5383 js2-ts-regexp-flags nil
5388 js2-ts-lineno (or line 1)
5389 js2-ts-line-end-char -1
5390 js2-ts-cursor (point-min)
5391 js2-ts-is-xml-attribute nil
5392 js2-ts-xml-is-tag-content nil
5393 js2-ts-xml-open-tags-count 0
5394 js2-ts-string-buffer nil)))
5396 ;; This function uses the cached op, string and number fields in
5397 ;; TokenStream; if getToken has been called since the passed token
5398 ;; was scanned, the op or string printed may be incorrect.
5399 (defun js2-token-to-string (token)
5400 ;; Not sure where this function is used in Rhino. Not tested.
5401 (if (not js2-debug-print-trees)
5403 (let ((name (js2-token-name token)))
5405 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5406 (concat name " `" js2-ts-string "'"))
5407 ((eq token js2-NUMBER)
5408 (format "NUMBER %g" js2-ts-number))
5412 (defconst js2-keywords
5414 case catch const continue
5415 debugger default delete do
5417 false finally for function
5418 if in instanceof import
5423 this throw true try typeof
5428 ;; Token names aren't exactly the same as the keywords, unfortunately.
5429 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5430 (defconst js2-kwd-tokens
5431 (let ((table (make-vector js2-num-tokens nil))
5434 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5435 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5437 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5438 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5443 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5448 (aset table i 'font-lock-keyword-face))
5449 (aset table js2-STRING 'font-lock-string-face)
5450 (aset table js2-REGEXP 'font-lock-string-face)
5451 (aset table js2-COMMENT 'font-lock-comment-face)
5452 (aset table js2-THIS 'font-lock-builtin-face)
5453 (aset table js2-VOID 'font-lock-constant-face)
5454 (aset table js2-NULL 'font-lock-constant-face)
5455 (aset table js2-TRUE 'font-lock-constant-face)
5456 (aset table js2-FALSE 'font-lock-constant-face)
5458 "Vector whose values are non-nil for tokens that are keywords.
5459 The values are default faces to use for highlighting the keywords.")
5461 (defconst js2-reserved-words
5469 implements import int interface
5472 package private protected public
5473 short static super synchronized
5477 (defconst js2-keyword-names
5478 (let ((table (make-hash-table :test 'equal)))
5479 (loop for k in js2-keywords
5481 (symbol-name k) ; instanceof
5482 (intern (concat "js2-"
5483 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5486 "JavaScript keywords by name, mapped to their symbols.")
5488 (defconst js2-reserved-word-names
5489 (let ((table (make-hash-table :test 'equal)))
5490 (loop for k in js2-reserved-words
5492 (puthash (symbol-name k) 'js2-RESERVED table))
5494 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5496 (defsubst js2-collect-string (buf)
5497 "Convert BUF, a list of chars, to a string.
5498 Reverses BUF before converting."
5502 ((null buf) ; for emacs21 compat
5506 (apply #'string (nreverse buf))
5509 (defun js2-string-to-keyword (s)
5510 "Return token for S, a string, if S is a keyword or reserved word.
5511 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5512 (or (gethash s js2-keyword-names)
5513 (gethash s js2-reserved-word-names)))
5515 (defsubst js2-ts-set-char-token-bounds ()
5516 "Used when next token is one character."
5517 (setq js2-token-beg (1- js2-ts-cursor)
5518 js2-token-end js2-ts-cursor))
5520 (defsubst js2-ts-return (token)
5521 "Return an N-character TOKEN from `js2-get-token'.
5522 Updates `js2-token-end' accordingly."
5523 (setq js2-token-end js2-ts-cursor)
5524 (throw 'return token))
5526 (defsubst js2-x-digit-to-int (c accumulator)
5527 "Build up a hex number.
5528 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5529 corresponding number. Otherwise return -1."
5532 ;; Use 0..9 < A..Z < a..z
5537 (throw 'check nil)))
5541 (throw 'check nil)))
5545 (throw 'check nil))))
5547 (logior c (lsh accumulator 4))))
5549 (defun js2-get-token ()
5550 "Return next JavaScript token, an int such as js2-RETURN."
5554 is-unicode-escape-start
5568 ;; Eat whitespace, possibly sensitive to newlines.
5571 (setq c (js2-get-char))
5573 ((eq c js2-EOF_CHAR)
5574 (js2-ts-set-char-token-bounds)
5575 (throw 'return js2-EOF))
5577 (js2-ts-set-char-token-bounds)
5578 (setq js2-ts-dirty-line nil)
5579 (throw 'return js2-EOL))
5580 ((not (js2-js-space-p c))
5581 (if (/= c ?-) ; in case end of HTML comment
5582 (setq js2-ts-dirty-line t))
5583 (setq continue nil))))
5584 ;; Assume the token will be 1 char - fixed up below.
5585 (js2-ts-set-char-token-bounds)
5587 (throw 'return js2-XMLATTR))
5588 ;; identifier/keyword/instanceof?
5589 ;; watch out for starting with a <backslash>
5592 (setq c (js2-get-char))
5594 (setq identifier-start t
5595 is-unicode-escape-start t
5596 js2-ts-string-buffer nil)
5597 (setq identifier-start nil)
5601 (when (setq identifier-start (js2-java-identifier-start-p c))
5602 (setq js2-ts-string-buffer nil)
5603 (js2-add-to-string c))))
5604 (when identifier-start
5605 (setq contains-escape is-unicode-escape-start)
5608 (if is-unicode-escape-start
5609 ;; strictly speaking we should probably push-back
5610 ;; all the bad characters if the <backslash>uXXXX
5611 ;; sequence is malformed. But since there isn't a
5612 ;; correct context(is there?) for a bad Unicode
5613 ;; escape sequence in an identifier, we can report
5618 (setq c (js2-get-char)
5619 escape-val (js2-x-digit-to-int c escape-val))
5620 ;; Next check takes care of c < 0 and bad escape
5621 (if (minusp escape-val)
5622 (throw 'break nil)))
5623 (if (minusp escape-val)
5624 (js2-report-scan-error "msg.invalid.escape" t))
5625 (js2-add-to-string escape-val)
5626 (setq is-unicode-escape-start nil))
5627 (setq c (js2-get-char))
5630 (setq c (js2-get-char))
5632 (setq is-unicode-escape-start t
5634 (js2-report-scan-error "msg.illegal.character" t)))
5636 (if (or (eq c js2-EOF_CHAR)
5637 (not (js2-java-identifier-part-p c)))
5639 (js2-add-to-string c))))))
5641 (setq str (js2-get-string-from-buffer))
5642 (unless contains-escape
5643 ;; OPT we shouldn't have to make a string (object!) to
5644 ;; check if it's a keyword.
5645 ;; Return the corresponding token if it's a keyword
5646 (when (setq result (js2-string-to-keyword str))
5647 (if (and (< js2-language-version 170)
5648 (memq result '(js2-LET js2-YIELD)))
5649 ;; LET and YIELD are tokens only in 1.7 and later
5650 (setq result 'js2-NAME))
5651 (if (not (eq result 'js2-RESERVED))
5652 (throw 'return (js2-token-code result)))
5653 (js2-report-warning "msg.reserved.keyword" str)))
5654 ;; If we want to intern these as Rhino does, just use (intern str)
5655 (setq js2-ts-string str)
5656 (throw 'return js2-NAME)) ; end identifier/kwd check
5658 (when (or (js2-digit-p c)
5659 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5660 (setq js2-ts-string-buffer nil
5663 (setq c (js2-get-char))
5665 ((or (eq c ?x) (eq c ?X))
5667 (setq c (js2-get-char)))
5671 (js2-add-to-string ?0))))
5673 (while (<= 0 (js2-x-digit-to-int c 0))
5674 (js2-add-to-string c)
5675 (setq c (js2-get-char)))
5676 (while (and (<= ?0 c) (<= c ?9))
5677 ;; We permit 08 and 09 as decimal numbers, which
5678 ;; makes our behavior a superset of the ECMA
5679 ;; numeric grammar. We might not always be so
5680 ;; permissive, so we warn about it.
5681 (when (and (eq base 8) (>= c ?8))
5682 (js2-report-warning "msg.bad.octal.literal"
5683 (if (eq c ?8) "8" "9"))
5685 (js2-add-to-string c)
5686 (setq c (js2-get-char))))
5688 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5689 (setq is-integer nil)
5692 (js2-add-to-string c)
5693 (setq c (js2-get-char))
5694 while (js2-digit-p c)))
5695 (when (memq c '(?e ?E))
5696 (js2-add-to-string c)
5697 (setq c (js2-get-char))
5698 (when (memq c '(?+ ?-))
5699 (js2-add-to-string c)
5700 (setq c (js2-get-char)))
5701 (unless (js2-digit-p c)
5702 (js2-report-scan-error "msg.missing.exponent" t))
5704 (js2-add-to-string c)
5705 (setq c (js2-get-char))
5706 while (js2-digit-p c))))
5708 (setq js2-ts-string (js2-get-string-from-buffer)
5710 (if (and (eq base 10) (not is-integer))
5711 (string-to-number js2-ts-string)
5712 ;; TODO: call runtime number-parser. Some of it is in
5713 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5714 (string-to-number js2-ts-string)))
5715 (throw 'return js2-NUMBER))
5717 (when (memq c '(?\" ?\'))
5718 ;; We attempt to accumulate a string the fast way, by
5719 ;; building it directly out of the reader. But if there
5720 ;; are any escaped characters in the string, we revert to
5721 ;; building it out of a string buffer.
5723 js2-ts-string-buffer nil
5726 (while (/= c quote-char)
5728 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5730 (setq js2-token-end js2-ts-cursor)
5731 (js2-report-error "msg.unterminated.string.lit")
5732 (throw 'return js2-STRING))
5734 ;; We've hit an escaped character
5735 (setq c (js2-get-char))
5744 (setq c1 (js2-read-unicode-escape))
5745 (if js2-parse-ide-mode
5748 ;; just copy the string in IDE-mode
5749 (js2-add-to-string ?\\)
5750 (js2-add-to-string ?u)
5752 (js2-add-to-string (js2-get-char)))
5753 (setq c (js2-get-char))) ; added at end of loop
5754 ;; flag it as an invalid escape
5755 (js2-report-warning "msg.invalid.escape"
5756 nil (- js2-ts-cursor 2) 6))
5757 ;; Get 4 hex digits; if the u escape is not
5758 ;; followed by 4 hex digits, use 'u' + the
5759 ;; literal character sequence that follows.
5760 (js2-add-to-string ?u)
5763 (setq c (js2-get-char)
5764 escape-val (js2-x-digit-to-int c escape-val))
5765 (if (minusp escape-val)
5766 (throw 'continue nil))
5767 (js2-add-to-string c))
5768 ;; prepare for replace of stored 'u' sequence by escape value
5769 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5772 ;; Get 2 hex digits, defaulting to 'x'+literal
5773 ;; sequence, as above.
5774 (setq c (js2-get-char)
5775 escape-val (js2-x-digit-to-int c 0))
5776 (if (minusp escape-val)
5778 (js2-add-to-string ?x)
5779 (throw 'continue nil))
5782 escape-val (js2-x-digit-to-int c escape-val))
5783 (if (minusp escape-val)
5785 (js2-add-to-string ?x)
5786 (js2-add-to-string c1)
5787 (throw 'continue nil))
5789 (setq c escape-val))))
5791 ;; Remove line terminator after escape to follow
5792 ;; SpiderMonkey and C/C++
5793 (setq c (js2-get-char))
5794 (throw 'continue nil))
5796 (when (and (<= ?0 c) (< c ?8))
5799 (when (and (<= ?0 c) (< c ?8))
5800 (setq val (- (+ (* 8 val) c) ?0)
5802 (when (and (<= ?0 c)
5805 ;; c is 3rd char of octal sequence only
5806 ;; if the resulting val <= 0377
5807 (setq val (- (+ (* 8 val) c) ?0)
5811 (js2-add-to-string c)
5812 (setq c (js2-get-char)))))
5813 (setq js2-ts-string (js2-get-string-from-buffer))
5814 (throw 'return js2-STRING))
5817 (throw 'return js2-SEMI))
5819 (throw 'return js2-LB))
5821 (throw 'return js2-RB))
5823 (throw 'return js2-LC))
5825 (throw 'return js2-RC))
5827 (throw 'return js2-LP))
5829 (throw 'return js2-RP))
5831 (throw 'return js2-COMMA))
5833 (throw 'return js2-HOOK))
5835 (if (js2-match-char ?:)
5836 (js2-ts-return js2-COLONCOLON)
5837 (throw 'return js2-COLON)))
5839 (if (js2-match-char ?.)
5840 (if (js2-match-char ?.)
5841 (js2-ts-return js2-TRIPLEDOT)
5842 (js2-ts-return js2-DOTDOT))
5843 (if (js2-match-char ?\()
5844 (js2-ts-return js2-DOTQUERY)
5845 (throw 'return js2-DOT))))
5847 (if (js2-match-char ?|)
5848 (throw 'return js2-OR)
5849 (if (js2-match-char ?=)
5850 (js2-ts-return js2-ASSIGN_BITOR)
5851 (throw 'return js2-BITOR))))
5853 (if (js2-match-char ?=)
5854 (js2-ts-return js2-ASSIGN_BITOR)
5855 (throw 'return js2-BITXOR)))
5857 (if (js2-match-char ?&)
5858 (throw 'return js2-AND)
5859 (if (js2-match-char ?=)
5860 (js2-ts-return js2-ASSIGN_BITAND)
5861 (throw 'return js2-BITAND))))
5863 (if (js2-match-char ?=)
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-SHEQ)
5866 (throw 'return js2-EQ))
5867 (throw 'return js2-ASSIGN)))
5869 (if (js2-match-char ?=)
5870 (if (js2-match-char ?=)
5871 (js2-ts-return js2-SHNE)
5872 (js2-ts-return js2-NE))
5873 (throw 'return js2-NOT)))
5875 ;; NB:treat HTML begin-comment as comment-till-eol
5876 (when (js2-match-char ?!)
5877 (when (js2-match-char ?-)
5878 (when (js2-match-char ?-)
5880 (setq js2-ts-comment-type 'html)
5881 (throw 'return js2-COMMENT)))
5883 (if (js2-match-char ?<)
5884 (if (js2-match-char ?=)
5885 (js2-ts-return js2-ASSIGN_LSH)
5886 (js2-ts-return js2-LSH))
5887 (if (js2-match-char ?=)
5888 (js2-ts-return js2-LE)
5889 (throw 'return js2-LT))))
5891 (if (js2-match-char ?>)
5892 (if (js2-match-char ?>)
5893 (if (js2-match-char ?=)
5894 (js2-ts-return js2-ASSIGN_URSH)
5895 (js2-ts-return js2-URSH))
5896 (if (js2-match-char ?=)
5897 (js2-ts-return js2-ASSIGN_RSH)
5898 (js2-ts-return js2-RSH)))
5899 (if (js2-match-char ?=)
5900 (js2-ts-return js2-GE)
5901 (throw 'return js2-GT))))
5903 (if (js2-match-char ?=)
5904 (js2-ts-return js2-ASSIGN_MUL)
5905 (throw 'return js2-MUL)))
5907 ;; is it a // comment?
5908 (when (js2-match-char ?/)
5909 (setq js2-token-beg (- js2-ts-cursor 2))
5911 (setq js2-ts-comment-type 'line)
5912 ;; include newline so highlighting goes to end of window
5913 (incf js2-token-end)
5914 (throw 'return js2-COMMENT))
5915 ;; is it a /* comment?
5916 (when (js2-match-char ?*)
5917 (setq look-for-slash nil
5918 js2-token-beg (- js2-ts-cursor 2)
5920 (if (js2-match-char ?*)
5922 (setq look-for-slash t)
5926 (setq c (js2-get-char))
5928 ((eq c js2-EOF_CHAR)
5929 (setq js2-token-end (1- js2-ts-cursor))
5930 (js2-report-error "msg.unterminated.comment")
5931 (throw 'return js2-COMMENT))
5933 (setq look-for-slash t))
5936 (js2-ts-return js2-COMMENT)))
5938 (setq look-for-slash nil
5939 js2-token-end js2-ts-cursor)))))
5940 (if (js2-match-char ?=)
5941 (js2-ts-return js2-ASSIGN_DIV)
5942 (throw 'return js2-DIV)))
5944 (when js2-skip-preprocessor-directives
5946 (setq js2-ts-comment-type 'preprocessor
5947 js2-token-end js2-ts-cursor)
5948 (throw 'return js2-COMMENT))
5949 (throw 'return js2-ERROR))
5951 (if (js2-match-char ?=)
5952 (js2-ts-return js2-ASSIGN_MOD)
5953 (throw 'return js2-MOD)))
5955 (throw 'return js2-BITNOT))
5957 (if (js2-match-char ?=)
5958 (js2-ts-return js2-ASSIGN_ADD)
5959 (if (js2-match-char ?+)
5960 (js2-ts-return js2-INC)
5961 (throw 'return js2-ADD))))
5964 ((js2-match-char ?=)
5965 (setq c js2-ASSIGN_SUB))
5966 ((js2-match-char ?-)
5967 (unless js2-ts-dirty-line
5968 ;; treat HTML end-comment after possible whitespace
5969 ;; after line start as comment-until-eol
5970 (when (js2-match-char ?>)
5972 (setq js2-ts-comment-type 'html)
5973 (throw 'return js2-COMMENT)))
5977 (setq js2-ts-dirty-line t)
5980 (js2-report-scan-error "msg.illegal.character")))))))
5982 (defun js2-read-regexp (start-token)
5983 "Called by parser when it gets / or /= in literal context."
5986 in-class ; inside a '[' .. ']' character-class
5989 (setq js2-token-beg js2-ts-cursor
5990 js2-ts-string-buffer nil
5991 js2-ts-regexp-flags nil)
5992 (if (eq start-token js2-ASSIGN_DIV)
5994 (js2-add-to-string ?=)
5995 (if (not (eq start-token js2-DIV))
5996 (error "failed assertion")))
5997 (while (and (not err)
5998 (or (/= (setq c (js2-get-char)) ?/)
6003 (setq js2-token-end (1- js2-ts-cursor)
6005 js2-ts-string (js2-collect-string js2-ts-string-buffer))
6006 (js2-report-error "msg.unterminated.re.lit"))
6009 (js2-add-to-string c)
6010 (setq c (js2-get-char)))
6014 (setq in-class nil)))
6015 (js2-add-to-string c))))
6019 ((js2-match-char ?g)
6021 ((js2-match-char ?i)
6023 ((js2-match-char ?m)
6026 (setq continue nil))))
6027 (if (js2-alpha-p (js2-peek-char))
6028 (js2-report-scan-error "msg.invalid.re.flag" t
6030 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
6031 js2-ts-regexp-flags (js2-collect-string flags)
6032 js2-token-end js2-ts-cursor)
6033 ;; tell `parse-partial-sexp' to ignore this range of chars
6034 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6036 (defun js2-get-first-xml-token ()
6037 (setq js2-ts-xml-open-tags-count 0
6038 js2-ts-is-xml-attribute nil
6039 js2-ts-xml-is-tag-content nil)
6041 (js2-get-next-xml-token))
6043 (defsubst js2-xml-discard-string ()
6044 "Throw away the string in progress and flag an XML parse error."
6045 (setq js2-ts-string-buffer nil
6047 (js2-report-scan-error "msg.XML.bad.form" t))
6049 (defun js2-get-next-xml-token ()
6050 (setq js2-ts-string-buffer nil ; for recording the XML
6051 js2-token-beg js2-ts-cursor)
6056 (setq c (js2-get-char))
6059 (throw 'return js2-ERROR))
6060 (js2-ts-xml-is-tag-content
6063 (js2-add-to-string c)
6064 (setq js2-ts-xml-is-tag-content nil
6065 js2-ts-is-xml-attribute nil))
6067 (js2-add-to-string c)
6068 (when (eq ?> (js2-peek-char))
6069 (setq c (js2-get-char))
6070 (js2-add-to-string c)
6071 (setq js2-ts-xml-is-tag-content nil)
6072 (decf js2-ts-xml-open-tags-count)))
6075 (setq js2-ts-string (js2-get-string-from-buffer))
6076 (throw 'return js2-XML))
6078 (js2-add-to-string c)
6079 (unless (js2-read-quoted-string c)
6080 (throw 'return js2-ERROR)))
6082 (js2-add-to-string c)
6083 (setq js2-ts-is-xml-attribute t))
6085 (js2-add-to-string c))
6087 (js2-add-to-string c)
6088 (setq js2-ts-is-xml-attribute nil)))
6089 (when (and (not js2-ts-xml-is-tag-content)
6090 (zerop js2-ts-xml-open-tags-count))
6091 (setq js2-ts-string (js2-get-string-from-buffer))
6092 (throw 'return js2-XMLEND)))
6094 ;; else not tag content
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)
6103 (setq c (js2-peek-char))
6106 (setq c (js2-get-char)) ;; skip -
6107 (js2-add-to-string c)
6110 (js2-add-to-string c)
6111 (unless (js2-read-xml-comment)
6112 (throw 'return js2-ERROR)))
6113 (js2-xml-discard-string)
6114 (throw 'return js2-ERROR)))
6116 (setq c (js2-get-char)) ;; skip [
6117 (js2-add-to-string c)
6118 (if (and (= (js2-get-char) ?C)
6119 (= (js2-get-char) ?D)
6120 (= (js2-get-char) ?A)
6121 (= (js2-get-char) ?T)
6122 (= (js2-get-char) ?A)
6123 (= (js2-get-char) ?\[))
6125 (js2-add-to-string ?C)
6126 (js2-add-to-string ?D)
6127 (js2-add-to-string ?A)
6128 (js2-add-to-string ?T)
6129 (js2-add-to-string ?A)
6130 (js2-add-to-string ?\[)
6131 (unless (js2-read-cdata)
6132 (throw 'return js2-ERROR)))
6133 (js2-xml-discard-string)
6134 (throw 'return js2-ERROR)))
6136 (unless (js2-read-entity)
6137 (throw 'return js2-ERROR))))
6138 ;; allow bare CDATA section
6139 ;; ex) let xml = <![CDATA[ foo bar baz ]]>;
6140 (when (zerop js2-ts-xml-open-tags-count)
6141 (throw 'return js2-XMLEND)))
6143 (setq c (js2-get-char)) ;; skip ?
6144 (js2-add-to-string c)
6145 (unless (js2-read-PI)
6146 (throw 'return js2-ERROR)))
6149 (setq c (js2-get-char)) ;; skip /
6150 (js2-add-to-string c)
6151 (when (zerop js2-ts-xml-open-tags-count)
6152 (js2-xml-discard-string)
6153 (throw 'return js2-ERROR))
6154 (setq js2-ts-xml-is-tag-content t)
6155 (decf js2-ts-xml-open-tags-count))
6158 (setq js2-ts-xml-is-tag-content t)
6159 (incf js2-ts-xml-open-tags-count))))
6162 (setq js2-ts-string (js2-get-string-from-buffer))
6163 (throw 'return js2-XML))
6165 (js2-add-to-string c))))))))
6166 (setq js2-token-end js2-ts-cursor)
6169 (defun js2-read-quoted-string (quote)
6172 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6173 (js2-add-to-string c)
6176 (js2-xml-discard-string) ;; throw away string in progress
6179 (defun js2-read-xml-comment ()
6180 (let ((c (js2-get-char)))
6182 (while (/= c js2-EOF_CHAR)
6184 (js2-add-to-string c)
6185 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6186 (setq c (js2-get-char))
6187 (js2-add-to-string c)
6188 (if (eq (js2-peek-char) ?>)
6190 (setq c (js2-get-char)) ;; skip >
6191 (js2-add-to-string c)
6193 (throw 'continue nil)))
6194 (setq c (js2-get-char))))
6195 (js2-xml-discard-string)
6198 (defun js2-read-cdata ()
6199 (let ((c (js2-get-char)))
6201 (while (/= c js2-EOF_CHAR)
6203 (js2-add-to-string c)
6204 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6205 (setq c (js2-get-char))
6206 (js2-add-to-string c)
6207 (if (eq (js2-peek-char) ?>)
6209 (setq c (js2-get-char)) ;; Skip >
6210 (js2-add-to-string c)
6212 (throw 'continue nil)))
6213 (setq c (js2-get-char))))
6214 (js2-xml-discard-string)
6217 (defun js2-read-entity ()
6221 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6222 (js2-add-to-string c)
6228 (if (zerop decl-tags)
6229 (throw 'return t)))))
6230 (js2-xml-discard-string)
6233 (defun js2-read-PI ()
6234 "Scan an XML processing instruction."
6237 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6238 (js2-add-to-string c)
6239 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6240 (setq c (js2-get-char)) ;; Skip >
6241 (js2-add-to-string c)
6243 (js2-xml-discard-string)
6246 (defun js2-scanner-get-line ()
6247 "Return the text of the current scan line."
6248 (buffer-substring (point-at-bol) (point-at-eol)))
6252 (defsubst js2-set-face (beg end face &optional record)
6253 "Fontify a region. If RECORD is non-nil, record for later."
6254 (when (plusp js2-highlight-level)
6255 (setq beg (min (point-max) beg)
6256 beg (max (point-min) beg)
6257 end (min (point-max) end)
6258 end (max (point-min) end))
6260 (push (list beg end face) js2-mode-fontifications)
6261 (put-text-property beg end 'font-lock-face face))))
6263 (defsubst js2-set-kid-face (pos kid len face)
6264 "Set-face on a child node.
6265 POS is absolute buffer position of parent.
6266 KID is the child node.
6267 LEN is the length to fontify.
6268 FACE is the face to fontify with."
6269 (js2-set-face (+ pos (js2-node-pos kid))
6270 (+ pos (js2-node-pos kid) (js2-node-len kid))
6273 (defsubst js2-fontify-kwd (start length)
6274 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6276 (defsubst js2-clear-face (beg end)
6277 (remove-text-properties beg end '(font-lock-face nil
6282 (defconst js2-ecma-global-props
6285 '("Infinity" "NaN" "undefined" "arguments") t)
6287 "Value properties of the Ecma-262 Global Object.
6288 Shown at or above `js2-highlight-level' 2.")
6290 ;; might want to add the name "arguments" to this list?
6291 (defconst js2-ecma-object-props
6294 '("prototype" "__proto__" "__parent__") t)
6296 "Value properties of the Ecma-262 Object constructor.
6297 Shown at or above `js2-highlight-level' 2.")
6299 (defconst js2-ecma-global-funcs
6303 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6304 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6306 "Function properties of the Ecma-262 Global object.
6307 Shown at or above `js2-highlight-level' 2.")
6309 (defconst js2-ecma-number-props
6311 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6313 "POSITIVE_INFINITY") t)
6315 "Properties of the Ecma-262 Number constructor.
6316 Shown at or above `js2-highlight-level' 2.")
6318 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6319 "Properties of the Ecma-262 Date constructor.
6320 Shown at or above `js2-highlight-level' 2.")
6322 (defconst js2-ecma-math-props
6325 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6328 "Properties of the Ecma-262 Math object.
6329 Shown at or above `js2-highlight-level' 2.")
6331 (defconst js2-ecma-math-funcs
6334 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6335 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6337 "Function properties of the Ecma-262 Math object.
6338 Shown at or above `js2-highlight-level' 2.")
6340 (defconst js2-ecma-function-props
6344 '(;; properties of the Object prototype object
6345 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6346 "toLocaleString" "toString" "valueOf"
6347 ;; properties of the Function prototype object
6349 ;; properties of the Array prototype object
6350 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6352 ;; properties of the String prototype object
6353 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6354 "localeCompare" "match" "replace" "search" "split" "substring"
6355 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6357 ;; properties of the Number prototype object
6358 "toExponential" "toFixed" "toPrecision"
6359 ;; properties of the Date prototype object
6360 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6361 "getMinutes" "getMonth" "getSeconds" "getTime"
6362 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6363 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6364 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6365 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6366 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6367 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6368 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6369 "toTimeString" "toUTCString"
6370 ;; properties of the RegExp prototype object
6372 ;; properties of the JSON prototype object
6374 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6375 "toSource" "__defineGetter__" "__defineSetter__"
6376 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6377 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6380 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6381 Shown at or above `js2-highlight-level' 3.")
6383 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6384 (let ((target-name (and target
6385 (js2-name-node-p target)
6386 (js2-name-node-name target)))
6387 (prop-name (if prop (js2-name-node-name prop)))
6388 (level1 (>= js2-highlight-level 1))
6389 (level2 (>= js2-highlight-level 2))
6390 (level3 (>= js2-highlight-level 3))
6398 ((and level3 (string-match js2-ecma-function-props prop-name))
6399 (setq face 'font-lock-builtin-face))
6400 ((and target-name prop)
6402 ((string= target-name "Date")
6403 (if (string-match js2-ecma-date-props prop-name)
6404 (setq face 'font-lock-builtin-face)))
6405 ((string= target-name "Math")
6406 (if (string-match js2-ecma-math-funcs prop-name)
6407 (setq face 'font-lock-builtin-face)))))))
6409 (if (string-match js2-ecma-global-funcs prop-name)
6410 (setq face 'font-lock-builtin-face))))
6414 ((string= target-name "Number")
6415 (if (string-match js2-ecma-number-props prop-name)
6416 (setq face 'font-lock-constant-face)))
6417 ((string= target-name "Math")
6418 (if (string-match js2-ecma-math-props prop-name)
6419 (setq face 'font-lock-constant-face)))))
6421 (if (string-match js2-ecma-object-props prop-name)
6422 (setq face 'font-lock-constant-face)))))
6424 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6425 (js2-node-pos prop))) ; relative
6426 (+ pos (js2-node-len prop))
6429 (defun js2-parse-highlight-member-expr-node (node)
6430 "Perform syntax highlighting of EcmaScript built-in properties.
6431 The variable `js2-highlight-level' governs this highighting."
6432 (let (face target prop name pos end parent call-p callee)
6434 ;; case 1: simple name, e.g. foo
6435 ((js2-name-node-p node)
6436 (setq name (js2-name-node-name node))
6437 ;; possible for name to be nil in rare cases - saw it when
6438 ;; running js2-mode on an elisp buffer. Might as well try to
6439 ;; make it so js2-mode never barfs.
6441 (setq face (if (string-match js2-ecma-global-props name)
6442 'font-lock-constant-face))
6444 (setq pos (js2-node-pos node)
6445 end (+ pos (js2-node-len node)))
6446 (js2-set-face pos end face 'record))))
6447 ;; case 2: property access or function call
6448 ((or (js2-prop-get-node-p node)
6449 ;; highlight function call if expr is a prop-get node
6450 ;; or a plain name (i.e. unqualified function call)
6451 (and (setq call-p (js2-call-node-p node))
6452 (setq callee (js2-call-node-target node)) ; separate setq!
6453 (or (js2-prop-get-node-p callee)
6454 (js2-name-node-p callee))))
6456 node (if call-p callee node))
6457 (if (and call-p (js2-name-node-p callee))
6459 (setq target (js2-prop-get-node-left node)
6460 prop (js2-prop-get-node-right node)))
6462 ((js2-name-node-p target)
6463 (if (js2-name-node-p prop)
6464 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6465 (js2-parse-highlight-prop-get parent target prop call-p)
6466 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6467 (js2-parse-highlight-prop-get parent target nil call-p)))
6468 ((js2-name-node-p prop)
6469 ;; case 2c: complex target, simple name, e.g. x[y].bar
6470 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6472 (defun js2-parse-highlight-member-expr-fn-name (expr)
6473 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6474 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6475 We currently only handle the case where the last component is a prop-get
6476 of a simple name. Called before EXPR has a parent node."
6478 (name (and (js2-prop-get-node-p expr)
6479 (js2-prop-get-node-right expr))))
6480 (when (js2-name-node-p name)
6481 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6482 (js2-node-pos name)))
6483 (+ pos (js2-node-len name))
6484 'font-lock-function-name-face
6487 ;; source: http://jsdoc.sourceforge.net/
6488 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6489 ;; allows type specifications, and needs work before entering the wild.
6491 (defconst js2-jsdoc-param-tag-regexp
6492 (concat "^\\s-*\\*+\\s-*\\(@"
6493 "\\(?:param\\|argument\\)"
6495 "\\s-*\\({[^}]+}\\)?" ; optional type
6496 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6498 "Matches jsdoc tags with optional type and optional param name.")
6500 (defconst js2-jsdoc-typed-tag-regexp
6501 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6515 "\\)\\)\\s-*\\({[^}]+}\\)?")
6516 "Matches jsdoc tags with optional type.")
6518 (defconst js2-jsdoc-arg-tag-regexp
6519 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6542 "\\)\\)\\s-+\\([^ \t]+\\)")
6543 "Matches jsdoc tags with a single argument.")
6545 (defconst js2-jsdoc-empty-tag-regexp
6546 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6586 "Matches empty jsdoc tags.")
6588 (defconst js2-jsdoc-link-tag-regexp
6589 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6590 "Matches a jsdoc link or code tag.")
6592 (defconst js2-jsdoc-see-tag-regexp
6593 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6594 "Matches a jsdoc @see tag.")
6596 (defconst js2-jsdoc-html-tag-regexp
6597 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6598 "Matches a simple (no attributes) html start- or end-tag.")
6600 (defsubst js2-jsdoc-highlight-helper ()
6601 (js2-set-face (match-beginning 1)
6603 'js2-jsdoc-tag-face)
6604 (if (match-beginning 2)
6606 (goto-char (match-beginning 2))
6607 (= (char-after) ?{))
6608 (js2-set-face (1+ (match-beginning 2))
6610 'js2-jsdoc-type-face)
6611 (js2-set-face (match-beginning 2)
6613 'js2-jsdoc-value-face)))
6614 (if (match-beginning 3)
6615 (js2-set-face (match-beginning 3)
6617 'js2-jsdoc-value-face)))
6619 (defun js2-highlight-jsdoc (ast)
6620 "Highlight doc comment tags."
6621 (let ((comments (js2-ast-root-comments ast))
6624 (dolist (node comments)
6625 (when (eq (js2-comment-node-format node) 'jsdoc)
6626 (setq beg (js2-node-abs-pos node)
6627 end (+ beg (js2-node-len node)))
6629 (narrow-to-region beg end)
6630 (dolist (re (list js2-jsdoc-param-tag-regexp
6631 js2-jsdoc-typed-tag-regexp
6632 js2-jsdoc-arg-tag-regexp
6633 js2-jsdoc-link-tag-regexp
6634 js2-jsdoc-see-tag-regexp
6635 js2-jsdoc-empty-tag-regexp))
6637 (while (re-search-forward re nil t)
6638 (js2-jsdoc-highlight-helper)))
6639 ;; simple highlighting for html tags
6641 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6642 (js2-set-face (match-beginning 1)
6644 'js2-jsdoc-html-tag-delimiter-face)
6645 (js2-set-face (match-beginning 2)
6647 'js2-jsdoc-html-tag-name-face)
6648 (js2-set-face (match-beginning 3)
6650 'js2-jsdoc-html-tag-delimiter-face))))))))
6652 (defun js2-highlight-assign-targets (node left right)
6653 "Highlight function properties and external variables."
6654 (let (leftpos end name)
6655 ;; highlight vars and props assigned function values
6656 (when (js2-function-node-p right)
6658 ;; var foo = function() {...}
6659 ((js2-name-node-p left)
6661 ;; foo.bar.baz = function() {...}
6662 ((and (js2-prop-get-node-p left)
6663 (js2-name-node-p (js2-prop-get-node-right left)))
6664 (setq name (js2-prop-get-node-right left))))
6666 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6667 (+ leftpos (js2-node-len name))
6668 'font-lock-function-name-face
6671 (defun js2-record-name-node (node)
6672 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6673 later. NODE must be a name node."
6675 (push (list node js2-current-scope
6676 (setq leftpos (js2-node-abs-pos node))
6677 (setq end (+ leftpos (js2-node-len node))))
6678 js2-recorded-identifiers)))
6680 (defun js2-highlight-undeclared-vars ()
6681 "After entire parse is finished, look for undeclared variable references.
6682 We have to wait until entire buffer is parsed, since JavaScript permits var
6683 decls to occur after they're used.
6685 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6686 it is considered declared."
6688 (dolist (entry js2-recorded-identifiers)
6689 (destructuring-bind (name-node scope pos end) entry
6690 (setq name (js2-name-node-name name-node))
6691 (unless (or (member name js2-global-externs)
6692 (member name js2-default-externs)
6693 (member name js2-additional-externs)
6694 (js2-get-defining-scope scope name))
6695 (js2-set-face pos end 'js2-external-variable-face 'record)
6696 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6697 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6698 (setq js2-recorded-identifiers nil)))
6702 ;; We currently only support imenu, but eventually should support speedbar and
6703 ;; possibly other browsing mechanisms.
6705 ;; The basic strategy is to identify function assignment targets of the form
6706 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6707 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6708 ;; for imenu after parsing is finished.
6710 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6711 ;; JavaScript, and the general problem is undecidable. However, several forms
6712 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6715 ;; function foo() -- function declaration
6716 ;; foo = function() -- function expression assigned to variable
6717 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6718 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6719 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6720 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6721 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6722 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6723 ;; function foo() {function bar() {...}} -- nested function
6724 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6726 ;; This list boils down to a few forms that can be combined recursively.
6727 ;; Top-level named function declarations include both the left-hand (name)
6728 ;; and the right-hand (function value) expressions needed to produce an imenu
6729 ;; entry. The other "right-hand" forms we need to look for are:
6730 ;; - functions declared as props/getters/setters in object literals
6731 ;; - nested named function declarations
6732 ;; The "left-hand" expressions that functions can be assigned to include:
6733 ;; - local/global variables
6734 ;; - nested property-get expressions like a.b.c.d
6735 ;; - element gets like foo[10] or foo['bar'] where the index
6736 ;; expression can be trivially converted to a property name. They
6737 ;; effectively then become property gets.
6739 ;; All the different definition types are canonicalized into the form
6740 ;; foo.bar.baz = position-of-function-keyword
6742 ;; We need to build a trie-like structure for imenu. As an example,
6743 ;; consider the following JavaScript code:
6745 ;; a = function() {...} // function at position 5
6746 ;; b = function() {...} // function at position 25
6747 ;; foo = function() {...} // function at position 100
6748 ;; foo.bar = function() {...} // function at position 200
6749 ;; foo.bar.baz = function() {...} // function at position 300
6750 ;; foo.bar.zab = function() {...} // function at position 400
6752 ;; During parsing we accumulate an entry for each definition in
6753 ;; the variable `js2-imenu-recorder', like so:
6759 ;; (fn foo bar baz 300)
6760 ;; (fn foo bar zab 400))
6762 ;; Where 'fn' is the respective function node.
6763 ;; After parsing these entries are merged into this alist-trie:
6767 ;; (foo (<definition> . 3)
6768 ;; (bar (<definition> . 6)
6772 ;; Note the wacky need for a <definition> name. The token can be anything
6773 ;; that isn't a valid JavaScript identifier, because you might make foo
6774 ;; a function and then start setting properties on it that are also functions.
6776 (defsubst js2-prop-node-name (node)
6777 "Return the name of a node that may be a property-get/property-name.
6778 If NODE is not a valid name-node, string-node or integral number-node,
6779 returns nil. Otherwise returns the string name/value of the node."
6781 ((js2-name-node-p node)
6782 (js2-name-node-name node))
6783 ((js2-string-node-p node)
6784 (js2-string-node-value node))
6785 ((and (js2-number-node-p node)
6786 (string-match "^[0-9]+$" (js2-number-node-value node)))
6787 (js2-number-node-value node))
6788 ((js2-this-node-p node)
6791 (defsubst js2-node-qname-component (node)
6792 "Return the name of this node, if it contributes to a qname.
6793 Returns nil if the node doesn't contribute."
6795 (or (js2-prop-node-name node)
6796 (if (and (js2-function-node-p node)
6797 (js2-function-node-name node))
6798 (js2-name-node-name (js2-function-node-name node))))))
6800 (defsubst js2-record-imenu-entry (fn-node qname pos)
6801 "Add an entry to `js2-imenu-recorder'.
6802 FN-NODE should be the current item's function node.
6804 Associate FN-NODE with its QNAME for later lookup.
6805 This is used in postprocessing the chain list. For each chain, we find
6806 the parent function, look up its qname, then prepend a copy of it to the chain."
6807 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6808 (unless js2-imenu-function-map
6809 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6810 (puthash fn-node qname js2-imenu-function-map))
6812 (defun js2-record-imenu-functions (node &optional var)
6813 "Record function definitions for imenu.
6814 NODE is a function node or an object literal.
6815 VAR, if non-nil, is the expression that NODE is being assigned to.
6816 When passed arguments of wrong type, does nothing."
6817 (when js2-parse-ide-mode
6818 (let ((fun-p (js2-function-node-p node))
6819 qname left fname-node pos)
6821 ;; non-anonymous function declaration?
6824 (setq fname-node (js2-function-node-name node)))
6825 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6826 ;; for remaining forms, compute left-side tree branch first
6827 ((and var (setq qname (js2-compute-nested-prop-get var)))
6829 ;; foo.bar.baz = function
6831 (js2-record-imenu-entry node qname (js2-node-pos node)))
6832 ;; foo.bar.baz = object-literal
6833 ;; look for nested functions: {a: {b: function() {...} }}
6834 ((js2-object-node-p node)
6835 ;; Node position here is still absolute, since the parser
6836 ;; passes the assignment target and value expressions
6837 ;; to us before they are added as children of the assignment node.
6838 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6840 (defun js2-compute-nested-prop-get (node)
6841 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6842 component nodes as a list. Otherwise return nil. Element-gets are treated
6843 as property-gets if the index expression is a string, or a positive integer."
6844 (let (left right head)
6846 ((or (js2-name-node-p node)
6847 (js2-this-node-p node))
6849 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6850 ((js2-prop-get-node-p node) ; foo.bar
6851 (setq left (js2-prop-get-node-left node)
6852 right (js2-prop-get-node-right node))
6853 (if (setq head (js2-compute-nested-prop-get left))
6854 (nconc head (list right))))
6855 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6856 (setq left (js2-elem-get-node-target node)
6857 right (js2-elem-get-node-element node))
6858 (if (or (js2-string-node-p right) ; ['bar']
6859 (and (js2-number-node-p right) ; [10]
6860 (string-match "^[0-9]+$"
6861 (js2-number-node-value right))))
6862 (if (setq head (js2-compute-nested-prop-get left))
6863 (nconc head (list right))))))))
6865 (defun js2-record-object-literal (node qname pos)
6866 "Recursively process an object literal looking for functions.
6867 NODE is an object literal that is the right-hand child of an assignment
6868 expression. QNAME is a list of nodes representing the assignment target,
6869 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6870 POS is the absolute position of the node.
6871 We do a depth-first traversal of NODE. For any functions we find,
6872 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6873 (let (left right prop-qname)
6874 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6875 (let ((left (js2-infix-node-left e))
6876 ;; Element positions are relative to the parent position.
6877 (pos (+ pos (js2-node-pos e))))
6879 ;; foo: function() {...}
6880 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6881 (when (js2-prop-node-name left)
6882 ;; As a policy decision, we record the position of the property,
6883 ;; not the position of the `function' keyword, since the property
6884 ;; is effectively the name of the function.
6885 (js2-record-imenu-entry right (append qname (list left)) pos)))
6886 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6887 ((js2-object-node-p right)
6888 (js2-record-object-literal right
6889 (append qname (list (js2-infix-node-left e)))
6890 (+ pos (js2-node-pos right)))))))))
6892 (defsubst js2-node-top-level-decl-p (node)
6893 "Return t if NODE's name is defined in the top-level scope.
6894 Also returns t if NODE's name is not defined in any scope, since it implies
6895 that it's an external variable, which must also be in the top-level scope."
6896 (let* ((name (js2-prop-node-name node))
6897 (this-scope (js2-node-get-enclosing-scope node))
6900 ((js2-this-node-p node)
6904 ((setq defining-scope (js2-get-defining-scope this-scope name))
6905 (js2-ast-root-p defining-scope))
6908 (defsubst js2-wrapper-function-p (node)
6909 "Returns t if NODE is a function expression that's immediately invoked.
6910 NODE must be `js2-function-node'."
6911 (let ((parent (js2-node-parent node)))
6913 ;; function(){...}();
6914 (js2-call-node-p parent)
6915 (and (js2-paren-node-p parent)
6916 ;; (function(){...})();
6917 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6918 ;; (function(){...}).call(this);
6919 (and (js2-prop-get-node-p parent)
6920 (member (js2-name-node-name (js2-prop-get-node-right parent))
6922 (js2-call-node-p (js2-node-parent parent))))))))
6924 (defun js2-browse-postprocess-chains (entries)
6925 "Modify function-declaration name chains after parsing finishes.
6926 Some of the information is only available after the parse tree is complete.
6927 For instance, processing a nested scope requires a parent function node."
6928 (let (result head fn current-fn parent-qname qname p elem)
6929 (dolist (entry entries)
6930 ;; function node goes first
6931 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6932 ;; Examine head's defining scope:
6933 ;; Pre-processed chain, or top-level/external, keep as-is.
6934 (if (or (stringp head) (js2-node-top-level-decl-p head))
6936 (when (js2-this-node-p head)
6937 (setq chain (cdr chain))) ; discard this-node
6938 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6939 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6940 (when (eq parent-qname 'not-found)
6941 ;; anonymous function expressions are not recorded
6942 ;; during the parse, so we need to handle this case here
6944 (if (js2-wrapper-function-p fn)
6945 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6946 (if (js2-ast-root-p grandparent)
6948 (gethash grandparent js2-imenu-function-map 'skip)))
6950 (puthash fn parent-qname js2-imenu-function-map))
6951 (unless (eq parent-qname 'skip)
6952 ;; prefix parent fn qname to this chain.
6953 (let ((qname (append parent-qname chain)))
6954 (puthash current-fn (butlast qname) js2-imenu-function-map)
6955 (push qname result)))))))
6956 ;; finally replace each node in each chain with its name.
6957 (dolist (chain result)
6960 (if (js2-node-p (setq elem (car p)))
6961 (setcar p (js2-node-qname-component elem)))
6965 ;; Merge name chains into a trie-like tree structure of nested lists.
6966 ;; To simplify construction of the trie, we first build it out using the rule
6967 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6968 ;; [key, num-or-list]. The second element can be a number; if so, this key
6969 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6970 ;; associated with the key at this level.) Otherwise the second element is
6971 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6972 ;; a simple recursive formulation.
6974 ;; js2-mode is building the data structure for imenu. The imenu documentation
6975 ;; claims that it's the structure above, but in practice it wants the children
6976 ;; at the same list level as the key for that level, which is how I've drawn
6977 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6978 ;; list wrapper around the children at each level.
6980 ;; A completed nested imenu-alist entry looks like this:
6982 ;; ("<definition>" . 7)
6987 ;; In particular, the documentation for `imenu--index-alist' says that
6988 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6989 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6991 (defun js2-treeify (lst)
6992 "Convert (a b c d) to (a ((b ((c d)))))"
6993 (if (null (cddr lst)) ; list length <= 2
6995 (list (car lst) (list (js2-treeify (cdr lst))))))
6997 (defun js2-build-alist-trie (chains trie)
6998 "Merge declaration name chains into a trie-like alist structure for imenu.
6999 CHAINS is the qname chain list produced during parsing. TRIE is a
7000 list of elements built up so far."
7001 (let (head tail pos branch kids)
7002 (dolist (chain chains)
7003 (setq head (car chain)
7005 pos (if (numberp (car tail)) (car tail))
7006 branch (js2-find-if (lambda (n)
7007 (string= (car n) head))
7009 kids (second branch))
7011 ;; case 1: this key isn't in the trie yet
7014 (setcdr (last trie) (list (js2-treeify chain)))
7015 (setq trie (list (js2-treeify chain)))))
7016 ;; case 2: key is present with a single number entry: replace w/ list
7017 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
7018 ;; ("<definition>" 20)))
7020 (setcar (cdr branch)
7021 (list (list "<definition-1>" kids)
7023 (list "<definition-2>" pos)
7024 (js2-treeify tail)))))
7025 ;; case 3: key is there (with kids), and we're a number entry
7029 (list (format "<definition-%d>"
7030 (1+ (loop for kid in kids
7031 count (eq ?< (aref (car kid) 0)))))
7033 ;; case 4: key is there with kids, need to merge in our chain
7035 (js2-build-alist-trie (list tail) kids))))
7038 (defun js2-flatten-trie (trie)
7039 "Convert TRIE to imenu-format.
7040 Recurses through nodes, and for each one whose second element is a list,
7041 appends the list's flattened elements to the current element. Also
7042 changes the tails into conses. For instance, this pre-flattened trie
7054 Note that the root of the trie has no key, just a list of chains.
7055 This is also true for the value of any key with multiple children,
7056 e.g. key 'c' in the example above."
7059 (mapcar #'js2-flatten-trie trie))
7061 (if (numberp (second trie))
7062 (cons (car trie) (second trie))
7063 ;; else pop list and append its kids
7064 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7066 (defun js2-build-imenu-index ()
7067 "Turn `js2-imenu-recorder' into an imenu data structure."
7068 (unless (eq js2-imenu-recorder 'empty)
7069 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7070 (result (js2-build-alist-trie chains nil)))
7071 (js2-flatten-trie result))))
7073 (defun js2-test-print-chains (chains)
7074 "Print a list of qname chains.
7075 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7076 i.e. one or more nodes, and an integer position as the list tail."
7077 (mapconcat (lambda (chain)
7079 (mapconcat (lambda (elem)
7080 (if (js2-node-p elem)
7081 (or (js2-node-qname-component elem)
7083 (number-to-string elem)))
7092 (defconst js2-version "1.8.0"
7093 "Version of JavaScript supported, plus minor js2 version.")
7095 (defmacro js2-record-face (face)
7096 "Record a style run of FACE for the current token."
7097 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7099 (defsubst js2-node-end (n)
7100 "Computes the absolute end of node N.
7101 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7102 is only true until the node is added to its parent; i.e., while parsing."
7106 (defsubst js2-record-comment ()
7107 "Record a comment in `js2-scanned-comments'."
7108 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7109 :format js2-ts-comment-type)
7110 js2-scanned-comments)
7111 (when js2-parse-ide-mode
7112 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7114 'font-lock-comment-face))
7115 (when (memq js2-ts-comment-type '(html preprocessor))
7116 ;; Tell cc-engine the bounds of the comment.
7117 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7119 ;; This function is called depressingly often, so it should be fast.
7120 ;; Most of the time it's looking at the same token it peeked before.
7121 (defsubst js2-peek-token ()
7122 "Returns the next token without consuming it.
7123 If previous token was consumed, calls scanner to get new token.
7124 If previous token was -not- consumed, returns it (idempotent).
7126 This function will not return a newline (js2-EOL) - instead, it
7127 gobbles newlines until it finds a non-newline token, and flags
7128 that token as appearing just after a newline.
7130 This function will also not return a js2-COMMENT. Instead, it
7131 records comments found in `js2-scanned-comments'. If the token
7132 returned by this function immediately follows a jsdoc comment,
7133 the token is flagged as such.
7135 Note that this function always returned the un-flagged token!
7136 The flags, if any, are saved in `js2-current-flagged-token'."
7137 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7138 js2-current-token ; most common case - return already-peeked token
7139 (let ((tt (js2-get-token)) ; call scanner
7142 ;; process comments and whitespace
7143 (while (or (= tt js2-EOL)
7148 (if js2-record-comments
7149 (js2-record-comment)))
7150 (setq tt (js2-get-token))) ; call scanner
7151 (setq js2-current-token tt
7152 js2-current-flagged-token (if saw-eol
7153 (logior tt js2-ti-after-eol)
7155 ;; perform lexical fontification as soon as token is scanned
7156 (when js2-parse-ide-mode
7159 (js2-record-face 'js2-error-face))
7160 ((setq face (aref js2-kwd-tokens tt))
7161 (js2-record-face face))
7162 ((and (= tt js2-NAME)
7163 (equal js2-ts-string "undefined"))
7164 (js2-record-face 'font-lock-constant-face))))
7165 tt))) ; return unflagged token
7167 (defsubst js2-peek-flagged-token ()
7168 "Returns the current token along with any flags set for it."
7170 js2-current-flagged-token)
7172 (defsubst js2-consume-token ()
7173 (setq js2-current-flagged-token js2-EOF))
7175 (defsubst js2-next-token ()
7178 (js2-consume-token)))
7180 (defsubst js2-next-flagged-token ()
7182 (prog1 js2-current-flagged-token
7183 (js2-consume-token)))
7185 (defsubst js2-match-token (match)
7186 "Consume and return t if next token matches MATCH, a bytecode.
7187 Returns nil and consumes nothing if MATCH is not the next token."
7188 (if (/= (js2-peek-token) match)
7193 (defun js2-match-contextual-kwd (name)
7194 "Consume and return t if next token is `js2-NAME', and its
7195 string is NAME. Returns nil and does nothing otherwise."
7196 (if (or (/= (js2-peek-token) js2-NAME)
7197 (not (string= js2-ts-string name)))
7200 (js2-record-face 'font-lock-keyword-face)
7203 (defsubst js2-valid-prop-name-token (tt)
7205 (when (and js2-allow-keywords-as-property-names
7207 (aref js2-kwd-tokens tt))
7208 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
7211 (defsubst js2-match-prop-name ()
7212 "Consume token and return t if next token is a valid property name.
7213 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7214 is non-nil and it's a keyword token."
7215 (if (js2-valid-prop-name-token (js2-peek-token))
7221 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7222 (if (js2-match-prop-name)
7224 (js2-report-error msg-id nil pos len)
7227 (defsubst js2-peek-token-or-eol ()
7228 "Return js2-EOL if the current token immediately follows a newline.
7229 Else returns the current token. Used in situations where we don't
7230 consider certain token types valid if they are preceded by a newline.
7231 One example is the postfix ++ or -- operator, which has to be on the
7232 same line as its operand."
7233 (let ((tt (js2-peek-token)))
7234 ;; Check for last peeked token flags
7235 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7239 (defsubst js2-set-check-for-label ()
7240 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7241 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7243 (defsubst js2-must-match (token msg-id &optional pos len)
7244 "Match next token to token code TOKEN, or record a syntax error.
7245 MSG-ID is the error message to report if the match fails.
7246 Returns t on match, nil if no match."
7247 (if (js2-match-token token)
7249 (js2-report-error msg-id nil pos len)
7252 (defsubst js2-inside-function ()
7253 (plusp js2-nesting-of-function))
7255 (defsubst js2-set-requires-activation ()
7256 (if (js2-function-node-p js2-current-script-or-fn)
7257 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7259 (defsubst js2-check-activation-name (name token)
7260 (when (js2-inside-function)
7261 ;; skip language-version 1.2 check from Rhino
7262 (if (or (string= "arguments" name)
7263 (and js2-compiler-activation-names ; only used in codegen
7264 (gethash name js2-compiler-activation-names)))
7265 (js2-set-requires-activation))))
7267 (defsubst js2-set-is-generator ()
7268 (if (js2-function-node-p js2-current-script-or-fn)
7269 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7271 (defsubst js2-must-have-xml ()
7272 (unless js2-compiler-xml-available
7273 (js2-report-error "msg.XML.not.available")))
7275 (defsubst js2-push-scope (scope)
7276 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7277 (assert (js2-scope-p scope))
7278 (assert (null (js2-scope-parent-scope scope)))
7279 (assert (not (eq js2-current-scope scope)))
7280 (setf (js2-scope-parent-scope scope) js2-current-scope
7281 js2-current-scope scope))
7283 (defsubst js2-pop-scope ()
7284 (setq js2-current-scope
7285 (js2-scope-parent-scope js2-current-scope)))
7287 (defsubst js2-enter-loop (loop-node)
7288 (push loop-node js2-loop-set)
7289 (push loop-node js2-loop-and-switch-set)
7290 (js2-push-scope loop-node)
7291 ;; Tell the current labeled statement (if any) its statement,
7292 ;; and set the jump target of the first label to the loop.
7293 ;; These are used in `js2-parse-continue' to verify that the
7294 ;; continue target is an actual labeled loop. (And for codegen.)
7295 (when js2-labeled-stmt
7296 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7297 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7298 js2-labeled-stmt))) loop-node)))
7300 (defsubst js2-exit-loop ()
7302 (pop js2-loop-and-switch-set)
7305 (defsubst js2-enter-switch (switch-node)
7306 (push switch-node js2-loop-and-switch-set))
7308 (defsubst js2-exit-switch ()
7309 (pop js2-loop-and-switch-set))
7311 (defun js2-parse (&optional buf cb)
7312 "Tells the js2 parser to parse a region of JavaScript.
7314 BUF is a buffer or buffer name containing the code to parse.
7315 Call `narrow-to-region' first to parse only part of the buffer.
7317 The returned AST root node is given some additional properties:
7318 `node-count' - total number of nodes in the AST
7319 `buffer' - BUF. The buffer it refers to may change or be killed,
7320 so the value is not necessarily reliable.
7322 An optional callback CB can be specified to report parsing
7323 progress. If `(functionp CB)' returns t, it will be called with
7324 the current line number once before parsing begins, then again
7325 each time the lexer reaches a new line number.
7327 CB can also be a list of the form `(symbol cb ...)' to specify
7328 multiple callbacks with different criteria. Each symbol is a
7329 criterion keyword, and the following element is the callback to
7332 :line - called whenever the line number changes
7333 :token - called for each new token consumed
7335 The list of criteria could be extended to include entering or
7336 leaving a statement, an expression, or a function definition."
7337 (if (and cb (not (functionp cb)))
7338 (error "criteria callbacks not yet implemented"))
7339 (let ((inhibit-point-motion-hooks t)
7340 (js2-compiler-xml-available (>= js2-language-version 160))
7341 ;; This is a recursive-descent parser, so give it a big stack.
7342 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7343 (max-specpdl-size (max max-specpdl-size 3000))
7344 (case-fold-search nil)
7346 (message nil) ; clear any error message from previous parse
7348 (when buf (set-buffer buf))
7349 (setq js2-scanned-comments nil
7350 js2-parsed-errors nil
7351 js2-parsed-warnings nil
7352 js2-imenu-recorder nil
7353 js2-imenu-function-map nil
7356 (setq ast (js2-with-unmodifying-text-property-changes
7358 (unless js2-ts-hit-eof
7359 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7360 (setf (js2-ast-root-errors ast) js2-parsed-errors
7361 (js2-ast-root-warnings ast) js2-parsed-warnings)
7362 ;; if we didn't find any declarations, put a dummy in this list so we
7363 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7364 (unless js2-imenu-recorder
7365 (setq js2-imenu-recorder 'empty))
7366 (run-hooks 'js2-parse-finished-hook)
7369 ;; Corresponds to Rhino's Parser.parse() method.
7370 (defun js2-do-parse ()
7371 "Parse current buffer starting from current point.
7372 Scanner should be initialized."
7373 (let ((pos js2-ts-cursor)
7374 (end js2-ts-cursor) ; in case file is empty
7376 ;; initialize buffer-local parsing vars
7377 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7378 js2-current-script-or-fn root
7379 js2-current-scope root
7380 js2-current-flagged-token js2-EOF
7381 js2-nesting-of-function 0
7382 js2-labeled-stmt nil
7383 js2-recorded-identifiers nil) ; for js2-highlight
7384 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7385 (if (= tt js2-FUNCTION)
7388 (setq n (js2-parse-function (if js2-called-by-compile-function
7389 'FUNCTION_EXPRESSION
7390 'FUNCTION_STATEMENT))))
7391 ;; not a function - parse a statement
7392 (setq n (js2-parse-statement)))
7393 ;; add function or statement to script
7394 (setq end (js2-node-end n))
7395 (js2-block-node-push root n))
7396 ;; add comments to root in lexical order
7397 (when js2-scanned-comments
7398 ;; if we find a comment beyond end of normal kids, use its end
7399 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7400 (dolist (comment js2-scanned-comments)
7401 (push comment (js2-ast-root-comments root))
7402 (js2-node-add-children root comment)))
7403 (setf (js2-node-len root) (- end pos))
7404 ;; Give extensions a chance to muck with things before highlighting starts.
7405 (let ((js2-additional-externs js2-additional-externs))
7406 (dolist (callback js2-post-parse-callbacks)
7408 (js2-highlight-undeclared-vars))
7411 (defun js2-function-parser ()
7413 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7415 (defun js2-parse-function-closure-body (fn-node)
7416 "Parse a JavaScript 1.8 function closure body."
7417 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7419 (js2-report-error "msg.no.brace.body" nil
7420 (js2-node-pos fn-node)
7421 (- js2-ts-cursor (js2-node-pos fn-node)))
7422 (js2-node-add-children fn-node
7423 (setf (js2-function-node-body fn-node)
7424 (js2-parse-expr t))))))
7426 (defun js2-parse-function-body (fn-node)
7427 (js2-must-match js2-LC "msg.no.brace.body"
7428 (js2-node-pos fn-node)
7429 (- js2-ts-cursor (js2-node-pos fn-node)))
7430 (let ((pos js2-token-beg) ; LC position
7431 (pn (make-js2-block-node)) ; starts at LC position
7434 (incf js2-nesting-of-function)
7436 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7439 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7440 (js2-parse-statement)
7442 (js2-parse-function 'FUNCTION_STATEMENT))))
7443 (decf js2-nesting-of-function))
7444 (setq end js2-token-end) ; assume no curly and leave at current token
7445 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7446 (setq end js2-token-end))
7447 (setf (js2-node-pos pn) pos
7448 (js2-node-len pn) (- end pos))
7449 (setf (js2-function-node-body fn-node) pn)
7450 (js2-node-add-children fn-node pn)
7453 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7454 "Declare and fontify destructuring parameters inside NODE.
7455 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7457 ((js2-name-node-p node)
7459 (js2-define-symbol decl-type (js2-name-node-name node)
7460 node ignore-not-in-block)
7462 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7463 (+ leftpos (js2-node-len node))
7465 ((js2-object-node-p node)
7466 (dolist (elem (js2-object-node-elems node))
7467 (js2-define-destruct-symbols
7468 (if (js2-object-prop-node-p elem)
7469 (js2-object-prop-node-right elem)
7470 ;; abbreviated destructuring {a, b}
7472 decl-type face ignore-not-in-block)))
7473 ((js2-array-node-p node)
7474 (dolist (elem (js2-array-node-elems node))
7476 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7477 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7478 (js2-node-len node)))))
7480 (defun js2-parse-function-params (fn-node pos)
7481 (if (js2-match-token js2-RP)
7482 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7483 (let (params len param default-found rest-param-at)
7484 (loop for tt = (js2-peek-token)
7487 ;; destructuring param
7488 ((or (= tt js2-LB) (= tt js2-LC))
7490 (js2-report-error "msg.no.default.after.default.param"))
7491 (setq param (js2-parse-destruct-primary-expr))
7492 (js2-define-destruct-symbols param
7494 'js2-function-param-face)
7495 (push param params))
7498 (when (and (>= js2-language-version 200)
7499 (js2-match-token js2-TRIPLEDOT)
7500 (not rest-param-at))
7501 ;; to report errors if there are more parameters
7502 (setq rest-param-at (length params)))
7503 (js2-must-match js2-NAME "msg.no.parm")
7504 (js2-record-face 'js2-function-param-face)
7505 (setq param (js2-create-name-node))
7506 (js2-define-symbol js2-LP js2-ts-string param)
7507 ;; default parameter value
7508 (when (or (and default-found
7510 (js2-must-match js2-ASSIGN
7511 "msg.no.default.after.default.param"
7512 (js2-node-pos param)
7513 (js2-node-len param)))
7514 (and (>= js2-language-version 200)
7515 (js2-match-token js2-ASSIGN)))
7516 (let* ((pos (js2-node-pos param))
7517 (tt js2-current-token)
7518 (op-pos (- js2-token-beg pos))
7520 (right (js2-parse-assign-expr))
7521 (len (- (js2-node-end right) pos)))
7522 (setq param (make-js2-assign-node
7523 :type tt :pos pos :len len :op-pos op-pos
7524 :left left :right right)
7526 (js2-node-add-children param left right)))
7527 (push param params)))
7528 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7529 (js2-report-error "msg.param.after.rest" nil
7530 (js2-node-pos param) (js2-node-len param)))
7532 (js2-match-token js2-COMMA))
7533 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7534 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7536 (setf (js2-function-node-rest-p fn-node) t))
7538 (js2-node-add-children fn-node p)
7539 (push p (js2-function-node-params fn-node))))))
7541 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7542 "Possibly show inconsistent-return warning.
7543 Last token scanned is the close-curly for the function body."
7544 (when (and js2-mode-show-strict-warnings
7545 js2-strict-inconsistent-return-warning
7546 (not (js2-has-consistent-return-usage
7547 (js2-function-node-body fn-node))))
7548 ;; Have it extend from close-curly to bol or beginning of block.
7549 (let ((pos (save-excursion
7550 (goto-char js2-token-end)
7551 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7553 (end js2-token-end))
7554 (if (plusp (js2-name-node-length name))
7555 (js2-add-strict-warning "msg.no.return.value"
7556 (js2-name-node-name name) pos end)
7557 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7559 (defun js2-parse-function (function-type)
7560 "Function parser. FUNCTION-TYPE is a symbol."
7561 (let ((pos js2-token-beg) ; start of 'function' keyword
7567 (synthetic-type function-type)
7569 ;; parse function name, expression, or non-name (anonymous)
7571 ;; function foo(...)
7572 ((js2-match-token js2-NAME)
7573 (setq name (js2-create-name-node t)
7574 name-beg js2-token-beg
7575 name-end js2-token-end)
7576 (unless (js2-match-token js2-LP)
7577 (when js2-allow-member-expr-as-function-name
7578 ;; function foo.bar(...)
7579 (setq member-expr-node name
7581 member-expr-node (js2-parse-member-expr-tail
7582 nil member-expr-node)))
7583 (js2-must-match js2-LP "msg.no.paren.parms")))
7584 ((js2-match-token js2-LP)
7585 nil) ; anonymous function: leave name as null
7587 ;; function random-member-expr(...)
7588 (when js2-allow-member-expr-as-function-name
7589 ;; Note that memberExpr can not start with '(' like
7590 ;; in function (1+2).toString(), because 'function (' already
7591 ;; processed as anonymous function
7592 (setq member-expr-node (js2-parse-member-expr)))
7593 (js2-must-match js2-LP "msg.no.paren.parms")))
7594 (if (= js2-current-token js2-LP) ; eventually matched LP?
7595 (setq lp js2-token-beg))
7596 (if member-expr-node
7598 (setq synthetic-type 'FUNCTION_EXPRESSION)
7599 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7601 (js2-set-face name-beg name-end
7602 'font-lock-function-name-face 'record)))
7603 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7604 (plusp (js2-name-node-length name)))
7605 ;; Function statements define a symbol in the enclosing scope
7606 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7607 (setf fn-node (make-js2-function-node :pos pos
7610 :lp (if lp (- lp pos))))
7611 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7612 ;; 1. Nested functions are not affected by the dynamic scope flag
7613 ;; as dynamic scope is already a parent of their scope.
7614 ;; 2. Functions defined under the with statement also immune to
7615 ;; this setup, in which case dynamic scope is ignored in favor
7616 ;; of the with object.
7617 (setf (js2-function-node-ignore-dynamic fn-node) t))
7618 ;; dynamically bind all the per-function variables
7619 (let ((js2-current-script-or-fn fn-node)
7620 (js2-current-scope fn-node)
7621 (js2-nesting-of-with 0)
7625 js2-loop-and-switch-set)
7626 (js2-parse-function-params fn-node pos)
7627 (if (and (>= js2-language-version 180)
7628 (/= (js2-peek-token) js2-LC))
7629 (js2-parse-function-closure-body fn-node)
7630 (js2-parse-function-body fn-node))
7632 (js2-node-add-children fn-node name))
7633 (js2-check-inconsistent-return-warning fn-node name)
7634 ;; Function expressions define a name only in the body of the
7635 ;; function, and only if not hidden by a parameter name
7637 (eq synthetic-type 'FUNCTION_EXPRESSION)
7638 (null (js2-scope-get-symbol js2-current-scope
7639 (js2-name-node-name name))))
7640 (js2-define-symbol js2-FUNCTION
7641 (js2-name-node-name name)
7644 (not (eq function-type 'FUNCTION_EXPRESSION)))
7645 (js2-record-imenu-functions fn-node)))
7646 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7647 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7648 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7649 ;; We wait until after parsing the function to set its parent scope,
7650 ;; since `js2-define-symbol' needs the defining-scope check to stop
7651 ;; at the function boundary when checking for redeclarations.
7652 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7655 (defun js2-parse-statements (&optional parent)
7656 "Parse a statement list. Last token consumed must be js2-LC.
7658 PARENT can be a `js2-block-node', in which case the statements are
7659 appended to PARENT. Otherwise a new `js2-block-node' is created
7662 This function does not match the closing js2-RC: the caller
7663 matches the RC so it can provide a suitable error message if not
7664 matched. This means it's up to the caller to set the length of
7665 the node to include the closing RC. The node start pos is set to
7666 the absolute buffer start position, and the caller should fix it
7667 up to be relative to the parent node. All children of this block
7668 node are given relative start positions and correct lengths."
7669 (let ((pn (or parent (make-js2-block-node)))
7671 (setf (js2-node-pos pn) js2-token-beg)
7672 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7674 (js2-block-node-push pn (js2-parse-statement)))
7677 (defun js2-parse-statement ()
7678 (let (tt pn beg end)
7679 ;; coarse-grained user-interrupt check - needs work
7680 (and js2-parse-interruptable-p
7681 (zerop (% (incf js2-parse-stmt-count)
7682 js2-statements-per-pause))
7684 (throw 'interrupted t))
7685 (setq pn (js2-statement-helper))
7686 ;; no-side-effects warning check
7687 (unless (js2-node-has-side-effects pn)
7688 (setq end (js2-node-end pn))
7691 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7692 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7695 ;; These correspond to the switch cases in Parser.statementHelper
7696 (defconst js2-parsers
7697 (let ((parsers (make-vector js2-num-tokens
7698 #'js2-parse-expr-stmt)))
7699 (aset parsers js2-BREAK #'js2-parse-break)
7700 (aset parsers js2-CONST #'js2-parse-const-var)
7701 (aset parsers js2-CONTINUE #'js2-parse-continue)
7702 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7703 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7704 (aset parsers js2-DO #'js2-parse-do)
7705 (aset parsers js2-FOR #'js2-parse-for)
7706 (aset parsers js2-FUNCTION #'js2-function-parser)
7707 (aset parsers js2-IF #'js2-parse-if)
7708 (aset parsers js2-LC #'js2-parse-block)
7709 (aset parsers js2-LET #'js2-parse-let-stmt)
7710 (aset parsers js2-NAME #'js2-parse-name-or-label)
7711 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7712 (aset parsers js2-SEMI #'js2-parse-semi)
7713 (aset parsers js2-SWITCH #'js2-parse-switch)
7714 (aset parsers js2-THROW #'js2-parse-throw)
7715 (aset parsers js2-TRY #'js2-parse-try)
7716 (aset parsers js2-VAR #'js2-parse-const-var)
7717 (aset parsers js2-WHILE #'js2-parse-while)
7718 (aset parsers js2-WITH #'js2-parse-with)
7719 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7721 "A vector mapping token types to parser functions.")
7723 (defsubst js2-parse-warn-missing-semi (beg end)
7724 (and js2-mode-show-strict-warnings
7725 js2-strict-missing-semi-warning
7726 (js2-add-strict-warning
7727 "msg.missing.semi" nil
7728 ;; back up to beginning of statement or line
7729 (max beg (save-excursion
7734 (defconst js2-no-semi-insertion
7746 "List of tokens that don't do automatic semicolon insertion.")
7748 (defconst js2-autoinsert-semi-and-warn
7749 (list js2-ERROR js2-EOF js2-RC))
7751 (defun js2-statement-helper ()
7752 (let* ((tt (js2-peek-token))
7755 (parser (if (= tt js2-ERROR)
7757 (aref js2-parsers tt)))
7760 ;; If the statement is set, then it's been told its label by now.
7761 (and js2-labeled-stmt
7762 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7763 (setq js2-labeled-stmt nil))
7764 (setq pn (funcall parser))
7765 ;; Don't do auto semi insertion for certain statement types.
7766 (unless (or (memq first-tt js2-no-semi-insertion)
7767 (js2-labeled-stmt-node-p pn))
7768 (js2-auto-insert-semicolon pn))
7771 (defun js2-auto-insert-semicolon (pn)
7772 (let* ((tt-flagged (js2-peek-flagged-token))
7773 (tt (logand tt-flagged js2-clear-ti-mask))
7774 (pos (js2-node-pos pn)))
7777 ;; Consume ';' as a part of expression
7779 ;; extend the node bounds to include the semicolon.
7780 (setf (js2-node-len pn) (- js2-token-end pos)))
7781 ((memq tt js2-autoinsert-semi-and-warn)
7783 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7785 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7786 ;; Report error if no EOL or autoinsert ';' otherwise
7787 (js2-report-error "msg.no.semi.stmt")
7788 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7790 (defun js2-parse-condition ()
7791 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7792 The parens are discarded and the expression node is returned.
7793 The `pos' field of the return value is set to an absolute position
7794 that must be fixed up by the caller.
7795 Return value is a list (EXPR LP RP), with absolute paren positions."
7797 (if (js2-must-match js2-LP "msg.no.paren.cond")
7798 (setq lp js2-token-beg))
7799 (setq pn (js2-parse-expr))
7800 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7801 (setq rp js2-token-beg))
7802 ;; Report strict warning on code like "if (a = 7) ..."
7803 (if (and js2-strict-cond-assign-warning
7804 (js2-assign-node-p pn))
7805 (js2-add-strict-warning "msg.equal.as.assign" nil
7807 (+ (js2-node-pos pn)
7808 (js2-node-len pn))))
7811 (defun js2-parse-if ()
7812 "Parser for if-statement. Last matched token must be js2-IF."
7813 (let ((pos js2-token-beg)
7821 (setq cond (js2-parse-condition)
7822 if-true (js2-parse-statement)
7823 if-false (if (js2-match-token js2-ELSE)
7825 (setq else-pos (- js2-token-beg pos))
7826 (js2-parse-statement)))
7827 end (js2-node-end (or if-false if-true))
7828 pn (make-js2-if-node :pos pos
7830 :condition (car cond)
7834 :lp (js2-relpos (second cond) pos)
7835 :rp (js2-relpos (third cond) pos)))
7836 (js2-node-add-children pn (car cond) if-true if-false)
7839 (defun js2-parse-switch ()
7840 "Parser for if-statement. Last matched token must be js2-SWITCH."
7841 (let ((pos js2-token-beg)
7854 (if (js2-must-match js2-LP "msg.no.paren.switch")
7855 (setq lp js2-token-beg))
7856 (setq discriminant (js2-parse-expr)
7857 pn (make-js2-switch-node :discriminant discriminant
7859 :lp (js2-relpos lp pos)))
7860 (js2-node-add-children pn discriminant)
7861 (js2-enter-switch pn)
7864 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7865 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7866 (js2-must-match js2-LC "msg.no.brace.switch")
7869 (setq tt (js2-next-token)
7870 case-pos js2-token-beg)
7873 (setf (js2-node-len pn) (- js2-token-end pos))
7874 (throw 'break nil)) ; done
7876 (setq case-expr (js2-parse-expr))
7877 (js2-must-match js2-COLON "msg.no.colon.case"))
7880 (js2-report-error "msg.double.switch.default"))
7883 (js2-must-match js2-COLON "msg.no.colon.case"))
7885 (js2-report-error "msg.bad.switch")
7886 (throw 'break nil)))
7887 (setq case-node (make-js2-case-node :pos case-pos
7888 :len (- js2-token-end case-pos)
7890 (js2-node-add-children case-node case-expr)
7891 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7895 (setf stmt (js2-parse-statement)
7896 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7897 (js2-block-node-push case-node stmt))
7898 (push case-node cases)))
7899 ;; add cases last, as pushing reverses the order to be correct
7901 (js2-node-add-children pn kid)
7902 (push kid (js2-switch-node-cases pn)))
7904 (js2-exit-switch))))
7906 (defun js2-parse-while ()
7907 "Parser for while-statement. Last matched token must be js2-WHILE."
7908 (let ((pos js2-token-beg)
7909 (pn (make-js2-while-node))
7916 (setf cond (js2-parse-condition)
7917 (js2-while-node-condition pn) (car cond)
7918 body (js2-parse-statement)
7919 (js2-while-node-body pn) body
7920 (js2-node-len pn) (- (js2-node-end body) pos)
7921 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7922 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7923 (js2-node-add-children pn body (car cond)))
7927 (defun js2-parse-do ()
7928 "Parser for do-statement. Last matched token must be js2-DO."
7929 (let ((pos js2-token-beg)
7930 (pn (make-js2-do-node))
7938 (setq body (js2-parse-statement))
7939 (js2-must-match js2-WHILE "msg.no.while.do")
7940 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7941 cond (js2-parse-condition)
7942 (js2-do-node-condition pn) (car cond)
7943 (js2-do-node-body pn) body
7945 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7946 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7947 (js2-node-add-children pn (car cond) body))
7949 ;; Always auto-insert semicolon to follow SpiderMonkey:
7950 ;; It is required by ECMAScript but is ignored by the rest of
7951 ;; world; see bug 238945
7952 (if (js2-match-token js2-SEMI)
7953 (setq end js2-ts-cursor))
7954 (setf (js2-node-len pn) (- end pos))
7957 (defun js2-parse-for ()
7958 "Parser for for-statement. Last matched token must be js2-FOR.
7959 Parses for, for-in, and for each-in statements."
7960 (let ((for-pos js2-token-beg)
7968 init ; Node init is also foo in 'foo in object'
7969 cond ; Node cond is also object in 'foo in object'
7970 incr ; 3rd section of for-loop initializer
7976 ;; See if this is a for each () instead of just a for ()
7977 (when (js2-match-token js2-NAME)
7978 (if (string= "each" js2-ts-string)
7981 each-pos (- js2-token-beg for-pos)) ; relative
7982 (js2-record-face 'font-lock-keyword-face))
7983 (js2-report-error "msg.no.paren.for")))
7984 (if (js2-must-match js2-LP "msg.no.paren.for")
7985 (setq lp (- js2-token-beg for-pos)))
7986 (setq tt (js2-peek-token))
7987 ;; 'for' makes local scope
7988 (js2-push-scope (make-js2-scope))
7990 ;; parse init clause
7991 (let ((js2-in-for-init t)) ; set as dynamic variable
7994 (setq init (make-js2-empty-expr-node)))
7995 ((or (= tt js2-VAR) (= tt js2-LET))
7997 (setq init (js2-parse-variables tt js2-token-beg)))
7999 (setq init (js2-parse-expr)))))
8000 (if (or (js2-match-token js2-IN)
8001 (and (>= js2-language-version 200)
8002 (js2-match-contextual-kwd "of")
8003 (setq is-for-of t)))
8004 (setq is-for-in-or-of t
8005 in-pos (- js2-token-beg for-pos)
8006 ;; scope of iteration target object is not the scope we've created above.
8007 ;; stash current scope temporary.
8008 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
8009 (js2-parse-expr))) ; object over which we're iterating
8010 ;; else ordinary for loop - parse cond and incr
8011 (js2-must-match js2-SEMI "msg.no.semi.for")
8012 (setq cond (if (= (js2-peek-token) js2-SEMI)
8013 (make-js2-empty-expr-node) ; no loop condition
8015 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
8016 (setq tmp-pos js2-token-end
8017 incr (if (= (js2-peek-token) js2-RP)
8018 (make-js2-empty-expr-node :pos tmp-pos)
8020 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
8021 (setq rp (- js2-token-beg for-pos)))
8022 (if (not is-for-in-or-of)
8023 (setq pn (make-js2-for-node :init init
8028 ;; cond could be null if 'in obj' got eaten by the init node.
8029 (if (js2-infix-node-p init)
8030 ;; it was (foo in bar) instead of (var foo in bar)
8031 (setq cond (js2-infix-node-right init)
8032 init (js2-infix-node-left init))
8033 (if (and (js2-var-decl-node-p init)
8034 (> (length (js2-var-decl-node-kids init)) 1))
8035 (js2-report-error "msg.mult.index")))
8036 (setq pn (make-js2-for-in-node :iterator init
8039 :foreach-p is-for-each
8047 ;; We have to parse the body -after- creating the loop node,
8048 ;; so that the loop node appears in the js2-loop-set, allowing
8049 ;; break/continue statements to find the enclosing loop.
8050 (setf body (js2-parse-statement)
8051 (js2-loop-node-body pn) body
8052 (js2-node-pos pn) for-pos
8053 (js2-node-len pn) (- (js2-node-end body) for-pos))
8054 (js2-node-add-children pn init cond incr body))
8060 (defun js2-parse-try ()
8061 "Parser for try-statement. Last matched token must be js2-TRY."
8062 (let ((try-pos js2-token-beg)
8080 (if (/= (js2-peek-token) js2-LC)
8081 (js2-report-error "msg.no.brace.try"))
8082 (setq try-block (js2-parse-statement)
8083 try-end (js2-node-end try-block)
8084 peek (js2-peek-token))
8087 (while (js2-match-token js2-CATCH)
8088 (setq catch-pos js2-token-beg
8093 (if saw-default-catch
8094 (js2-report-error "msg.catch.unreachable"))
8095 (if (js2-must-match js2-LP "msg.no.paren.catch")
8096 (setq lp (- js2-token-beg catch-pos)))
8097 (js2-push-scope (make-js2-scope))
8098 (let ((tt (js2-peek-token)))
8100 ;; destructuring pattern
8101 ;; catch ({ message, file }) { ... }
8102 ((or (= tt js2-LB) (= tt js2-LC))
8103 (setq param (js2-parse-destruct-primary-expr))
8104 (js2-define-destruct-symbols param js2-LET nil))
8107 (js2-must-match js2-NAME "msg.bad.catchcond")
8108 (setq param (js2-create-name-node))
8109 (js2-define-symbol js2-LET js2-ts-string param))))
8111 (if (js2-match-token js2-IF)
8112 (setq guard-kwd (- js2-token-beg catch-pos)
8113 catch-cond (js2-parse-expr))
8114 (setq saw-default-catch t))
8115 (if (js2-must-match js2-RP "msg.bad.catchcond")
8116 (setq rp (- js2-token-beg catch-pos)))
8117 (js2-must-match js2-LC "msg.no.brace.catchblock")
8118 (setq block (js2-parse-statements)
8119 try-end (js2-node-end block)
8120 catch-node (make-js2-catch-node :pos catch-pos
8122 :guard-expr catch-cond
8123 :guard-kwd guard-kwd
8128 (if (js2-must-match js2-RC "msg.no.brace.after.body")
8129 (setq try-end js2-token-beg))
8130 (setf (js2-node-len block) (- try-end (js2-node-pos block))
8131 (js2-node-len catch-node) (- try-end catch-pos))
8132 (js2-node-add-children catch-node param catch-cond block)
8133 (push catch-node catch-blocks)))
8134 ((/= peek js2-FINALLY)
8135 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
8136 (js2-node-pos try-block)
8137 (- (setq try-end (js2-node-end try-block))
8138 (js2-node-pos try-block)))))
8139 (when (js2-match-token js2-FINALLY)
8140 (setq finally-pos js2-token-beg
8141 block (js2-parse-statement)
8142 try-end (js2-node-end block)
8143 finally-block (make-js2-finally-node :pos finally-pos
8144 :len (- try-end finally-pos)
8146 (js2-node-add-children finally-block block))
8147 (setq pn (make-js2-try-node :pos try-pos
8148 :len (- try-end try-pos)
8149 :try-block try-block
8150 :finally-block finally-block))
8151 (js2-node-add-children pn try-block finally-block)
8152 ;; push them onto the try-node, which reverses and corrects their order
8153 (dolist (cb catch-blocks)
8154 (js2-node-add-children pn cb)
8155 (push cb (js2-try-node-catch-clauses pn)))
8158 (defun js2-parse-throw ()
8159 "Parser for throw-statement. Last matched token must be js2-THROW."
8160 (let ((pos js2-token-beg)
8164 (if (= (js2-peek-token-or-eol) js2-EOL)
8165 ;; ECMAScript does not allow new lines before throw expression,
8167 (js2-report-error "msg.bad.throw.eol"))
8168 (setq expr (js2-parse-expr)
8169 pn (make-js2-throw-node :pos pos
8170 :len (- (js2-node-end expr) pos)
8172 (js2-node-add-children pn expr)
8175 (defsubst js2-match-jump-label-name (label-name)
8176 "If break/continue specified a label, return that label's labeled stmt.
8177 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8178 does not match an existing label, reports an error and returns nil."
8179 (let ((bundle (cdr (assoc label-name js2-label-set))))
8181 (js2-report-error "msg.undef.label"))
8184 (defun js2-parse-break ()
8185 "Parser for break-statement. Last matched token must be js2-BREAK."
8186 (let ((pos js2-token-beg)
8188 break-target ; statement to break from
8189 break-label ; in "break foo", name-node representing the foo
8190 labels ; matching labeled statement to break to
8192 (js2-consume-token) ; `break'
8193 (when (eq (js2-peek-token-or-eol) js2-NAME)
8195 (setq break-label (js2-create-name-node)
8196 end (js2-node-end break-label)
8197 ;; matchJumpLabelName only matches if there is one
8198 labels (js2-match-jump-label-name js2-ts-string)
8199 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8200 (unless (or break-target break-label)
8201 ;; no break target specified - try for innermost enclosing loop/switch
8202 (if (null js2-loop-and-switch-set)
8204 (js2-report-error "msg.bad.break" nil pos (length "break")))
8205 (setq break-target (car js2-loop-and-switch-set))))
8206 (setq pn (make-js2-break-node :pos pos
8209 :target break-target))
8210 (js2-node-add-children pn break-label) ; but not break-target
8213 (defun js2-parse-continue ()
8214 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8215 (let ((pos js2-token-beg)
8217 label ; optional user-specified label, a `js2-name-node'
8218 labels ; current matching labeled stmt, if any
8219 target ; the `js2-loop-node' target of this continue stmt
8221 (js2-consume-token) ; `continue'
8222 (when (= (js2-peek-token-or-eol) js2-NAME)
8224 (setq label (js2-create-name-node)
8225 end (js2-node-end label)
8226 ;; matchJumpLabelName only matches if there is one
8227 labels (js2-match-jump-label-name js2-ts-string)))
8229 ((null labels) ; no current label to go to
8230 (if (null js2-loop-set) ; no loop to continue to
8231 (js2-report-error "msg.continue.outside" nil pos
8232 (length "continue"))
8233 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8235 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8236 (setq target (js2-labeled-stmt-node-stmt labels))
8237 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8238 (setq pn (make-js2-continue-node :pos pos
8242 (js2-node-add-children pn label) ; but not target - it's not our child
8245 (defun js2-parse-with ()
8246 "Parser for with-statement. Last matched token must be js2-WITH."
8248 (let ((pos js2-token-beg)
8250 (if (js2-must-match js2-LP "msg.no.paren.with")
8251 (setq lp js2-token-beg))
8252 (setq obj (js2-parse-expr))
8253 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8254 (setq rp js2-token-beg))
8255 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8256 (setq body (js2-parse-statement)))
8257 (setq pn (make-js2-with-node :pos pos
8258 :len (- (js2-node-end body) pos)
8261 :lp (js2-relpos lp pos)
8262 :rp (js2-relpos rp pos)))
8263 (js2-node-add-children pn obj body)
8266 (defun js2-parse-const-var ()
8267 "Parser for var- or const-statement.
8268 Last matched token must be js2-CONST or js2-VAR."
8269 (let ((tt (js2-peek-token))
8274 (setq expr (js2-parse-variables tt js2-token-beg)
8275 pn (make-js2-expr-stmt-node :pos pos
8276 :len (- (js2-node-end expr) pos)
8278 (js2-node-add-children pn expr)
8281 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8282 (let ((pn (make-js2-expr-stmt-node :pos pos
8283 :len (js2-node-len expr)
8284 :type (if (js2-inside-function)
8289 (js2-node-add-children pn expr))
8292 (defun js2-parse-let-stmt ()
8293 "Parser for let-statement. Last matched token must be js2-LET."
8295 (let ((pos js2-token-beg)
8298 (if (= (js2-peek-token) js2-LP)
8299 ;; let expression in statement context
8300 (setq expr (js2-parse-let pos 'statement)
8301 pn (js2-wrap-with-expr-stmt pos expr t))
8302 ;; else we're looking at a statement like let x=6, y=7;
8303 (setf expr (js2-parse-variables js2-LET pos)
8304 pn (js2-wrap-with-expr-stmt pos expr t)
8305 (js2-node-type pn) js2-EXPR_RESULT))
8308 (defun js2-parse-ret-yield ()
8309 (js2-parse-return-or-yield (js2-peek-token) nil))
8311 (defconst js2-parse-return-stmt-enders
8312 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8314 (defsubst js2-now-all-set (before after mask)
8315 "Return whether or not the bits in the mask have changed to all set.
8316 BEFORE is bits before change, AFTER is bits after change, and MASK is
8317 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8319 (and (/= (logand before mask) mask)
8320 (= (logand after mask) mask)))
8322 (defun js2-parse-return-or-yield (tt expr-context)
8323 (let ((pos js2-token-beg)
8325 (before js2-end-flags)
8326 (inside-function (js2-inside-function))
8330 (unless inside-function
8331 (js2-report-error (if (eq tt js2-RETURN)
8335 ;; This is ugly, but we don't want to require a semicolon.
8336 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8337 (setq e (js2-parse-expr)
8338 end (js2-node-end e)))
8341 (js2-set-flag js2-end-flags (if (null e)
8343 js2-end-returns-value))
8344 (setq ret (make-js2-return-node :pos pos
8347 (js2-node-add-children ret e)
8348 ;; See if we need a strict mode warning.
8349 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8350 ;; more thorough and accurate than this before/after flag check.
8351 ;; E.g. if there's a finally-block that always returns, we shouldn't
8352 ;; show a warning generated by inconsistent returns in the catch blocks.
8353 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8354 ;; so we know which returns/yields to highlight, and we should get rid of
8355 ;; all the checking in `js2-parse-return-or-yield'.
8356 (if (and js2-strict-inconsistent-return-warning
8357 (js2-now-all-set before js2-end-flags
8358 (logior js2-end-returns js2-end-returns-value)))
8359 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8361 (unless (js2-inside-function)
8362 (js2-report-error "msg.bad.yield"))
8363 (js2-set-flag js2-end-flags js2-end-yields)
8364 (setq ret (make-js2-yield-node :pos pos
8367 (js2-node-add-children ret e)
8368 (unless expr-context
8370 ret (js2-wrap-with-expr-stmt pos e t))
8371 (js2-set-requires-activation)
8372 (js2-set-is-generator))))
8373 ;; see if we are mixing yields and value returns.
8374 (when (and inside-function
8375 (js2-now-all-set before js2-end-flags
8376 (logior js2-end-yields js2-end-returns-value)))
8377 (setq name (js2-function-name js2-current-script-or-fn))
8378 (if (zerop (length name))
8379 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8380 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8383 (defun js2-parse-debugger ()
8385 (make-js2-keyword-node :type js2-DEBUGGER))
8387 (defun js2-parse-block ()
8388 "Parser for a curly-delimited statement block.
8389 Last token matched must be js2-LC."
8390 (let ((pos js2-token-beg)
8391 (pn (make-js2-scope)))
8396 (js2-parse-statements pn)
8397 (js2-must-match js2-RC "msg.no.brace.block")
8398 (setf (js2-node-len pn) (- js2-token-end pos)))
8402 ;; for js2-ERROR too, to have a node for error recovery to work on
8403 (defun js2-parse-semi ()
8404 "Parse a statement or handle an error.
8405 Last matched token is js2-SEMI or js2-ERROR."
8406 (let ((tt (js2-peek-token)) pos len)
8408 (if (eq tt js2-SEMI)
8409 (make-js2-empty-expr-node :len 1)
8410 (setq pos js2-token-beg
8411 len (- js2-token-beg pos))
8412 (js2-report-error "msg.syntax" nil pos len)
8413 (make-js2-error-node :pos pos :len len))))
8415 (defun js2-parse-default-xml-namespace ()
8416 "Parse a `default xml namespace = <expr>' e4x statement."
8417 (let ((pos js2-token-beg)
8418 end len expr unary es)
8421 (js2-set-requires-activation)
8422 (setq len (- js2-ts-cursor pos))
8423 (unless (and (js2-match-token js2-NAME)
8424 (string= js2-ts-string "xml"))
8425 (js2-report-error "msg.bad.namespace" nil pos len))
8426 (unless (and (js2-match-token js2-NAME)
8427 (string= js2-ts-string "namespace"))
8428 (js2-report-error "msg.bad.namespace" nil pos len))
8429 (unless (js2-match-token js2-ASSIGN)
8430 (js2-report-error "msg.bad.namespace" nil pos len))
8431 (setq expr (js2-parse-expr)
8432 end (js2-node-end expr)
8433 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8437 (js2-node-add-children unary expr)
8438 (make-js2-expr-stmt-node :pos pos
8442 (defun js2-record-label (label bundle)
8443 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8445 (let ((name (js2-label-node-name label))
8448 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8449 ;; flag both labels if possible when used in editing mode
8450 (if (and js2-parse-ide-mode
8451 (setq dup (js2-get-label-by-name labeled-stmt name)))
8452 (js2-report-error "msg.dup.label" nil
8453 (js2-node-abs-pos dup) (js2-node-len dup)))
8454 (js2-report-error "msg.dup.label" nil
8455 (js2-node-pos label) (js2-node-len label)))
8456 (js2-labeled-stmt-node-add-label bundle label)
8457 (js2-node-add-children bundle label)
8458 ;; Add one reference to the bundle per label in `js2-label-set'
8459 (push (cons name bundle) js2-label-set)))
8461 (defun js2-parse-name-or-label ()
8462 "Parser for identifier or label. Last token matched must be js2-NAME.
8463 Called when we found a name in a statement context. If it's a label, we gather
8464 up any following labels and the next non-label statement into a
8465 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8466 expression and return it wrapped in a `js2-expr-stmt-node'."
8467 (let ((pos js2-token-beg)
8474 ;; set check for label and call down to `js2-parse-primary-expr'
8475 (js2-set-check-for-label)
8476 (setq expr (js2-parse-expr))
8477 (if (/= (js2-node-type expr) js2-LABEL)
8478 ;; Parsed non-label expression - wrap with expression stmt.
8479 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8480 ;; else parsed a label
8481 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8482 (js2-record-label expr bundle)
8483 ;; look for more labels
8484 (while (and continue (= (js2-peek-token) js2-NAME))
8485 (js2-set-check-for-label)
8486 (setq expr (js2-parse-expr))
8487 (if (/= (js2-node-type expr) js2-LABEL)
8489 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8491 (js2-auto-insert-semicolon stmt))
8492 (js2-record-label expr bundle)))
8493 ;; no more labels; now parse the labeled statement
8496 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8497 (setq stmt (js2-statement-helper))))
8498 ;; remove the labels for this statement from the global set
8499 (dolist (label (js2-labeled-stmt-node-labels bundle))
8500 (setq js2-label-set (remove label js2-label-set))))
8501 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8502 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8503 (js2-node-add-children bundle stmt)
8506 (defun js2-parse-expr-stmt ()
8507 "Default parser in statement context, if no recognized statement found."
8508 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8510 (defun js2-parse-variables (decl-type pos)
8511 "Parse a comma-separated list of variable declarations.
8512 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8514 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8515 For 'var' or 'const', the keyword should be the token last scanned.
8517 POS is the position where the node should start. It's sometimes the
8518 var/const/let keyword, and other times the beginning of the first token
8519 in the first variable declaration.
8521 Returns the parsed `js2-var-decl-node' expression node."
8522 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8534 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8535 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8536 ;; var {a, b} = baz;
8538 (setq destructuring nil
8541 kid-pos js2-token-beg
8544 (if (or (= tt js2-LB) (= tt js2-LC))
8545 ;; Destructuring assignment, e.g., var [a, b] = ...
8546 (setq destructuring (js2-parse-destruct-primary-expr)
8547 end (js2-node-end destructuring))
8548 ;; Simple variable name
8549 (when (js2-must-match js2-NAME "msg.bad.var")
8550 (setq name (js2-create-name-node)
8554 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8555 (when (js2-match-token js2-ASSIGN)
8556 (setq init (js2-parse-assign-expr)
8557 end (js2-node-end init))
8558 (js2-record-imenu-functions init name))
8560 (js2-set-face nbeg nend (if (js2-function-node-p init)
8561 'font-lock-function-name-face
8562 'font-lock-variable-name-face)
8564 (setq vi (make-js2-var-init-node :pos kid-pos
8565 :len (- end kid-pos)
8569 (if (and (null init) (not js2-in-for-init))
8570 (js2-report-error "msg.destruct.assign.no.init"))
8571 (js2-define-destruct-symbols destructuring
8573 'font-lock-variable-name-face)
8574 (setf (js2-var-init-node-target vi) destructuring))
8575 (setf (js2-var-init-node-target vi) name))
8576 (setf (js2-var-init-node-initializer vi) init)
8577 (js2-node-add-children vi name destructuring init)
8578 (js2-block-node-push result vi)
8579 (unless (js2-match-token js2-COMMA)
8580 (setq continue nil)))
8581 (setf (js2-node-len result) (- end pos))
8584 (defun js2-parse-let (pos &optional stmt-p)
8585 "Parse a let expression or statement.
8586 A let-expression is of the form `let (vars) expr'.
8587 A let-statment is of the form `let (vars) {statements}'.
8588 The third form of let is a variable declaration list, handled
8589 by `js2-parse-variables'."
8590 (let ((pn (make-js2-let-node :pos pos))
8592 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8593 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8597 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8598 (if (js2-must-match js2-RP "msg.no.paren.let")
8599 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8600 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8604 (setf beg js2-token-beg ; position stmt at LC
8605 body (js2-parse-statements))
8606 (js2-must-match js2-RC "msg.no.curly.let")
8607 (setf (js2-node-len body) (- js2-token-end beg)
8608 (js2-node-len pn) (- js2-token-end pos)
8609 (js2-let-node-body pn) body
8610 (js2-node-type pn) js2-LET))
8612 (setf body (js2-parse-expr)
8613 (js2-node-len pn) (- (js2-node-end body) pos)
8614 (js2-let-node-body pn) body))
8615 (js2-node-add-children pn vars body))
8619 (defsubst js2-define-new-symbol (decl-type name node &optional scope)
8620 (js2-scope-put-symbol (or scope js2-current-scope)
8622 (make-js2-symbol decl-type name node)))
8624 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8625 "Define a symbol in the current scope.
8626 If NODE is non-nil, it is the AST node associated with the symbol."
8627 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8628 (symbol (if defining-scope
8629 (js2-scope-get-symbol defining-scope name)))
8630 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8632 ((and symbol ; already defined
8633 (or (= sdt js2-CONST) ; old version is const
8634 (= decl-type js2-CONST) ; new version is const
8635 ;; two let-bound vars in this block have same name
8636 (and (= sdt js2-LET)
8637 (eq defining-scope js2-current-scope))))
8640 ((= sdt js2-CONST) "msg.const.redecl")
8641 ((= sdt js2-LET) "msg.let.redecl")
8642 ((= sdt js2-VAR) "msg.var.redecl")
8643 ((= sdt js2-FUNCTION) "msg.function.redecl")
8644 (t "msg.parm.redecl"))
8646 ((= decl-type js2-LET)
8647 (if (and (not ignore-not-in-block)
8648 (or (= (js2-node-type js2-current-scope) js2-IF)
8649 (js2-loop-node-p js2-current-scope)))
8650 (js2-report-error "msg.let.decl.not.in.block")
8651 (js2-define-new-symbol decl-type name node)))
8652 ((or (= decl-type js2-VAR)
8653 (= decl-type js2-CONST)
8654 (= decl-type js2-FUNCTION))
8656 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8657 (js2-add-strict-warning "msg.var.redecl" name)
8658 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8659 (js2-add-strict-warning "msg.var.hides.arg" name)))
8660 (js2-define-new-symbol decl-type name node
8661 js2-current-script-or-fn)))
8662 ((= decl-type js2-LP)
8664 ;; must be duplicate parameter. Second parameter hides the
8665 ;; first, so go ahead and add the second pararameter
8666 (js2-report-warning "msg.dup.parms" name))
8667 (js2-define-new-symbol decl-type name node))
8668 (t (js2-code-bug)))))
8670 (defun js2-parse-expr (&optional oneshot)
8671 (let* ((pn (js2-parse-assign-expr))
8672 (pos (js2-node-pos pn))
8676 (while (and (not oneshot)
8677 (js2-match-token js2-COMMA))
8678 (setq op-pos (- js2-token-beg pos)) ; relative
8679 (if (= (js2-peek-token) js2-YIELD)
8680 (js2-report-error "msg.yield.parenthesized"))
8681 (setq right (js2-parse-assign-expr)
8683 pn (make-js2-infix-node :type js2-COMMA
8685 :len (- js2-ts-cursor pos)
8689 (js2-node-add-children pn left right))
8692 (defun js2-parse-assign-expr ()
8693 (let ((tt (js2-peek-token))
8699 (if (= tt js2-YIELD)
8700 (js2-parse-return-or-yield tt t)
8701 ;; not yield - parse assignment expression
8702 (setq pn (js2-parse-cond-expr)
8703 tt (js2-peek-token))
8704 (when (and (<= js2-first-assign tt)
8705 (<= tt js2-last-assign))
8706 ;; tt express assignment (=, |=, ^=, ..., %=)
8708 (setq op-pos (- js2-token-beg pos) ; relative
8710 right (js2-parse-assign-expr)
8711 pn (make-js2-assign-node :type tt
8713 :len (- (js2-node-end right) pos)
8717 (when js2-parse-ide-mode
8718 (js2-highlight-assign-targets pn left right)
8719 (js2-record-imenu-functions right left))
8720 ;; do this last so ide checks above can use absolute positions
8721 (js2-node-add-children pn left right))
8724 (defun js2-parse-cond-expr ()
8725 (let ((pos js2-token-beg)
8726 (pn (js2-parse-or-expr))
8732 (when (js2-match-token js2-HOOK)
8733 (setq q-pos (- js2-token-beg pos)
8734 if-true (js2-parse-assign-expr))
8735 (js2-must-match js2-COLON "msg.no.colon.cond")
8736 (setq c-pos (- js2-token-beg pos)
8737 if-false (js2-parse-assign-expr)
8739 pn (make-js2-cond-node :pos pos
8740 :len (- (js2-node-end if-false) pos)
8741 :test-expr test-expr
8743 :false-expr if-false
8746 (js2-node-add-children pn test-expr if-true if-false))
8749 (defun js2-make-binary (type left parser)
8750 "Helper for constructing a binary-operator AST node.
8751 LEFT is the left-side-expression, already parsed, and the
8752 binary operator should have just been matched.
8753 PARSER is a function to call to parse the right operand,
8754 or a `js2-node' struct if it has already been parsed."
8755 (let* ((pos (js2-node-pos left))
8756 (op-pos (- js2-token-beg pos))
8757 (right (if (js2-node-p parser)
8760 (pn (make-js2-infix-node :type type
8762 :len (- (js2-node-end right) pos)
8766 (js2-node-add-children pn left right)
8769 (defun js2-parse-or-expr ()
8770 (let ((pn (js2-parse-and-expr)))
8771 (when (js2-match-token js2-OR)
8772 (setq pn (js2-make-binary js2-OR
8774 'js2-parse-or-expr)))
8777 (defun js2-parse-and-expr ()
8778 (let ((pn (js2-parse-bit-or-expr)))
8779 (when (js2-match-token js2-AND)
8780 (setq pn (js2-make-binary js2-AND
8782 'js2-parse-and-expr)))
8785 (defun js2-parse-bit-or-expr ()
8786 (let ((pn (js2-parse-bit-xor-expr)))
8787 (while (js2-match-token js2-BITOR)
8788 (setq pn (js2-make-binary js2-BITOR
8790 'js2-parse-bit-xor-expr)))
8793 (defun js2-parse-bit-xor-expr ()
8794 (let ((pn (js2-parse-bit-and-expr)))
8795 (while (js2-match-token js2-BITXOR)
8796 (setq pn (js2-make-binary js2-BITXOR
8798 'js2-parse-bit-and-expr)))
8801 (defun js2-parse-bit-and-expr ()
8802 (let ((pn (js2-parse-eq-expr)))
8803 (while (js2-match-token js2-BITAND)
8804 (setq pn (js2-make-binary js2-BITAND
8806 'js2-parse-eq-expr)))
8809 (defconst js2-parse-eq-ops
8810 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8812 (defun js2-parse-eq-expr ()
8813 (let ((pn (js2-parse-rel-expr))
8815 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8817 (setq pn (js2-make-binary tt
8819 'js2-parse-rel-expr)))
8822 (defconst js2-parse-rel-ops
8823 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8825 (defun js2-parse-rel-expr ()
8826 (let ((pn (js2-parse-shift-expr))
8830 (setq tt (js2-peek-token))
8832 ((and js2-in-for-init (= tt js2-IN))
8833 (setq continue nil))
8834 ((memq tt js2-parse-rel-ops)
8836 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8838 (setq continue nil))))
8841 (defconst js2-parse-shift-ops
8842 (list js2-LSH js2-URSH js2-RSH))
8844 (defun js2-parse-shift-expr ()
8845 (let ((pn (js2-parse-add-expr))
8849 (setq tt (js2-peek-token))
8850 (if (memq tt js2-parse-shift-ops)
8853 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8854 (setq continue nil)))
8857 (defun js2-parse-add-expr ()
8858 (let ((pn (js2-parse-mul-expr))
8862 (setq tt (js2-peek-token))
8863 (if (or (= tt js2-ADD) (= tt js2-SUB))
8866 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8867 (setq continue nil)))
8870 (defconst js2-parse-mul-ops
8871 (list js2-MUL js2-DIV js2-MOD))
8873 (defun js2-parse-mul-expr ()
8874 (let ((pn (js2-parse-unary-expr))
8878 (setq tt (js2-peek-token))
8879 (if (memq tt js2-parse-mul-ops)
8882 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8883 (setq continue nil)))
8886 (defsubst js2-make-unary (type parser &rest args)
8887 "Make a unary node of type TYPE.
8888 PARSER is either a node (for postfix operators) or a function to call
8889 to parse the operand (for prefix operators)."
8890 (let* ((pos js2-token-beg)
8891 (postfix (js2-node-p parser))
8894 (apply parser args)))
8897 (if postfix ; e.g. i++
8898 (setq pos (js2-node-pos expr)
8900 (setq end (js2-node-end expr)))
8901 (setq pn (make-js2-unary-node :type type
8905 (js2-node-add-children pn expr)
8908 (defconst js2-incrementable-node-types
8909 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8910 "Node types that can be the operand of a ++ or -- operator.")
8912 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8913 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8914 js2-incrementable-node-types)
8915 (js2-report-error (if (= tt js2-INC)
8918 nil beg (- end beg))))
8920 (defun js2-parse-unary-expr ()
8921 (let ((tt (js2-peek-token))
8924 ((or (= tt js2-VOID)
8929 (js2-make-unary tt 'js2-parse-unary-expr))
8932 ;; Convert to special POS token in decompiler and parse tree
8933 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8936 ;; Convert to special NEG token in decompiler and parse tree
8937 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8942 (setq beg js2-token-beg
8944 expr (js2-make-unary tt 'js2-parse-member-expr t))
8945 (js2-check-bad-inc-dec tt beg end expr)))
8948 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8951 (make-js2-error-node)) ; try to continue
8953 js2-compiler-xml-available)
8954 ;; XML stream encountered in expression.
8956 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8958 (setq pn (js2-parse-member-expr t)
8959 ;; Don't look across a newline boundary for a postfix incop.
8960 tt (js2-peek-token-or-eol))
8961 (when (or (= tt js2-INC) (= tt js2-DEC))
8964 pn (js2-make-unary tt expr))
8965 (js2-node-set-prop pn 'postfix t)
8966 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8969 (defun js2-parse-xml-initializer ()
8970 "Parse an E4X XML initializer.
8971 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8972 Then I'll postprocess the result, depending on whether we're in IDE
8973 mode or codegen mode, and generate the appropriate rewritten AST.
8974 IDE mode uses a rich AST that models the XML structure. Codegen mode
8975 just concatenates everything and makes a new XML or XMLList out of it."
8976 (let ((tt (js2-get-first-xml-token))
8984 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8985 (js2-report-error "msg.syntax"))
8986 (setq pn-xml (make-js2-xml-node))
8989 (setq first-token nil)
8990 (setq tt (js2-get-next-xml-token)))
8992 ;; js2-XML means we found a {expr} in the XML stream.
8993 ;; The js2-ts-string is the XML up to the left-curly.
8995 (push (make-js2-string-node :pos js2-token-beg
8996 :len (- js2-ts-cursor js2-token-beg))
8998 (js2-must-match js2-LC "msg.syntax")
8999 (setq expr-pos js2-ts-cursor
9000 expr (if (eq (js2-peek-token) js2-RC)
9001 (make-js2-empty-expr-node :pos expr-pos)
9003 (js2-must-match js2-RC "msg.syntax")
9004 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
9005 :len (js2-node-len expr)
9007 (js2-node-add-children pn expr)
9009 ;; a js2-XMLEND token means we hit the final close-tag.
9011 (push (make-js2-string-node :pos js2-token-beg
9012 :len (- js2-ts-cursor js2-token-beg))
9014 (dolist (kid (nreverse kids))
9015 (js2-block-node-push pn-xml kid))
9016 (setf (js2-node-len pn-xml) (- js2-ts-cursor
9017 (js2-node-pos pn-xml))
9020 (js2-report-error "msg.syntax")
9021 (setq continue nil))))
9025 (defun js2-parse-argument-list ()
9026 "Parse an argument list and return it as a lisp list of nodes.
9027 Returns the list in reverse order. Consumes the right-paren token."
9029 (unless (js2-match-token js2-RP)
9031 (if (= (js2-peek-token) js2-YIELD)
9032 (js2-report-error "msg.yield.parenthesized"))
9033 (push (js2-parse-assign-expr) result)
9035 (js2-match-token js2-COMMA))
9036 (js2-must-match js2-RP "msg.no.paren.arg")
9039 (defun js2-parse-member-expr (&optional allow-call-syntax)
9040 (let ((tt (js2-peek-token))
9050 (setq pn (js2-parse-primary-expr))
9051 ;; parse a 'new' expression
9053 (setq pos js2-token-beg
9055 target (js2-parse-member-expr)
9056 end (js2-node-end target)
9057 pn (make-js2-new-node :pos pos
9060 (js2-node-add-children pn target)
9061 (when (js2-match-token js2-LP)
9062 ;; Add the arguments to pn, if any are supplied.
9063 (setf beg pos ; start of "new" keyword
9065 args (nreverse (js2-parse-argument-list))
9066 (js2-new-node-args pn) args
9068 (js2-new-node-lp pn) (- pos beg)
9069 (js2-new-node-rp pn) (- end 1 beg))
9070 (apply #'js2-node-add-children pn args))
9071 (when (and js2-allow-rhino-new-expr-initializer
9072 (js2-match-token js2-LC))
9073 (setf init (js2-parse-object-literal)
9074 end (js2-node-end init)
9075 (js2-new-node-initializer pn) init)
9076 (js2-node-add-children pn init))
9077 (setf (js2-node-len pn) (- end beg))) ; end outer if
9078 (js2-parse-member-expr-tail allow-call-syntax pn)))
9080 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
9081 "Parse a chain of property/array accesses or function calls.
9082 Includes parsing for E4X operators like `..' and `.@'.
9083 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
9084 Returns an expression tree that includes PN, the parent node."
9085 (let ((beg (js2-node-pos pn))
9089 (setq tt (js2-peek-token))
9091 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
9092 (setq pn (js2-parse-property-access tt pn)))
9093 ((= tt js2-DOTQUERY)
9094 (setq pn (js2-parse-dot-query pn)))
9096 (setq pn (js2-parse-element-get pn)))
9098 (if allow-call-syntax
9099 (setq pn (js2-parse-function-call pn))
9100 (setq continue nil)))
9102 (setq continue nil))))
9103 (if (>= js2-highlight-level 2)
9104 (js2-parse-highlight-member-expr-node pn))
9107 (defun js2-parse-dot-query (pn)
9108 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
9109 Last token parsed must be `js2-DOTQUERY'."
9110 (let ((pos (js2-node-pos pn))
9116 (js2-set-requires-activation)
9117 (setq op-pos js2-token-beg
9118 expr (js2-parse-expr)
9119 end (js2-node-end expr)
9120 pn (make-js2-xml-dot-query-node :left pn
9124 (js2-node-add-children pn
9125 (js2-xml-dot-query-node-left pn)
9126 (js2-xml-dot-query-node-right pn))
9127 (if (js2-must-match js2-RP "msg.no.paren")
9128 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
9130 (setf (js2-node-len pn) (- end pos))
9133 (defun js2-parse-element-get (pn)
9134 "Parse an element-get expression, e.g. foo[bar].
9135 Last token parsed must be `js2-RB'."
9136 (let ((lb js2-token-beg)
9137 (pos (js2-node-pos pn))
9141 (setq expr (js2-parse-expr))
9142 (if (js2-must-match js2-RB "msg.no.bracket.index")
9143 (setq rb js2-token-beg))
9144 (setq pn (make-js2-elem-get-node :target pn
9147 :lb (js2-relpos lb pos)
9148 :rb (js2-relpos rb pos)
9149 :len (- js2-token-end pos)))
9150 (js2-node-add-children pn
9151 (js2-elem-get-node-target pn)
9152 (js2-elem-get-node-element pn))
9155 (defun js2-parse-function-call (pn)
9157 (pos (js2-node-pos pn)))
9159 (setq pn (make-js2-call-node :pos pos
9161 :lp (- js2-token-beg pos)))
9162 (js2-node-add-children pn (js2-call-node-target pn))
9163 ;; Add the arguments to pn, if any are supplied.
9164 (setf args (nreverse (js2-parse-argument-list))
9165 (js2-call-node-rp pn) (- js2-token-beg pos)
9166 (js2-call-node-args pn) args)
9167 (apply #'js2-node-add-children pn args)
9168 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9171 (defun js2-parse-property-access (tt pn)
9172 "Parse a property access, XML descendants access, or XML attr access."
9173 (let ((member-type-flags 0)
9174 (dot-pos js2-token-beg)
9175 (dot-len (if (= tt js2-DOTDOT) 2 1))
9177 ref ; right side of . or .. operator
9180 (when (= tt js2-DOTDOT)
9182 (setq member-type-flags js2-descendants-flag))
9183 (if (not js2-compiler-xml-available)
9185 (js2-must-match-prop-name "msg.no.name.after.dot")
9186 (setq name (js2-create-name-node t js2-GETPROP)
9187 result (make-js2-prop-get-node :left pn
9190 :len (- js2-token-end
9192 (js2-node-add-children result pn name)
9194 ;; otherwise look for XML operators
9195 (setf result (if (= tt js2-DOT)
9196 (make-js2-prop-get-node)
9197 (make-js2-infix-node :type js2-DOTDOT))
9198 (js2-node-pos result) (js2-node-pos pn)
9199 (js2-infix-node-op-pos result) dot-pos
9200 (js2-infix-node-left result) pn ; do this after setting position
9201 tt (js2-next-token))
9203 ;; needed for generator.throw()
9205 (js2-save-name-token-data js2-token-beg "throw")
9206 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9207 ;; handles: name, ns::name, ns::*, ns::[expr]
9208 ((js2-valid-prop-name-token tt)
9209 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9210 ;; handles: *, *::name, *::*, *::[expr]
9212 (js2-save-name-token-data js2-token-beg "*")
9213 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9214 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9216 (setq result (js2-parse-attribute-access)))
9218 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9220 (setf (js2-node-len result) (- (js2-node-end ref)
9221 (js2-node-pos result))
9222 (js2-infix-node-right result) ref))
9223 (if (js2-infix-node-p result)
9224 (js2-node-add-children result
9225 (js2-infix-node-left result)
9226 (js2-infix-node-right result)))
9229 (defun js2-parse-attribute-access ()
9230 "Parse an E4X XML attribute expression.
9231 This includes expressions of the forms:
9233 @attr @ns::attr @ns::*
9235 @[expr] @*::[expr] @ns::[expr]
9237 Called if we peeked an '@' token."
9238 (let ((tt (js2-next-token))
9239 (at-pos js2-token-beg))
9241 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9242 ((js2-valid-prop-name-token tt)
9243 (js2-parse-property-name at-pos js2-ts-string 0))
9244 ;; handles: @*, @*::name, @*::*, @*::[expr]
9246 (js2-save-name-token-data js2-token-beg "*")
9247 (js2-parse-property-name js2-token-beg "*" 0))
9250 (js2-parse-xml-elem-ref at-pos))
9252 (js2-report-error "msg.no.name.after.xmlAttr")
9253 ;; Avoid cascaded errors that happen if we make an error node here.
9254 (js2-save-name-token-data js2-token-beg "")
9255 (js2-parse-property-name js2-token-beg "" 0)))))
9257 (defun js2-parse-property-name (at-pos s member-type-flags)
9258 "Check if :: follows name in which case it becomes qualified name.
9260 AT-POS is a natural number if we just read an '@' token, else nil.
9261 S is the name or string that was matched: an identifier, 'throw' or '*'.
9262 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9264 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9265 operator, or the name is followed by ::. For a plain name, returns a
9266 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9267 (let ((pos (or at-pos js2-token-beg))
9269 (name (js2-create-name-node t js2-current-token))
9275 (when (js2-match-token js2-COLONCOLON)
9277 colon-pos js2-token-beg
9278 tt (js2-next-token))
9280 ;; handles name::name
9281 ((js2-valid-prop-name-token tt)
9282 (setq name (js2-create-name-node)))
9285 (js2-save-name-token-data js2-token-beg "*")
9286 (setq name (js2-create-name-node)))
9287 ;; handles name::[expr]
9289 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9291 (js2-report-error "msg.no.name.after.coloncolon"))))
9292 (if (and (null ns) (zerop member-type-flags))
9296 (make-js2-xml-prop-ref-node :pos pos
9297 :len (- (js2-node-end name) pos)
9299 :colon-pos colon-pos
9301 (js2-node-add-children pn name))))))
9303 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9304 "Parse the [expr] portion of an xml element reference.
9305 For instance, @[expr], @*::[expr], or ns::[expr]."
9306 (let* ((lb js2-token-beg)
9307 (pos (or at-pos lb))
9309 (expr (js2-parse-expr))
9310 (end (js2-node-end expr))
9312 (if (js2-must-match js2-RB "msg.no.bracket.index")
9313 (setq rb js2-token-beg
9317 (make-js2-xml-elem-ref-node :pos pos
9319 :namespace namespace
9320 :colon-pos colon-pos
9323 :lb (js2-relpos lb pos)
9324 :rb (js2-relpos rb pos)))
9325 (js2-node-add-children pn namespace expr))))
9327 (defun js2-parse-destruct-primary-expr ()
9328 (let ((js2-is-in-destructuring t))
9329 (js2-parse-primary-expr)))
9331 (defun js2-parse-primary-expr ()
9332 "Parses a literal (leaf) expression of some sort.
9333 Includes complex literals such as functions, object-literals,
9334 array-literals, array comprehensions and regular expressions."
9335 (let ((tt-flagged (js2-next-flagged-token))
9336 pn ; parent node (usually return value)
9338 px-pos ; paren-expr pos
9340 flags ; regexp flags
9342 (setq tt js2-current-token)
9344 ((= tt js2-FUNCTION)
9345 (js2-parse-function 'FUNCTION_EXPRESSION))
9347 (js2-parse-array-literal))
9349 (js2-parse-object-literal))
9351 (js2-parse-let js2-token-beg))
9353 (setq px-pos js2-token-beg
9354 expr (js2-parse-expr))
9355 (js2-must-match js2-RP "msg.no.paren")
9356 (setq pn (make-js2-paren-node :pos px-pos
9358 :len (- js2-token-end px-pos)))
9359 (js2-node-add-children pn (js2-paren-node-expr pn))
9363 (js2-parse-attribute-access))
9365 (js2-parse-name tt-flagged tt))
9367 (make-js2-number-node))
9370 (make-js2-string-node)
9371 (js2-record-face 'font-lock-string-face)))
9372 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9373 ;; Got / or /= which in this context means a regexp literal
9374 (setq px-pos js2-token-beg)
9375 (js2-read-regexp tt)
9376 (setq flags js2-ts-regexp-flags
9377 js2-ts-regexp-flags nil)
9379 (make-js2-regexp-node :pos px-pos
9380 :len (- js2-ts-cursor px-pos)
9381 :value js2-ts-string
9383 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9384 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9385 ((or (= tt js2-NULL)
9389 (make-js2-keyword-node :type tt))
9390 ((= tt js2-RESERVED)
9391 (js2-report-error "msg.reserved.id")
9392 (make-js2-name-node))
9394 ;; the scanner or one of its subroutines reported the error.
9395 (make-js2-error-node))
9397 (setq px-pos (point-at-bol)
9398 len (- js2-ts-cursor px-pos))
9399 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9400 (make-js2-error-node :pos px-pos :len len))
9402 (js2-report-error "msg.syntax")
9403 (make-js2-error-node)))))
9405 (defun js2-parse-name (tt-flagged tt)
9406 (let ((name js2-ts-string)
9407 (name-pos js2-token-beg)
9409 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9410 (= (js2-peek-token) js2-COLON))
9412 ;; Do not consume colon, it is used as unwind indicator
9413 ;; to return to statementHelper.
9414 (make-js2-label-node :pos name-pos
9415 :len (- js2-token-end name-pos)
9417 (js2-set-face name-pos
9419 'font-lock-variable-name-face 'record))
9420 ;; Otherwise not a label, just a name. Unfortunately peeking
9421 ;; the next token to check for a colon has biffed js2-token-beg
9422 ;; and js2-token-end. We store the name's bounds in buffer vars
9423 ;; and `js2-create-name-node' uses them.
9424 (js2-save-name-token-data name-pos name)
9425 (setq node (if js2-compiler-xml-available
9426 (js2-parse-property-name nil name 0)
9427 (js2-create-name-node 'check-activation)))
9428 (if js2-highlight-external-variables
9429 (js2-record-name-node node))
9432 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9433 (js2-add-strict-warning
9435 ;; back up from comma to beginning of line or array/objlit
9437 (js2-node-pos (car elems))
9440 (goto-char comma-pos)
9441 (back-to-indentation)
9445 (defun js2-parse-array-literal ()
9446 (let ((pos js2-token-beg)
9448 (after-lb-or-comma t)
9454 (unless js2-is-in-destructuring
9455 (js2-push-scope (make-js2-scope))) ; for array comp
9457 (setq tt (js2-peek-token))
9462 (setq after-comma js2-token-end)
9463 (if (not after-lb-or-comma)
9464 (setq after-lb-or-comma t)
9468 (= tt js2-EOF)) ; prevent infinite loop
9470 (js2-report-error "msg.no.bracket.arg" nil pos)
9471 (js2-consume-token))
9474 pn (make-js2-array-node :pos pos
9475 :len (- js2-ts-cursor pos)
9476 :elems (nreverse elems)))
9477 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9478 (when (and after-comma (not js2-is-in-destructuring))
9479 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9480 pos elems after-comma)))
9481 ;; destructuring binding
9482 (js2-is-in-destructuring
9483 (push (if (or (= tt js2-LC)
9486 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9487 (js2-parse-destruct-primary-expr)
9490 (js2-report-error "msg.bad.var")
9491 (make-js2-error-node))
9493 (setq after-lb-or-comma nil
9496 ((and (>= js2-language-version 170)
9497 (= tt js2-FOR) ; check for array comprehension
9498 (not after-lb-or-comma) ; "for" can't follow a comma
9499 elems ; must have at least 1 element
9500 (not (cdr elems))) ; but no 2nd element
9502 pn (js2-parse-array-comprehension (car elems) pos)))
9506 (unless after-lb-or-comma
9507 (js2-report-error "msg.no.bracket.arg"))
9508 (push (js2-parse-assign-expr) elems)
9509 (setq after-lb-or-comma nil
9511 (unless js2-is-in-destructuring
9515 (defun js2-parse-array-comprehension (expr pos)
9516 "Parse a JavaScript 1.7 Array Comprehension.
9517 EXPR is the first expression after the opening left-bracket.
9518 POS is the beginning of the LB token preceding EXPR.
9519 We should have just parsed the 'for' keyword before calling this function."
9527 (while (= (js2-peek-token) js2-FOR)
9528 (let ((prev (car loops))) ; rearrange scope chain
9529 (push (setq loop (js2-parse-array-comp-loop)) loops)
9530 (if prev ; each loop is parent scope to the next one
9531 (setf (js2-scope-parent-scope loop) prev)
9532 ; first loop takes expr scope's parent
9533 (setf (js2-scope-parent-scope (setq first loop))
9534 (js2-scope-parent-scope js2-current-scope)))))
9535 ;; set expr scope's parent to the last loop
9536 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9537 (when (= (js2-peek-token) js2-IF)
9539 (setq if-pos (- js2-token-beg pos) ; relative
9540 filter (js2-parse-condition)))
9541 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9542 (setq result (make-js2-array-comp-node :pos pos
9543 :len (- js2-ts-cursor pos)
9545 :loops (nreverse loops)
9546 :filter (car filter)
9547 :lp (js2-relpos (second filter) pos)
9548 :rp (js2-relpos (third filter) pos)
9550 (apply #'js2-node-add-children result expr (car filter)
9551 (js2-array-comp-node-loops result))
9552 (setq js2-current-scope first) ; pop to the first loop
9555 (defun js2-parse-array-comp-loop ()
9556 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9557 Last token peeked should be the initial FOR."
9558 (let ((pos js2-token-beg)
9559 (pn (make-js2-array-comp-loop-node))
9569 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9573 (when (js2-match-token js2-NAME)
9574 (if (string= js2-ts-string "each")
9577 each-pos (- js2-token-beg pos)) ; relative
9578 (js2-record-face 'font-lock-keyword-face))
9579 (js2-report-error "msg.no.paren.for")))
9580 (if (js2-must-match js2-LP "msg.no.paren.for")
9581 (setq lp (- js2-token-beg pos)))
9582 (setq tt (js2-peek-token))
9586 (setq iter (js2-parse-destruct-primary-expr))
9587 (js2-define-destruct-symbols iter js2-LET
9588 'font-lock-variable-name-face t))
9589 ((js2-match-token js2-NAME)
9590 (setq iter (js2-create-name-node)))
9592 (js2-report-error "msg.bad.var")))
9593 ;; Define as a let since we want the scope of the variable to
9594 ;; be restricted to the array comprehension
9595 (if (js2-name-node-p iter)
9596 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9597 (if (or (js2-match-token js2-IN)
9598 (and (>= js2-language-version 200)
9599 (js2-match-contextual-kwd "of")
9601 (setq in-pos (- js2-token-beg pos))
9602 (js2-report-error "msg.in.after.for.name"))
9603 (setq obj (js2-parse-expr))
9604 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9605 (setq rp (- js2-token-beg pos)))
9606 (setf (js2-node-pos pn) pos
9607 (js2-node-len pn) (- js2-ts-cursor pos)
9608 (js2-array-comp-loop-node-iterator pn) iter
9609 (js2-array-comp-loop-node-object pn) obj
9610 (js2-array-comp-loop-node-in-pos pn) in-pos
9611 (js2-array-comp-loop-node-each-pos pn) each-pos
9612 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9613 (js2-array-comp-loop-node-forof-p pn) forof-p
9614 (js2-array-comp-loop-node-lp pn) lp
9615 (js2-array-comp-loop-node-rp pn) rp)
9616 (js2-node-add-children pn iter obj))
9620 (defun js2-parse-object-literal ()
9621 (let ((pos js2-token-beg)
9628 (setq tt (js2-peek-token))
9630 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9631 ((or (js2-valid-prop-name-token tt)
9633 (setq after-comma nil
9634 result (js2-parse-named-prop tt))
9635 (if (and (null result)
9636 (not js2-recover-from-parse-errors))
9638 (push result elems)))
9639 ;; {12: x} or {10.7: x}
9642 (setq after-comma nil)
9643 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9648 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9649 pos elems after-comma)))
9651 (js2-report-error "msg.bad.prop")
9652 (unless js2-recover-from-parse-errors
9653 (setq continue nil)))) ; end switch
9654 (if (js2-match-token js2-COMMA)
9655 (setq after-comma js2-token-end)
9656 (setq continue nil))) ; end loop
9657 (js2-must-match js2-RC "msg.no.brace.prop")
9658 (setq result (make-js2-object-node :pos pos
9659 :len (- js2-ts-cursor pos)
9660 :elems (nreverse elems)))
9661 (apply #'js2-node-add-children result (js2-object-node-elems result))
9664 (defun js2-parse-named-prop (tt)
9665 "Parse a name, string, or getter/setter object property.
9666 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9668 (let ((string-prop (and (= tt js2-STRING)
9669 (make-js2-string-node)))
9671 (ppos js2-token-beg)
9672 (pend js2-token-end)
9673 (name (js2-create-name-node))
9674 (prop js2-ts-string))
9676 ;; getter/setter prop
9677 ((and (= tt js2-NAME)
9678 (= (js2-peek-token) js2-NAME)
9679 (or (string= prop "get")
9680 (string= prop "set")))
9682 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9683 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9684 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9685 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9686 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9687 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9688 ;; when patterns are used in variable declarations, function parameters,
9689 ;; catch-clause, and iterators.
9690 ;; We have to set `js2-is-in-destructuring' to t when the current
9691 ;; expressions are on the left side of any assignment, but it's difficult
9692 ;; because it requires looking ahead of expression.
9693 ((and js2-is-in-destructuring
9695 (let ((ctk (js2-peek-token)))
9696 (or (= ctk js2-COMMA)
9698 (js2-valid-prop-name-token ctk))))
9703 (setq expr (js2-parse-plain-property (or string-prop name)))
9704 (js2-set-face ppos pend
9705 (if (js2-function-node-p
9706 (js2-object-prop-node-right expr))
9707 'font-lock-function-name-face
9708 'font-lock-variable-name-face)
9711 (defun js2-parse-plain-property (prop)
9712 "Parse a non-getter/setter property in an object literal.
9713 PROP is the node representing the property: a number, name or string."
9714 (js2-must-match js2-COLON "msg.no.colon.prop")
9715 (let* ((pos (js2-node-pos prop))
9716 (colon (- js2-token-beg pos))
9717 (expr (js2-parse-assign-expr))
9718 (result (make-js2-object-prop-node
9720 ;; don't include last consumed token in length
9721 :len (- (+ (js2-node-pos expr)
9722 (js2-node-len expr))
9727 (js2-node-add-children result prop expr)
9730 (defun js2-parse-getter-setter-prop (pos prop get-p)
9731 "Parse getter or setter property in an object literal.
9732 JavaScript syntax is:
9734 { get foo() {...}, set foo(x) {...} }
9736 and expression closure style is also supported
9738 { get foo() x, set foo(x) _x = x }
9740 POS is the start position of the `get' or `set' keyword.
9741 PROP is the `js2-name-node' representing the property name.
9742 GET-P is non-nil if the keyword was `get'."
9743 (let ((type (if get-p js2-GET js2-SET))
9746 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9747 ;; it has to be an anonymous function, as we already parsed the name
9748 (if (/= (js2-node-type fn) js2-FUNCTION)
9749 (js2-report-error "msg.bad.prop")
9750 (if (plusp (length (js2-function-name fn)))
9751 (js2-report-error "msg.bad.prop")))
9752 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9753 (setq end (js2-node-end fn)
9754 result (make-js2-getter-setter-node :type type
9759 (js2-node-add-children result prop fn)
9762 (defun js2-create-name-node (&optional check-activation-p token)
9763 "Create a name node using the token info from last scanned name.
9764 In some cases we need to either synthesize a name node, or we lost
9765 the name token information by peeking. If the TOKEN parameter is
9766 not `js2-NAME', then we use the token info saved in instance vars."
9767 (let ((beg js2-token-beg)
9770 (when (/= js2-current-token js2-NAME)
9771 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9772 s js2-prev-name-token-string
9773 js2-prev-name-token-start nil
9774 js2-prev-name-token-string nil))
9775 (setq name (make-js2-name-node :pos beg
9778 (if check-activation-p
9779 (js2-check-activation-name s (or token js2-NAME)))
9782 ;;; Indentation support
9784 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9785 ;; Karl cleverly deduces that the desired indentation level is often a
9786 ;; function of paren/bracket/brace nesting depth, which can be determined
9787 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9788 ;; then does some equally clever checks to see if we're in the context of a
9789 ;; substatement of a possibly braceless statement keyword such as if, while,
9790 ;; or finally. This approach yields pretty good results.
9792 ;; The indenter is often "wrong", however, and needs to be overridden.
9793 ;; The right long-term solution is probably to emulate (or integrate
9794 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9795 ;; parse tree from `js2-parse' is present, which is not true at the
9796 ;; moment the user is typing, computing indentation is still thousands
9797 ;; of lines of code to handle every possible syntactic edge case.
9799 ;; In the meantime, the compromise solution is that we offer a "bounce
9800 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9801 ;; current line indent among various likely guess points. This approach
9802 ;; is far from perfect, but should at least make it slightly easier to
9803 ;; move the line towards its desired indentation when manually
9804 ;; overriding Karl's heuristic nesting guesser.
9806 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9807 ;; extensions such as `let' and Array comprehensions. Major kudos to
9808 ;; Karl for coming up with the initial approach, which packs a lot of
9809 ;; punch for so little code.
9811 (defconst js2-possibly-braceless-keywords-re
9812 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9813 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9814 "try" "while" "with" "let")))
9815 "Regular expression matching keywords that are optionally
9816 followed by an opening brace.")
9818 (defconst js2-indent-operator-re
9819 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9820 (regexp-opt '("in" "instanceof") 'words))
9821 "Regular expression matching operators that affect indentation
9822 of continued expressions.")
9824 (defconst js2-declaration-keyword-re
9825 (regexp-opt '("var" "let" "const") 'words)
9826 "Regular expression matching variable declaration keywords.")
9828 ;; This function has horrible results if you're typing an array
9829 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9830 ;; in conjunction with electric-indent, so just disabling it.
9831 (defsubst js2-code-at-bol-p ()
9832 "Return t if the first character on line is non-whitespace."
9835 (defun js2-insert-and-indent (key)
9836 "Run command bound to key and indent current line. Runs the command
9837 bound to KEY in the global keymap and indents the current line."
9838 (interactive (list (this-command-keys)))
9839 (let ((cmd (lookup-key (current-global-map) key)))
9841 (call-interactively cmd)))
9842 ;; don't do the electric keys inside comments or strings,
9843 ;; and don't do bounce-indent with them.
9844 (let ((parse-state (syntax-ppss (point)))
9845 (js2-bounce-indent-p (js2-code-at-bol-p)))
9846 (unless (or (nth 3 parse-state)
9847 (nth 4 parse-state))
9848 (indent-according-to-mode))))
9850 (defun js2-re-search-forward-inner (regexp &optional bound count)
9851 "Auxiliary function for `js2-re-search-forward'."
9852 (let (parse saved-point)
9854 (re-search-forward regexp bound)
9855 (setq parse (if saved-point
9856 (parse-partial-sexp saved-point (point))
9857 (syntax-ppss (point))))
9858 (cond ((nth 3 parse)
9860 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9861 (save-excursion (end-of-line) (point)) t))
9865 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9866 (re-search-forward "\\*/"))
9868 (setq count (1- count))))
9869 (setq saved-point (point))))
9872 (defun js2-re-search-forward (regexp &optional bound noerror count)
9873 "Search forward but ignore strings and comments. Invokes
9874 `re-search-forward' but treats the buffer as if strings and
9875 comments have been removed."
9876 (let ((saved-point (point))
9879 '(js2-re-search-forward-inner regexp bound 1))
9881 '(js2-re-search-backward-inner regexp bound (- count)))
9883 '(js2-re-search-forward-inner regexp bound count)))))
9887 (goto-char saved-point)
9889 (error (error-message-string err)))))))
9891 (defun js2-re-search-backward-inner (regexp &optional bound count)
9892 "Auxiliary function for `js2-re-search-backward'."
9893 (let (parse saved-point)
9895 (re-search-backward regexp bound)
9896 (setq parse (if saved-point
9897 (parse-partial-sexp saved-point (point))
9898 (syntax-ppss (point))))
9899 (cond ((nth 3 parse)
9901 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9902 (save-excursion (beginning-of-line) (point)) t))
9904 (goto-char (nth 8 parse)))
9906 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9907 (re-search-backward "/\\*"))
9909 (setq count (1- count))))))
9912 (defun js2-re-search-backward (regexp &optional bound noerror count)
9913 "Search backward but ignore strings and comments. Invokes
9914 `re-search-backward' but treats the buffer as if strings and
9915 comments have been removed."
9916 (let ((saved-point (point))
9919 '(js2-re-search-backward-inner regexp bound 1))
9921 '(js2-re-search-forward-inner regexp bound (- count)))
9923 '(js2-re-search-backward-inner regexp bound count)))))
9927 (goto-char saved-point)
9929 (error (error-message-string err)))))))
9931 (defun js2-looking-at-operator-p ()
9932 "Return non-nil if text after point is an operator (that is not
9935 (and (looking-at js2-indent-operator-re)
9936 (or (not (looking-at ":"))
9938 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9939 (looking-at "?")))))))
9941 (defun js2-continued-expression-p ()
9942 "Returns non-nil if the current line continues an expression."
9944 (back-to-indentation)
9945 (or (js2-looking-at-operator-p)
9947 (and (js2-re-search-backward "\n" nil t)
9949 (skip-chars-backward " \t")
9952 (and (js2-looking-at-operator-p)
9955 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))))))
9957 (defun js2-end-of-do-while-loop-p ()
9958 "Returns non-nil if word after point is `while' of a do-while
9959 statement, else returns nil. A braceless do-while statement
9960 spanning several lines requires that the start of the loop is
9961 indented to the same column as the current line."
9965 (when (looking-at "\\s-*\\<while\\>")
9967 (skip-chars-backward "[ \t\n]*}")
9968 (looking-at "[ \t\n]*}"))
9970 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9971 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9972 (or (looking-at "\\<do\\>")
9973 (let ((saved-indent (current-indentation)))
9974 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9975 (/= (current-indentation) saved-indent)))
9976 (and (looking-at "[ \t]*\\<do\\>")
9977 (not (js2-re-search-forward
9978 "\\<while\\>" (point-at-eol) t))
9979 (= (current-indentation) saved-indent)))))))))
9981 (defun js2-multiline-decl-indentation ()
9982 "Returns the declaration indentation column if the current line belongs
9983 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9984 (let (forward-sexp-function ; use Lisp version
9987 (back-to-indentation)
9988 (when (not (looking-at js2-declaration-keyword-re))
9989 (when (looking-at js2-indent-operator-re)
9990 (goto-char (match-end 0))) ; continued expressions are ok
9991 (while (and (not at-opening-bracket)
9993 (let ((pos (point)))
9996 (or (eq (char-before) ?,)
9997 (and (not (eq (char-before) ?\;))
9999 (prog2 (skip-chars-backward "[[:punct:]]")
10000 (looking-at js2-indent-operator-re)
10001 (js2-backward-sws))
10002 (not (eq (char-before) ?\;))))
10003 (js2-same-line pos)))))
10004 (condition-case err
10006 (scan-error (setq at-opening-bracket t))))
10007 (when (looking-at js2-declaration-keyword-re)
10008 (- (1+ (match-end 0)) (point-at-bol)))))))
10010 (defun js2-ctrl-statement-indentation ()
10011 "Returns the proper indentation of the current line if it
10012 starts the body of a control statement without braces, else
10014 (let (forward-sexp-function) ; temporarily unbind it
10016 (back-to-indentation)
10017 (when (and (not (js2-same-line (point-min)))
10018 (not (looking-at "{"))
10019 (js2-re-search-backward "[[:graph:]]" nil t)
10020 (not (looking-at "[{([]"))
10023 (when (= (char-before) ?\))
10024 ;; scan-sexps sometimes throws an error
10025 (ignore-errors (backward-sexp))
10026 (skip-chars-backward " \t" (point-at-bol)))
10027 (let ((pt (point)))
10028 (back-to-indentation)
10029 (and (looking-at js2-possibly-braceless-keywords-re)
10030 (= (match-end 0) pt)
10031 (not (js2-end-of-do-while-loop-p))))))
10032 (+ (current-indentation) js2-basic-offset)))))
10034 (defun js2-indent-in-array-comp (parse-status)
10035 "Return non-nil if we think we're in an array comprehension.
10036 In particular, return the buffer position of the first `for' kwd."
10037 (let ((bracket (nth 1 parse-status))
10041 (goto-char bracket)
10042 (when (looking-at "\\[")
10045 (if (looking-at "[[{]")
10046 (let (forward-sexp-function) ; use lisp version
10047 (forward-sexp) ; skip destructuring form
10049 (if (and (/= (char-after) ?,) ; regular array
10050 (looking-at "for"))
10051 (match-beginning 0)))
10052 ;; to skip arbitrary expressions we need the parser,
10053 ;; so we'll just guess at it.
10054 (if (and (> end (point)) ; not empty literal
10055 (re-search-forward "[^,]]* \\(for\\) " end t)
10056 ;; not inside comment or string literal
10057 (let ((state (parse-partial-sexp bracket (point))))
10058 (not (or (nth 3 state) (nth 4 state)))))
10059 (match-beginning 1))))))))
10061 (defun js2-array-comp-indentation (parse-status for-kwd)
10062 (if (js2-same-line for-kwd)
10063 ;; first continuation line
10065 (goto-char (nth 1 parse-status))
10067 (skip-chars-forward " \t")
10070 (goto-char for-kwd)
10071 (current-column))))
10073 (defun js2-proper-indentation (parse-status)
10074 "Return the proper indentation for the current line."
10076 (back-to-indentation)
10077 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
10078 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
10079 (continued-expr-p (js2-continued-expression-p))
10080 (declaration-indent (and js2-pretty-multiline-declarations
10081 (js2-multiline-decl-indentation)))
10082 (bracket (nth 1 parse-status))
10085 ;; indent array comprehension continuation lines specially
10087 (>= js2-language-version 170)
10088 (not (js2-same-line bracket))
10089 (setq beg (js2-indent-in-array-comp parse-status))
10090 (>= (point) (save-excursion
10092 (point-at-bol)))) ; at or after first loop?
10093 (js2-array-comp-indentation parse-status beg))
10097 ((and declaration-indent continued-expr-p)
10098 (+ declaration-indent js2-basic-offset))
10100 (declaration-indent)
10103 (goto-char bracket)
10105 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
10106 (when (save-excursion (skip-chars-backward " \t)")
10109 (back-to-indentation)
10110 (and (eq js2-pretty-multiline-declarations 'all)
10111 (looking-at js2-declaration-keyword-re)
10112 (goto-char (1+ (match-end 0))))
10113 (cond (same-indent-p
10116 (+ (current-column) (* 2 js2-basic-offset)))
10118 (+ (current-column) js2-basic-offset))))
10120 (unless same-indent-p
10122 (skip-chars-forward " \t"))
10123 (current-column))))
10125 (continued-expr-p js2-basic-offset)
10129 (defun js2-lineup-comment (parse-status)
10130 "Indent a multi-line block comment continuation line."
10131 (let* ((beg (nth 8 parse-status))
10132 (first-line (js2-same-line beg))
10133 (offset (save-excursion
10135 (if (looking-at "/\\*")
10136 (+ 1 (current-column))
10139 (indent-line-to offset))))
10141 (defun js2-backward-sws ()
10142 "Move backward through whitespace and comments."
10144 (while (forward-comment -1)))
10146 (defun js2-forward-sws ()
10147 "Move forward through whitespace and comments."
10149 (while (forward-comment 1)))
10151 (defsubst js2-current-indent (&optional pos)
10152 "Return column of indentation on current line.
10153 If POS is non-nil, go to that point and return indentation for that line."
10157 (back-to-indentation)
10160 (defsubst js2-arglist-close ()
10161 "Return non-nil if we're on a line beginning with a close-paren/brace."
10164 (goto-char (point-at-bol))
10166 (looking-at "[])}]"))))
10168 (defsubst js2-indent-looks-like-label-p ()
10169 (goto-char (point-at-bol))
10171 (looking-at (concat js2-mode-identifier-re ":")))
10173 (defun js2-indent-in-objlit-p (parse-status)
10174 "Return non-nil if this looks like an object-literal entry."
10175 (let ((start (nth 1 parse-status)))
10179 (and (zerop (forward-line -1))
10180 (not (< (point) start)) ; crossed a {} boundary
10181 (js2-indent-looks-like-label-p)))
10183 (js2-indent-looks-like-label-p)))))
10185 ;; if prev line looks like foobar({ then we're passing an object
10186 ;; literal to a function call, and people pretty much always want to
10187 ;; de-dent back to the previous line, so move the 'basic-offset'
10188 ;; position to the front.
10189 (defsubst js2-indent-objlit-arg-p (parse-status)
10191 (back-to-indentation)
10193 (and (eq (1- (point)) (nth 1 parse-status))
10194 (eq (char-before) ?{)
10197 (skip-chars-backward " \t")
10198 (eq (char-before) ?\()))))
10200 (defsubst js2-indent-case-block-p ()
10202 (back-to-indentation)
10204 (goto-char (point-at-bol))
10205 (skip-chars-forward " \t")
10207 (looking-at "case\\s-.+:"))))
10209 (defsubst js2-syntax-bol ()
10210 "Return the point at the first non-whitespace char on the line.
10211 Returns `point-at-bol' if the line is empty."
10213 (beginning-of-line)
10214 (skip-chars-forward " \t")
10217 (defun js2-bounce-indent (normal-col parse-status backwards)
10218 "Cycle among alternate computed indentation positions.
10219 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
10220 of the buffer to the current point. NORMAL-COL is the indentation
10221 column computed by the heuristic guesser based on current paren,
10222 bracket, brace and statement nesting. If BACKWARDS, cycle positions
10224 (let ((cur-indent (js2-current-indent))
10225 (old-buffer-undo-list buffer-undo-list)
10226 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
10227 (current-line (save-excursion
10228 (forward-line 0) ; move to bol
10229 (1+ (count-lines (point-min) (point)))))
10239 ;; temporarily don't record undo info, if user requested this
10240 (if js2-mode-indent-inhibit-undo
10241 (setq buffer-undo-list t))
10244 ;; first likely point: indent from beginning of previous code line
10245 (push (setq basic-offset
10247 (back-to-indentation)
10249 (back-to-indentation)
10250 (setq prev-line-col (current-column)))
10254 ;; (first + epsilon) likely point: indent 2x from beginning of
10255 ;; previous code line. Some companies like this approach. Ahem.
10256 ;; Seriously, though -- 4-space indent for expression continuation
10257 ;; lines isn't a bad idea. We should eventually implement it
10259 (push (setq basic-offset
10261 (back-to-indentation)
10263 (back-to-indentation)
10264 (setq prev-line-col (current-column)))
10265 (* 2 js2-basic-offset)))
10268 ;; second likely point: indent from assign-expr RHS. This
10269 ;; is just a crude guess based on finding " = " on the previous
10270 ;; line containing actual code.
10271 (setq pos (save-excursion
10274 (goto-char (point-at-bol))
10275 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10277 (goto-char (match-end 1))
10278 (skip-chars-forward " \t\r\n")
10279 (current-column)))))
10281 (incf pos js2-basic-offset)
10282 (push pos positions))
10284 ;; third likely point: same indent as previous line of code.
10285 ;; Make it the first likely point if we're not on an
10286 ;; arglist-close line and previous line ends in a comma, or
10287 ;; both this line and prev line look like object-literal
10289 (setq pos (save-excursion
10290 (goto-char (point-at-bol))
10292 (back-to-indentation)
10295 ;; while we're here, look for trailing comma
10296 (if (save-excursion
10297 (goto-char (point-at-eol))
10299 (eq (char-before) ?,))
10300 (setq arglist-cont (1- (point)))))))
10302 (if (and (or arglist-cont
10303 (js2-indent-in-objlit-p parse-status))
10304 (not (js2-arglist-close)))
10305 (setq same-indent pos))
10306 (push pos positions))
10308 ;; fourth likely point: first preceding code with less indentation
10309 ;; than the immediately preceding code line.
10310 (setq pos (save-excursion
10311 (back-to-indentation)
10313 (back-to-indentation)
10314 (setq anchor (current-column))
10315 (while (and (zerop (forward-line -1))
10317 (back-to-indentation)
10320 (setq pos (current-column))))
10321 (push pos positions)
10323 ;; nesting-heuristic position, main by default
10324 (push (setq main-pos normal-col) positions)
10326 ;; delete duplicates and sort positions list
10327 (setq positions (sort (delete-dups positions) '<))
10329 ;; comma-list continuation lines: prev line indent takes precedence
10331 (setq main-pos same-indent))
10333 ;; common special cases where we want to indent in from previous line
10334 (if (or (js2-indent-case-block-p)
10335 (js2-indent-objlit-arg-p parse-status))
10336 (setq main-pos basic-offset))
10338 ;; if bouncing backwards, reverse positions list
10340 (setq positions (reverse positions)))
10342 ;; record whether we're already sitting on one of the alternatives
10343 (setq pos (member cur-indent positions))
10346 ;; case 0: we're one one of the alternatives and this is the
10347 ;; first time they've pressed TAB on this line (best-guess).
10348 ((and js2-mode-indent-ignore-first-tab
10350 ;; first time pressing TAB on this line?
10351 (not (eq js2-mode-last-indented-line current-line)))
10353 (setq computed-pos nil))
10354 ;; case 1: only one computed position => use it
10355 ((null (cdr positions))
10356 (setq computed-pos 0))
10357 ;; case 2: not on any of the computed spots => use main spot
10359 (setq computed-pos (js2-position main-pos positions)))
10360 ;; case 3: on last position: cycle to first position
10362 (setq computed-pos 0))
10363 ;; case 4: on intermediate position: cycle to next position
10365 (setq computed-pos (js2-position (second pos) positions))))
10367 ;; see if any hooks want to indent; otherwise we do it
10368 (loop with result = nil
10369 for hook in js2-indent-hook
10370 while (null result)
10372 (setq result (funcall hook positions computed-pos))
10374 (unless (or result (null computed-pos))
10375 (indent-line-to (nth computed-pos positions)))))
10378 (if js2-mode-indent-inhibit-undo
10379 (setq buffer-undo-list old-buffer-undo-list))
10380 ;; see commentary for `js2-mode-last-indented-line'
10381 (setq js2-mode-last-indented-line current-line))))
10383 (defun js2-indent-bounce-backwards ()
10384 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10385 cycles between the computed indentation positions in reverse order."
10387 (js2-indent-line t))
10389 (defsubst js2-1-line-comment-continuation-p ()
10390 "Return t if we're in a 1-line comment continuation.
10391 If so, we don't ever want to use bounce-indent."
10396 (looking-at "\\s-*//"))
10400 (when (looking-at "\\s-*$")
10403 (looking-at "\\s-*//"))))))
10405 (defun js2-indent-line (&optional bounce-backwards)
10406 "Indent the current line as JavaScript source text."
10412 ;; don't whine about errors/warnings when we're indenting.
10413 ;; This has to be set before calling parse-partial-sexp below.
10414 (inhibit-point-motion-hooks t))
10415 (setq parse-status (save-excursion
10416 (syntax-ppss (point-at-bol)))
10417 offset (- (point) (save-excursion
10418 (back-to-indentation)
10420 (js2-with-underscore-as-word-syntax
10421 (if (nth 4 parse-status)
10422 (js2-lineup-comment parse-status)
10423 (setq indent-col (js2-proper-indentation parse-status))
10424 ;; see comments below about js2-mode-last-indented-line
10426 ;; bounce-indenting is disabled during electric-key indent.
10427 ;; It doesn't work well on first line of buffer.
10428 ((and js2-bounce-indent-p
10429 (not (js2-same-line (point-min)))
10430 (not (js2-1-line-comment-continuation-p)))
10431 (js2-bounce-indent indent-col parse-status bounce-backwards))
10432 ;; just indent to the guesser's likely spot
10433 (t (indent-line-to indent-col)))
10434 (when (plusp offset)
10435 (forward-char offset))))))
10437 (defun js2-indent-region (start end)
10438 "Indent the region, but don't use bounce indenting."
10439 (let ((js2-bounce-indent-p nil)
10440 (indent-region-function nil)
10441 (after-change-functions (remq 'js2-mode-edit
10442 after-change-functions)))
10443 (indent-region start end nil) ; nil for byte-compiler
10444 (js2-mode-edit start end (- end start))))
10446 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10450 "Major mode for editing JavaScript code."
10452 (kill-all-local-variables)
10453 (set-syntax-table js2-mode-syntax-table)
10454 (use-local-map js2-mode-map)
10455 (make-local-variable 'comment-start)
10456 (make-local-variable 'comment-end)
10457 (make-local-variable 'comment-start-skip)
10458 (setq major-mode 'js2-mode
10459 mode-name "JavaScript-IDE"
10460 comment-start "//" ; used by comment-region; don't change it
10462 (setq local-abbrev-table js2-mode-abbrev-table)
10463 (set (make-local-variable 'max-lisp-eval-depth)
10464 (max max-lisp-eval-depth 3000))
10465 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10466 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10468 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10469 ;; on most platforms other than the one I originally wrote it on.
10470 ;; So it's back to `c-fill-paragraph'.
10471 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10473 (add-hook 'before-save-hook #'js2-before-save nil t)
10474 (set (make-local-variable 'next-error-function) #'js2-next-error)
10475 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10476 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10477 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10478 ;; for characters inside regexp literals.
10479 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10480 ;; this is necessary to make `show-paren-function' work properly
10481 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10482 ;; needed for M-x rgrep, among other things
10483 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10485 ;; some variables needed by cc-engine for paragraph-fill, etc.
10486 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10487 c-comment-start-regexp "/[*/]\\|\\s|"
10488 c-line-comment-starter "//"
10489 c-paragraph-start js2-paragraph-start
10490 c-paragraph-separate "$"
10491 comment-start-skip js2-comment-start-skip
10492 c-syntactic-ws-start js2-syntactic-ws-start
10493 c-syntactic-ws-end js2-syntactic-ws-end
10494 c-syntactic-eol js2-syntactic-eol)
10496 (let ((c-buffer-is-cc-mode t))
10497 ;; Copied from `js-mode'. Also see Bug#6071.
10498 (make-local-variable 'paragraph-start)
10499 (make-local-variable 'paragraph-separate)
10500 (make-local-variable 'paragraph-ignore-fill-prefix)
10501 (make-local-variable 'adaptive-fill-mode)
10502 (make-local-variable 'adaptive-fill-regexp)
10503 (c-setup-paragraph-variables))
10505 (setq js2-default-externs
10506 (append js2-ecma-262-externs
10507 (if js2-include-browser-externs
10508 js2-browser-externs)
10509 (if js2-include-gears-externs
10511 (if js2-include-rhino-externs
10512 js2-rhino-externs)))
10514 ;; We do our own syntax highlighting based on the parse tree.
10515 ;; However, we want minor modes that add keywords to highlight properly
10516 ;; (examples: doxymacs, column-marker).
10517 ;; To customize highlighted keywords, use `font-lock-add-keywords'.
10518 (setq font-lock-defaults '(nil t))
10520 ;; Experiment: make reparse-delay longer for longer files.
10521 (if (plusp js2-dynamic-idle-timer-adjust)
10522 (setq js2-idle-timer-delay
10523 (* js2-idle-timer-delay
10524 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10526 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10527 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10528 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10529 (imenu-add-to-menubar (concat "IM-" mode-name))
10530 (when js2-mirror-mode
10531 (js2-enter-mirror-mode))
10532 (add-to-invisibility-spec '(js2-outline . t))
10533 (set (make-local-variable 'line-move-ignore-invisible) t)
10534 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10536 (if (fboundp 'run-mode-hooks)
10537 (run-mode-hooks 'js2-mode-hook)
10538 (run-hooks 'js2-mode-hook))
10540 (setq js2-mode-functions-hidden nil
10541 js2-mode-comments-hidden nil
10542 js2-mode-buffer-dirty-p t
10543 js2-mode-parsing nil)
10546 (defun js2-mode-exit ()
10547 "Exit `js2-mode' and clean up."
10549 (when js2-mode-node-overlay
10550 (delete-overlay js2-mode-node-overlay)
10551 (setq js2-mode-node-overlay nil))
10552 (js2-remove-overlays)
10553 (setq js2-mode-ast nil)
10554 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10555 (remove-from-invisibility-spec '(js2-outline . t))
10556 (js2-mode-show-all)
10557 (js2-with-unmodifying-text-property-changes
10558 (js2-clear-face (point-min) (point-max))))
10560 (defun js2-before-save ()
10561 "Clean up whitespace before saving file.
10562 You can disable this by customizing `js2-cleanup-whitespace'."
10563 (when js2-cleanup-whitespace
10564 (let ((col (current-column)))
10565 (delete-trailing-whitespace)
10566 ;; don't change trailing whitespace on current line
10567 (unless (eq (current-column) col)
10568 (indent-to col)))))
10570 (defsubst js2-mode-reset-timer ()
10571 "Cancel any existing parse timer and schedule a new one."
10572 (if js2-mode-parse-timer
10573 (cancel-timer js2-mode-parse-timer))
10574 (setq js2-mode-parsing nil)
10575 (setq js2-mode-parse-timer
10576 (run-with-idle-timer js2-idle-timer-delay nil
10577 #'js2-mode-idle-reparse (current-buffer))))
10579 (defun js2-mode-idle-reparse (buffer)
10580 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10581 it to be reparsed when the buffer is selected."
10582 (if (eq buffer (current-buffer))
10584 ;; reparse when the buffer is selected again
10585 (with-current-buffer buffer
10586 (add-hook 'window-configuration-change-hook
10587 #'js2-mode-idle-reparse-inner
10590 (defun js2-mode-idle-reparse-inner ()
10591 (remove-hook 'window-configuration-change-hook
10592 #'js2-mode-idle-reparse-inner
10596 (defun js2-mode-edit (beg end len)
10597 "Schedule a new parse after buffer is edited.
10598 Buffer edit spans from BEG to END and is of length LEN.
10599 Also clears the `js2-magic' bit on autoinserted parens/brackets
10600 if the edit occurred on a line different from the magic paren."
10601 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10602 (line (if magic-pos (line-number-at-pos magic-pos))))
10604 (or (/= (line-number-at-pos beg) line)
10606 (/= (line-number-at-pos end) line)))
10607 (js2-mode-mundanify-parens)))
10608 (setq js2-mode-buffer-dirty-p t)
10609 (js2-mode-hide-overlay)
10610 (js2-mode-reset-timer))
10612 (defun js2-reparse (&optional force)
10613 "Re-parse current buffer after user finishes some data entry.
10614 If we get any user input while parsing, including cursor motion,
10615 we discard the parse and reschedule it. If FORCE is nil, then the
10616 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10619 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10620 (unless js2-mode-parsing
10621 (setq js2-mode-parsing t)
10623 (when (or js2-mode-buffer-dirty-p force)
10624 (js2-remove-overlays)
10625 (js2-with-unmodifying-text-property-changes
10626 (setq js2-mode-buffer-dirty-p nil
10627 js2-mode-fontifications nil
10628 js2-mode-deferred-properties nil)
10629 (if js2-mode-verbose-parse-p
10630 (message "parsing..."))
10633 (setq interrupted-p
10634 (catch 'interrupted
10635 (setq js2-mode-ast (js2-parse))
10636 ;; if parsing is interrupted, comments and regex
10637 ;; literals stay ignored by `parse-partial-sexp'
10638 (remove-text-properties (point-min) (point-max)
10640 (js2-mode-apply-deferred-properties)
10641 (js2-mode-remove-suppressed-warnings)
10642 (js2-mode-show-warnings)
10643 (js2-mode-show-errors)
10644 (js2-mode-highlight-magic-parens)
10645 (if (>= js2-highlight-level 1)
10646 (js2-highlight-jsdoc js2-mode-ast))
10650 ;; unfinished parse => try again
10651 (setq js2-mode-buffer-dirty-p t)
10652 (js2-mode-reset-timer))
10653 (if js2-mode-verbose-parse-p
10654 (message "Parse time: %s" time)))))
10655 (setq js2-mode-parsing nil)
10656 (unless interrupted-p
10657 (setq js2-mode-parse-timer nil))))))
10659 (defun js2-mode-show-node ()
10660 "Debugging aid: highlight selected AST node on mouse click."
10662 (let ((node (js2-node-at-point))
10665 (when js2-mode-show-overlay
10667 (message "No node found at location %s" (point))
10668 (setq beg (js2-node-abs-pos node)
10669 end (+ beg (js2-node-len node)))
10670 (if js2-mode-node-overlay
10671 (move-overlay js2-mode-node-overlay beg end)
10672 (setq js2-mode-node-overlay (make-overlay beg end))
10673 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10674 (js2-with-unmodifying-text-property-changes
10675 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10676 (message "%s, parent: %s"
10677 (js2-node-short-name node)
10678 (if (js2-node-parent node)
10679 (js2-node-short-name (js2-node-parent node))
10682 (defun js2-mode-hide-overlay (&optional p1 p2)
10683 "Remove the debugging overlay when the point moves.
10684 P1 and P2 are the old and new values of point, respectively."
10685 (when js2-mode-node-overlay
10686 (let ((beg (overlay-start js2-mode-node-overlay))
10687 (end (overlay-end js2-mode-node-overlay)))
10688 ;; Sometimes we're called spuriously.
10692 (js2-with-unmodifying-text-property-changes
10693 (remove-text-properties beg end '(point-left nil)))
10694 (delete-overlay js2-mode-node-overlay)
10695 (setq js2-mode-node-overlay nil)))))
10697 (defun js2-mode-reset ()
10698 "Debugging helper: reset everything."
10703 (defsubst js2-mode-show-warn-or-err (e face)
10704 "Highlight a warning or error E with FACE.
10705 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10706 (let* ((key (first e))
10708 (end (+ beg (third e)))
10709 ;; Don't inadvertently go out of bounds.
10710 (beg (max (point-min) (min beg (point-max))))
10711 (end (max (point-min) (min end (point-max))))
10712 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10713 (ovl (make-overlay beg end)))
10714 (overlay-put ovl 'font-lock-face face)
10715 (overlay-put ovl 'js2-error t)
10716 (put-text-property beg end 'help-echo (js2-get-msg key))
10717 (put-text-property beg end 'point-entered #'js2-echo-error)))
10719 (defun js2-remove-overlays ()
10720 "Remove overlays from buffer that have a `js2-error' property."
10721 (let ((beg (point-min))
10724 (dolist (o (overlays-in beg end))
10725 (when (overlay-get o 'js2-error)
10726 (delete-overlay o))))))
10728 (defun js2-error-at-point (&optional pos)
10729 "Return non-nil if there's an error overlay at POS.
10730 Defaults to point."
10731 (loop with pos = (or pos (point))
10732 for o in (overlays-at pos)
10733 thereis (overlay-get o 'js2-error)))
10735 (defun js2-mode-apply-deferred-properties ()
10736 "Apply fontifications and other text properties recorded during parsing."
10737 (when (plusp js2-highlight-level)
10738 ;; We defer clearing faces as long as possible to eliminate flashing.
10739 (js2-clear-face (point-min) (point-max))
10740 ;; Have to reverse the recorded fontifications list so that errors
10741 ;; and warnings overwrite the normal fontifications.
10742 (dolist (f (nreverse js2-mode-fontifications))
10743 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10744 (setq js2-mode-fontifications nil))
10745 (dolist (p js2-mode-deferred-properties)
10746 (apply #'put-text-property p))
10747 (setq js2-mode-deferred-properties nil))
10749 (defun js2-mode-show-errors ()
10750 "Highlight syntax errors."
10751 (when js2-mode-show-parse-errors
10752 (dolist (e (js2-ast-root-errors js2-mode-ast))
10753 (js2-mode-show-warn-or-err e 'js2-error-face))))
10755 (defun js2-mode-remove-suppressed-warnings ()
10756 "Take suppressed warnings out of the AST warnings list.
10757 This ensures that the counts and `next-error' are correct."
10758 (setf (js2-ast-root-warnings js2-mode-ast)
10761 (let ((key (caar e)))
10763 (and (not js2-strict-trailing-comma-warning)
10764 (string-match "trailing\\.comma" key))
10765 (and (not js2-strict-cond-assign-warning)
10766 (string= key "msg.equal.as.assign"))
10767 (and js2-missing-semi-one-line-override
10768 (string= key "msg.missing.semi")
10769 (let* ((beg (second e))
10770 (node (js2-node-at-point beg))
10771 (fn (js2-mode-find-parent-fn node))
10772 (body (and fn (js2-function-node-body fn)))
10773 (lc (and body (js2-node-abs-pos body)))
10774 (rc (and lc (+ lc (js2-node-len body)))))
10779 (and (js2-same-line lc)
10780 (js2-same-line rc))))))))))
10781 (js2-ast-root-warnings js2-mode-ast))))
10783 (defun js2-mode-show-warnings ()
10784 "Highlight strict-mode warnings."
10785 (when js2-mode-show-strict-warnings
10786 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10787 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10789 (defun js2-echo-error (old-point new-point)
10790 "Called by point-motion hooks."
10791 (let ((msg (get-text-property new-point 'help-echo)))
10792 (if (and msg (or (not (current-message))
10793 (string= (current-message) "Quit")))
10796 (defalias #'js2-echo-help #'js2-echo-error)
10798 (defun js2-enter-key ()
10799 "Handle user pressing the Enter key."
10801 (let ((parse-status (save-excursion
10802 (syntax-ppss (point))))
10803 (js2-bounce-indent-p nil))
10805 ;; check if we're inside a string
10806 ((nth 3 parse-status)
10807 (if js2-concat-multiline-strings
10808 (js2-mode-split-string parse-status)
10810 ;; check if inside a block comment
10811 ((nth 4 parse-status)
10812 (js2-mode-extend-comment))
10814 ;; should probably figure out what the mode-map says we should do
10815 (if js2-indent-on-enter-key
10818 (if js2-enter-indents-newline
10819 (js2-indent-line))))))
10821 (defun js2-mode-split-string (parse-status)
10822 "Turn a newline in mid-string into a string concatenation.
10823 PARSE-STATUS is as documented in `parse-partial-sexp'."
10824 (let* ((col (current-column))
10825 (quote-char (nth 3 parse-status))
10826 (quote-string (string quote-char))
10827 (string-beg (nth 8 parse-status))
10828 (at-eol (eq js2-concat-multiline-strings 'eol))
10829 (indent (save-match-data
10832 (back-to-indentation)
10833 (if (looking-at "\\+")
10836 (goto-char string-beg)
10837 (if (looking-back "\\+\\s-+")
10838 (goto-char (match-beginning 0)))
10839 (current-column))))))
10840 (insert quote-char)
10844 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10848 (insert quote-string)
10850 (insert quote-string)
10851 (backward-char 1))))
10853 (defun js2-mode-extend-comment ()
10854 "Indent the line and, when inside a comment block, add comment prefix."
10855 (let (star single col first-line needs-close)
10857 (back-to-indentation)
10859 ((looking-at "\\*[^/]")
10861 col (current-column)))
10862 ((looking-at "/\\*")
10865 col (1+ (current-column))))
10868 col (current-column)))))
10869 ;; Heuristic for whether we need to close the comment:
10870 ;; if we've got a parse error here, assume it's an unterminated
10874 (eq (get-text-property (1- (point)) 'point-entered)
10876 ;; The heuristic above doesn't work well when we're
10877 ;; creating a comment and there's another one downstream,
10878 ;; as our parser thinks this one ends at the end of the
10879 ;; next one. (You can have a /* inside a js block comment.)
10880 ;; So just close it if the next non-ws char isn't a *.
10884 (skip-chars-forward " \t\r\n")
10885 (not (eq (char-after) ?*))))))
10891 (if (and first-line needs-close)
10898 (and (zerop (forward-line 1))
10899 (looking-at "\\s-*//"))))
10902 ;; don't need to extend the comment after all
10903 (js2-enter-indents-newline
10904 (js2-indent-line)))))
10906 (defun js2-beginning-of-line ()
10907 "Toggles point between bol and first non-whitespace char in line.
10908 Also moves past comment delimiters when inside comments."
10913 (back-to-indentation))
10915 (skip-chars-forward "/ \t"))
10916 ((and (eq (char-after) ?*)
10917 (setq node (js2-comment-at-point))
10918 (memq (js2-comment-node-format node) '(jsdoc block))
10920 (skip-chars-backward " \t")
10922 (skip-chars-forward "\* \t"))
10924 (goto-char (point-at-bol))))))
10926 (defun js2-end-of-line ()
10927 "Toggles point between eol and last non-whitespace char in line."
10930 (skip-chars-backward " \t")
10931 (goto-char (point-at-eol))))
10933 (defun js2-enter-mirror-mode()
10934 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10937 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10938 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10939 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10940 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10941 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10942 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10943 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10944 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10946 (defun js2-leave-mirror-mode()
10947 "Turns off mirror mode."
10949 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10950 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10952 (defsubst js2-mode-inside-string ()
10953 "Return non-nil if inside a string.
10954 Actually returns the quote character that begins the string."
10955 (let ((parse-state (save-excursion
10956 (syntax-ppss (point)))))
10957 (nth 3 parse-state)))
10959 (defsubst js2-mode-inside-comment-or-string ()
10960 "Return non-nil if inside a comment or string."
10962 (let ((comment-start
10964 (goto-char (point-at-bol))
10965 (if (re-search-forward "//" (point-at-eol) t)
10966 (match-beginning 0)))))
10968 (<= comment-start (point))))
10969 (let ((parse-state (save-excursion
10970 (syntax-ppss (point)))))
10971 (or (nth 3 parse-state)
10972 (nth 4 parse-state)))))
10974 (defsubst js2-make-magic-delimiter (delim &optional pos)
10975 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10976 Sets value of `js2-magic' text property to line number at POS."
10978 'js2-magic (line-number-at-pos pos)
10979 'font-lock-face 'js2-magic-paren-face))
10981 (defun js2-mode-match-delimiter (open close)
10982 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10983 The rule we use, which as far as we can tell is how Eclipse works,
10984 is that we insert the match if we're not in a comment or string,
10985 and the next non-whitespace character is either punctuation or
10986 occurs on another line."
10988 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10989 (not (js2-mode-inside-comment-or-string)))
10991 (insert (js2-make-magic-delimiter close)))
10992 (when js2-auto-indent-p
10993 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10994 (js2-indent-line)))))
10996 (defun js2-mode-match-bracket ()
10997 "Insert matching bracket."
10999 (js2-mode-match-delimiter "[" "]"))
11001 (defun js2-mode-match-paren ()
11002 "Insert matching paren unless already inserted."
11004 (js2-mode-match-delimiter "(" ")"))
11006 (defun js2-mode-match-curly (arg)
11007 "Insert matching curly-brace.
11008 With prefix arg, no formatting or indentation will occur -- the close-brace
11009 is simply inserted directly at the point."
11013 (current-prefix-arg
11014 (js2-mode-match-delimiter "{" "}"))
11015 ((and js2-auto-insert-catch-block
11016 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
11018 (match-beginning 1))))
11019 (js2-insert-catch-skel try-pos))
11021 ;; Otherwise try to do something smarter.
11023 (unless (or (not (looking-at "\\s-*$"))
11025 (skip-chars-forward " \t\r\n")
11026 (and (looking-at "}")
11027 (js2-error-at-point)))
11028 (js2-mode-inside-comment-or-string))
11030 ;; absolutely mystifying bug: when inserting the next "\n",
11031 ;; the buffer-undo-list is given two new entries: the inserted range,
11032 ;; and the incorrect position of the point. It's recorded incorrectly
11033 ;; as being before the opening "{", not after it. But it's recorded
11034 ;; as the correct value if you're debugging `js2-mode-match-curly'
11035 ;; in edebug. I have no idea why it's doing this, but incrementing
11036 ;; the inserted position fixes the problem, so that the undo takes us
11037 ;; back to just after the user-inserted "{".
11040 (incf (cadr buffer-undo-list)))
11044 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
11045 (js2-indent-line))))))))
11047 (defun js2-insert-catch-skel (try-pos)
11048 "Complete a try/catch block after inserting a { following a try keyword.
11049 Rationale is that a try always needs a catch or a finally, and the catch is
11050 the more likely of the two.
11052 TRY-POS is the buffer position of the try keyword. The open-curly should
11053 already have been inserted."
11055 (let ((try-col (save-excursion
11056 (goto-char try-pos)
11057 (current-column))))
11060 (js2-indent-line) ;; indent the blank line where cursor will end up
11063 (indent-to try-col)
11064 (insert "} catch (x) {\n\n")
11065 (indent-to try-col)
11068 (defun js2-mode-highlight-magic-parens ()
11069 "Re-highlight magic parens after parsing nukes the 'face prop."
11070 (let ((beg (point-min))
11072 (while (setq beg (next-single-property-change beg 'js2-magic))
11073 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11074 (if (get-text-property beg 'js2-magic)
11075 (js2-with-unmodifying-text-property-changes
11076 (put-text-property beg (or end (1+ beg))
11077 'font-lock-face 'js2-magic-paren-face))))))
11079 (defun js2-mode-mundanify-parens ()
11080 "Clear all magic parens and brackets."
11081 (let ((beg (point-min))
11083 (while (setq beg (next-single-property-change beg 'js2-magic))
11084 (setq end (next-single-property-change (1+ beg) 'js2-magic))
11085 (remove-text-properties beg (or end (1+ beg))
11086 '(js2-magic face)))))
11088 (defsubst js2-match-quote (quote-string)
11089 (let ((start-quote (js2-mode-inside-string)))
11091 ;; inside a comment - don't do quote-matching, since we can't
11092 ;; reliably figure out if we're in a string inside the comment
11093 ((js2-comment-at-point)
11094 (insert quote-string))
11096 ;; not in string => insert matched quotes
11097 (insert quote-string)
11098 ;; exception: if we're just before a word, don't double it.
11099 (unless (looking-at "[^ \t\r\n]")
11101 (insert quote-string))))
11102 ((looking-at quote-string)
11103 (if (looking-back "[^\\]\\\\")
11104 (insert quote-string)
11106 ((and js2-mode-escape-quotes
11109 (re-search-forward quote-string (point-at-eol) t))))
11110 ;; inside terminated string, escape quote (unless already escaped)
11111 (insert (if (looking-back "[^\\]\\\\")
11113 (concat "\\" quote-string))))
11115 (insert quote-string))))) ; else terminate the string
11117 (defun js2-mode-match-single-quote ()
11118 "Insert matching single-quote."
11120 (let ((parse-status (syntax-ppss (point))))
11121 ;; don't match inside comments, since apostrophe is more common
11122 (if (nth 4 parse-status)
11124 (js2-match-quote "'"))))
11126 (defun js2-mode-match-double-quote ()
11127 "Insert matching double-quote."
11129 (js2-match-quote "\""))
11131 ;; Eclipse works as follows:
11132 ;; * type an open-paren and it auto-inserts close-paren
11133 ;; - auto-inserted paren gets a green bracket
11134 ;; - green bracket means typing close-paren there will skip it
11135 ;; * if you insert any text on a different line, it turns off
11136 (defun js2-mode-magic-close-paren ()
11137 "Skip over close-paren rather than inserting, where appropriate."
11139 (let* ((here (point))
11140 (parse-status (syntax-ppss here))
11141 (open-pos (nth 1 parse-status))
11142 (close last-input-event)
11151 (if (and (eq (char-after) close)
11152 (eq open (char-after open-pos))
11153 (js2-same-line open-pos)
11154 (get-text-property here 'js2-magic))
11156 (remove-text-properties here (1+ here) '(js2-magic face))
11158 (insert-char close 1))
11159 (blink-matching-open)))
11161 (defun js2-mode-wait-for-parse (callback)
11162 "Invoke CALLBACK when parsing is finished.
11163 If parsing is already finished, calls CALLBACK immediately."
11164 (if (not js2-mode-buffer-dirty-p)
11166 (push callback js2-mode-pending-parse-callbacks)
11167 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
11169 (defun js2-mode-parse-finished ()
11170 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
11171 ;; We can't let errors propagate up, since it prevents the
11172 ;; `js2-parse' method from completing normally and returning
11173 ;; the ast, which makes things mysteriously not work right.
11175 (dolist (cb js2-mode-pending-parse-callbacks)
11176 (condition-case err
11178 (error (message "%s" err))))
11179 (setq js2-mode-pending-parse-callbacks nil)))
11181 (defun js2-mode-flag-region (from to flag)
11182 "Hide or show text from FROM to TO, according to FLAG.
11183 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
11184 Returns the created overlay if FLAG is non-nil."
11185 (remove-overlays from to 'invisible 'js2-outline)
11187 (let ((o (make-overlay from to)))
11188 (overlay-put o 'invisible 'js2-outline)
11189 (overlay-put o 'isearch-open-invisible
11190 'js2-isearch-open-invisible)
11193 ;; Function to be set as an outline-isearch-open-invisible' property
11194 ;; to the overlay that makes the outline invisible (see
11195 ;; `js2-mode-flag-region').
11196 (defun js2-isearch-open-invisible (overlay)
11197 ;; We rely on the fact that isearch places point on the matched text.
11198 (js2-mode-show-element))
11200 (defun js2-mode-invisible-overlay-bounds (&optional pos)
11201 "Return cons cell of bounds of folding overlay at POS.
11202 Returns nil if not found."
11203 (let ((overlays (overlays-at (or pos (point))))
11205 (while (and overlays
11207 (if (overlay-get (car overlays) 'invisible)
11208 (setq o (car overlays))
11209 (setq overlays (cdr overlays))))
11211 (cons (overlay-start o) (overlay-end o)))))
11213 (defun js2-mode-function-at-point (&optional pos)
11214 "Return the innermost function node enclosing current point.
11215 Returns nil if point is not in a function."
11216 (let ((node (js2-node-at-point pos)))
11217 (while (and node (not (js2-function-node-p node)))
11218 (setq node (js2-node-parent node)))
11219 (if (js2-function-node-p node)
11222 (defun js2-mode-toggle-element ()
11223 "Hide or show the foldable element at the point."
11225 (let (comment fn pos)
11229 ;; /* ... */ comment?
11230 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
11231 (if (js2-mode-invisible-overlay-bounds
11232 (setq pos (+ 3 (js2-node-abs-pos comment))))
11235 (js2-mode-show-element))
11236 (js2-mode-hide-element)))
11239 (back-to-indentation)
11240 (looking-at js2-mode-//-comment-re))
11241 (js2-mode-toggle-//-comment))
11243 ((setq fn (js2-mode-function-at-point))
11244 (setq pos (and (js2-function-node-body fn)
11245 (js2-node-abs-pos (js2-function-node-body fn))))
11246 (goto-char (1+ pos))
11247 (if (js2-mode-invisible-overlay-bounds)
11248 (js2-mode-show-element)
11249 (js2-mode-hide-element)))
11251 (message "Nothing at point to hide or show")))))))
11253 (defun js2-mode-hide-element ()
11254 "Fold/hide contents of a block, showing ellipses.
11255 Show the hidden text with \\[js2-mode-show-element]."
11257 (if js2-mode-buffer-dirty-p
11258 (js2-mode-wait-for-parse #'js2-mode-hide-element))
11259 (let (node body beg end)
11261 ((js2-mode-invisible-overlay-bounds)
11262 (message "already hidden"))
11264 (setq node (js2-node-at-point))
11266 ((js2-block-comment-p node)
11267 (js2-mode-hide-comment node))
11269 (while (and node (not (js2-function-node-p node)))
11270 (setq node (js2-node-parent node)))
11272 (setq body (js2-function-node-body node)))
11274 (setq beg (js2-node-abs-pos body)
11275 end (+ beg (js2-node-len body)))
11276 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11277 (message "No collapsable element found at point"))))))))
11279 (defun js2-mode-show-element ()
11280 "Show the hidden element at current point."
11282 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11284 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11285 (message "Nothing to un-hide"))))
11287 (defun js2-mode-show-all ()
11288 "Show all of the text in the buffer."
11290 (js2-mode-flag-region (point-min) (point-max) nil))
11292 (defun js2-mode-toggle-hide-functions ()
11294 (if js2-mode-functions-hidden
11295 (js2-mode-show-functions)
11296 (js2-mode-hide-functions)))
11298 (defun js2-mode-hide-functions ()
11299 "Hides all non-nested function bodies in the buffer.
11300 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11301 to open an individual entry."
11303 (if js2-mode-buffer-dirty-p
11304 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11305 (if (null js2-mode-ast)
11306 (message "Oops - parsing failed")
11307 (setq js2-mode-functions-hidden t)
11308 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11310 (defun js2-mode-function-hider (n endp)
11312 (let ((tt (js2-node-type n))
11315 ((and (= tt js2-FUNCTION)
11316 (setq body (js2-function-node-body n)))
11317 (setq beg (js2-node-abs-pos body)
11318 end (+ beg (js2-node-len body)))
11319 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11320 nil) ; don't process children of function
11322 t))))) ; keep processing other AST nodes
11324 (defun js2-mode-show-functions ()
11325 "Un-hide any folded function bodies in the buffer."
11327 (setq js2-mode-functions-hidden nil)
11329 (goto-char (point-min))
11330 (while (/= (goto-char (next-overlay-change (point)))
11332 (dolist (o (overlays-at (point)))
11333 (when (and (overlay-get o 'invisible)
11334 (not (overlay-get o 'comment)))
11335 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11337 (defun js2-mode-hide-comment (n)
11338 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11341 (beg (+ (js2-node-abs-pos n) head))
11342 (end (- (+ beg (js2-node-len n)) head 2))
11343 (o (js2-mode-flag-region beg end 'hide)))
11344 (overlay-put o 'comment t)))
11346 (defun js2-mode-toggle-hide-comments ()
11347 "Folds all block comments in the buffer.
11348 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11349 to open an individual entry."
11351 (if js2-mode-comments-hidden
11352 (js2-mode-show-comments)
11353 (js2-mode-hide-comments)))
11355 (defun js2-mode-hide-comments ()
11357 (if js2-mode-buffer-dirty-p
11358 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11359 (if (null js2-mode-ast)
11360 (message "Oops - parsing failed")
11361 (setq js2-mode-comments-hidden t)
11362 (dolist (n (js2-ast-root-comments js2-mode-ast))
11363 (let ((format (js2-comment-node-format n)))
11364 (when (js2-block-comment-p n)
11365 (js2-mode-hide-comment n))))
11366 (js2-mode-hide-//-comments)))
11368 (defsubst js2-mode-extend-//-comment (direction)
11369 "Find start or end of a block of similar //-comment lines.
11370 DIRECTION is -1 to look back, 1 to look forward.
11371 INDENT is the indentation level to match.
11372 Returns the end-of-line position of the furthest adjacent
11373 //-comment line with the same indentation as the current line.
11374 If there is no such matching line, returns current end of line."
11375 (let ((pos (point-at-eol))
11376 (indent (current-indentation)))
11379 (while (and (zerop (forward-line direction))
11380 (looking-at js2-mode-//-comment-re)
11381 (eq indent (length (match-string 1))))
11382 (setq pos (point-at-eol)))
11385 (defun js2-mode-hide-//-comments ()
11386 "Fold adjacent 1-line comments, showing only snippet of first one."
11390 (goto-char (point-min))
11391 (while (re-search-forward js2-mode-//-comment-re nil t)
11393 end (js2-mode-extend-//-comment 1))
11394 (unless (eq beg end)
11395 (overlay-put (js2-mode-flag-region beg end 'hide)
11398 (forward-char 1))))))
11400 (defun js2-mode-toggle-//-comment ()
11401 "Fold or un-fold any multi-line //-comment at point.
11402 Caller should have determined that this line starts with a //-comment."
11403 (let* ((beg (point-at-eol))
11407 (if (js2-mode-invisible-overlay-bounds)
11408 (js2-mode-show-element)
11409 ;; else hide the comment
11410 (setq beg (js2-mode-extend-//-comment -1)
11411 end (js2-mode-extend-//-comment 1))
11412 (unless (eq beg end)
11413 (overlay-put (js2-mode-flag-region beg end 'hide)
11416 (defun js2-mode-show-comments ()
11417 "Un-hide any hidden comments, leaving other hidden elements alone."
11419 (setq js2-mode-comments-hidden nil)
11421 (goto-char (point-min))
11422 (while (/= (goto-char (next-overlay-change (point)))
11424 (dolist (o (overlays-at (point)))
11425 (when (overlay-get o 'comment)
11426 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11428 (defun js2-mode-display-warnings-and-errors ()
11429 "Turn on display of warnings and errors."
11431 (setq js2-mode-show-parse-errors t
11432 js2-mode-show-strict-warnings t)
11433 (js2-reparse 'force))
11435 (defun js2-mode-hide-warnings-and-errors ()
11436 "Turn off display of warnings and errors."
11438 (setq js2-mode-show-parse-errors nil
11439 js2-mode-show-strict-warnings nil)
11440 (js2-reparse 'force))
11442 (defun js2-mode-toggle-warnings-and-errors ()
11443 "Toggle the display of warnings and errors.
11444 Some users don't like having warnings/errors reported while they type."
11446 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11447 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11448 (if (interactive-p)
11449 (message "warnings and errors %s"
11450 (if js2-mode-show-parse-errors
11453 (js2-reparse 'force))
11455 (defun js2-mode-customize ()
11457 (customize-group 'js2-mode))
11459 (defun js2-mode-forward-sexp (&optional arg)
11460 "Move forward across one statement or balanced expression.
11461 With ARG, do it that many times. Negative arg -N means
11462 move backward across N balanced expressions."
11464 (setq arg (or arg 1))
11465 (if js2-mode-buffer-dirty-p
11466 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11467 (let (node end (start (point)))
11470 ;; could probably make this better for some cases:
11471 ;; - if in statement block (e.g. function body), go to parent
11472 ;; - infix exprs like (foo in bar) - maybe go to beginning
11473 ;; of infix expr if in the right-side expression?
11474 ((and arg (minusp arg))
11475 (dotimes (i (- arg))
11477 (forward-char -1) ; enter the node we backed up to
11478 (setq node (js2-node-at-point (point) t))
11479 (goto-char (if node
11480 (js2-node-abs-pos node)
11487 (setq node (js2-node-at-point (point) t)
11488 end (if node (+ (js2-node-abs-pos node)
11489 (js2-node-len node))))
11490 (goto-char (or end (point-max))))))))
11492 (defun js2-next-error (&optional arg reset)
11493 "Move to next parse error.
11494 Typically invoked via \\[next-error].
11495 ARG is the number of errors, forward or backward, to move.
11496 RESET means start over from the beginning."
11498 (if (or (null js2-mode-ast)
11499 (and (null (js2-ast-root-errors js2-mode-ast))
11500 (null (js2-ast-root-warnings js2-mode-ast))))
11501 (message "No errors")
11503 (goto-char (point-min)))
11504 (let* ((errs (copy-sequence
11505 (append (js2-ast-root-errors js2-mode-ast)
11506 (js2-ast-root-warnings js2-mode-ast))))
11510 (backward (minusp count))
11511 (sorter (if backward '> '<))
11512 (stopper (if backward '< '>))
11513 (count (abs count))
11516 ;; sort by start position
11517 (setq errs (sort errs (lambda (e1 e2)
11518 (funcall sorter (second e1) (second e2))))
11520 ;; find nth error with pos > start
11521 (while (and errs continue)
11522 (when (funcall stopper (cadar errs) start)
11523 (setq err (car errs))
11524 (if (zerop (decf count))
11525 (setq continue nil)))
11526 (setq errs (cdr errs)))
11528 (goto-char (second err))
11529 ;; wrap around to first error
11530 (goto-char (second (car all-errs)))
11531 ;; if we were already on it, echo msg again
11532 (if (= (point) start)
11533 (js2-echo-error (point) (point)))))))
11535 (defun js2-down-mouse-3 ()
11536 "Make right-click move the point to the click location.
11537 This makes right-click context menu operations a bit more intuitive.
11538 The point will not move if the region is active, however, to avoid
11539 destroying the region selection."
11541 (when (and js2-move-point-on-right-click
11543 (let ((e last-input-event))
11545 (goto-char (cadadr e))))))
11547 (defun js2-mode-create-imenu-index ()
11548 "Return an alist for `imenu--index-alist'."
11549 ;; This is built up in `js2-parse-record-imenu' during parsing.
11551 ;; if we have an ast but no recorder, they're requesting a rescan
11552 (unless js2-imenu-recorder
11553 (js2-reparse 'force))
11555 (js2-build-imenu-index)
11556 (setq js2-imenu-recorder nil
11557 js2-imenu-function-map nil))))
11559 (defun js2-mode-find-tag ()
11560 "Replacement for `find-tag-default'.
11561 `find-tag-default' returns a ridiculous answer inside comments."
11563 (js2-with-underscore-as-word-syntax
11565 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11566 (looking-back "[A-Za-z0-9_$]"))
11567 (setq beg (progn (forward-word -1) (point))
11568 end (progn (forward-word 1) (point)))
11569 (setq beg (progn (forward-word 1) (point))
11570 end (progn (forward-word -1) (point))))
11571 (replace-regexp-in-string
11573 (buffer-substring-no-properties beg end))))))
11575 (defun js2-mode-forward-sibling ()
11576 "Move to the end of the sibling following point in parent.
11577 Returns non-nil if successful, or nil if there was no following sibling."
11578 (let* ((node (js2-node-at-point))
11579 (parent (js2-mode-find-enclosing-fn node))
11581 (when (setq sib (js2-node-find-child-after (point) parent))
11582 (goto-char (+ (js2-node-abs-pos sib)
11583 (js2-node-len sib))))))
11585 (defun js2-mode-backward-sibling ()
11586 "Move to the beginning of the sibling node preceding point in parent.
11587 Parent is defined as the enclosing script or function."
11588 (let* ((node (js2-node-at-point))
11589 (parent (js2-mode-find-enclosing-fn node))
11591 (when (setq sib (js2-node-find-child-before (point) parent))
11592 (goto-char (js2-node-abs-pos sib)))))
11594 (defun js2-beginning-of-defun (&optional arg)
11595 "Go to line on which current function starts, and return t on success.
11596 If we're not in a function or already at the beginning of one, go
11597 to beginning of previous script-level element.
11598 With ARG N, do that N times. If N is negative, move forward."
11599 (setq arg (or arg 1))
11601 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11603 ((js2-function-node-p parent)
11604 (goto-char (js2-node-abs-pos parent)))
11606 (js2-mode-backward-sibling)))
11608 (js2-beginning-of-defun (1- arg))
11610 (when (js2-end-of-defun)
11612 (js2-beginning-of-defun 1)
11613 (js2-beginning-of-defun (1+ arg))))))
11615 (defun js2-end-of-defun ()
11616 "Go to the char after the last position of the current function
11617 or script-level element."
11618 (let* ((node (js2-node-at-point))
11619 (parent (or (and (js2-function-node-p node) node)
11620 (js2-node-parent-script-or-fn node)))
11622 (unless (js2-function-node-p parent)
11623 ;; use current script-level node, or, if none, the next one
11624 (setq script (or parent node))
11625 (setq parent (js2-node-find-child-before (point) script))
11626 (when (or (null parent)
11627 (>= (point) (+ (js2-node-abs-pos parent)
11628 (js2-node-len parent))))
11629 (setq parent (js2-node-find-child-after (point) script))))
11631 (goto-char (+ (js2-node-abs-pos parent)
11632 (js2-node-len parent))))))
11634 (defun js2-mark-defun (&optional allow-extend)
11635 "Put mark at end of this function, point at beginning.
11636 The function marked is the one that contains point.
11638 Interactively, if this command is repeated,
11639 or (in Transient Mark mode) if the mark is active,
11640 it marks the next defun after the ones already marked."
11643 (when (and allow-extend
11644 (or (and (eq last-command this-command) (mark t))
11645 (and transient-mark-mode mark-active)))
11646 (let ((sib (save-excursion
11648 (if (js2-mode-forward-sibling)
11655 ;; no more siblings - try extending to enclosing node
11656 (goto-char (mark t)))))
11657 (when (not extended)
11658 (let ((node (js2-node-at-point (point) t)) ; skip comments
11659 ast fn stmt parent beg end)
11660 (when (js2-ast-root-p node)
11662 node (or (js2-node-find-child-after (point) node)
11663 (js2-node-find-child-before (point) node))))
11664 ;; only mark whole buffer if we can't find any children
11667 (if (js2-function-node-p node)
11669 (setq fn (js2-mode-find-enclosing-fn node)
11670 stmt (if (or (null fn)
11671 (js2-ast-root-p fn))
11672 (js2-mode-find-first-stmt node))
11673 parent (or stmt fn)))
11674 (setq beg (js2-node-abs-pos parent)
11675 end (+ beg (js2-node-len parent)))
11678 (exchange-point-and-mark)))))
11680 (defun js2-narrow-to-defun ()
11681 "Narrow to the function enclosing point."
11683 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11684 (fn (if (js2-script-node-p node)
11686 (js2-mode-find-enclosing-fn node)))
11687 (beg (js2-node-abs-pos fn)))
11688 (unless (js2-ast-root-p fn)
11689 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11691 (provide 'js2-mode)
11693 ;;; js2-mode.el ends here