1 ;;; js2-mode.el --- Improved JavaScript editing mode
3 ;; Copyright (C) 2009, 2012 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
48 ;; To install it as your major mode for JavaScript editing:
50 ;; (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
52 ;; Alternately, to install it as a minor mode just for JavaScript linting,
53 ;; you must add it to the appropriate major-mode hook. Normally this would be:
55 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
57 ;; To customize how it works:
58 ;; M-x customize-group RET js2-mode RET
62 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
63 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
64 ;; `js2-mode' current as the EcmaScript language standard evolves.
66 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
67 ;; customizable. It is a surprising amount of work to support customizable
68 ;; indentation. The current compromise is that the tab key lets you cycle among
69 ;; various likely indentation points, similar to the behavior of python-mode.
71 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
72 ;; and `mumamo', although it could be made to do so with some effort.
73 ;; This means that `js2-mode' is currently only useful for editing JavaScript
74 ;; files, and not for editing JavaScript within <script> tags or templates.
82 (require 'cc-cmds) ; for `c-fill-paragraph'
85 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
86 (require 'cc-langs) ; it's here in Emacs 21...
87 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
89 (defvar electric-layout-rules)
91 ;;; Externs (variables presumed to be defined by the host system)
93 (defvar js2-ecma-262-externs
95 '(Array Boolean Date Error EvalError Function Infinity
96 Math NaN Number Object RangeError ReferenceError RegExp
97 String SyntaxError TypeError URIError arguments
98 decodeURI decodeURIComponent encodeURI
99 encodeURIComponent escape eval isFinite isNaN
100 parseFloat parseInt undefined unescape))
101 "Ecma-262 externs. Included in `js2-externs' by default.")
103 (defvar js2-browser-externs
106 Attr CDATASection CharacterData Comment DOMException
107 DOMImplementation Document DocumentFragment
108 DocumentType Element Entity EntityReference
109 ExceptionCode NamedNodeMap Node NodeList Notation
110 ProcessingInstruction Text
113 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
114 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
115 HTMLBodyElement HTMLButtonElement HTMLCollection
116 HTMLDListElement HTMLDirectoryElement HTMLDivElement
117 HTMLDocument HTMLElement HTMLFieldSetElement
118 HTMLFontElement HTMLFormElement HTMLFrameElement
119 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
120 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
121 HTMLImageElement HTMLInputElement HTMLIsIndexElement
122 HTMLLIElement HTMLLabelElement HTMLLegendElement
123 HTMLLinkElement HTMLMapElement HTMLMenuElement
124 HTMLMetaElement HTMLModElement HTMLOListElement
125 HTMLObjectElement HTMLOptGroupElement
126 HTMLOptionElement HTMLOptionsCollection
127 HTMLParagraphElement HTMLParamElement HTMLPreElement
128 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
129 HTMLStyleElement HTMLTableCaptionElement
130 HTMLTableCellElement HTMLTableColElement
131 HTMLTableElement HTMLTableRowElement
132 HTMLTableSectionElement HTMLTextAreaElement
133 HTMLTitleElement HTMLUListElement
136 DOMConfiguration DOMError DOMException
137 DOMImplementationList DOMImplementationSource
138 DOMLocator DOMStringList NameList TypeInfo
142 window alert confirm document java navigator prompt screen
146 CSSCharsetRule CSSFontFace CSSFontFaceRule
147 CSSImportRule CSSMediaRule CSSPageRule
148 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
149 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
150 CSSValue CSSValueList Counter DOMImplementationCSS
151 DocumentCSS DocumentStyle ElementCSSInlineStyle
152 LinkStyle MediaList RGBColor Rect StyleSheet
153 StyleSheetList ViewCSS
156 EventListener EventTarget Event DocumentEvent UIEvent
157 MouseEvent MutationEvent KeyboardEvent
160 DocumentRange Range RangeException
163 XPathResult XMLHttpRequest))
165 You can cause these to be included or excluded with the custom
166 variable `js2-include-browser-externs'.")
168 (defvar js2-rhino-externs
170 '(Packages importClass importPackage com org java
171 ;; Global object (shell) externs.
172 defineClass deserialize doctest gc help load
173 loadClass print quit readFile readUrl runCommand seal
174 serialize spawn sync toint32 version))
175 "Mozilla Rhino externs.
176 Set `js2-include-rhino-externs' to t to include them.")
178 (defvar js2-gears-externs
181 ;; TODO(stevey): add these
183 "Google Gears externs.
184 Set `js2-include-gears-externs' to t to include them.")
188 (defun js2-mark-safe-local (name pred)
189 "Make the variable NAME buffer-local and mark it as safe file-local
190 variable with predicate PRED."
191 (make-variable-buffer-local name)
192 (put name 'safe-local-variable pred))
194 (defcustom js2-highlight-level 2
195 "Amount of syntax highlighting to perform.
196 0 or a negative value means none.
197 1 adds basic syntax highlighting.
198 2 adds highlighting of some Ecma built-in properties.
199 3 adds highlighting of many Ecma built-in functions."
201 :type '(choice (const :tag "None" 0)
202 (const :tag "Basic" 1)
203 (const :tag "Include Properties" 2)
204 (const :tag "Include Functions" 3)))
206 (defvar js2-mode-dev-mode-p nil
207 "Non-nil if running in development mode. Normally nil.")
209 (defgroup js2-mode nil
210 "An improved JavaScript mode."
213 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
214 (numberp c-basic-offset))
217 "Number of spaces to indent nested statements.
218 Similar to `c-basic-offset'."
221 (js2-mark-safe-local 'js2-basic-offset 'integerp)
224 (defcustom js2-bounce-indent-p nil
225 "Non-nil to have indent-line function choose among alternatives.
226 If nil, the indent-line function will indent to a predetermined column
227 based on heuristic guessing. If non-nil, then if the current line is
228 already indented to that predetermined column, indenting will choose
229 another likely column and indent to that spot. Repeated invocation of
230 the indent-line function will cycle among the computed alternatives.
231 See the function `js2-bounce-indent' for details. When it is non-nil,
232 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
236 (defcustom js2-pretty-multiline-declarations t
237 "Non-nil to line up multiline declarations vertically:
243 If the value is not `all', and the first assigned value in
244 declaration is a function/array/object literal spanning several
245 lines, it won't be indented additionally:
247 var o = { var bar = 2,
253 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
255 (defcustom js2-indent-on-enter-key nil
256 "Non-nil to have Enter/Return key indent the line.
257 This is unusual for Emacs modes but common in IDEs like Eclipse."
261 (defcustom js2-enter-indents-newline nil
262 "Non-nil to have Enter/Return key indent the newly-inserted line.
263 This is unusual for Emacs modes but common in IDEs like Eclipse."
267 (defcustom js2-idle-timer-delay 0.2
268 "Delay in secs before re-parsing after user makes changes.
269 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
272 (make-variable-buffer-local 'js2-idle-timer-delay)
274 (defcustom js2-dynamic-idle-timer-adjust 0
275 "Positive to adjust `js2-idle-timer-delay' based on file size.
276 The idea is that for short files, parsing is faster so we can be
277 more responsive to user edits without interfering with editing.
278 The buffer length in characters (typically bytes) is divided by
279 this value and used to multiply `js2-idle-timer-delay' for the
280 buffer. For example, a 21k file and 10k adjust yields 21k/10k
281 == 2, so js2-idle-timer-delay is multiplied by 2.
282 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
283 `js2-idle-timer-delay' is not dependent on the file size."
287 (defcustom js2-mode-escape-quotes t
288 "Non-nil to disable automatic quote-escaping inside strings."
292 (defcustom js2-concat-multiline-strings t
293 "Non-nil to automatically turn a newline in mid-string into a
294 string concatenation. When `eol', the '+' will be inserted at the
295 end of the line, otherwise, at the beginning of the next line."
296 :type '(choice (const t) (const eol) (const nil))
299 (defcustom js2-mode-squeeze-spaces t
300 "Non-nil to normalize whitespace when filling in comments.
301 Multiple runs of spaces are converted to a single space."
305 (defcustom js2-mode-show-parse-errors t
306 "True to highlight parse errors."
310 (defcustom js2-mode-show-strict-warnings t
311 "Non-nil to emit Ecma strict-mode warnings.
312 Some of the warnings can be individually disabled by other flags,
313 even if this flag is non-nil."
317 (defcustom js2-strict-trailing-comma-warning t
318 "Non-nil to warn about trailing commas in array literals.
319 Ecma-262 forbids them, but many browsers permit them. IE is the
320 big exception, and can produce bugs if you have trailing commas."
324 (defcustom js2-strict-missing-semi-warning t
325 "Non-nil to warn about semicolon auto-insertion after statement.
326 Technically this is legal per Ecma-262, but some style guides disallow
331 (defcustom js2-missing-semi-one-line-override nil
332 "Non-nil to permit missing semicolons in one-line functions.
333 In one-liner functions such as `function identity(x) {return x}'
334 people often omit the semicolon for a cleaner look. If you are
335 such a person, you can suppress the missing-semicolon warning
336 by setting this variable to t."
340 (defcustom js2-strict-inconsistent-return-warning t
341 "Non-nil to warn about mixing returns with value-returns.
342 It's perfectly legal to have a `return' and a `return foo' in the
343 same function, but it's often an indicator of a bug, and it also
344 interferes with type inference (in systems that support it.)"
348 (defcustom js2-strict-cond-assign-warning t
349 "Non-nil to warn about expressions like if (a = b).
350 This often should have been '==' instead of '='. If the warning
351 is enabled, you can suppress it on a per-expression basis by
352 parenthesizing the expression, e.g. if ((a = b)) ..."
356 (defcustom js2-strict-var-redeclaration-warning t
357 "Non-nil to warn about redeclaring variables in a script or function."
361 (defcustom js2-strict-var-hides-function-arg-warning t
362 "Non-nil to warn about a var decl hiding a function argument."
366 (defcustom js2-skip-preprocessor-directives nil
367 "Non-nil to treat lines beginning with # as comments.
368 Useful for viewing Mozilla JavaScript source code."
372 (defcustom js2-language-version 180
373 "Configures what JavaScript language version to recognize.
374 Currently versions 150, 160, 170 and 180 are supported, corresponding
375 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
376 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
377 and 1.8 adds function closures."
381 (defcustom js2-allow-keywords-as-property-names t
382 "If non-nil, you can use JavaScript keywords as object property names.
385 var foo = {int: 5, while: 6, continue: 7};
388 Ecma-262 forbids this syntax, but many browsers support it."
392 (defcustom js2-instanceof-has-side-effects nil
393 "If non-nil, treats the instanceof operator as having side effects.
394 This is useful for xulrunner apps."
398 (defcustom js2-move-point-on-right-click t
399 "Non-nil to move insertion point when you right-click.
400 This makes right-click context menu behavior a bit more intuitive,
401 since menu operations generally apply to the point. The exception
402 is if there is a region selection, in which case the point does -not-
403 move, so cut/copy/paste can work properly.
405 Note that IntelliJ moves the point, and Eclipse leaves it alone,
406 so this behavior is customizable."
410 (defcustom js2-allow-rhino-new-expr-initializer t
411 "Non-nil to support a Rhino's experimental syntactic construct.
413 Rhino supports the ability to follow a `new' expression with an object
414 literal, which is used to set additional properties on the new object
415 after calling its constructor. Syntax:
417 new <expr> [ ( arglist ) ] [initializer]
419 Hence, this expression:
421 new Object {a: 1, b: 2}
423 results in an Object with properties a=1 and b=2. This syntax is
424 apparently not configurable in Rhino - it's currently always enabled,
425 as of Rhino version 1.7R2."
429 (defcustom js2-allow-member-expr-as-function-name nil
430 "Non-nil to support experimental Rhino syntax for function names.
432 Rhino supports an experimental syntax configured via the Rhino Context
433 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
435 function <member-expr> ( [ arg-list ] ) { <body> }
437 Where member-expr is a non-parenthesized 'member expression', which
438 is anything at the grammar level of a new-expression or lower, meaning
439 any expression that does not involve infix or unary operators.
441 When <member-expr> is not a simple identifier, then it is syntactic
442 sugar for assigning the anonymous function to the <member-expr>. Hence,
445 function a.b().c[2] (x, y) { ... }
449 a.b().c[2] = function(x, y) {...}
451 which doesn't seem particularly useful, but Rhino permits it."
455 (defvar js2-mode-version 20120416
456 "Release number for `js2-mode'.")
460 (defmacro js2-deflocal (name value &optional comment)
461 "Define a buffer-local variable NAME with VALUE and COMMENT."
463 (defvar ,name ,value ,comment)
464 (make-variable-buffer-local ',name)))
466 ;; We record the start and end position of each token.
467 (js2-deflocal js2-token-beg 1)
468 (js2-deflocal js2-token-end -1)
470 (defvar js2-EOF_CHAR -1
471 "Represents end of stream. Distinct from js2-EOF token type.")
473 ;; I originally used symbols to represent tokens, but Rhino uses
474 ;; ints and then sets various flag bits in them, so ints it is.
475 ;; The upshot is that we need a `js2-' prefix in front of each name.
476 (defvar js2-ERROR -1)
479 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
480 (defvar js2-LEAVEWITH 3)
481 (defvar js2-RETURN 4)
485 (defvar js2-SETNAME 8)
487 (defvar js2-BITXOR 10)
488 (defvar js2-BITAND 11)
498 (defvar js2-ADD 21) ; infix plus
499 (defvar js2-SUB 22) ; infix minus
504 (defvar js2-BITNOT 27)
505 (defvar js2-POS 28) ; unary plus
506 (defvar js2-NEG 29) ; unary minus
508 (defvar js2-DELPROP 31)
509 (defvar js2-TYPEOF 32)
510 (defvar js2-GETPROP 33)
511 (defvar js2-GETPROPNOWARN 34)
512 (defvar js2-SETPROP 35)
513 (defvar js2-GETELEM 36)
514 (defvar js2-SETELEM 37)
516 (defvar js2-NAME 39) ; an identifier
517 (defvar js2-NUMBER 40)
518 (defvar js2-STRING 41)
521 (defvar js2-FALSE 44)
523 (defvar js2-SHEQ 46) ; shallow equality (===)
524 (defvar js2-SHNE 47) ; shallow inequality (!==)
525 (defvar js2-REGEXP 48)
526 (defvar js2-BINDNAME 49)
527 (defvar js2-THROW 50)
528 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
530 (defvar js2-INSTANCEOF 53)
531 (defvar js2-LOCAL_LOAD 54)
532 (defvar js2-GETVAR 55)
533 (defvar js2-SETVAR 56)
534 (defvar js2-CATCH_SCOPE 57)
535 (defvar js2-ENUM_INIT_KEYS 58)
536 (defvar js2-ENUM_INIT_VALUES 59)
537 (defvar js2-ENUM_INIT_ARRAY 60)
538 (defvar js2-ENUM_NEXT 61)
539 (defvar js2-ENUM_ID 62)
540 (defvar js2-THISFN 63)
541 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
542 (defvar js2-ARRAYLIT 65) ; array literal
543 (defvar js2-OBJECTLIT 66) ; object literal
544 (defvar js2-GET_REF 67) ; *reference
545 (defvar js2-SET_REF 68) ; *reference = something
546 (defvar js2-DEL_REF 69) ; delete reference
547 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
548 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
549 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
552 (defvar js2-DEFAULTNAMESPACE 73)
553 (defvar js2-ESCXMLATTR 74)
554 (defvar js2-ESCXMLTEXT 75)
555 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
556 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
557 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
558 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
560 (defvar js2-first-bytecode js2-ENTERWITH)
561 (defvar js2-last-bytecode js2-REF_NS_NAME)
564 (defvar js2-SEMI 81) ; semicolon
565 (defvar js2-LB 82) ; left and right brackets
567 (defvar js2-LC 84) ; left and right curly-braces
569 (defvar js2-LP 86) ; left and right parens
571 (defvar js2-COMMA 88) ; comma operator
573 (defvar js2-ASSIGN 89) ; simple assignment (=)
574 (defvar js2-ASSIGN_BITOR 90) ; |=
575 (defvar js2-ASSIGN_BITXOR 91) ; ^=
576 (defvar js2-ASSIGN_BITAND 92) ; &=
577 (defvar js2-ASSIGN_LSH 93) ; <<=
578 (defvar js2-ASSIGN_RSH 94) ; >>=
579 (defvar js2-ASSIGN_URSH 95) ; >>>=
580 (defvar js2-ASSIGN_ADD 96) ; +=
581 (defvar js2-ASSIGN_SUB 97) ; -=
582 (defvar js2-ASSIGN_MUL 98) ; *=
583 (defvar js2-ASSIGN_DIV 99) ; /=
584 (defvar js2-ASSIGN_MOD 100) ; %=
586 (defvar js2-first-assign js2-ASSIGN)
587 (defvar js2-last-assign js2-ASSIGN_MOD)
589 (defvar js2-HOOK 101) ; conditional (?:)
590 (defvar js2-COLON 102)
591 (defvar js2-OR 103) ; logical or (||)
592 (defvar js2-AND 104) ; logical and (&&)
593 (defvar js2-INC 105) ; increment/decrement (++ --)
595 (defvar js2-DOT 107) ; member operator (.)
596 (defvar js2-FUNCTION 108) ; function keyword
597 (defvar js2-EXPORT 109) ; export keyword
598 (defvar js2-IMPORT 110) ; import keyword
599 (defvar js2-IF 111) ; if keyword
600 (defvar js2-ELSE 112) ; else keyword
601 (defvar js2-SWITCH 113) ; switch keyword
602 (defvar js2-CASE 114) ; case keyword
603 (defvar js2-DEFAULT 115) ; default keyword
604 (defvar js2-WHILE 116) ; while keyword
605 (defvar js2-DO 117) ; do keyword
606 (defvar js2-FOR 118) ; for keyword
607 (defvar js2-BREAK 119) ; break keyword
608 (defvar js2-CONTINUE 120) ; continue keyword
609 (defvar js2-VAR 121) ; var keyword
610 (defvar js2-WITH 122) ; with keyword
611 (defvar js2-CATCH 123) ; catch keyword
612 (defvar js2-FINALLY 124) ; finally keyword
613 (defvar js2-VOID 125) ; void keyword
614 (defvar js2-RESERVED 126) ; reserved keywords
616 (defvar js2-EMPTY 127)
618 ;; Types used for the parse tree - never returned by scanner.
620 (defvar js2-BLOCK 128) ; statement block
621 (defvar js2-LABEL 129) ; label
622 (defvar js2-TARGET 130)
623 (defvar js2-LOOP 131)
624 (defvar js2-EXPR_VOID 132) ; expression statement in functions
625 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
627 (defvar js2-SCRIPT 135) ; top-level node for entire script
628 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
629 (defvar js2-USE_STACK 137)
630 (defvar js2-SETPROP_OP 138) ; x.y op= something
631 (defvar js2-SETELEM_OP 139) ; x[y] op= something
632 (defvar js2-LOCAL_BLOCK 140)
633 (defvar js2-SET_REF_OP 141) ; *reference op= something
636 (defvar js2-DOTDOT 142) ; member operator (..)
637 (defvar js2-COLONCOLON 143) ; namespace::name
638 (defvar js2-XML 144) ; XML type
639 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
640 (defvar js2-XMLATTR 146) ; @
641 (defvar js2-XMLEND 147)
643 ;; Optimizer-only tokens
644 (defvar js2-TO_OBJECT 148)
645 (defvar js2-TO_DOUBLE 149)
647 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
648 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
649 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
650 (defvar js2-CONST 153)
651 (defvar js2-SETCONST 154)
652 (defvar js2-SETCONSTVAR 155)
653 (defvar js2-ARRAYCOMP 156)
654 (defvar js2-LETEXPR 157)
655 (defvar js2-WITHEXPR 158)
656 (defvar js2-DEBUGGER 159)
658 (defvar js2-COMMENT 160)
659 (defvar js2-ENUM 161) ; for "enum" reserved word
661 (defconst js2-num-tokens (1+ js2-ENUM))
663 (defconst js2-debug-print-trees nil)
665 ;; Rhino accepts any string or stream as input. Emacs character
666 ;; processing works best in buffers, so we'll assume the input is a
667 ;; buffer. JavaScript strings can be copied into temp buffers before
670 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
671 ;; They're the Emacs equivalent of instance variables, more or less.
673 (js2-deflocal js2-ts-dirty-line nil
674 "Token stream buffer-local variable.
675 Indicates stuff other than whitespace since start of line.")
677 (js2-deflocal js2-ts-regexp-flags nil
678 "Token stream buffer-local variable.")
680 (js2-deflocal js2-ts-string ""
681 "Token stream buffer-local variable.
682 Last string scanned.")
684 (js2-deflocal js2-ts-number nil
685 "Token stream buffer-local variable.
686 Last literal number scanned.")
688 (js2-deflocal js2-ts-hit-eof nil
689 "Token stream buffer-local variable.")
691 (js2-deflocal js2-ts-line-start 0
692 "Token stream buffer-local variable.")
694 (js2-deflocal js2-ts-lineno 1
695 "Token stream buffer-local variable.")
697 (js2-deflocal js2-ts-line-end-char -1
698 "Token stream buffer-local variable.")
700 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
701 "Token stream buffer-local variable.
702 Current scan position.")
704 (js2-deflocal js2-ts-is-xml-attribute nil
705 "Token stream buffer-local variable.")
707 (js2-deflocal js2-ts-xml-is-tag-content nil
708 "Token stream buffer-local variable.")
710 (js2-deflocal js2-ts-xml-open-tags-count 0
711 "Token stream buffer-local variable.")
713 (js2-deflocal js2-ts-string-buffer nil
714 "Token stream buffer-local variable.
715 List of chars built up while scanning various tokens.")
717 (js2-deflocal js2-ts-comment-type nil
718 "Token stream buffer-local variable.")
722 (js2-deflocal js2-parsed-errors nil
723 "List of errors produced during scanning/parsing.")
725 (js2-deflocal js2-parsed-warnings nil
726 "List of warnings produced during scanning/parsing.")
728 (js2-deflocal js2-recover-from-parse-errors t
729 "Non-nil to continue parsing after a syntax error.
731 In recovery mode, the AST will be built in full, and any error
732 nodes will be flagged with appropriate error information. If
733 this flag is nil, a syntax error will result in an error being
736 The variable is automatically buffer-local, because different
737 modes that use the parser will need different settings.")
739 (js2-deflocal js2-parse-hook nil
740 "List of callbacks for receiving parsing progress.")
742 (defvar js2-parse-finished-hook nil
743 "List of callbacks to notify when parsing finishes.
744 Not called if parsing was interrupted.")
746 (js2-deflocal js2-is-eval-code nil
747 "True if we're evaluating code in a string.
748 If non-nil, the tokenizer will record the token text, and the AST nodes
749 will record their source text. Off by default for IDE modes, since the
750 text is available in the buffer.")
752 (defvar js2-parse-ide-mode t
753 "Non-nil if the parser is being used for `js2-mode'.
754 If non-nil, the parser will set text properties for fontification
755 and the syntax table. The value should be nil when using the
756 parser as a frontend to an interpreter or byte compiler.")
758 ;;; Parser instance variables (buffer-local vars for js2-parse)
760 (defconst js2-clear-ti-mask #xFFFF
761 "Mask to clear token information bits.")
763 (defconst js2-ti-after-eol (lsh 1 16)
764 "Flag: first token of the source line.")
766 (defconst js2-ti-check-label (lsh 1 17)
767 "Flag: indicates to check for label.")
769 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
771 (js2-deflocal js2-compiler-generate-debug-info t)
772 (js2-deflocal js2-compiler-use-dynamic-scope nil)
773 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
774 (js2-deflocal js2-compiler-xml-available t)
775 (js2-deflocal js2-compiler-optimization-level 0)
776 (js2-deflocal js2-compiler-generating-source t)
777 (js2-deflocal js2-compiler-strict-mode nil)
778 (js2-deflocal js2-compiler-report-warning-as-error nil)
779 (js2-deflocal js2-compiler-generate-observer-count nil)
780 (js2-deflocal js2-compiler-activation-names nil)
784 ;; There's a compileFunction method in Context.java - may need it.
785 (js2-deflocal js2-called-by-compile-function nil
786 "True if `js2-parse' was called by `js2-compile-function'.
787 Will only be used when we finish implementing the interpreter.")
789 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
791 (js2-deflocal js2-current-flagged-token js2-EOF)
792 (js2-deflocal js2-current-token js2-EOF)
794 ;; SKIP: node factory - we're going to just call functions directly,
795 ;; and eventually go to a unified AST format.
797 (js2-deflocal js2-nesting-of-function 0)
799 (js2-deflocal js2-recorded-identifiers nil
800 "Tracks identifiers found during parsing.")
802 (defmacro js2-in-lhs (body)
803 `(let ((js2-is-in-lhs t))
806 (defmacro js2-in-rhs (body)
807 `(let ((js2-is-in-lhs nil))
810 (js2-deflocal js2-is-in-lhs nil
811 "True while parsing lhs statement")
813 (defcustom js2-global-externs nil
814 "A list of any extern names you'd like to consider always declared.
815 This list is global and is used by all `js2-mode' files.
816 You can create buffer-local externs list using `js2-additional-externs'.
818 There is also a buffer-local variable `js2-default-externs',
819 which is initialized by default to include the Ecma-262 externs
820 and the standard browser externs. The three lists are all
821 checked during highlighting."
825 (js2-deflocal js2-default-externs nil
826 "Default external declarations.
828 These are currently only used for highlighting undeclared variables,
829 which only worries about top-level (unqualified) references.
830 As js2-mode's processing improves, we will flesh out this list.
832 The initial value is set to `js2-ecma-262-externs', unless you
833 have set `js2-include-browser-externs', in which case the browser
834 externs are also included.
836 See `js2-additional-externs' for more information.")
838 (defcustom js2-include-browser-externs t
839 "Non-nil to include browser externs in the master externs list.
840 If you work on JavaScript files that are not intended for browsers,
841 such as Mozilla Rhino server-side JavaScript, set this to nil.
842 You can always include them on a per-file basis by calling
843 `js2-add-browser-externs' from a function on `js2-mode-hook'.
845 See `js2-additional-externs' for more information about externs."
849 (defcustom js2-include-rhino-externs t
850 "Non-nil to include Mozilla Rhino externs in the master externs list.
851 See `js2-additional-externs' for more information about externs."
855 (defcustom js2-include-gears-externs t
856 "Non-nil to include Google Gears externs in the master externs list.
857 See `js2-additional-externs' for more information about externs."
861 (js2-deflocal js2-additional-externs nil
862 "A buffer-local list of additional external declarations.
863 It is used to decide whether variables are considered undeclared
864 for purposes of highlighting.
866 Each entry is a Lisp string. The string should be the fully qualified
867 name of an external entity. All externs should be added to this list,
868 so that as js2-mode's processing improves it can take advantage of them.
870 You may want to declare your externs in three ways.
871 First, you can add externs that are valid for all your JavaScript files.
872 You should probably do this by adding them to `js2-global-externs', which
873 is a global list used for all js2-mode files.
875 Next, you can add a function to `js2-mode-hook' that adds additional
876 externs appropriate for the specific file, perhaps based on its path.
877 These should go in `js2-additional-externs', which is buffer-local.
879 Finally, you can add a function to `js2-post-parse-callbacks',
880 which is called after parsing completes, and `root' is bound to
881 the root of the parse tree. At this stage you can set up an AST
882 node visitor using `js2-visit-ast' and examine the parse tree
883 for specific import patterns that may imply the existence of
884 other externs, possibly tied to your build system. These should also
885 be added to `js2-additional-externs'.
887 Your post-parse callback may of course also use the simpler and
888 faster (but perhaps less robust) approach of simply scanning the
889 buffer text for your imports, using regular expressions.")
892 ;; SKIP: encoded-source
894 ;;; The following variables are per-function and should be saved/restored
895 ;;; during function parsing...
897 (js2-deflocal js2-current-script-or-fn nil)
898 (js2-deflocal js2-current-scope nil)
899 (js2-deflocal js2-nesting-of-with 0)
900 (js2-deflocal js2-label-set nil
901 "An alist mapping label names to nodes.")
903 (js2-deflocal js2-loop-set nil)
904 (js2-deflocal js2-loop-and-switch-set nil)
905 (js2-deflocal js2-has-return-value nil)
906 (js2-deflocal js2-end-flags 0)
908 ;;; ...end of per function variables
910 ;; Without 2-token lookahead, labels are a problem.
911 ;; These vars store the token info of the last matched name,
912 ;; iff it wasn't the last matched token. Only valid in some contexts.
913 (defvar js2-prev-name-token-start nil)
914 (defvar js2-prev-name-token-string nil)
916 (defsubst js2-save-name-token-data (pos name)
917 (setq js2-prev-name-token-start pos
918 js2-prev-name-token-string name))
920 ;; These flags enumerate the possible ways a statement/function can
921 ;; terminate. These flags are used by endCheck() and by the Parser to
922 ;; detect inconsistent return usage.
924 ;; END_UNREACHED is reserved for code paths that are assumed to always be
925 ;; able to execute (example: throw, continue)
927 ;; END_DROPS_OFF indicates if the statement can transfer control to the
928 ;; next one. Statement such as return dont. A compound statement may have
929 ;; some branch that drops off control to the next statement.
931 ;; END_RETURNS indicates that the statement can return (without arguments)
932 ;; END_RETURNS_VALUE indicates that the statement can return a value.
934 ;; A compound statement such as
938 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
940 (defconst js2-end-unreached #x0)
941 (defconst js2-end-drops-off #x1)
942 (defconst js2-end-returns #x2)
943 (defconst js2-end-returns-value #x4)
944 (defconst js2-end-yields #x8)
946 ;; Rhino awkwardly passes a statementLabel parameter to the
947 ;; statementHelper() function, the main statement parser, which
948 ;; is then used by quite a few of the sub-parsers. We just make
949 ;; it a buffer-local variable and make sure it's cleaned up properly.
950 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
952 ;; Similarly, Rhino passes an inForInit boolean through about half
953 ;; the expression parsers. We use a dynamically-scoped variable,
954 ;; which makes it easier to funcall the parsers individually without
955 ;; worrying about whether they take the parameter or not.
956 (js2-deflocal js2-in-for-init nil)
957 (js2-deflocal js2-temp-name-counter 0)
958 (js2-deflocal js2-parse-stmt-count 0)
960 (defsubst js2-get-next-temp-name ()
961 (format "$%d" (incf js2-temp-name-counter)))
963 (defvar js2-parse-interruptable-p t
964 "Set this to nil to force parse to continue until finished.
965 This will mostly be useful for interpreters.")
967 (defvar js2-statements-per-pause 50
968 "Pause after this many statements to check for user input.
969 If user input is pending, stop the parse and discard the tree.
970 This makes for a smoother user experience for large files.
971 You may have to wait a second or two before the highlighting
972 and error-reporting appear, but you can always type ahead if
973 you wish. This appears to be more or less how Eclipse, IntelliJ
974 and other editors work.")
976 (js2-deflocal js2-record-comments t
977 "Instructs the scanner to record comments in `js2-scanned-comments'.")
979 (js2-deflocal js2-scanned-comments nil
980 "List of all comments from the current parse.")
982 (defcustom js2-mode-indent-inhibit-undo nil
983 "Non-nil to disable collection of Undo information when indenting lines.
984 Some users have requested this behavior. It's nil by default because
985 other Emacs modes don't work this way."
989 (defcustom js2-mode-indent-ignore-first-tab nil
990 "If non-nil, ignore first TAB keypress if we look indented properly.
991 It's fairly common for users to navigate to an already-indented line
992 and press TAB for reassurance that it's been indented. For this class
993 of users, we want the first TAB press on a line to be ignored if the
994 line is already indented to one of the precomputed alternatives.
996 This behavior is only partly implemented. If you TAB-indent a line,
997 navigate to another line, and then navigate back, it fails to clear
998 the last-indented variable, so it thinks you've already hit TAB once,
999 and performs the indent. A full solution would involve getting on the
1000 point-motion hooks for the entire buffer. If we come across another
1001 use cases that requires watching point motion, I'll consider doing it.
1003 If you set this variable to nil, then the TAB key will always change
1004 the indentation of the current line, if more than one alternative
1005 indentation spot exists."
1009 (defvar js2-indent-hook nil
1010 "A hook for user-defined indentation rules.
1012 Functions on this hook should expect two arguments: (LIST INDEX)
1013 The LIST argument is the list of computed indentation points for
1014 the current line. INDEX is the list index of the indentation point
1015 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1016 indent function is not going to change the current line indentation.
1018 If a hook function on this list returns a non-nil value, then
1019 `js2-bounce-indent' assumes the hook function has performed its own
1020 indentation, and will do nothing. If all hook functions on the list
1021 return nil, then `js2-bounce-indent' will use its computed indentation
1022 and reindent the line.
1024 When hook functions on this hook list are called, the variable
1025 `js2-mode-ast' may or may not be set, depending on whether the
1026 parse tree is available. If the variable is nil, you can pass a
1027 callback to `js2-mode-wait-for-parse', and your callback will be
1028 called after the new parse tree is built. This can take some time
1031 (defface js2-warning
1032 `((((class color) (background light))
1033 (:underline "orange"))
1034 (((class color) (background dark))
1035 (:underline "orange"))
1037 "Face for JavaScript warnings."
1041 `((((class color) (background light))
1042 (:foreground "red"))
1043 (((class color) (background dark))
1044 (:foreground "red"))
1045 (t (:foreground "red")))
1046 "Face for JavaScript errors."
1049 (defface js2-jsdoc-tag
1050 '((t :foreground "SlateGray"))
1051 "Face used to highlight @whatever tags in jsdoc comments."
1054 (defface js2-jsdoc-type
1055 '((t :foreground "SteelBlue"))
1056 "Face used to highlight {FooBar} types in jsdoc comments."
1059 (defface js2-jsdoc-value
1060 '((t :foreground "PeachPuff3"))
1061 "Face used to highlight tag values in jsdoc comments."
1064 (defface js2-function-param
1065 '((t :foreground "SeaGreen"))
1066 "Face used to highlight function parameters in javascript."
1069 (defface js2-instance-member
1070 '((t :foreground "DarkOrchid"))
1071 "Face used to highlight instance variables in javascript.
1072 Not currently used."
1075 (defface js2-private-member
1076 '((t :foreground "PeachPuff3"))
1077 "Face used to highlight calls to private methods in javascript.
1078 Not currently used."
1081 (defface js2-private-function-call
1082 '((t :foreground "goldenrod"))
1083 "Face used to highlight calls to private functions in javascript.
1084 Not currently used."
1087 (defface js2-jsdoc-html-tag-name
1088 '((((class color) (min-colors 88) (background light))
1089 (:foreground "rosybrown"))
1090 (((class color) (min-colors 8) (background dark))
1091 (:foreground "yellow"))
1092 (((class color) (min-colors 8) (background light))
1093 (:foreground "magenta")))
1094 "Face used to highlight jsdoc html tag names"
1097 (defface js2-jsdoc-html-tag-delimiter
1098 '((((class color) (min-colors 88) (background light))
1099 (:foreground "dark khaki"))
1100 (((class color) (min-colors 8) (background dark))
1101 (:foreground "green"))
1102 (((class color) (min-colors 8) (background light))
1103 (:foreground "green")))
1104 "Face used to highlight brackets in jsdoc html tags."
1108 (defcustom js2-post-parse-callbacks nil
1109 "A list of callback functions invoked after parsing finishes.
1110 Currently, the main use for this function is to add synthetic
1111 declarations to `js2-recorded-identifiers', which see."
1115 (defcustom js2-highlight-external-variables t
1116 "Non-nil to highlight undeclared variable identifiers.
1117 An undeclared variable is any variable not declared with var or let
1118 in the current scope or any lexically enclosing scope. If you use
1119 such a variable, then you are either expecting it to originate from
1120 another file, or you've got a potential bug."
1124 (defcustom js2-auto-insert-catch-block t
1125 "Non-nil to insert matching catch block on open-curly after `try'."
1129 (defvar js2-mode-map
1130 (let ((map (make-sparse-keymap))
1132 (define-key map [mouse-1] #'js2-mode-show-node)
1133 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1134 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1135 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1136 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1137 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1138 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1139 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1140 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1141 (when js2-bounce-indent-p
1142 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1144 (define-key map [menu-bar javascript]
1145 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1147 (define-key map [menu-bar javascript customize-js2-mode]
1148 '(menu-item "Customize js2-mode" js2-mode-customize
1149 :help "Customize the behavior of this mode"))
1151 (define-key map [menu-bar javascript js2-force-refresh]
1152 '(menu-item "Force buffer refresh" js2-mode-reset
1153 :help "Re-parse the buffer from scratch"))
1155 (define-key map [menu-bar javascript separator-2]
1158 (define-key map [menu-bar javascript next-error]
1159 '(menu-item "Next warning or error" next-error
1160 :enabled (and js2-mode-ast
1161 (or (js2-ast-root-errors js2-mode-ast)
1162 (js2-ast-root-warnings js2-mode-ast)))
1163 :help "Move to next warning or error"))
1165 (define-key map [menu-bar javascript display-errors]
1166 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1167 :visible (not js2-mode-show-parse-errors)
1168 :help "Turn on display of warnings and errors"))
1170 (define-key map [menu-bar javascript hide-errors]
1171 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1172 :visible js2-mode-show-parse-errors
1173 :help "Turn off display of warnings and errors"))
1175 (define-key map [menu-bar javascript separator-1]
1178 (define-key map [menu-bar javascript js2-toggle-function]
1179 '(menu-item "Show/collapse element" js2-mode-toggle-element
1180 :help "Hide or show function body or comment"))
1182 (define-key map [menu-bar javascript show-comments]
1183 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1184 :visible js2-mode-comments-hidden
1185 :help "Expand all hidden block comments"))
1187 (define-key map [menu-bar javascript hide-comments]
1188 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1189 :visible (not js2-mode-comments-hidden)
1190 :help "Show block comments as /*...*/"))
1192 (define-key map [menu-bar javascript show-all-functions]
1193 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1194 :visible js2-mode-functions-hidden
1195 :help "Expand all hidden function bodies"))
1197 (define-key map [menu-bar javascript hide-all-functions]
1198 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1199 :visible (not js2-mode-functions-hidden)
1200 :help "Show {...} for all top-level function bodies"))
1203 "Keymap used in `js2-mode' buffers.")
1205 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1207 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1208 "Matches a //-comment line. Must be first non-whitespace on line.
1209 First match-group is the leading whitespace.")
1211 (defvar js2-mode-hook nil)
1213 (js2-deflocal js2-mode-ast nil "Private variable.")
1214 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1215 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1216 (js2-deflocal js2-mode-parsing nil "Private variable.")
1217 (js2-deflocal js2-mode-node-overlay nil)
1219 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1220 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1222 (js2-deflocal js2-mode-fontifications nil "Private variable")
1223 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1224 (js2-deflocal js2-imenu-recorder nil "Private variable")
1225 (js2-deflocal js2-imenu-function-map nil "Private variable")
1227 (defvar js2-paragraph-start
1228 "\\(@[a-zA-Z]+\\>\\|$\\)")
1230 ;; Note that we also set a 'c-in-sws text property in html comments,
1231 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1232 (defvar js2-syntactic-ws-start
1233 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1235 (defvar js2-syntactic-ws-end
1236 "\\s \\|[\n\r/]\\|\\s!")
1238 (defvar js2-syntactic-eol
1239 (concat "\\s *\\(/\\*[^*\n\r]*"
1240 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1242 "\\(//\\|/\\*[^*\n\r]*"
1243 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1245 "Copied from `java-mode'. Needed for some cc-engine functions.")
1247 (defvar js2-comment-prefix-regexp
1250 (defvar js2-comment-start-skip
1251 "\\(//+\\|/\\*+\\)\\s *")
1253 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1254 "Non-nil to emit status messages during parsing.")
1256 (defvar js2-mode-functions-hidden nil "Private variable.")
1257 (defvar js2-mode-comments-hidden nil "Private variable.")
1259 (defvar js2-mode-syntax-table
1260 (let ((table (make-syntax-table)))
1261 (c-populate-syntax-table table)
1263 "Syntax table used in `js2-mode' buffers.")
1265 (defvar js2-mode-abbrev-table nil
1266 "Abbrev table in use in `js2-mode' buffers.")
1267 (define-abbrev-table 'js2-mode-abbrev-table ())
1269 (defvar js2-mode-pending-parse-callbacks nil
1270 "List of functions waiting to be notified that parse is finished.")
1272 (defvar js2-mode-last-indented-line -1)
1274 ;;; Localizable error and warning messages
1276 ;; Messages are copied from Rhino's Messages.properties.
1277 ;; Many of the Java-specific messages have been elided.
1278 ;; Add any js2-specific ones at the end, so we can keep
1279 ;; this file synced with changes to Rhino's.
1281 (defvar js2-message-table
1282 (make-hash-table :test 'equal :size 250)
1283 "Contains localized messages for `js2-mode'.")
1285 ;; TODO(stevey): construct this table at compile-time.
1286 (defmacro js2-msg (key &rest strings)
1287 `(puthash ,key (funcall #'concat ,@strings)
1290 (defun js2-get-msg (msg-key)
1291 "Look up a localized message.
1292 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1293 the correct number of ARGS must be provided."
1294 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1295 (args (if (listp msg-key) (cdr msg-key)))
1296 (msg (gethash key js2-message-table)))
1298 (apply #'format msg args)
1299 key))) ; default to showing the key
1301 (js2-msg "msg.dup.parms"
1302 "Duplicate parameter name '%s'.")
1304 (js2-msg "msg.too.big.jump"
1305 "Program too complex: jump offset too big.")
1307 (js2-msg "msg.too.big.index"
1308 "Program too complex: internal index exceeds 64K limit.")
1310 (js2-msg "msg.while.compiling.fn"
1311 "Encountered code generation error while compiling function '%s': %s")
1313 (js2-msg "msg.while.compiling.script"
1314 "Encountered code generation error while compiling script: %s")
1317 (js2-msg "msg.ctor.not.found"
1318 "Constructor for '%s' not found.")
1320 (js2-msg "msg.not.ctor"
1321 "'%s' is not a constructor.")
1324 (js2-msg "msg.varargs.ctor"
1325 "Method or constructor '%s' must be static "
1326 "with the signature (Context cx, Object[] args, "
1327 "Function ctorObj, boolean inNewExpr) "
1328 "to define a variable arguments constructor.")
1330 (js2-msg "msg.varargs.fun"
1331 "Method '%s' must be static with the signature "
1332 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1333 "to define a variable arguments function.")
1335 (js2-msg "msg.incompat.call"
1336 "Method '%s' called on incompatible object.")
1338 (js2-msg "msg.bad.parms"
1339 "Unsupported parameter type '%s' in method '%s'.")
1341 (js2-msg "msg.bad.method.return"
1342 "Unsupported return type '%s' in method '%s'.")
1344 (js2-msg "msg.bad.ctor.return"
1345 "Construction of objects of type '%s' is not supported.")
1347 (js2-msg "msg.no.overload"
1348 "Method '%s' occurs multiple times in class '%s'.")
1350 (js2-msg "msg.method.not.found"
1351 "Method '%s' not found in '%s'.")
1355 (js2-msg "msg.bad.for.in.lhs"
1356 "Invalid left-hand side of for..in loop.")
1358 (js2-msg "msg.mult.index"
1359 "Only one variable allowed in for..in loop.")
1361 (js2-msg "msg.bad.for.in.destruct"
1362 "Left hand side of for..in loop must be an array of "
1363 "length 2 to accept key/value pair.")
1365 (js2-msg "msg.cant.convert"
1366 "Can't convert to type '%s'.")
1368 (js2-msg "msg.bad.assign.left"
1369 "Invalid assignment left-hand side.")
1371 (js2-msg "msg.bad.decr"
1372 "Invalid decerement operand.")
1374 (js2-msg "msg.bad.incr"
1375 "Invalid increment operand.")
1377 (js2-msg "msg.bad.yield"
1378 "yield must be in a function.")
1380 (js2-msg "msg.yield.parenthesized"
1381 "yield expression must be parenthesized.")
1384 (js2-msg "msg.cant.call.indirect"
1385 "Function '%s' must be called directly, and not by way of a "
1386 "function of another name.")
1388 (js2-msg "msg.eval.nonstring"
1389 "Calling eval() with anything other than a primitive "
1390 "string value will simply return the value. "
1391 "Is this what you intended?")
1393 (js2-msg "msg.eval.nonstring.strict"
1394 "Calling eval() with anything other than a primitive "
1395 "string value is not allowed in strict mode.")
1397 (js2-msg "msg.bad.destruct.op"
1398 "Invalid destructuring assignment operator")
1401 (js2-msg "msg.only.from.new"
1402 "'%s' may only be invoked from a `new' expression.")
1404 (js2-msg "msg.deprec.ctor"
1405 "The '%s' constructor is deprecated.")
1408 (js2-msg "msg.no.function.ref.found"
1409 "no source found to decompile function reference %s")
1411 (js2-msg "msg.arg.isnt.array"
1412 "second argument to Function.prototype.apply must be an array")
1415 (js2-msg "msg.bad.esc.mask"
1416 "invalid string escape mask")
1419 (js2-msg "msg.bad.quant"
1420 "Invalid quantifier %s")
1422 (js2-msg "msg.overlarge.backref"
1423 "Overly large back reference %s")
1425 (js2-msg "msg.overlarge.min"
1426 "Overly large minimum %s")
1428 (js2-msg "msg.overlarge.max"
1429 "Overly large maximum %s")
1431 (js2-msg "msg.zero.quant"
1432 "Zero quantifier %s")
1434 (js2-msg "msg.max.lt.min"
1435 "Maximum %s less than minimum")
1437 (js2-msg "msg.unterm.quant"
1438 "Unterminated quantifier %s")
1440 (js2-msg "msg.unterm.paren"
1441 "Unterminated parenthetical %s")
1443 (js2-msg "msg.unterm.class"
1444 "Unterminated character class %s")
1446 (js2-msg "msg.bad.range"
1447 "Invalid range in character class.")
1449 (js2-msg "msg.trail.backslash"
1450 "Trailing \\ in regular expression.")
1452 (js2-msg "msg.re.unmatched.right.paren"
1453 "unmatched ) in regular expression.")
1455 (js2-msg "msg.no.regexp"
1456 "Regular expressions are not available.")
1458 (js2-msg "msg.bad.backref"
1459 "back-reference exceeds number of capturing parentheses.")
1461 (js2-msg "msg.bad.regexp.compile"
1462 "Only one argument may be specified if the first "
1463 "argument to RegExp.prototype.compile is a RegExp object.")
1466 (js2-msg "msg.got.syntax.errors"
1467 "Compilation produced %s syntax errors.")
1469 (js2-msg "msg.var.redecl"
1470 "TypeError: redeclaration of var %s.")
1472 (js2-msg "msg.const.redecl"
1473 "TypeError: redeclaration of const %s.")
1475 (js2-msg "msg.let.redecl"
1476 "TypeError: redeclaration of variable %s.")
1478 (js2-msg "msg.parm.redecl"
1479 "TypeError: redeclaration of formal parameter %s.")
1481 (js2-msg "msg.fn.redecl"
1482 "TypeError: redeclaration of function %s.")
1484 (js2-msg "msg.let.decl.not.in.block"
1485 "SyntaxError: let declaration not directly within block")
1488 (js2-msg "msg.dup.label"
1491 (js2-msg "msg.undef.label"
1494 (js2-msg "msg.bad.break"
1495 "unlabelled break must be inside loop or switch")
1497 (js2-msg "msg.continue.outside"
1498 "continue must be inside loop")
1500 (js2-msg "msg.continue.nonloop"
1501 "continue can only use labels of iteration statements")
1503 (js2-msg "msg.bad.throw.eol"
1504 "Line terminator is not allowed between the throw "
1505 "keyword and throw expression.")
1507 (js2-msg "msg.no.paren.parms"
1508 "missing ( before function parameters.")
1510 (js2-msg "msg.no.parm"
1511 "missing formal parameter")
1513 (js2-msg "msg.no.paren.after.parms"
1514 "missing ) after formal parameters")
1516 (js2-msg "msg.no.brace.body"
1517 "missing '{' before function body")
1519 (js2-msg "msg.no.brace.after.body"
1520 "missing } after function body")
1522 (js2-msg "msg.no.paren.cond"
1523 "missing ( before condition")
1525 (js2-msg "msg.no.paren.after.cond"
1526 "missing ) after condition")
1528 (js2-msg "msg.no.semi.stmt"
1529 "missing ; before statement")
1531 (js2-msg "msg.missing.semi"
1532 "missing ; after statement")
1534 (js2-msg "msg.no.name.after.dot"
1535 "missing name after . operator")
1537 (js2-msg "msg.no.name.after.coloncolon"
1538 "missing name after :: operator")
1540 (js2-msg "msg.no.name.after.dotdot"
1541 "missing name after .. operator")
1543 (js2-msg "msg.no.name.after.xmlAttr"
1544 "missing name after .@")
1546 (js2-msg "msg.no.bracket.index"
1547 "missing ] in index expression")
1549 (js2-msg "msg.no.paren.switch"
1550 "missing ( before switch expression")
1552 (js2-msg "msg.no.paren.after.switch"
1553 "missing ) after switch expression")
1555 (js2-msg "msg.no.brace.switch"
1556 "missing '{' before switch body")
1558 (js2-msg "msg.bad.switch"
1559 "invalid switch statement")
1561 (js2-msg "msg.no.colon.case"
1562 "missing : after case expression")
1564 (js2-msg "msg.double.switch.default"
1565 "double default label in the switch statement")
1567 (js2-msg "msg.no.while.do"
1568 "missing while after do-loop body")
1570 (js2-msg "msg.no.paren.for"
1571 "missing ( after for")
1573 (js2-msg "msg.no.semi.for"
1574 "missing ; after for-loop initializer")
1576 (js2-msg "msg.no.semi.for.cond"
1577 "missing ; after for-loop condition")
1579 (js2-msg "msg.in.after.for.name"
1580 "missing in after for")
1582 (js2-msg "msg.no.paren.for.ctrl"
1583 "missing ) after for-loop control")
1585 (js2-msg "msg.no.paren.with"
1586 "missing ( before with-statement object")
1588 (js2-msg "msg.no.paren.after.with"
1589 "missing ) after with-statement object")
1591 (js2-msg "msg.no.paren.after.let"
1592 "missing ( after let")
1594 (js2-msg "msg.no.paren.let"
1595 "missing ) after variable list")
1597 (js2-msg "msg.no.curly.let"
1598 "missing } after let statement")
1600 (js2-msg "msg.bad.return"
1603 (js2-msg "msg.no.brace.block"
1604 "missing } in compound statement")
1606 (js2-msg "msg.bad.label"
1609 (js2-msg "msg.bad.var"
1610 "missing variable name")
1612 (js2-msg "msg.bad.var.init"
1613 "invalid variable initialization")
1615 (js2-msg "msg.no.colon.cond"
1616 "missing : in conditional expression")
1618 (js2-msg "msg.no.paren.arg"
1619 "missing ) after argument list")
1621 (js2-msg "msg.no.bracket.arg"
1622 "missing ] after element list")
1624 (js2-msg "msg.bad.prop"
1625 "invalid property id")
1627 (js2-msg "msg.no.colon.prop"
1628 "missing : after property id")
1630 (js2-msg "msg.no.brace.prop"
1631 "missing } after property list")
1633 (js2-msg "msg.no.paren"
1634 "missing ) in parenthetical")
1636 (js2-msg "msg.reserved.id"
1637 "identifier is a reserved word")
1639 (js2-msg "msg.no.paren.catch"
1640 "missing ( before catch-block condition")
1642 (js2-msg "msg.bad.catchcond"
1643 "invalid catch block condition")
1645 (js2-msg "msg.catch.unreachable"
1646 "any catch clauses following an unqualified catch are unreachable")
1648 (js2-msg "msg.no.brace.try"
1649 "missing '{' before try block")
1651 (js2-msg "msg.no.brace.catchblock"
1652 "missing '{' before catch-block body")
1654 (js2-msg "msg.try.no.catchfinally"
1655 "'try' without 'catch' or 'finally'")
1657 (js2-msg "msg.no.return.value"
1658 "function %s does not always return a value")
1660 (js2-msg "msg.anon.no.return.value"
1661 "anonymous function does not always return a value")
1663 (js2-msg "msg.return.inconsistent"
1664 "return statement is inconsistent with previous usage")
1666 (js2-msg "msg.generator.returns"
1667 "TypeError: generator function '%s' returns a value")
1669 (js2-msg "msg.anon.generator.returns"
1670 "TypeError: anonymous generator function returns a value")
1672 (js2-msg "msg.syntax"
1675 (js2-msg "msg.unexpected.eof"
1676 "Unexpected end of file")
1678 (js2-msg "msg.XML.bad.form"
1679 "illegally formed XML syntax")
1681 (js2-msg "msg.XML.not.available"
1682 "XML runtime not available")
1684 (js2-msg "msg.too.deep.parser.recursion"
1685 "Too deep recursion while parsing")
1687 (js2-msg "msg.no.side.effects"
1688 "Code has no side effects")
1690 (js2-msg "msg.extra.trailing.comma"
1691 "Trailing comma is not legal in an ECMA-262 object initializer")
1693 (js2-msg "msg.array.trailing.comma"
1694 "Trailing comma yields different behavior across browsers")
1696 (js2-msg "msg.equal.as.assign"
1697 (concat "Test for equality (==) mistyped as assignment (=)?"
1698 " (parenthesize to suppress warning)"))
1700 (js2-msg "msg.var.hides.arg"
1701 "Variable %s hides argument")
1703 (js2-msg "msg.destruct.assign.no.init"
1704 "Missing = in destructuring declaration")
1707 (js2-msg "msg.no.properties"
1708 "%s has no properties.")
1710 (js2-msg "msg.invalid.iterator"
1711 "Invalid iterator value")
1713 (js2-msg "msg.iterator.primitive"
1714 "__iterator__ returned a primitive value")
1716 (js2-msg "msg.assn.create.strict"
1717 "Assignment to undeclared variable %s")
1719 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1720 "Undeclared variable or function '%s'")
1722 (js2-msg "msg.ref.undefined.prop"
1723 "Reference to undefined property '%s'")
1725 (js2-msg "msg.prop.not.found"
1726 "Property %s not found.")
1728 (js2-msg "msg.invalid.type"
1729 "Invalid JavaScript value of type %s")
1731 (js2-msg "msg.primitive.expected"
1732 "Primitive type expected (had %s instead)")
1734 (js2-msg "msg.namespace.expected"
1735 "Namespace object expected to left of :: (found %s instead)")
1737 (js2-msg "msg.null.to.object"
1738 "Cannot convert null to an object.")
1740 (js2-msg "msg.undef.to.object"
1741 "Cannot convert undefined to an object.")
1743 (js2-msg "msg.cyclic.value"
1744 "Cyclic %s value not allowed.")
1746 (js2-msg "msg.is.not.defined"
1747 "'%s' is not defined.")
1749 (js2-msg "msg.undef.prop.read"
1750 "Cannot read property '%s' from %s")
1752 (js2-msg "msg.undef.prop.write"
1753 "Cannot set property '%s' of %s to '%s'")
1755 (js2-msg "msg.undef.prop.delete"
1756 "Cannot delete property '%s' of %s")
1758 (js2-msg "msg.undef.method.call"
1759 "Cannot call method '%s' of %s")
1761 (js2-msg "msg.undef.with"
1762 "Cannot apply 'with' to %s")
1764 (js2-msg "msg.isnt.function"
1765 "%s is not a function, it is %s.")
1767 (js2-msg "msg.isnt.function.in"
1768 "Cannot call property %s in object %s. "
1769 "It is not a function, it is '%s'.")
1771 (js2-msg "msg.function.not.found"
1772 "Cannot find function %s.")
1774 (js2-msg "msg.function.not.found.in"
1775 "Cannot find function %s in object %s.")
1777 (js2-msg "msg.isnt.xml.object"
1778 "%s is not an xml object.")
1780 (js2-msg "msg.no.ref.to.get"
1781 "%s is not a reference to read reference value.")
1783 (js2-msg "msg.no.ref.to.set"
1784 "%s is not a reference to set reference value to %s.")
1786 (js2-msg "msg.no.ref.from.function"
1787 "Function %s can not be used as the left-hand "
1788 "side of assignment or as an operand of ++ or -- operator.")
1790 (js2-msg "msg.bad.default.value"
1791 "Object's getDefaultValue() method returned an object.")
1793 (js2-msg "msg.instanceof.not.object"
1794 "Can't use instanceof on a non-object.")
1796 (js2-msg "msg.instanceof.bad.prototype"
1797 "'prototype' property of %s is not an object.")
1799 (js2-msg "msg.bad.radix"
1800 "illegal radix %s.")
1803 (js2-msg "msg.default.value"
1804 "Cannot find default value for object.")
1806 (js2-msg "msg.zero.arg.ctor"
1807 "Cannot load class '%s' which has no zero-parameter constructor.")
1809 (js2-msg "msg.ctor.multiple.parms"
1810 "Can't define constructor or class %s since more than "
1811 "one constructor has multiple parameters.")
1813 (js2-msg "msg.extend.scriptable"
1814 "%s must extend ScriptableObject in order to define property %s.")
1816 (js2-msg "msg.bad.getter.parms"
1817 "In order to define a property, getter %s must have zero "
1818 "parameters or a single ScriptableObject parameter.")
1820 (js2-msg "msg.obj.getter.parms"
1821 "Expected static or delegated getter %s to take "
1822 "a ScriptableObject parameter.")
1824 (js2-msg "msg.getter.static"
1825 "Getter and setter must both be static or neither be static.")
1827 (js2-msg "msg.setter.return"
1828 "Setter must have void return type: %s")
1830 (js2-msg "msg.setter2.parms"
1831 "Two-parameter setter must take a ScriptableObject as "
1832 "its first parameter.")
1834 (js2-msg "msg.setter1.parms"
1835 "Expected single parameter setter for %s")
1837 (js2-msg "msg.setter2.expected"
1838 "Expected static or delegated setter %s to take two parameters.")
1840 (js2-msg "msg.setter.parms"
1841 "Expected either one or two parameters for setter.")
1843 (js2-msg "msg.setter.bad.type"
1844 "Unsupported parameter type '%s' in setter '%s'.")
1846 (js2-msg "msg.add.sealed"
1847 "Cannot add a property to a sealed object: %s.")
1849 (js2-msg "msg.remove.sealed"
1850 "Cannot remove a property from a sealed object: %s.")
1852 (js2-msg "msg.modify.sealed"
1853 "Cannot modify a property of a sealed object: %s.")
1855 (js2-msg "msg.modify.readonly"
1856 "Cannot modify readonly property: %s.")
1859 (js2-msg "msg.missing.exponent"
1862 (js2-msg "msg.caught.nfe"
1863 "number format error")
1865 (js2-msg "msg.unterminated.string.lit"
1866 "unterminated string literal")
1868 (js2-msg "msg.unterminated.comment"
1869 "unterminated comment")
1871 (js2-msg "msg.unterminated.re.lit"
1872 "unterminated regular expression literal")
1874 (js2-msg "msg.invalid.re.flag"
1875 "invalid flag after regular expression")
1877 (js2-msg "msg.no.re.input.for"
1880 (js2-msg "msg.illegal.character"
1881 "illegal character")
1883 (js2-msg "msg.invalid.escape"
1884 "invalid Unicode escape sequence")
1886 (js2-msg "msg.bad.namespace"
1887 "not a valid default namespace statement. "
1888 "Syntax is: default xml namespace = EXPRESSION;")
1890 ;; TokensStream warnings
1891 (js2-msg "msg.bad.octal.literal"
1892 "illegal octal literal digit %s; "
1893 "interpreting it as a decimal digit")
1895 (js2-msg "msg.reserved.keyword"
1896 "illegal usage of future reserved keyword %s; "
1897 "interpreting it as ordinary identifier")
1899 (js2-msg "msg.script.is.not.constructor"
1900 "Script objects are not constructors.")
1903 (js2-msg "msg.arraylength.bad"
1904 "Inappropriate array length.")
1907 (js2-msg "msg.arraylength.too.big"
1908 "Array length %s exceeds supported capacity limit.")
1911 (js2-msg "msg.bad.uri"
1912 "Malformed URI sequence.")
1915 (js2-msg "msg.bad.precision"
1916 "Precision %s out of range.")
1919 (js2-msg "msg.send.newborn"
1920 "Attempt to send value to newborn generator")
1922 (js2-msg "msg.already.exec.gen"
1923 "Already executing generator")
1925 (js2-msg "msg.StopIteration.invalid"
1926 "StopIteration may not be changed to an arbitrary object.")
1929 (js2-msg "msg.yield.closing"
1930 "Yield from closing generator")
1934 (defun js2-delete-if (predicate list)
1935 "Remove all items satisfying PREDICATE in LIST."
1936 (loop for item in list
1937 if (not (funcall predicate item))
1940 (defun js2-position (element list)
1941 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1942 Returns nil if element is not found in the list."
1945 (while (and list (not found))
1946 (if (eq element (car list))
1948 (setq count (1+ count)
1952 (defun js2-find-if (predicate list)
1953 "Find first item satisfying PREDICATE in LIST."
1955 (while (and list (not result))
1956 (if (funcall predicate (car list))
1957 (setq result (car list)))
1958 (setq list (cdr list)))
1961 (defmacro js2-time (form)
1962 "Evaluate FORM, discard result, and return elapsed time in sec."
1964 (let ((beg (make-symbol "--js2-time-beg--"))
1965 (delta (make-symbol "--js2-time-end--")))
1966 `(let ((,beg (current-time))
1969 (/ (truncate (* (- (float-time (current-time))
1974 (defsubst js2-same-line (pos)
1975 "Return t if POS is on the same line as current point."
1976 (and (>= pos (point-at-bol))
1977 (<= pos (point-at-eol))))
1979 (defun js2-same-line-2 (p1 p2)
1980 "Return t if P1 is on the same line as P2."
1983 (js2-same-line p2)))
1985 (defun js2-code-bug ()
1986 "Signal an error when we encounter an unexpected code path."
1987 (error "failed assertion"))
1989 (defsubst js2-record-text-property (beg end prop value)
1990 "Record a text property to set when parsing finishes."
1991 (push (list beg end prop value) js2-mode-deferred-properties))
1993 ;; I'd like to associate errors with nodes, but for now the
1994 ;; easiest thing to do is get the context info from the last token.
1995 (defun js2-record-parse-error (msg &optional arg pos len)
1996 (push (list (list msg arg)
1997 (or pos js2-token-beg)
1998 (or len (- js2-token-end js2-token-beg)))
2001 (defun js2-report-error (msg &optional msg-arg pos len)
2002 "Signal a syntax error or record a parse error."
2003 (if js2-recover-from-parse-errors
2004 (js2-record-parse-error msg msg-arg pos len)
2005 (signal 'js2-syntax-error
2009 (goto-char js2-ts-cursor)
2013 (defun js2-report-warning (msg &optional msg-arg pos len)
2014 (if js2-compiler-report-warning-as-error
2015 (js2-report-error msg msg-arg pos len)
2016 (push (list (list msg msg-arg)
2017 (or pos js2-token-beg)
2018 (or len (- js2-token-end js2-token-beg)))
2019 js2-parsed-warnings)))
2021 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2022 (if js2-compiler-strict-mode
2023 (js2-report-warning msg-id msg-arg beg
2024 (and beg end (- end beg)))))
2026 (put 'js2-syntax-error 'error-conditions
2027 '(error syntax-error js2-syntax-error))
2028 (put 'js2-syntax-error 'error-message "Syntax error")
2030 (put 'js2-parse-error 'error-conditions
2031 '(error parse-error js2-parse-error))
2032 (put 'js2-parse-error 'error-message "Parse error")
2034 (defmacro js2-clear-flag (flags flag)
2035 `(setq ,flags (logand ,flags (lognot ,flag))))
2037 (defmacro js2-set-flag (flags flag)
2038 "Logical-or FLAG into FLAGS."
2039 `(setq ,flags (logior ,flags ,flag)))
2041 (defsubst js2-flag-set-p (flags flag)
2042 (/= 0 (logand flags flag)))
2044 (defsubst js2-flag-not-set-p (flags flag)
2045 (zerop (logand flags flag)))
2047 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2048 "Evaluate BODY with the _ character set to be word-syntax."
2049 (declare (indent 0) (debug t))
2050 (let ((old-syntax (make-symbol "old-syntax")))
2051 `(let ((,old-syntax (string (char-syntax ?_))))
2054 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2056 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2058 (defsubst js2-char-uppercase-p (c)
2059 "Return t if C is an uppercase character.
2060 Handles unicode and latin chars properly."
2061 (/= c (downcase c)))
2063 (defsubst js2-char-lowercase-p (c)
2064 "Return t if C is an uppercase character.
2065 Handles unicode and latin chars properly."
2068 ;;; AST struct and function definitions
2070 ;; flags for ast node property 'member-type (used for e4x operators)
2071 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2072 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2073 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2075 (defsubst js2-relpos (pos anchor)
2076 "Convert POS to be relative to ANCHOR.
2077 If POS is nil, returns nil."
2078 (and pos (- pos anchor)))
2080 (defun js2-make-pad (indent)
2083 (make-string (* indent js2-basic-offset) ? )))
2085 (defun js2-visit-ast (node callback)
2086 "Visit every node in ast NODE with visitor CALLBACK.
2088 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2089 called twice: once to visit the node, and again after all the node's
2090 children have been processed. The END-P argument is nil on the first
2091 call and non-nil on the second call. The return value of the callback
2092 affects the traversal: if non-nil, the children of NODE are processed.
2093 If the callback returns nil, or if the node has no children, then the
2094 callback is called immediately with a non-nil END-P argument.
2096 The node traversal is approximately lexical-order, although there
2097 are currently no guarantees around this."
2099 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2101 (when (funcall callback node nil)
2104 ((eq vfunc 'js2-visit-none)
2105 nil) ; don't even bother calling it
2106 ;; Each AST node type has to define a `js2-visitor' function
2107 ;; that takes a node and a callback, and calls `js2-visit-ast'
2108 ;; on each child of the node.
2110 (funcall vfunc node callback))
2112 (error "%s does not define a visitor-traversal function"
2114 ;; call the end-visit
2115 (funcall callback node t))))
2117 (defstruct (js2-node
2118 (:constructor nil)) ; abstract
2119 "Base AST node type."
2120 (type -1) ; token type
2121 (pos -1) ; start position of this AST node in parsed input
2122 (len 1) ; num characters spanned by the node
2123 props ; optional node property list (an alist)
2124 parent) ; link to parent node; null for root
2126 (defsubst js2-node-get-prop (node prop &optional default)
2127 (or (cadr (assoc prop (js2-node-props node))) default))
2129 (defsubst js2-node-set-prop (node prop value)
2130 (setf (js2-node-props node)
2131 (cons (list prop value) (js2-node-props node))))
2133 (defun js2-fixup-starts (n nodes)
2134 "Adjust the start positions of NODES to be relative to N.
2135 Any node in the list may be nil, for convenience."
2136 (dolist (node nodes)
2138 (setf (js2-node-pos node) (- (js2-node-pos node)
2139 (js2-node-pos n))))))
2141 (defun js2-node-add-children (parent &rest nodes)
2142 "Set parent node of NODES to PARENT, and return PARENT.
2143 Does nothing if we're not recording parent links.
2144 If any given node in NODES is nil, doesn't record that link."
2145 (js2-fixup-starts parent nodes)
2146 (dolist (node nodes)
2148 (setf (js2-node-parent node) parent))))
2150 ;; Non-recursive since it's called a frightening number of times.
2151 (defun js2-node-abs-pos (n)
2152 (let ((pos (js2-node-pos n)))
2153 (while (setq n (js2-node-parent n))
2154 (setq pos (+ pos (js2-node-pos n))))
2157 (defsubst js2-node-abs-end (n)
2158 "Return absolute buffer position of end of N."
2159 (+ (js2-node-abs-pos n) (js2-node-len n)))
2161 ;; It's important to make sure block nodes have a Lisp list for the
2162 ;; child nodes, to limit printing recursion depth in an AST that
2163 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2164 ;; a sufficiently large vector tree.
2166 (defstruct (js2-block-node
2169 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2174 "A block of statements."
2175 kids) ; a Lisp list of the child statement nodes
2177 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2178 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2180 (defun js2-visit-block (ast callback)
2181 "Visit the `js2-block-node' children of AST."
2182 (dolist (kid (js2-block-node-kids ast))
2183 (js2-visit-ast kid callback)))
2185 (defun js2-print-block (n i)
2186 (let ((pad (js2-make-pad i)))
2188 (dolist (kid (js2-block-node-kids n))
2189 (js2-print-ast kid (1+ i)))
2192 (defstruct (js2-scope
2193 (:include js2-block-node)
2195 (:constructor make-js2-scope (&key (type js2-BLOCK)
2199 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2200 ;; I don't have one of those handy, so I'll use an alist for now.
2201 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2202 ;; and is much lighter-weight to construct (both CPU and mem).
2203 ;; The keys are interned strings (symbols) for faster lookup.
2204 ;; Should switch to hybrid alist/hashtable eventually.
2205 symbol-table ; an alist of (symbol . js2-symbol)
2206 parent-scope ; a `js2-scope'
2207 top) ; top-level `js2-scope' (script/function)
2209 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2210 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2212 (defun js2-scope-set-parent-scope (scope parent)
2213 (setf (js2-scope-parent-scope scope) parent
2214 (js2-scope-top scope) (if (null parent)
2216 (js2-scope-top parent))))
2218 (defun js2-node-get-enclosing-scope (node)
2219 "Return the innermost `js2-scope' node surrounding NODE.
2220 Returns nil if there is no enclosing scope node."
2221 (let ((parent (js2-node-parent node)))
2222 (while (not (js2-scope-p parent))
2223 (setq parent (js2-node-parent parent)))
2226 (defun js2-get-defining-scope (scope name)
2227 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2228 Returns `js2-scope' in which NAME is defined, or nil if not found."
2229 (let ((sym (if (symbolp name)
2235 (while (and scope continue)
2236 (if (and (setq table (js2-scope-symbol-table scope))
2240 (setq scope (js2-scope-parent-scope scope))))
2243 (defun js2-scope-get-symbol (scope name)
2244 "Return symbol table entry for NAME in SCOPE.
2245 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2246 (and (js2-scope-symbol-table scope)
2247 (cdr (assq (if (symbolp name)
2250 (js2-scope-symbol-table scope)))))
2252 (defun js2-scope-put-symbol (scope name symbol)
2253 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2254 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2255 (let* ((table (js2-scope-symbol-table scope))
2256 (sym (if (symbolp name) name (intern name)))
2257 (entry (assq sym table)))
2259 (setcdr entry symbol)
2260 (push (cons sym symbol)
2261 (js2-scope-symbol-table scope)))))
2263 (defstruct (js2-symbol
2265 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2266 "A symbol table entry."
2267 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2268 ;; js2-LET, or js2-CONST
2271 ast-node) ; a `js2-node'
2273 (defstruct (js2-error-node
2275 (:constructor nil) ; silence emacs21 byte-compiler
2276 (:constructor make-js2-error-node (&key (type js2-ERROR)
2279 "AST node representing a parse error.")
2281 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2282 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2284 (defstruct (js2-script-node
2285 (:include js2-scope)
2287 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2292 functions ; Lisp list of nested functions
2293 regexps ; Lisp list of (string . flags)
2294 symbols ; alist (every symbol gets unique index)
2296 var-names ; vector of string names
2297 consts ; bool-vector matching var-decls
2298 (temp-number 0)) ; for generating temp variables
2300 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2301 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2303 (defun js2-print-script (node indent)
2304 (dolist (kid (js2-block-node-kids node))
2305 (js2-print-ast kid indent)))
2307 (defstruct (js2-ast-root
2308 (:include js2-script-node)
2310 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2314 "The root node of a js2 AST."
2315 buffer ; the source buffer from which the code was parsed
2316 comments ; a Lisp list of comments, ordered by start position
2317 errors ; a Lisp list of errors found during parsing
2318 warnings ; a Lisp list of warnings found during parsing
2319 node-count) ; number of nodes in the tree, including the root
2321 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2322 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2324 (defun js2-visit-ast-root (ast callback)
2325 (dolist (kid (js2-ast-root-kids ast))
2326 (js2-visit-ast kid callback))
2327 (dolist (comment (js2-ast-root-comments ast))
2328 (js2-visit-ast comment callback)))
2330 (defstruct (js2-comment-node
2333 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2336 (format js2-ts-comment-type))))
2337 format) ; 'line, 'block, 'jsdoc or 'html
2339 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2340 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2342 (defun js2-print-comment (n i)
2343 ;; We really ought to link end-of-line comments to their nodes.
2344 ;; Or maybe we could add a new comment type, 'endline.
2345 (insert (js2-make-pad i)
2346 (js2-node-string n)))
2348 (defstruct (js2-expr-stmt-node
2351 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2355 "An expression statement."
2358 (defsubst js2-expr-stmt-node-set-has-result (node)
2359 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2360 (setf (js2-node-type node) js2-EXPR_RESULT))
2362 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2363 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2365 (defun js2-visit-expr-stmt-node (n v)
2366 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2368 (defun js2-print-expr-stmt-node (n indent)
2369 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2372 (defstruct (js2-loop-node
2373 (:include js2-scope)
2375 "Abstract supertype of loop nodes."
2376 body ; a `js2-block-node'
2377 lp ; position of left-paren, nil if omitted
2378 rp) ; position of right-paren, nil if omitted
2380 (defstruct (js2-do-node
2381 (:include js2-loop-node)
2383 (:constructor make-js2-do-node (&key (type js2-DO)
2391 "AST node for do-loop."
2392 condition ; while (expression)
2393 while-pos) ; buffer position of 'while' keyword
2395 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2396 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2398 (defun js2-visit-do-node (n v)
2399 (js2-visit-ast (js2-do-node-body n) v)
2400 (js2-visit-ast (js2-do-node-condition n) v))
2402 (defun js2-print-do-node (n i)
2403 (let ((pad (js2-make-pad i)))
2404 (insert pad "do {\n")
2405 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2406 (js2-print-ast kid (1+ i)))
2407 (insert pad "} while (")
2408 (js2-print-ast (js2-do-node-condition n) 0)
2411 (defstruct (js2-while-node
2412 (:include js2-loop-node)
2414 (:constructor make-js2-while-node (&key (type js2-WHILE)
2419 "AST node for while-loop."
2420 condition) ; while-condition
2422 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2423 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2425 (defun js2-visit-while-node (n v)
2426 (js2-visit-ast (js2-while-node-condition n) v)
2427 (js2-visit-ast (js2-while-node-body n) v))
2429 (defun js2-print-while-node (n i)
2430 (let ((pad (js2-make-pad i)))
2431 (insert pad "while (")
2432 (js2-print-ast (js2-while-node-condition n) 0)
2434 (js2-print-body (js2-while-node-body n) (1+ i))
2435 (insert pad "}\n")))
2437 (defstruct (js2-for-node
2438 (:include js2-loop-node)
2440 (:constructor make-js2-for-node (&key (type js2-FOR)
2445 "AST node for a C-style for-loop."
2446 init ; initialization expression
2447 condition ; loop condition
2448 update) ; update clause
2450 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2451 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2453 (defun js2-visit-for-node (n v)
2454 (js2-visit-ast (js2-for-node-init n) v)
2455 (js2-visit-ast (js2-for-node-condition n) v)
2456 (js2-visit-ast (js2-for-node-update n) v)
2457 (js2-visit-ast (js2-for-node-body n) v))
2459 (defun js2-print-for-node (n i)
2460 (let ((pad (js2-make-pad i)))
2461 (insert pad "for (")
2462 (js2-print-ast (js2-for-node-init n) 0)
2464 (js2-print-ast (js2-for-node-condition n) 0)
2466 (js2-print-ast (js2-for-node-update n) 0)
2468 (js2-print-body (js2-for-node-body n) (1+ i))
2469 (insert pad "}\n")))
2471 (defstruct (js2-for-in-node
2472 (:include js2-loop-node)
2474 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2483 "AST node for a for..in loop."
2484 iterator ; [var] foo in ...
2485 object ; object over which we're iterating
2486 in-pos ; buffer position of 'in' keyword
2487 each-pos ; buffer position of 'each' keyword, if foreach-p
2488 foreach-p) ; t if it's a for-each loop
2490 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2491 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2493 (defun js2-visit-for-in-node (n v)
2494 (js2-visit-ast (js2-for-in-node-iterator n) v)
2495 (js2-visit-ast (js2-for-in-node-object n) v)
2496 (js2-visit-ast (js2-for-in-node-body n) v))
2498 (defun js2-print-for-in-node (n i)
2499 (let ((pad (js2-make-pad i))
2500 (foreach (js2-for-in-node-foreach-p n)))
2505 (js2-print-ast (js2-for-in-node-iterator n) 0)
2507 (js2-print-ast (js2-for-in-node-object n) 0)
2509 (js2-print-body (js2-for-in-node-body n) (1+ i))
2510 (insert pad "}\n")))
2512 (defstruct (js2-return-node
2515 (:constructor make-js2-return-node (&key (type js2-RETURN)
2519 "AST node for a return statement."
2520 retval) ; expression to return, or 'undefined
2522 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2523 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2525 (defun js2-visit-return-node (n v)
2526 (js2-visit-ast (js2-return-node-retval n) v))
2528 (defun js2-print-return-node (n i)
2529 (insert (js2-make-pad i) "return")
2530 (when (js2-return-node-retval n)
2532 (js2-print-ast (js2-return-node-retval n) 0))
2535 (defstruct (js2-if-node
2538 (:constructor make-js2-if-node (&key (type js2-IF)
2545 "AST node for an if-statement."
2546 condition ; expression
2547 then-part ; statement or block
2548 else-pos ; optional buffer position of 'else' keyword
2549 else-part ; optional statement or block
2550 lp ; position of left-paren, nil if omitted
2551 rp) ; position of right-paren, nil if omitted
2553 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2554 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2556 (defun js2-visit-if-node (n v)
2557 (js2-visit-ast (js2-if-node-condition n) v)
2558 (js2-visit-ast (js2-if-node-then-part n) v)
2559 (js2-visit-ast (js2-if-node-else-part n) v))
2561 (defun js2-print-if-node (n i)
2562 (let ((pad (js2-make-pad i))
2563 (then-part (js2-if-node-then-part n))
2564 (else-part (js2-if-node-else-part n)))
2566 (js2-print-ast (js2-if-node-condition n) 0)
2568 (js2-print-body then-part (1+ i))
2573 ((js2-if-node-p else-part)
2575 (js2-print-body else-part i))
2577 (insert " else {\n")
2578 (js2-print-body else-part (1+ i))
2579 (insert pad "}\n")))))
2581 (defstruct (js2-try-node
2584 (:constructor make-js2-try-node (&key (type js2-TRY)
2590 "AST node for a try-statement."
2592 catch-clauses ; a Lisp list of `js2-catch-node'
2593 finally-block) ; a `js2-finally-node'
2595 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2596 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2598 (defun js2-visit-try-node (n v)
2599 (js2-visit-ast (js2-try-node-try-block n) v)
2600 (dolist (clause (js2-try-node-catch-clauses n))
2601 (js2-visit-ast clause v))
2602 (js2-visit-ast (js2-try-node-finally-block n) v))
2604 (defun js2-print-try-node (n i)
2605 (let ((pad (js2-make-pad i))
2606 (catches (js2-try-node-catch-clauses n))
2607 (finally (js2-try-node-finally-block n)))
2608 (insert pad "try {\n")
2609 (js2-print-body (js2-try-node-try-block n) (1+ i))
2612 (dolist (catch catches)
2613 (js2-print-ast catch i)))
2615 (js2-print-ast finally i)
2618 (defstruct (js2-catch-node
2621 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2629 "AST node for a catch clause."
2630 param ; destructuring form or simple name node
2631 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2632 guard-expr ; catch condition, a `js2-node'
2633 block ; statements, a `js2-block-node'
2634 lp ; buffer position of left-paren, nil if omitted
2635 rp) ; buffer position of right-paren, nil if omitted
2637 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2638 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2640 (defun js2-visit-catch-node (n v)
2641 (js2-visit-ast (js2-catch-node-param n) v)
2642 (when (js2-catch-node-guard-kwd n)
2643 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2644 (js2-visit-ast (js2-catch-node-block n) v))
2646 (defun js2-print-catch-node (n i)
2647 (let ((pad (js2-make-pad i))
2648 (guard-kwd (js2-catch-node-guard-kwd n))
2649 (guard-expr (js2-catch-node-guard-expr n)))
2651 (js2-print-ast (js2-catch-node-param n) 0)
2654 (js2-print-ast guard-expr 0))
2656 (js2-print-body (js2-catch-node-block n) (1+ i))
2659 (defstruct (js2-finally-node
2662 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2665 "AST node for a finally clause."
2666 body) ; a `js2-node', often but not always a block node
2668 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2669 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2671 (defun js2-visit-finally-node (n v)
2672 (js2-visit-ast (js2-finally-node-body n) v))
2674 (defun js2-print-finally-node (n i)
2675 (let ((pad (js2-make-pad i)))
2676 (insert " finally {\n")
2677 (js2-print-body (js2-finally-node-body n) (1+ i))
2678 (insert pad "}\n")))
2680 (defstruct (js2-switch-node
2683 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2689 "AST node for a switch statement."
2690 discriminant ; a `js2-node' (switch expression)
2691 cases ; a Lisp list of `js2-case-node'
2692 lp ; position of open-paren for discriminant, nil if omitted
2693 rp) ; position of close-paren for discriminant, nil if omitted
2695 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2696 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2698 (defun js2-visit-switch-node (n v)
2699 (js2-visit-ast (js2-switch-node-discriminant n) v)
2700 (dolist (c (js2-switch-node-cases n))
2701 (js2-visit-ast c v)))
2703 (defun js2-print-switch-node (n i)
2704 (let ((pad (js2-make-pad i))
2705 (cases (js2-switch-node-cases n)))
2706 (insert pad "switch (")
2707 (js2-print-ast (js2-switch-node-discriminant n) 0)
2709 (dolist (case cases)
2710 (js2-print-ast case i))
2711 (insert pad "}\n")))
2713 (defstruct (js2-case-node
2714 (:include js2-block-node)
2716 (:constructor make-js2-case-node (&key (type js2-CASE)
2719 "AST node for a case clause of a switch statement."
2720 expr) ; the case expression (nil for default)
2722 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2723 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2725 (defun js2-visit-case-node (n v)
2726 (js2-visit-ast (js2-case-node-expr n) v)
2727 (js2-visit-block n v))
2729 (defun js2-print-case-node (n i)
2730 (let ((pad (js2-make-pad i))
2731 (expr (js2-case-node-expr n)))
2734 (insert "default:\n")
2736 (js2-print-ast expr 0)
2738 (dolist (kid (js2-case-node-kids n))
2739 (js2-print-ast kid (1+ i)))))
2741 (defstruct (js2-throw-node
2744 (:constructor make-js2-throw-node (&key (type js2-THROW)
2747 "AST node for a throw statement."
2748 expr) ; the expression to throw
2750 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2751 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2753 (defun js2-visit-throw-node (n v)
2754 (js2-visit-ast (js2-throw-node-expr n) v))
2756 (defun js2-print-throw-node (n i)
2757 (insert (js2-make-pad i) "throw ")
2758 (js2-print-ast (js2-throw-node-expr n) 0)
2761 (defstruct (js2-with-node
2764 (:constructor make-js2-with-node (&key (type js2-WITH)
2768 "AST node for a with-statement."
2771 lp ; buffer position of left-paren around object, nil if omitted
2772 rp) ; buffer position of right-paren around object, nil if omitted
2774 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2775 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2777 (defun js2-visit-with-node (n v)
2778 (js2-visit-ast (js2-with-node-object n) v)
2779 (js2-visit-ast (js2-with-node-body n) v))
2781 (defun js2-print-with-node (n i)
2782 (let ((pad (js2-make-pad i)))
2783 (insert pad "with (")
2784 (js2-print-ast (js2-with-node-object n) 0)
2786 (js2-print-body (js2-with-node-body n) (1+ i))
2787 (insert pad "}\n")))
2789 (defstruct (js2-label-node
2792 (:constructor make-js2-label-node (&key (type js2-LABEL)
2795 "AST node for a statement label or case label."
2797 loop) ; for validating and code-generating continue-to-label
2799 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2800 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2802 (defun js2-print-label (n i)
2803 (insert (js2-make-pad i)
2804 (js2-label-node-name n)
2807 (defstruct (js2-labeled-stmt-node
2810 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2811 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2812 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2815 "AST node for a statement with one or more labels.
2816 Multiple labels for a statement are collapsed into the labels field."
2817 labels ; Lisp list of `js2-label-node'
2818 stmt) ; the statement these labels are for
2820 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2821 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2823 (defun js2-get-label-by-name (lbl-stmt name)
2824 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2825 Returns nil if no such label is in the list."
2826 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2828 (while (and label-list (not result))
2829 (if (string= (js2-label-node-name (car label-list)) name)
2830 (setq result (car label-list))
2831 (setq label-list (cdr label-list))))
2834 (defun js2-visit-labeled-stmt (n v)
2835 (dolist (label (js2-labeled-stmt-node-labels n))
2836 (js2-visit-ast label v))
2837 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2839 (defun js2-print-labeled-stmt (n i)
2840 (dolist (label (js2-labeled-stmt-node-labels n))
2841 (js2-print-ast label i))
2842 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2844 (defun js2-labeled-stmt-node-contains (node label)
2845 "Return t if NODE contains LABEL in its label set.
2846 NODE is a `js2-labels-node'. LABEL is an identifier."
2847 (loop for nl in (js2-labeled-stmt-node-labels node)
2848 if (string= label (js2-label-node-name nl))
2850 finally return nil))
2852 (defsubst js2-labeled-stmt-node-add-label (node label)
2853 "Add a `js2-label-node' to the label set for this statement."
2854 (setf (js2-labeled-stmt-node-labels node)
2855 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2857 (defstruct (js2-jump-node
2860 "Abstract supertype of break and continue nodes."
2861 label ; `js2-name-node' for location of label identifier, if present
2862 target) ; target js2-labels-node or loop/switch statement
2864 (defun js2-visit-jump-node (n v)
2865 ;; We don't visit the target, since it's a back-link.
2866 (js2-visit-ast (js2-jump-node-label n) v))
2868 (defstruct (js2-break-node
2869 (:include js2-jump-node)
2871 (:constructor make-js2-break-node (&key (type js2-BREAK)
2874 "AST node for a break statement.
2875 The label field is a `js2-name-node', possibly nil, for the named label
2876 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2877 is the target of the break - a label node or enclosing loop/switch statement.")
2879 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2880 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2882 (defun js2-print-break-node (n i)
2883 (insert (js2-make-pad i) "break")
2884 (when (js2-break-node-label n)
2886 (js2-print-ast (js2-break-node-label n) 0))
2889 (defstruct (js2-continue-node
2890 (:include js2-jump-node)
2892 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2895 "AST node for a continue statement.
2896 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2897 It is nil if continue specifies no label. The target field is the jump target:
2898 a `js2-label-node' or the innermost enclosing loop.")
2900 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2901 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2903 (defun js2-print-continue-node (n i)
2904 (insert (js2-make-pad i) "continue")
2905 (when (js2-continue-node-label n)
2907 (js2-print-ast (js2-continue-node-label n) 0))
2910 (defstruct (js2-function-node
2911 (:include js2-script-node)
2913 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2917 (form 'FUNCTION_STATEMENT)
2921 "AST node for a function declaration.
2922 The `params' field is a Lisp list of nodes. Each node is either a simple
2923 `js2-name-node', or if it's a destructuring-assignment parameter, a
2924 `js2-array-node' or `js2-object-node'."
2925 ftype ; FUNCTION, GETTER or SETTER
2926 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2927 name ; function name (a `js2-name-node', or nil if anonymous)
2928 params ; a Lisp list of destructuring forms or simple name nodes
2929 body ; a `js2-block-node' or expression node (1.8 only)
2930 lp ; position of arg-list open-paren, or nil if omitted
2931 rp ; position of arg-list close-paren, or nil if omitted
2932 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2933 needs-activation ; t if we need an activation object for this frame
2934 is-generator ; t if this function contains a yield
2935 member-expr) ; nonstandard Ecma extension from Rhino
2937 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2938 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2940 (defun js2-visit-function-node (n v)
2941 (js2-visit-ast (js2-function-node-name n) v)
2942 (dolist (p (js2-function-node-params n))
2943 (js2-visit-ast p v))
2944 (js2-visit-ast (js2-function-node-body n) v))
2946 (defun js2-print-function-node (n i)
2947 (let ((pad (js2-make-pad i))
2948 (getter (js2-node-get-prop n 'GETTER_SETTER))
2949 (name (js2-function-node-name n))
2950 (params (js2-function-node-params n))
2951 (body (js2-function-node-body n))
2952 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2954 (insert pad "function"))
2957 (js2-print-ast name 0))
2959 (loop with len = (length params)
2963 (js2-print-ast param 0)
2969 ;; TODO: fix this to be smarter about indenting, etc.
2970 (js2-print-body body (1+ i))
2975 (defun js2-function-name (node)
2976 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2977 (and (js2-function-node-name node)
2978 (js2-name-node-name (js2-function-node-name node))))
2980 ;; Having this be an expression node makes it more flexible.
2981 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2982 ;; that work better if you assume it's an expression. Whenever we have
2983 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2984 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2985 (defstruct (js2-var-decl-node
2988 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2992 "AST node for a variable declaration list (VAR, CONST or LET).
2993 The node bounds differ depending on the declaration type. For VAR or
2994 CONST declarations, the bounds include the var/const keyword. For LET
2995 declarations, the node begins at the position of the first child."
2996 kids ; a Lisp list of `js2-var-init-node' structs.
2997 decl-type) ; js2-VAR, js2-CONST or js2-LET
2999 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3000 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3002 (defun js2-visit-var-decl (n v)
3003 (dolist (kid (js2-var-decl-node-kids n))
3004 (js2-visit-ast kid v)))
3006 (defun js2-print-var-decl (n i)
3007 (let ((pad (js2-make-pad i))
3008 (tt (js2-var-decl-node-decl-type n)))
3011 ((= tt js2-VAR) "var ")
3012 ((= tt js2-LET) "let ")
3013 ((= tt js2-CONST) "const ")
3015 (error "malformed var-decl node"))))
3016 (loop with kids = (js2-var-decl-node-kids n)
3017 with len = (length kids)
3021 (js2-print-ast kid 0)
3025 (defstruct (js2-var-init-node
3028 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3032 "AST node for a variable declaration.
3033 The type field will be js2-CONST for a const decl."
3034 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3035 initializer) ; initializer expression, a `js2-node'
3037 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3038 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3040 (defun js2-visit-var-init-node (n v)
3041 (js2-visit-ast (js2-var-init-node-target n) v)
3042 (js2-visit-ast (js2-var-init-node-initializer n) v))
3044 (defun js2-print-var-init-node (n i)
3045 (let ((pad (js2-make-pad i))
3046 (name (js2-var-init-node-target n))
3047 (init (js2-var-init-node-initializer n)))
3049 (js2-print-ast name 0)
3052 (js2-print-ast init 0))))
3054 (defstruct (js2-cond-node
3057 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3064 "AST node for the ternary operator"
3068 q-pos ; buffer position of ?
3069 c-pos) ; buffer position of :
3071 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3072 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3074 (defun js2-visit-cond-node (n v)
3075 (js2-visit-ast (js2-cond-node-test-expr n) v)
3076 (js2-visit-ast (js2-cond-node-true-expr n) v)
3077 (js2-visit-ast (js2-cond-node-false-expr n) v))
3079 (defun js2-print-cond-node (n i)
3080 (let ((pad (js2-make-pad i)))
3082 (js2-print-ast (js2-cond-node-test-expr n) 0)
3084 (js2-print-ast (js2-cond-node-true-expr n) 0)
3086 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3088 (defstruct (js2-infix-node
3091 (:constructor make-js2-infix-node (&key type
3095 "Represents infix expressions.
3096 Includes assignment ops like `|=', and the comma operator.
3097 The type field inherited from `js2-node' holds the operator."
3098 op-pos ; buffer position where operator begins
3099 left ; any `js2-node'
3100 right) ; any `js2-node'
3102 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3103 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3105 (defun js2-visit-infix-node (n v)
3106 (js2-visit-ast (js2-infix-node-left n) v)
3107 (js2-visit-ast (js2-infix-node-right n) v))
3109 (defconst js2-operator-tokens
3110 (let ((table (make-hash-table :test 'eq))
3112 (list (cons js2-IN "in")
3113 (cons js2-TYPEOF "typeof")
3114 (cons js2-INSTANCEOF "instanceof")
3115 (cons js2-DELPROP "delete")
3116 (cons js2-COMMA ",")
3117 (cons js2-COLON ":")
3122 (cons js2-BITOR "|")
3123 (cons js2-BITXOR "^")
3124 (cons js2-BITAND "&")
3133 (cons js2-URSH ">>>")
3134 (cons js2-ADD "+") ; infix plus
3135 (cons js2-SUB "-") ; infix minus
3140 (cons js2-BITNOT "~")
3141 (cons js2-POS "+") ; unary plus
3142 (cons js2-NEG "-") ; unary minus
3143 (cons js2-SHEQ "===") ; shallow equality
3144 (cons js2-SHNE "!==") ; shallow inequality
3145 (cons js2-ASSIGN "=")
3146 (cons js2-ASSIGN_BITOR "|=")
3147 (cons js2-ASSIGN_BITXOR "^=")
3148 (cons js2-ASSIGN_BITAND "&=")
3149 (cons js2-ASSIGN_LSH "<<=")
3150 (cons js2-ASSIGN_RSH ">>=")
3151 (cons js2-ASSIGN_URSH ">>>=")
3152 (cons js2-ASSIGN_ADD "+=")
3153 (cons js2-ASSIGN_SUB "-=")
3154 (cons js2-ASSIGN_MUL "*=")
3155 (cons js2-ASSIGN_DIV "/=")
3156 (cons js2-ASSIGN_MOD "%="))))
3157 (loop for (k . v) in tokens do
3158 (puthash k v table))
3161 (defun js2-print-infix-node (n i)
3162 (let* ((tt (js2-node-type n))
3163 (op (gethash tt js2-operator-tokens)))
3165 (error "unrecognized infix operator %s" (js2-node-type n)))
3166 (insert (js2-make-pad i))
3167 (js2-print-ast (js2-infix-node-left n) 0)
3168 (unless (= tt js2-COMMA)
3172 (js2-print-ast (js2-infix-node-right n) 0)))
3174 (defstruct (js2-assign-node
3175 (:include js2-infix-node)
3177 (:constructor make-js2-assign-node (&key type
3181 "Represents any assignment.
3182 The type field holds the actual assignment operator.")
3184 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3185 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3187 (defstruct (js2-unary-node
3190 (:constructor make-js2-unary-node (&key type ; required
3193 "AST node type for unary operator nodes.
3194 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3195 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3196 property is added if the operator follows the operand."
3197 operand) ; a `js2-node' expression
3199 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3200 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3202 (defun js2-visit-unary-node (n v)
3203 (js2-visit-ast (js2-unary-node-operand n) v))
3205 (defun js2-print-unary-node (n i)
3206 (let* ((tt (js2-node-type n))
3207 (op (gethash tt js2-operator-tokens))
3208 (postfix (js2-node-get-prop n 'postfix)))
3210 (error "unrecognized unary operator %s" tt))
3211 (insert (js2-make-pad i))
3214 (if (or (= tt js2-TYPEOF)
3217 (js2-print-ast (js2-unary-node-operand n) 0)
3221 (defstruct (js2-let-node
3222 (:include js2-scope)
3224 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3228 "AST node for a let expression or a let statement.
3229 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3230 vars ; a `js2-var-decl-node'
3231 body ; a `js2-node' representing the expression or body block
3235 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3236 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3238 (defun js2-visit-let-node (n v)
3239 (js2-visit-ast (js2-let-node-vars n) v)
3240 (js2-visit-ast (js2-let-node-body n) v))
3242 (defun js2-print-let-node (n i)
3243 (insert (js2-make-pad i) "let (")
3244 (js2-print-ast (js2-let-node-vars n) 0)
3246 (js2-print-ast (js2-let-node-body n) i))
3248 (defstruct (js2-keyword-node
3251 (:constructor make-js2-keyword-node (&key type
3253 (len (- js2-ts-cursor pos)))))
3254 "AST node representing a literal keyword such as `null'.
3255 Used for `null', `this', `true', `false' and `debugger'.
3256 The node type is set to js2-NULL, js2-THIS, etc.")
3258 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3259 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3261 (defun js2-print-keyword-node (n i)
3262 (insert (js2-make-pad i)
3263 (let ((tt (js2-node-type n)))
3265 ((= tt js2-THIS) "this")
3266 ((= tt js2-NULL) "null")
3267 ((= tt js2-TRUE) "true")
3268 ((= tt js2-FALSE) "false")
3269 ((= tt js2-DEBUGGER) "debugger")
3270 (t (error "Invalid keyword literal type: %d" tt))))))
3272 (defsubst js2-this-node-p (node)
3273 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3274 (eq (js2-node-type node) js2-THIS))
3276 (defstruct (js2-new-node
3279 (:constructor make-js2-new-node (&key (type js2-NEW)
3284 "AST node for new-expression such as new Foo()."
3285 target ; an identifier or reference
3286 args ; a Lisp list of argument nodes
3287 lp ; position of left-paren, nil if omitted
3288 rp ; position of right-paren, nil if omitted
3289 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3291 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3292 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3294 (defun js2-visit-new-node (n v)
3295 (js2-visit-ast (js2-new-node-target n) v)
3296 (dolist (arg (js2-new-node-args n))
3297 (js2-visit-ast arg v))
3298 (js2-visit-ast (js2-new-node-initializer n) v))
3300 (defun js2-print-new-node (n i)
3301 (insert (js2-make-pad i) "new ")
3302 (js2-print-ast (js2-new-node-target n))
3304 (js2-print-list (js2-new-node-args n))
3306 (when (js2-new-node-initializer n)
3308 (js2-print-ast (js2-new-node-initializer n))))
3310 (defstruct (js2-name-node
3313 (:constructor make-js2-name-node (&key (type js2-NAME)
3315 (len (- js2-ts-cursor
3317 (name js2-ts-string))))
3318 "AST node for a JavaScript identifier"
3320 scope) ; a `js2-scope' (optional, used for codegen)
3322 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3323 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3325 (defun js2-print-name-node (n i)
3326 (insert (js2-make-pad i)
3327 (js2-name-node-name n)))
3329 (defsubst js2-name-node-length (node)
3330 "Return identifier length of NODE, a `js2-name-node'.
3331 Returns 0 if NODE is nil or its identifier field is nil."
3333 (length (js2-name-node-name node))
3336 (defstruct (js2-number-node
3339 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3341 (len (- js2-ts-cursor
3343 (value js2-ts-string)
3344 (num-value js2-ts-number))))
3345 "AST node for a number literal."
3346 value ; the original string, e.g. "6.02e23"
3347 num-value) ; the parsed number value
3349 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3350 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3352 (defun js2-print-number-node (n i)
3353 (insert (js2-make-pad i)
3354 (number-to-string (js2-number-node-num-value n))))
3356 (defstruct (js2-regexp-node
3359 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3361 (len (- js2-ts-cursor
3364 "AST node for a regular expression literal."
3365 value ; the regexp string, without // delimiters
3366 flags) ; a string of flags, e.g. `mi'.
3368 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3369 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3371 (defun js2-print-regexp (n i)
3372 (insert (js2-make-pad i)
3374 (js2-regexp-node-value n)
3376 (if (js2-regexp-node-flags n)
3377 (insert (js2-regexp-node-flags n))))
3379 (defstruct (js2-string-node
3382 (:constructor make-js2-string-node (&key (type js2-STRING)
3384 (len (- js2-ts-cursor
3386 (value js2-ts-string))))
3388 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3389 You can tell the quote type by looking at the first character."
3390 value) ; the characters of the string, including the quotes
3392 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3393 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3395 (defun js2-print-string-node (n i)
3396 (insert (js2-make-pad i)
3397 (js2-node-string n)))
3399 (defstruct (js2-array-node
3402 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3405 "AST node for an array literal."
3406 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3408 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3409 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3411 (defun js2-visit-array-node (n v)
3412 (dolist (e (js2-array-node-elems n))
3413 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3415 (defun js2-print-array-node (n i)
3416 (insert (js2-make-pad i) "[")
3417 (js2-print-list (js2-array-node-elems n))
3420 (defstruct (js2-object-node
3423 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3427 "AST node for an object literal expression.
3428 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3429 The latter represents abbreviation in destructuring expressions."
3432 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3433 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3435 (defun js2-visit-object-node (n v)
3436 (dolist (e (js2-object-node-elems n))
3437 (js2-visit-ast e v)))
3439 (defun js2-print-object-node (n i)
3440 (insert (js2-make-pad i) "{")
3441 (js2-print-list (js2-object-node-elems n))
3444 (defstruct (js2-object-prop-node
3445 (:include js2-infix-node)
3447 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3451 "AST node for an object literal prop:value entry.
3452 The `left' field is the property: a name node, string node or number node.
3453 The `right' field is a `js2-node' representing the initializer value.")
3455 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3456 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3458 (defun js2-print-object-prop-node (n i)
3459 (insert (js2-make-pad i))
3460 (js2-print-ast (js2-object-prop-node-left n) 0)
3462 (js2-print-ast (js2-object-prop-node-right n) 0))
3464 (defstruct (js2-getter-setter-node
3465 (:include js2-infix-node)
3467 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3470 "AST node for a getter/setter property in an object literal.
3471 The `left' field is the `js2-name-node' naming the getter/setter prop.
3472 The `right' field is always an anonymous `js2-function-node' with a node
3473 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3475 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3476 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3478 (defun js2-print-getter-setter (n i)
3479 (let ((pad (js2-make-pad i))
3480 (left (js2-getter-setter-node-left n))
3481 (right (js2-getter-setter-node-right n)))
3483 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3484 (js2-print-ast left 0)
3485 (js2-print-ast right 0)))
3487 (defstruct (js2-prop-get-node
3488 (:include js2-infix-node)
3490 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3493 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3495 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3496 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3498 (defun js2-visit-prop-get-node (n v)
3499 (js2-visit-ast (js2-prop-get-node-left n) v)
3500 (js2-visit-ast (js2-prop-get-node-right n) v))
3502 (defun js2-print-prop-get-node (n i)
3503 (insert (js2-make-pad i))
3504 (js2-print-ast (js2-prop-get-node-left n) 0)
3506 (js2-print-ast (js2-prop-get-node-right n) 0))
3508 (defstruct (js2-elem-get-node
3511 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3515 "AST node for an array index expression such as foo[bar]."
3516 target ; a `js2-node' - the expression preceding the "."
3517 element ; a `js2-node' - the expression in brackets
3518 lb ; position of left-bracket, nil if omitted
3519 rb) ; position of right-bracket, nil if omitted
3521 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3522 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3524 (defun js2-visit-elem-get-node (n v)
3525 (js2-visit-ast (js2-elem-get-node-target n) v)
3526 (js2-visit-ast (js2-elem-get-node-element n) v))
3528 (defun js2-print-elem-get-node (n i)
3529 (insert (js2-make-pad i))
3530 (js2-print-ast (js2-elem-get-node-target n) 0)
3532 (js2-print-ast (js2-elem-get-node-element n) 0)
3535 (defstruct (js2-call-node
3538 (:constructor make-js2-call-node (&key (type js2-CALL)
3542 "AST node for a JavaScript function call."
3543 target ; a `js2-node' evaluating to the function to call
3544 args ; a Lisp list of `js2-node' arguments
3545 lp ; position of open-paren, or nil if missing
3546 rp) ; position of close-paren, or nil if missing
3548 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3549 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3551 (defun js2-visit-call-node (n v)
3552 (js2-visit-ast (js2-call-node-target n) v)
3553 (dolist (arg (js2-call-node-args n))
3554 (js2-visit-ast arg v)))
3556 (defun js2-print-call-node (n i)
3557 (insert (js2-make-pad i))
3558 (js2-print-ast (js2-call-node-target n) 0)
3560 (js2-print-list (js2-call-node-args n))
3563 (defstruct (js2-yield-node
3566 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3569 "AST node for yield statement or expression."
3570 value) ; optional: value to be yielded
3572 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3573 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3575 (defun js2-visit-yield-node (n v)
3576 (js2-visit-ast (js2-yield-node-value n) v))
3578 (defun js2-print-yield-node (n i)
3579 (insert (js2-make-pad i))
3581 (when (js2-yield-node-value n)
3583 (js2-print-ast (js2-yield-node-value n) 0)))
3585 (defstruct (js2-paren-node
3588 (:constructor make-js2-paren-node (&key (type js2-LP)
3591 "AST node for a parenthesized expression.
3592 In particular, used when the parens are syntactically optional,
3593 as opposed to required parens such as those enclosing an if-conditional."
3596 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3597 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3599 (defun js2-visit-paren-node (n v)
3600 (js2-visit-ast (js2-paren-node-expr n) v))
3602 (defun js2-print-paren-node (n i)
3603 (insert (js2-make-pad i))
3605 (js2-print-ast (js2-paren-node-expr n) 0)
3608 (defstruct (js2-array-comp-node
3609 (:include js2-scope)
3611 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3616 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3617 result ; result expression (just after left-bracket)
3618 loops ; a Lisp list of `js2-array-comp-loop-node'
3619 filter ; guard/filter expression
3620 if-pos ; buffer pos of 'if' keyword, if present, else nil
3621 lp ; buffer position of if-guard left-paren, or nil if not present
3622 rp) ; buffer position of if-guard right-paren, or nil if not present
3624 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3625 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3627 (defun js2-visit-array-comp-node (n v)
3628 (js2-visit-ast (js2-array-comp-node-result n) v)
3629 (dolist (l (js2-array-comp-node-loops n))
3630 (js2-visit-ast l v))
3631 (js2-visit-ast (js2-array-comp-node-filter n) v))
3633 (defun js2-print-array-comp-node (n i)
3634 (let ((pad (js2-make-pad i))
3635 (result (js2-array-comp-node-result n))
3636 (loops (js2-array-comp-node-loops n))
3637 (filter (js2-array-comp-node-filter n)))
3639 (js2-print-ast result 0)
3642 (js2-print-ast l 0))
3645 (js2-print-ast filter 0)
3649 (defstruct (js2-array-comp-loop-node
3650 (:include js2-for-in-node)
3652 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3659 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3661 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3662 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3664 (defun js2-visit-array-comp-loop (n v)
3665 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3666 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3668 (defun js2-print-array-comp-loop (n i)
3670 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3672 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3674 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3677 (defstruct (js2-empty-expr-node
3680 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3683 "AST node for an empty expression.")
3685 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3686 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3688 (defstruct (js2-xml-node
3689 (:include js2-block-node)
3691 (:constructor make-js2-xml-node (&key (type js2-XML)
3694 "AST node for initial parse of E4X literals.
3695 The kids field is a list of XML fragments, each a `js2-string-node' or
3696 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3698 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3699 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3701 (defun js2-print-xml-node (n i)
3702 (dolist (kid (js2-xml-node-kids n))
3703 (js2-print-ast kid i)))
3705 (defstruct (js2-xml-js-expr-node
3706 (:include js2-xml-node)
3708 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3711 "AST node for an embedded JavaScript {expression} in an E4X literal.
3712 The start and end fields correspond to the curly-braces."
3713 expr) ; a `js2-expr-node' of some sort
3715 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3716 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3718 (defun js2-visit-xml-js-expr (n v)
3719 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3721 (defun js2-print-xml-js-expr (n i)
3722 (insert (js2-make-pad i))
3724 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3727 (defstruct (js2-xml-dot-query-node
3728 (:include js2-infix-node)
3730 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3734 "AST node for an E4X foo.(bar) filter expression.
3735 Note that the left-paren is automatically the character immediately
3736 following the dot (.) in the operator. No whitespace is permitted
3737 between the dot and the lp by the scanner."
3740 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3741 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3743 (defun js2-print-xml-dot-query (n i)
3744 (insert (js2-make-pad i))
3745 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3747 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3750 (defstruct (js2-xml-ref-node
3752 (:constructor nil)) ; abstract
3753 "Base type for E4X XML attribute-access or property-get expressions.
3754 Such expressions can take a variety of forms. The general syntax has
3757 - (optional) an @ (specifying an attribute access)
3758 - (optional) a namespace (a `js2-name-node') and double-colon
3759 - (required) either a `js2-name-node' or a bracketed [expression]
3761 The property-name expressions (examples: ns::name, @name) are
3762 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3763 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3765 This node type (or more specifically, its subclasses) will sometimes
3766 be the right-hand child of a `js2-prop-get-node' or a
3767 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3768 The `js2-xml-ref-node' may also be a standalone primary expression with
3769 no explicit target, which is valid in certain expression contexts such as
3771 company..employee.(@id < 100)
3773 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3774 expression whose parent is a `js2-xml-dot-query-node'."
3779 (defsubst js2-xml-ref-node-attr-access-p (node)
3780 "Return non-nil if this expression began with an @-token."
3781 (and (numberp (js2-xml-ref-node-at-pos node))
3782 (plusp (js2-xml-ref-node-at-pos node))))
3784 (defstruct (js2-xml-prop-ref-node
3785 (:include js2-xml-ref-node)
3787 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3792 "AST node for an E4X XML [expr] property-ref expression.
3793 The JavaScript syntax is an optional @, an optional ns::, and a name.
3795 [ '@' ] [ name '::' ] name
3797 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3798 @ns::*, @*::attr, @*::*, and @*.
3800 The node starts at the @ token, if present. Otherwise it starts at the
3801 namespace name. The node bounds extend through the closing right-bracket,
3802 or if it is missing due to a syntax error, through the end of the index
3806 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3807 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3809 (defun js2-visit-xml-prop-ref-node (n v)
3810 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3811 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3813 (defun js2-print-xml-prop-ref-node (n i)
3814 (insert (js2-make-pad i))
3815 (if (js2-xml-ref-node-attr-access-p n)
3817 (when (js2-xml-prop-ref-node-namespace n)
3818 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3820 (if (js2-xml-prop-ref-node-propname n)
3821 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3823 (defstruct (js2-xml-elem-ref-node
3824 (:include js2-xml-ref-node)
3826 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3831 "AST node for an E4X XML [expr] member-ref expression.
3834 [ '@' ] [ name '::' ] '[' expr ']'
3836 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3838 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3839 is not a legal E4X XML element-ref expression, since it's already used
3840 for standard JavaScript element-get array indexing. Hence, a
3841 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3842 non-nil namespace node, or both.
3844 The node starts at the @ token, if present. Otherwise it starts
3845 at the namespace name. The node bounds extend through the closing
3846 right-bracket, or if it is missing due to a syntax error, through the
3847 end of the index expression."
3848 expr ; the bracketed index expression
3852 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3853 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3855 (defun js2-visit-xml-elem-ref-node (n v)
3856 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3857 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3859 (defun js2-print-xml-elem-ref-node (n i)
3860 (insert (js2-make-pad i))
3861 (if (js2-xml-ref-node-attr-access-p n)
3863 (when (js2-xml-elem-ref-node-namespace n)
3864 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3867 (if (js2-xml-elem-ref-node-expr n)
3868 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3871 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3873 (defstruct (js2-xml-start-tag-node
3874 (:include js2-xml-node)
3876 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3880 "AST node for an XML start-tag. Not currently used.
3881 The `kids' field is a Lisp list of child content nodes."
3882 name ; a `js2-xml-name-node'
3883 attrs ; a Lisp list of `js2-xml-attr-node'
3884 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3886 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3887 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3889 (defun js2-visit-xml-start-tag (n v)
3890 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3891 (dolist (attr (js2-xml-start-tag-node-attrs n))
3892 (js2-visit-ast attr v))
3893 (js2-visit-block n v))
3895 (defun js2-print-xml-start-tag (n i)
3896 (insert (js2-make-pad i) "<")
3897 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3898 (when (js2-xml-start-tag-node-attrs n)
3900 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3903 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3904 ;; and add the end-tag to the kids list of the parent as well.
3905 (defstruct (js2-xml-end-tag-node
3906 (:include js2-xml-node)
3908 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3911 "AST node for an XML end-tag. Not currently used."
3912 name) ; a `js2-xml-name-node'
3914 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3915 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3917 (defun js2-visit-xml-end-tag (n v)
3918 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3920 (defun js2-print-xml-end-tag (n i)
3921 (insert (js2-make-pad i))
3923 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3926 (defstruct (js2-xml-name-node
3927 (:include js2-xml-node)
3929 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3931 len namespace kids)))
3932 "AST node for an E4X XML name. Not currently used.
3933 Any XML name can be qualified with a namespace, hence the namespace field.
3934 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3935 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3936 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3937 namespace) ; a `js2-string-node'
3939 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3940 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3942 (defun js2-visit-xml-name-node (n v)
3943 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3945 (defun js2-print-xml-name-node (n i)
3946 (insert (js2-make-pad i))
3947 (when (js2-xml-name-node-namespace n)
3948 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3950 (dolist (kid (js2-xml-name-node-kids n))
3951 (js2-print-ast kid 0)))
3953 (defstruct (js2-xml-pi-node
3954 (:include js2-xml-node)
3956 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3959 "AST node for an E4X XML processing instruction. Not currently used."
3960 name ; a `js2-xml-name-node'
3961 attrs) ; a list of `js2-xml-attr-node'
3963 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3964 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3966 (defun js2-visit-xml-pi-node (n v)
3967 (js2-visit-ast (js2-xml-pi-node-name n) v)
3968 (dolist (attr (js2-xml-pi-node-attrs n))
3969 (js2-visit-ast attr v)))
3971 (defun js2-print-xml-pi-node (n i)
3972 (insert (js2-make-pad i) "<?")
3973 (js2-print-ast (js2-xml-pi-node-name n))
3974 (when (js2-xml-pi-node-attrs n)
3976 (js2-print-list (js2-xml-pi-node-attrs n)))
3979 (defstruct (js2-xml-cdata-node
3980 (:include js2-xml-node)
3982 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3985 "AST node for a CDATA escape section. Not currently used."
3986 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3988 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3989 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3991 (defun js2-visit-xml-cdata-node (n v)
3992 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3994 (defun js2-print-xml-cdata-node (n i)
3995 (insert (js2-make-pad i))
3996 (js2-print-ast (js2-xml-cdata-node-content n)))
3998 (defstruct (js2-xml-attr-node
3999 (:include js2-xml-node)
4001 (:constructor make-js2-attr-node (&key (type js2-XML)
4004 eq-pos quote-type)))
4005 "AST node representing a foo='bar' XML attribute value. Not yet used."
4006 name ; a `js2-xml-name-node'
4007 value ; a `js2-xml-name-node'
4008 eq-pos ; buffer position of "=" sign
4009 quote-type) ; 'single or 'double
4011 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4012 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4014 (defun js2-visit-xml-attr-node (n v)
4015 (js2-visit-ast (js2-xml-attr-node-name n) v)
4016 (js2-visit-ast (js2-xml-attr-node-value n) v))
4018 (defun js2-print-xml-attr-node (n i)
4019 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4022 (insert (js2-make-pad i))
4023 (js2-print-ast (js2-xml-attr-node-name n) 0)
4025 (js2-print-ast (js2-xml-attr-node-value n) 0)
4028 (defstruct (js2-xml-text-node
4029 (:include js2-xml-node)
4031 (:constructor make-js2-text-node (&key (type js2-XML)
4034 "AST node for an E4X XML text node. Not currently used."
4035 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4037 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4038 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4040 (defun js2-visit-xml-text-node (n v)
4041 (js2-visit-ast (js2-xml-text-node-content n) v))
4043 (defun js2-print-xml-text-node (n i)
4044 (insert (js2-make-pad i))
4045 (dolist (kid (js2-xml-text-node-content n))
4046 (js2-print-ast kid)))
4048 (defstruct (js2-xml-comment-node
4049 (:include js2-xml-node)
4051 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4054 "AST node for E4X XML comment. Not currently used.")
4056 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4057 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4059 (defun js2-print-xml-comment (n i)
4060 (insert (js2-make-pad i)
4061 (js2-node-string n)))
4065 (defsubst js2-node-line (n)
4066 "Fetch the source line number at the start of node N.
4067 This is O(n) in the length of the source buffer; use prudently."
4068 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4070 (defsubst js2-block-node-kid (n i)
4071 "Return child I of node N, or nil if there aren't that many."
4072 (nth i (js2-block-node-kids n)))
4074 (defsubst js2-block-node-first (n)
4075 "Return first child of block node N, or nil if there is none."
4076 (first (js2-block-node-kids n)))
4078 (defun js2-node-root (n)
4079 "Return the root of the AST containing N.
4080 If N has no parent pointer, returns N."
4081 (let ((parent (js2-node-parent n)))
4083 (js2-node-root parent)
4086 (defun js2-node-position-in-parent (node &optional parent)
4087 "Return the position of NODE in parent's block-kids list.
4088 PARENT can be supplied if known. Positioned returned is zero-indexed.
4089 Returns 0 if NODE is not a child of a block statement, or if NODE
4090 is not a statement node."
4091 (let ((p (or parent (js2-node-parent node)))
4093 (if (not (js2-block-node-p p))
4095 (or (js2-position node (js2-block-node-kids p))
4098 (defsubst js2-node-short-name (n)
4099 "Return the short name of node N as a string, e.g. `js2-if-node'."
4100 (substring (symbol-name (aref n 0))
4101 (length "cl-struct-")))
4103 (defun js2-node-child-list (node)
4104 "Return the child list for NODE, a Lisp list of nodes.
4105 Works for block nodes, array nodes, obj literals, funarg lists,
4106 var decls and try nodes (for catch clauses). Note that you should call
4107 `js2-block-node-kids' on the function body for the body statements.
4108 Returns nil for zero-length child lists or unsupported nodes."
4110 ((js2-function-node-p node)
4111 (js2-function-node-params node))
4112 ((js2-block-node-p node)
4113 (js2-block-node-kids node))
4114 ((js2-try-node-p node)
4115 (js2-try-node-catch-clauses node))
4116 ((js2-array-node-p node)
4117 (js2-array-node-elems node))
4118 ((js2-object-node-p node)
4119 (js2-object-node-elems node))
4120 ((js2-call-node-p node)
4121 (js2-call-node-args node))
4122 ((js2-new-node-p node)
4123 (js2-new-node-args node))
4124 ((js2-var-decl-node-p node)
4125 (js2-var-decl-node-kids node))
4129 (defun js2-node-set-child-list (node kids)
4130 "Set the child list for NODE to KIDS."
4132 ((js2-function-node-p node)
4133 (setf (js2-function-node-params node) kids))
4134 ((js2-block-node-p node)
4135 (setf (js2-block-node-kids node) kids))
4136 ((js2-try-node-p node)
4137 (setf (js2-try-node-catch-clauses node) kids))
4138 ((js2-array-node-p node)
4139 (setf (js2-array-node-elems node) kids))
4140 ((js2-object-node-p node)
4141 (setf (js2-object-node-elems node) kids))
4142 ((js2-call-node-p node)
4143 (setf (js2-call-node-args node) kids))
4144 ((js2-new-node-p node)
4145 (setf (js2-new-node-args node) kids))
4146 ((js2-var-decl-node-p node)
4147 (setf (js2-var-decl-node-kids node) kids))
4149 (error "Unsupported node type: %s" (js2-node-short-name node))))
4152 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4153 (defconst js2-paren-expr-nodes
4154 '(cl-struct-js2-array-comp-loop-node
4155 cl-struct-js2-array-comp-node
4156 cl-struct-js2-call-node
4157 cl-struct-js2-catch-node
4158 cl-struct-js2-do-node
4159 cl-struct-js2-elem-get-node
4160 cl-struct-js2-for-in-node
4161 cl-struct-js2-for-node
4162 cl-struct-js2-function-node
4163 cl-struct-js2-if-node
4164 cl-struct-js2-let-node
4165 cl-struct-js2-new-node
4166 cl-struct-js2-paren-node
4167 cl-struct-js2-switch-node
4168 cl-struct-js2-while-node
4169 cl-struct-js2-with-node
4170 cl-struct-js2-xml-dot-query-node)
4171 "Node types that can have a parenthesized child expression.
4172 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4174 (defsubst js2-paren-expr-node-p (node)
4175 "Return t for nodes that typically have a parenthesized child expression.
4176 Useful for computing the indentation anchors for arg-lists and conditions.
4177 Note that it may return a false positive, for instance when NODE is
4178 a `js2-new-node' and there are no arguments or parentheses."
4179 (memq (aref node 0) js2-paren-expr-nodes))
4181 ;; Fake polymorphism... yech.
4182 (defun js2-node-lp (node)
4183 "Return relative left-paren position for NODE, if applicable.
4184 For `js2-elem-get-node' structs, returns left-bracket position.
4185 Note that the position may be nil in the case of a parse error."
4187 ((js2-elem-get-node-p node)
4188 (js2-elem-get-node-lb node))
4189 ((js2-loop-node-p node)
4190 (js2-loop-node-lp node))
4191 ((js2-function-node-p node)
4192 (js2-function-node-lp node))
4193 ((js2-if-node-p node)
4194 (js2-if-node-lp node))
4195 ((js2-new-node-p node)
4196 (js2-new-node-lp node))
4197 ((js2-call-node-p node)
4198 (js2-call-node-lp node))
4199 ((js2-paren-node-p node)
4200 (js2-node-pos node))
4201 ((js2-switch-node-p node)
4202 (js2-switch-node-lp node))
4203 ((js2-catch-node-p node)
4204 (js2-catch-node-lp node))
4205 ((js2-let-node-p node)
4206 (js2-let-node-lp node))
4207 ((js2-array-comp-node-p node)
4208 (js2-array-comp-node-lp node))
4209 ((js2-with-node-p node)
4210 (js2-with-node-lp node))
4211 ((js2-xml-dot-query-node-p node)
4212 (1+ (js2-infix-node-op-pos node)))
4214 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4216 ;; Fake polymorphism... blech.
4217 (defun js2-node-rp (node)
4218 "Return relative right-paren position for NODE, if applicable.
4219 For `js2-elem-get-node' structs, returns right-bracket position.
4220 Note that the position may be nil in the case of a parse error."
4222 ((js2-elem-get-node-p node)
4223 (js2-elem-get-node-lb node))
4224 ((js2-loop-node-p node)
4225 (js2-loop-node-rp node))
4226 ((js2-function-node-p node)
4227 (js2-function-node-rp node))
4228 ((js2-if-node-p node)
4229 (js2-if-node-rp node))
4230 ((js2-new-node-p node)
4231 (js2-new-node-rp node))
4232 ((js2-call-node-p node)
4233 (js2-call-node-rp node))
4234 ((js2-paren-node-p node)
4235 (+ (js2-node-pos node) (js2-node-len node)))
4236 ((js2-switch-node-p node)
4237 (js2-switch-node-rp node))
4238 ((js2-catch-node-p node)
4239 (js2-catch-node-rp node))
4240 ((js2-let-node-p node)
4241 (js2-let-node-rp node))
4242 ((js2-array-comp-node-p node)
4243 (js2-array-comp-node-rp node))
4244 ((js2-with-node-p node)
4245 (js2-with-node-rp node))
4246 ((js2-xml-dot-query-node-p node)
4247 (1+ (js2-xml-dot-query-node-rp node)))
4249 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4251 (defsubst js2-node-first-child (node)
4252 "Return the first element of `js2-node-child-list' for NODE."
4253 (car (js2-node-child-list node)))
4255 (defsubst js2-node-last-child (node)
4256 "Return the last element of `js2-node-last-child' for NODE."
4257 (car (last (js2-node-child-list node))))
4259 (defun js2-node-prev-sibling (node)
4260 "Return the previous statement in parent.
4261 Works for parents supported by `js2-node-child-list'.
4262 Returns nil if NODE is not in the parent, or PARENT is
4263 not a supported node, or if NODE is the first child."
4264 (let* ((p (js2-node-parent node))
4265 (kids (js2-node-child-list p))
4268 (not (eq node (cadr kids))))
4269 (setq kids (cdr kids)
4273 (defun js2-node-next-sibling (node)
4274 "Return the next statement in parent block.
4275 Returns nil if NODE is not in the block, or PARENT is not
4276 a block node, or if NODE is the last statement."
4277 (let* ((p (js2-node-parent node))
4278 (kids (js2-node-child-list p)))
4280 (not (eq node (car kids))))
4281 (setq kids (cdr kids)))
4284 (defun js2-node-find-child-before (pos parent &optional after)
4285 "Find the last child that starts before POS in parent.
4286 If AFTER is non-nil, returns first child starting after POS.
4287 POS is an absolute buffer position. PARENT is any node
4288 supported by `js2-node-child-list'.
4289 Returns nil if no applicable child is found."
4290 (let ((kids (if (js2-function-node-p parent)
4291 (js2-block-node-kids (js2-function-node-body parent))
4292 (js2-node-child-list parent)))
4293 (beg (if (js2-function-node-p parent)
4294 (js2-node-abs-pos (js2-function-node-body parent))
4295 (js2-node-abs-pos parent)))
4298 (setq fn (if after '>= '<))
4299 (while (and kids continue)
4300 (setq kid (car kids))
4301 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4303 continue (if after nil t))
4304 (setq continue (if after t nil)))
4305 (setq kids (cdr kids)))
4308 (defun js2-node-find-child-after (pos parent)
4309 "Find first child that starts after POS in parent.
4310 POS is an absolute buffer position. PARENT is any node
4311 supported by `js2-node-child-list'.
4312 Returns nil if no applicable child is found."
4313 (js2-node-find-child-before pos parent 'after))
4315 (defun js2-node-replace-child (pos parent new-node)
4316 "Replace node at index POS in PARENT with NEW-NODE.
4317 Only works for parents supported by `js2-node-child-list'."
4318 (let ((kids (js2-node-child-list parent))
4321 (setq kids (cdr kids)
4323 (setcar kids new-node)
4324 (js2-node-add-children parent new-node)))
4326 (defun js2-node-buffer (n)
4327 "Return the buffer associated with AST N.
4328 Returns nil if the buffer is not set as a property on the root
4329 node, or if parent links were not recorded during parsing."
4330 (let ((root (js2-node-root n)))
4332 (js2-ast-root-p root)
4333 (js2-ast-root-buffer root))))
4335 (defun js2-block-node-push (n kid)
4336 "Push js2-node KID onto the end of js2-block-node N's child list.
4337 KID is always added to the -end- of the kids list.
4338 Function also calls `js2-node-add-children' to add the parent link."
4339 (let ((kids (js2-node-child-list n)))
4341 (setcdr kids (nconc (cdr kids) (list kid)))
4342 (js2-node-set-child-list n (list kid)))
4343 (js2-node-add-children n kid)))
4345 (defun js2-node-string (node)
4346 (with-current-buffer (or (js2-node-buffer node)
4347 (error "No buffer available for node %s" node))
4348 (let ((pos (js2-node-abs-pos node)))
4349 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4351 ;; Container for storing the node we're looking for in a traversal.
4352 (js2-deflocal js2-discovered-node nil)
4354 ;; Keep track of absolute node position during traversals.
4355 (js2-deflocal js2-visitor-offset nil)
4357 (js2-deflocal js2-node-search-point nil)
4359 (when js2-mode-dev-mode-p
4360 (defun js2-find-node-at-point ()
4362 (let ((node (js2-node-at-point)))
4363 (message "%s" (or node "No node found at point"))))
4364 (defun js2-node-name-at-point ()
4366 (let ((node (js2-node-at-point)))
4367 (message "%s" (if node
4368 (js2-node-short-name node)
4369 "No node found at point.")))))
4371 (defun js2-node-at-point (&optional pos skip-comments)
4372 "Return AST node at POS, a buffer position, defaulting to current point.
4373 The `js2-mode-ast' variable must be set to the current parse tree.
4374 Signals an error if the AST (`js2-mode-ast') is nil.
4375 Always returns a node - if it can't find one, it returns the root.
4376 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4377 (let ((ast js2-mode-ast)
4380 (error "No JavaScript AST available"))
4381 ;; Look through comments first, since they may be inside nodes that
4382 ;; would otherwise report a match.
4383 (setq pos (or pos (point))
4384 result (if (> pos (js2-node-abs-end ast))
4386 (if (not skip-comments)
4387 (js2-comment-at-point pos))))
4389 (setq js2-discovered-node nil
4390 js2-visitor-offset 0
4391 js2-node-search-point pos)
4393 (catch 'js2-visit-done
4394 (js2-visit-ast ast #'js2-node-at-point-visitor))
4395 (setq js2-visitor-offset nil
4396 js2-node-search-point nil))
4397 (setq result js2-discovered-node))
4398 ;; may have found a comment beyond end of last child node,
4399 ;; since visiting the ast-root looks at the comment-list last.
4400 (if (and skip-comments
4401 (js2-comment-node-p result))
4403 (or result js2-mode-ast)))
4405 (defun js2-node-at-point-visitor (node end-p)
4406 (let ((rel-pos (js2-node-pos node))
4409 (point js2-node-search-point))
4412 ;; this evaluates to a non-nil return value, even if it's zero
4413 (decf js2-visitor-offset rel-pos))
4414 ;; we already looked for comments before visiting, and don't want them now
4415 ((js2-comment-node-p node)
4418 (setq abs-pos (incf js2-visitor-offset rel-pos)
4419 ;; we only want to use the node if the point is before
4420 ;; the last character position in the node, so we decrement
4421 ;; the absolute end by 1.
4422 abs-end (+ abs-pos (js2-node-len node) -1))
4424 ;; If this node starts after search-point, stop the search.
4426 (throw 'js2-visit-done nil))
4427 ;; If this node ends before the search-point, don't check kids.
4431 ;; Otherwise point is within this node, possibly in a child.
4432 (setq js2-discovered-node node)
4433 t)))))) ; keep processing kids to look for more specific match
4435 (defsubst js2-block-comment-p (node)
4436 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4437 (and (js2-comment-node-p node)
4438 (memq (js2-comment-node-format node) '(jsdoc block))))
4440 ;; TODO: put the comments in a vector and binary-search them instead
4441 (defun js2-comment-at-point (&optional pos)
4442 "Look through scanned comment nodes for one containing POS.
4443 POS is a buffer position that defaults to current point.
4444 Function returns nil if POS was not in any comment node."
4445 (let ((ast js2-mode-ast)
4446 (x (or pos (point)))
4449 (error "No JavaScript AST available"))
4451 ;; Comments are stored in lexical order.
4452 (dolist (comment (js2-ast-root-comments ast) nil)
4453 (setq beg (js2-node-abs-pos comment)
4454 end (+ beg (js2-node-len comment)))
4457 (throw 'done comment))))))
4459 (defun js2-mode-find-parent-fn (node)
4460 "Find function enclosing NODE.
4461 Returns nil if NODE is not inside a function."
4462 (setq node (js2-node-parent node))
4463 (while (and node (not (js2-function-node-p node)))
4464 (setq node (js2-node-parent node)))
4465 (and (js2-function-node-p node) node))
4467 (defun js2-mode-find-enclosing-fn (node)
4468 "Find function or root enclosing NODE."
4469 (if (js2-ast-root-p node)
4471 (setq node (js2-node-parent node))
4472 (while (not (or (js2-ast-root-p node)
4473 (js2-function-node-p node)))
4474 (setq node (js2-node-parent node)))
4477 (defun js2-mode-find-enclosing-node (beg end)
4478 "Find script or function fully enclosing BEG and END."
4479 (let ((node (js2-node-at-point beg))
4483 (if (or (js2-ast-root-p node)
4484 (and (js2-function-node-p node)
4485 (<= (setq pos (js2-node-abs-pos node)) beg)
4486 (>= (+ pos (js2-node-len node)) end)))
4488 (setq node (js2-node-parent node))))
4491 (defun js2-node-parent-script-or-fn (node)
4492 "Find script or function immediately enclosing NODE.
4493 If NODE is the ast-root, returns nil."
4494 (if (js2-ast-root-p node)
4496 (setq node (js2-node-parent node))
4497 (while (and node (not (or (js2-function-node-p node)
4498 (js2-script-node-p node))))
4499 (setq node (js2-node-parent node)))
4502 (defun js2-nested-function-p (node)
4503 "Return t if NODE is a nested function, or is inside a nested function."
4504 (unless (js2-ast-root-p node)
4505 (js2-function-node-p (if (js2-function-node-p node)
4506 (js2-node-parent-script-or-fn node)
4507 (js2-node-parent-script-or-fn
4508 (js2-node-parent-script-or-fn node))))))
4510 (defun js2-mode-shift-kids (kids start offset)
4512 (if (> (js2-node-pos kid) start)
4513 (incf (js2-node-pos kid) offset))))
4515 (defun js2-mode-shift-children (parent start offset)
4516 "Update start-positions of all children of PARENT beyond START."
4517 (let ((root (js2-node-root parent)))
4518 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4519 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4521 (defun js2-node-is-descendant (node ancestor)
4522 "Return t if NODE is a descendant of ANCESTOR."
4524 (not (eq node ancestor)))
4525 (setq node (js2-node-parent node)))
4528 ;;; visitor infrastructure
4530 (defun js2-visit-none (node callback)
4531 "Visitor for AST node that have no node children."
4534 (defun js2-print-none (node indent)
4535 "Visitor for AST node with no printed representation.")
4537 (defun js2-print-body (node indent)
4538 "Print a statement, or a block without braces."
4539 (if (js2-block-node-p node)
4540 (dolist (kid (js2-block-node-kids node))
4541 (js2-print-ast kid indent))
4542 (js2-print-ast node indent)))
4544 (defun js2-print-list (args &optional delimiter)
4545 (loop with len = (length args)
4549 (when arg (js2-print-ast arg 0))
4551 (insert (or delimiter ", ")))))
4553 (defun js2-print-tree (ast)
4554 "Prints an AST to the current buffer.
4555 Makes `js2-ast-parent-nodes' available to the printer functions."
4556 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4557 (js2-print-ast ast)))
4559 (defun js2-print-ast (node &optional indent)
4560 "Helper function for printing AST nodes.
4561 Requires `js2-ast-parent-nodes' to be non-nil.
4562 You should use `js2-print-tree' instead of this function."
4563 (let ((printer (get (aref node 0) 'js2-printer))
4565 (pos (js2-node-abs-pos node)))
4566 ;; TODO: wedge comments in here somewhere
4568 (funcall printer node i))))
4570 (defconst js2-side-effecting-tokens
4571 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4572 (dolist (tt (list js2-ASSIGN
4641 (if js2-instanceof-has-side-effects
4642 (aset tokens js2-INSTANCEOF t))
4645 (defun js2-node-has-side-effects (node)
4646 "Return t if NODE has side effects."
4647 (when node ; makes it easier to handle malformed expressions
4648 (let ((tt (js2-node-type node)))
4650 ;; This doubtless needs some work, since EXPR_VOID is used
4651 ;; in several ways in Rhino and I may not have caught them all.
4652 ;; I'll wait for people to notice incorrect warnings.
4653 ((and (= tt js2-EXPR_VOID)
4654 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4655 (let ((expr (js2-expr-stmt-node-expr node)))
4656 (or (js2-node-has-side-effects expr)
4657 (when (js2-string-node-p expr)
4658 (string= "use strict" (js2-string-node-value expr))))))
4660 (js2-node-has-side-effects (js2-infix-node-right node)))
4663 (or (js2-node-has-side-effects (js2-infix-node-right node))
4664 (js2-node-has-side-effects (js2-infix-node-left node))))
4666 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4667 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4668 ((js2-paren-node-p node)
4669 (js2-node-has-side-effects (js2-paren-node-expr node)))
4670 ((= tt js2-ERROR) ; avoid cascaded error messages
4673 (aref js2-side-effecting-tokens tt))))))
4675 (defun js2-member-expr-leftmost-name (node)
4676 "For an expr such as foo.bar.baz, return leftmost node foo.
4677 NODE is any `js2-node' object. If it represents a member expression,
4678 which is any sequence of property gets, element-gets, function calls,
4679 or xml descendants/filter operators, then we look at the lexically
4680 leftmost (first) node in the chain. If it is a name-node we return it.
4681 Note that NODE can be a raw name-node and it will be returned as well.
4682 If NODE is not a name-node or member expression, or if it is a member
4683 expression whose leftmost target is not a name node, returns nil."
4686 (while (and continue (not result))
4688 ((js2-name-node-p node)
4690 ((js2-prop-get-node-p node)
4691 (setq node (js2-prop-get-node-left node)))
4692 ;; TODO: handle call-nodes, xml-nodes, others?
4694 (setq continue nil))))
4697 (defconst js2-stmt-node-types
4701 js2-DEFAULT ; e4x "default xml namespace" statement
4713 "Node types that only appear in statement contexts.
4714 The list does not include nodes that always appear as the child
4715 of another specific statement type, such as switch-cases,
4716 catch and finally blocks, and else-clauses. The list also excludes
4717 nodes like yield, let and var, which may appear in either expression
4718 or statement context, and in the latter context always have a
4719 `js2-expr-stmt-node' parent. Finally, the list does not include
4720 functions or scripts, which are treated separately from statements
4721 by the JavaScript parser and runtime.")
4723 (defun js2-stmt-node-p (node)
4724 "Heuristic for figuring out if NODE is a statement.
4725 Some node types can appear in either an expression context or a
4726 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4727 For these node types in a statement context, the parent will be a
4728 `js2-expr-stmt-node'.
4729 Functions aren't included in the check."
4730 (memq (js2-node-type node) js2-stmt-node-types))
4732 (defun js2-mode-find-first-stmt (node)
4733 "Search upward starting from NODE looking for a statement.
4734 For purposes of this function, a `js2-function-node' counts."
4735 (while (not (or (js2-stmt-node-p node)
4736 (js2-function-node-p node)))
4737 (setq node (js2-node-parent node)))
4740 (defun js2-node-parent-stmt (node)
4741 "Return the node's first ancestor that is a statement.
4742 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4743 appearing in a statement context will have a parent that is a
4744 `js2-expr-stmt-node' that will be returned by this function."
4745 (let ((parent (js2-node-parent node)))
4746 (if (or (null parent)
4747 (js2-stmt-node-p parent)
4748 (and (js2-function-node-p parent)
4749 (not (eq (js2-function-node-form parent)
4750 'FUNCTION_EXPRESSION))))
4752 (js2-node-parent-stmt parent))))
4754 ;; In the Mozilla Rhino sources, Roshan James writes:
4755 ;; Does consistent-return analysis on the function body when strict mode is
4758 ;; function (x) { return (x+1) }
4762 ;; function (x) { if (x < 0) return (x+1); }
4764 ;; is not because the function can potentially return a value when the
4765 ;; condition is satisfied and if not, the function does not explicitly
4768 ;; This extends to checking mismatches such as "return" and "return <value>"
4769 ;; used in the same function. Warnings are not emitted if inconsistent
4770 ;; returns exist in code that can be statically shown to be unreachable.
4772 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4774 ;; emits no warning. However if the loop had a break statement, then a
4775 ;; warning would be emitted.
4777 ;; The consistency analysis looks at control structures such as loops, ifs,
4778 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4779 ;; warns the user about an inconsistent set of termination possibilities.
4781 ;; These flags enumerate the possible ways a statement/function can
4782 ;; terminate. These flags are used by endCheck() and by the Parser to
4783 ;; detect inconsistent return usage.
4785 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4786 ;; able to execute (example: throw, continue)
4788 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4789 ;; next one. Statement such as return dont. A compound statement may have
4790 ;; some branch that drops off control to the next statement.
4792 ;; END_RETURNS indicates that the statement can return with no value.
4793 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4795 ;; A compound statement such as
4799 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4801 (defconst js2-END_UNREACHED 0)
4802 (defconst js2-END_DROPS_OFF 1)
4803 (defconst js2-END_RETURNS 2)
4804 (defconst js2-END_RETURNS_VALUE 4)
4805 (defconst js2-END_YIELDS 8)
4807 (defun js2-has-consistent-return-usage (node)
4808 "Check that every return usage in a function body is consistent.
4809 Returns t if the function satisfies strict mode requirement."
4810 (let ((n (js2-end-check node)))
4811 ;; either it doesn't return a value in any branch...
4812 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4813 ;; or it returns a value (or is unreached) at every branch
4814 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4818 (defun js2-end-check-if (node)
4819 "Ensure that return usage in then/else blocks is consistent.
4820 If there is no else block, then the return statement can fall through.
4821 Returns logical OR of END_* flags"
4822 (let ((th (js2-if-node-then-part node))
4823 (el (js2-if-node-else-part node)))
4826 (logior (js2-end-check th) (if el
4828 js2-END_DROPS_OFF)))))
4830 (defun js2-end-check-switch (node)
4831 "Consistency of return statements is checked between the case statements.
4832 If there is no default, then the switch can fall through. If there is a
4833 default, we check to see if all code paths in the default return or if
4834 there is a code path that can fall through.
4835 Returns logical OR of END_* flags."
4836 (let ((rv js2-END_UNREACHED)
4838 ;; examine the cases
4840 (dolist (c (js2-switch-node-cases node))
4841 (if (js2-case-node-expr c)
4842 (js2-set-flag rv (js2-end-check-block c))
4843 (setq default-case c)
4844 (throw 'break nil))))
4845 ;; we don't care how the cases drop into each other
4846 (js2-clear-flag rv js2-END_DROPS_OFF)
4847 ;; examine the default
4848 (js2-set-flag rv (if default-case
4849 (js2-end-check default-case)
4853 (defun js2-end-check-try (node)
4854 "If the block has a finally, return consistency is checked in the
4855 finally block. If all code paths in the finally return, then the
4856 returns in the try-catch blocks don't matter. If there is a code path
4857 that does not return or if there is no finally block, the returns
4858 of the try and catch blocks are checked for mismatch.
4859 Returns logical OR of END_* flags."
4860 (let ((finally (js2-try-node-finally-block node))
4862 ;; check the finally if it exists
4863 (setq rv (if finally
4864 (js2-end-check (js2-finally-node-body finally))
4866 ;; If the finally block always returns, then none of the returns
4867 ;; in the try or catch blocks matter.
4868 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4869 (js2-clear-flag rv js2-END_DROPS_OFF)
4870 ;; examine the try block
4871 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4872 ;; check each catch block
4873 (dolist (cb (js2-try-node-catch-clauses node))
4874 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4877 (defun js2-end-check-loop (node)
4878 "Return statement in the loop body must be consistent.
4879 The default assumption for any kind of a loop is that it will eventually
4880 terminate. The only exception is a loop with a constant true condition.
4881 Code that follows such a loop is examined only if one can determine
4882 statically that there is a break out of the loop.
4884 for(... ; ... ; ...) {}
4889 Returns logical OR of END_* flags."
4890 (let ((rv (js2-end-check (js2-loop-node-body node)))
4892 ((js2-while-node-p node)
4893 (js2-while-node-condition node))
4894 ((js2-do-node-p node)
4895 (js2-do-node-condition node))
4896 ((js2-for-node-p node)
4897 (js2-for-node-condition node)))))
4899 ;; check to see if the loop condition is always true
4901 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4902 (js2-clear-flag rv js2-END_DROPS_OFF))
4904 ;; look for effect of breaks
4905 (js2-set-flag rv (js2-node-get-prop node
4910 (defun js2-end-check-block (node)
4911 "A general block of code is examined statement by statement.
4912 If any statement (even a compound one) returns in all branches, then
4913 subsequent statements are not examined.
4914 Returns logical OR of END_* flags."
4915 (let* ((rv js2-END_DROPS_OFF)
4916 (kids (js2-block-node-kids node))
4918 ;; Check each statment. If the statement can continue onto the next
4919 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4920 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4921 (js2-clear-flag rv js2-END_DROPS_OFF)
4922 (js2-set-flag rv (js2-end-check n))
4923 (setq kids (cdr kids)
4927 (defun js2-end-check-label (node)
4928 "A labeled statement implies that there may be a break to the label.
4929 The function processes the labeled statement and then checks the
4930 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4932 Returns logical OR of END_* flags."
4933 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4934 (logior rv (js2-node-get-prop node
4936 js2-END_UNREACHED))))
4938 (defun js2-end-check-break (node)
4939 "When a break is encountered annotate the statement being broken
4940 out of by setting its CONTROL_BLOCK_PROP property.
4941 Returns logical OR of END_* flags."
4942 (and (js2-break-node-target node)
4943 (js2-node-set-prop (js2-break-node-target node)
4948 (defun js2-end-check (node)
4949 "Examine the body of a function, doing a basic reachability analysis.
4950 Returns a combination of flags END_* flags that indicate
4951 how the function execution can terminate. These constitute only the
4952 pessimistic set of termination conditions. It is possible that at
4953 runtime certain code paths will never be actually taken. Hence this
4954 analysis will flag errors in cases where there may not be errors.
4955 Returns logical OR of END_* flags"
4958 ((js2-break-node-p node)
4959 (js2-end-check-break node))
4960 ((js2-expr-stmt-node-p node)
4961 (if (setq kid (js2-expr-stmt-node-expr node))
4964 ((or (js2-continue-node-p node)
4965 (js2-throw-node-p node))
4967 ((js2-return-node-p node)
4968 (if (setq kid (js2-return-node-retval node))
4969 js2-END_RETURNS_VALUE
4971 ((js2-loop-node-p node)
4972 (js2-end-check-loop node))
4973 ((js2-switch-node-p node)
4974 (js2-end-check-switch node))
4975 ((js2-labeled-stmt-node-p node)
4976 (js2-end-check-label node))
4977 ((js2-if-node-p node)
4978 (js2-end-check-if node))
4979 ((js2-try-node-p node)
4980 (js2-end-check-try node))
4981 ((js2-block-node-p node)
4982 (if (null (js2-block-node-kids node))
4984 (js2-end-check-block node)))
4985 ((js2-yield-node-p node)
4988 js2-END_DROPS_OFF))))
4990 (defun js2-always-defined-boolean-p (node)
4991 "Check if NODE always evaluates to true or false in boolean context.
4992 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4994 (let ((tt (js2-node-type node))
4997 ((or (= tt js2-FALSE) (= tt js2-NULL))
5002 (setq num (js2-number-node-num-value node))
5003 (if (and (not (eq num 0.0e+NaN))
5010 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5011 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5013 (defvar js2-tokens nil
5014 "List of all defined token names.") ; initialized in `js2-token-names'
5016 (defconst js2-token-names
5017 (let* ((names (make-vector js2-num-tokens -1))
5018 (case-fold-search nil) ; only match js2-UPPER_CASE
5019 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5020 (loop for sym in syms
5023 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5025 (aset names (symbol-value sym) ; code, e.g. 152
5026 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5027 (push sym js2-tokens)))
5029 "Vector mapping int values to token string names, sans `js2-' prefix.")
5031 (defun js2-token-name (tok)
5032 "Return a string name for TOK, a token symbol or code.
5033 Signals an error if it's not a recognized token."
5036 (setq code (symbol-value tok)))
5039 (if (and (numberp code)
5041 (< code js2-num-tokens))
5042 (aref js2-token-names code)
5043 (error "Invalid token: %s" code)))))
5045 (defsubst js2-token-sym (tok)
5046 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5047 (intern (js2-token-name tok)))
5049 (defconst js2-token-codes
5050 (let ((table (make-hash-table :test 'eq :size 256)))
5051 (loop for name across js2-token-names
5052 for sym = (intern (concat "js2-" name))
5054 (puthash sym (symbol-value sym) table))
5055 ;; clean up a few that are "wrong" in Rhino's token codes
5056 (puthash 'js2-DELETE js2-DELPROP table)
5058 "Hashtable mapping token symbols to their bytecodes.")
5060 (defsubst js2-token-code (sym)
5061 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5062 (or (gethash sym js2-token-codes)
5063 (error "Invalid token symbol: %s " sym))) ; signal code bug
5065 (defun js2-report-scan-error (msg &optional no-throw beg len)
5066 (setq js2-token-end js2-ts-cursor)
5067 (js2-report-error msg nil
5068 (or beg js2-token-beg)
5069 (or len (- js2-token-end js2-token-beg)))
5071 (throw 'return js2-ERROR)))
5073 (defun js2-get-string-from-buffer ()
5074 "Reverse the char accumulator and return it as a string."
5075 (setq js2-token-end js2-ts-cursor)
5076 (if js2-ts-string-buffer
5077 (apply #'string (nreverse js2-ts-string-buffer))
5080 ;; TODO: could potentially avoid a lot of consing by allocating a
5081 ;; char buffer the way Rhino does.
5082 (defsubst js2-add-to-string (c)
5083 (push c js2-ts-string-buffer))
5085 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5086 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5087 ;; any other character: when it's not part of the current token, we
5088 ;; unget it, allowing it to be read again by the following call.
5089 (defsubst js2-unget-char ()
5090 (decf js2-ts-cursor))
5092 ;; Rhino distinguishes \r and \n line endings. We don't need to
5093 ;; because we only scan from Emacs buffers, which always use \n.
5094 (defun js2-get-char ()
5095 "Read and return the next character from the input buffer.
5096 Increments `js2-ts-lineno' if the return value is a newline char.
5097 Updates `js2-ts-cursor' to the point after the returned char.
5098 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5099 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5101 ;; check for end of buffer
5102 (if (>= js2-ts-cursor (point-max))
5103 (setq js2-ts-hit-eof t
5104 js2-ts-cursor (1+ js2-ts-cursor)
5105 c js2-EOF_CHAR) ; return value
5106 ;; otherwise read next char
5107 (setq c (char-before (incf js2-ts-cursor)))
5108 ;; if we read a newline, update counters
5110 (setq js2-ts-line-start js2-ts-cursor
5111 js2-ts-lineno (1+ js2-ts-lineno)))
5112 ;; TODO: skip over format characters
5115 (defun js2-read-unicode-escape ()
5116 "Read a \\uNNNN sequence from the input.
5117 Assumes the ?\ and ?u have already been read.
5118 Returns the unicode character, or nil if it wasn't a valid character.
5119 Doesn't change the values of any scanner variables."
5120 ;; I really wish I knew a better way to do this, but I can't
5121 ;; find the Emacs function that takes a 16-bit int and converts
5122 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5123 ;; Have to first check that it's 4 hex characters or it may stop
5126 (let ((s (buffer-substring-no-properties js2-ts-cursor
5127 (+ 4 js2-ts-cursor))))
5128 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5129 (read (concat "?\\u" s))))))
5131 (defun js2-match-char (test)
5132 "Consume and return next character if it matches TEST, a character.
5133 Returns nil and consumes nothing if TEST is not the next character."
5134 (let ((c (js2-get-char)))
5140 (defun js2-peek-char ()
5145 (defun js2-java-identifier-start-p (c)
5148 (js2-char-uppercase-p c)
5149 (js2-char-lowercase-p c)))
5151 (defun js2-java-identifier-part-p (c)
5152 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5153 ;; TODO: make me Unicode-friendly. See comments above.
5156 (js2-char-uppercase-p c)
5157 (js2-char-lowercase-p c)
5158 (and (>= c ?0) (<= c ?9))))
5160 (defun js2-alpha-p (c)
5161 (cond ((and (<= ?A c) (<= c ?Z)) t)
5162 ((and (<= ?a c) (<= c ?z)) t)
5165 (defsubst js2-digit-p (c)
5166 (and (<= ?0 c) (<= c ?9)))
5168 (defun js2-js-space-p (c)
5170 (memq c '(#x20 #x9 #xB #xC #xD))
5173 ;; TODO: change this nil to check for Unicode space character
5176 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5178 (defun js2-skip-line ()
5179 "Skip to end of line."
5181 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5183 (setq js2-token-end js2-ts-cursor)))
5185 (defun js2-init-scanner (&optional buf line)
5186 "Create token stream for BUF starting on LINE.
5187 BUF defaults to `current-buffer' and LINE defaults to 1.
5189 A buffer can only have one scanner active at a time, which yields
5190 dramatically simpler code than using a defstruct. If you need to
5191 have simultaneous scanners in a buffer, copy the regions to scan
5193 (with-current-buffer (or buf (current-buffer))
5194 (setq js2-ts-dirty-line nil
5195 js2-ts-regexp-flags nil
5200 js2-ts-lineno (or line 1)
5201 js2-ts-line-end-char -1
5202 js2-ts-cursor (point-min)
5203 js2-ts-is-xml-attribute nil
5204 js2-ts-xml-is-tag-content nil
5205 js2-ts-xml-open-tags-count 0
5206 js2-ts-string-buffer nil)))
5208 ;; This function uses the cached op, string and number fields in
5209 ;; TokenStream; if getToken has been called since the passed token
5210 ;; was scanned, the op or string printed may be incorrect.
5211 (defun js2-token-to-string (token)
5212 ;; Not sure where this function is used in Rhino. Not tested.
5213 (if (not js2-debug-print-trees)
5215 (let ((name (js2-token-name token)))
5217 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5218 (concat name " `" js2-ts-string "'"))
5219 ((eq token js2-NUMBER)
5220 (format "NUMBER %g" js2-ts-number))
5224 (defconst js2-keywords
5226 case catch const continue
5227 debugger default delete do
5229 false finally for function
5230 if in instanceof import
5235 this throw true try typeof
5240 ;; Token names aren't exactly the same as the keywords, unfortunately.
5241 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5242 (defconst js2-kwd-tokens
5243 (let ((table (make-vector js2-num-tokens nil))
5246 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5247 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5249 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5250 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5255 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5260 (aset table i 'font-lock-keyword-face))
5261 (aset table js2-STRING 'font-lock-string-face)
5262 (aset table js2-REGEXP 'font-lock-string-face)
5263 (aset table js2-COMMENT 'font-lock-comment-face)
5264 (aset table js2-THIS 'font-lock-builtin-face)
5265 (aset table js2-VOID 'font-lock-constant-face)
5266 (aset table js2-NULL 'font-lock-constant-face)
5267 (aset table js2-TRUE 'font-lock-constant-face)
5268 (aset table js2-FALSE 'font-lock-constant-face)
5270 "Vector whose values are non-nil for tokens that are keywords.
5271 The values are default faces to use for highlighting the keywords.")
5273 (defconst js2-reserved-words
5281 implements import int interface
5284 package private protected public
5285 short static super synchronized
5289 (defconst js2-keyword-names
5290 (let ((table (make-hash-table :test 'equal)))
5291 (loop for k in js2-keywords
5293 (symbol-name k) ; instanceof
5294 (intern (concat "js2-"
5295 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5298 "JavaScript keywords by name, mapped to their symbols.")
5300 (defconst js2-reserved-word-names
5301 (let ((table (make-hash-table :test 'equal)))
5302 (loop for k in js2-reserved-words
5304 (puthash (symbol-name k) 'js2-RESERVED table))
5306 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5308 (defun js2-collect-string (buf)
5309 "Convert BUF, a list of chars, to a string.
5310 Reverses BUF before converting."
5314 ((null buf) ; for emacs21 compat
5318 (apply #'string (nreverse buf))
5321 (defun js2-string-to-keyword (s)
5322 "Return token for S, a string, if S is a keyword or reserved word.
5323 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5324 (or (gethash s js2-keyword-names)
5325 (gethash s js2-reserved-word-names)))
5327 (defsubst js2-ts-set-char-token-bounds ()
5328 "Used when next token is one character."
5329 (setq js2-token-beg (1- js2-ts-cursor)
5330 js2-token-end js2-ts-cursor))
5332 (defsubst js2-ts-return (token)
5333 "Return an N-character TOKEN from `js2-get-token'.
5334 Updates `js2-token-end' accordingly."
5335 (setq js2-token-end js2-ts-cursor)
5336 (throw 'return token))
5338 (defun js2-x-digit-to-int (c accumulator)
5339 "Build up a hex number.
5340 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5341 corresponding number. Otherwise return -1."
5344 ;; Use 0..9 < A..Z < a..z
5349 (throw 'check nil)))
5353 (throw 'check nil)))
5357 (throw 'check nil))))
5359 (logior c (lsh accumulator 4))))
5361 (defun js2-get-token ()
5362 "Return next JavaScript token, an int such as js2-RETURN."
5363 (let (c c1 identifier-start is-unicode-escape-start
5364 contains-escape escape-val escape-start str result base
5365 is-integer quote-char val look-for-slash continue)
5368 ;; Eat whitespace, possibly sensitive to newlines.
5371 (setq c (js2-get-char))
5373 ((eq c js2-EOF_CHAR)
5374 (js2-ts-set-char-token-bounds)
5375 (throw 'return js2-EOF))
5377 (js2-ts-set-char-token-bounds)
5378 (setq js2-ts-dirty-line nil)
5379 (throw 'return js2-EOL))
5380 ((not (js2-js-space-p c))
5381 (if (/= c ?-) ; in case end of HTML comment
5382 (setq js2-ts-dirty-line t))
5383 (setq continue nil))))
5384 ;; Assume the token will be 1 char - fixed up below.
5385 (js2-ts-set-char-token-bounds)
5387 (throw 'return js2-XMLATTR))
5388 ;; identifier/keyword/instanceof?
5389 ;; watch out for starting with a <backslash>
5392 (setq c (js2-get-char))
5394 (setq identifier-start t
5395 is-unicode-escape-start t
5396 js2-ts-string-buffer nil)
5397 (setq identifier-start nil)
5401 (when (setq identifier-start (js2-java-identifier-start-p c))
5402 (setq js2-ts-string-buffer nil)
5403 (js2-add-to-string c))))
5404 (when identifier-start
5405 (setq contains-escape is-unicode-escape-start)
5408 (if is-unicode-escape-start
5409 ;; strictly speaking we should probably push-back
5410 ;; all the bad characters if the <backslash>uXXXX
5411 ;; sequence is malformed. But since there isn't a
5412 ;; correct context(is there?) for a bad Unicode
5413 ;; escape sequence in an identifier, we can report
5418 (setq c (js2-get-char)
5419 escape-val (js2-x-digit-to-int c escape-val))
5420 ;; Next check takes care of c < 0 and bad escape
5421 (if (minusp escape-val)
5422 (throw 'break nil)))
5423 (if (minusp escape-val)
5424 (js2-report-scan-error "msg.invalid.escape" t))
5425 (js2-add-to-string escape-val)
5426 (setq is-unicode-escape-start nil))
5427 (setq c (js2-get-char))
5430 (setq c (js2-get-char))
5432 (setq is-unicode-escape-start t
5434 (js2-report-scan-error "msg.illegal.character" t)))
5436 (if (or (eq c js2-EOF_CHAR)
5437 (not (js2-java-identifier-part-p c)))
5439 (js2-add-to-string c))))))
5441 (setq str (js2-get-string-from-buffer))
5442 (unless contains-escape
5443 ;; OPT we shouldn't have to make a string (object!) to
5444 ;; check if it's a keyword.
5445 ;; Return the corresponding token if it's a keyword
5446 (when (setq result (js2-string-to-keyword str))
5447 (if (and (< js2-language-version 170)
5448 (memq result '(js2-LET js2-YIELD)))
5449 ;; LET and YIELD are tokens only in 1.7 and later
5450 (setq result 'js2-NAME))
5451 (if (not (eq result 'js2-RESERVED))
5452 (throw 'return (js2-token-code result)))
5453 (js2-report-warning "msg.reserved.keyword" str)))
5454 ;; If we want to intern these as Rhino does, just use (intern str)
5455 (setq js2-ts-string str)
5456 (throw 'return js2-NAME)) ; end identifier/kwd check
5458 (when (or (js2-digit-p c)
5459 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5460 (setq js2-ts-string-buffer nil
5463 (setq c (js2-get-char))
5465 ((or (eq c ?x) (eq c ?X))
5467 (setq c (js2-get-char)))
5471 (js2-add-to-string ?0))))
5473 (while (<= 0 (js2-x-digit-to-int c 0))
5474 (js2-add-to-string c)
5475 (setq c (js2-get-char)))
5476 (while (and (<= ?0 c) (<= c ?9))
5477 ;; We permit 08 and 09 as decimal numbers, which
5478 ;; makes our behavior a superset of the ECMA
5479 ;; numeric grammar. We might not always be so
5480 ;; permissive, so we warn about it.
5481 (when (and (eq base 8) (>= c ?8))
5482 (js2-report-warning "msg.bad.octal.literal"
5483 (if (eq c ?8) "8" "9"))
5485 (js2-add-to-string c)
5486 (setq c (js2-get-char))))
5488 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5489 (setq is-integer nil)
5492 (js2-add-to-string c)
5493 (setq c (js2-get-char))
5494 while (js2-digit-p c)))
5495 (when (memq c '(?e ?E))
5496 (js2-add-to-string c)
5497 (setq c (js2-get-char))
5498 (when (memq c '(?+ ?-))
5499 (js2-add-to-string c)
5500 (setq c (js2-get-char)))
5501 (unless (js2-digit-p c)
5502 (js2-report-scan-error "msg.missing.exponent" t))
5504 (js2-add-to-string c)
5505 (setq c (js2-get-char))
5506 while (js2-digit-p c))))
5508 (setq js2-ts-string (js2-get-string-from-buffer)
5510 (if (and (eq base 10) (not is-integer))
5511 (string-to-number js2-ts-string)
5512 ;; TODO: call runtime number-parser. Some of it is in
5513 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5514 (string-to-number js2-ts-string)))
5515 (throw 'return js2-NUMBER))
5517 (when (memq c '(?\" ?\'))
5518 ;; We attempt to accumulate a string the fast way, by
5519 ;; building it directly out of the reader. But if there
5520 ;; are any escaped characters in the string, we revert to
5521 ;; building it out of a string buffer.
5523 js2-ts-string-buffer nil
5526 (while (/= c quote-char)
5528 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5530 (setq js2-token-end js2-ts-cursor)
5531 (js2-report-error "msg.unterminated.string.lit")
5532 (throw 'return js2-STRING))
5534 ;; We've hit an escaped character
5535 (setq c (js2-get-char))
5544 (setq c1 (js2-read-unicode-escape))
5545 (if js2-parse-ide-mode
5548 ;; just copy the string in IDE-mode
5549 (js2-add-to-string ?\\)
5550 (js2-add-to-string ?u)
5552 (js2-add-to-string (js2-get-char)))
5553 (setq c (js2-get-char))) ; added at end of loop
5554 ;; flag it as an invalid escape
5555 (js2-report-warning "msg.invalid.escape"
5556 nil (- js2-ts-cursor 2) 6))
5557 ;; Get 4 hex digits; if the u escape is not
5558 ;; followed by 4 hex digits, use 'u' + the
5559 ;; literal character sequence that follows.
5560 (js2-add-to-string ?u)
5563 (setq c (js2-get-char)
5564 escape-val (js2-x-digit-to-int c escape-val))
5565 (if (minusp escape-val)
5566 (throw 'continue nil))
5567 (js2-add-to-string c))
5568 ;; prepare for replace of stored 'u' sequence by escape value
5569 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5572 ;; Get 2 hex digits, defaulting to 'x'+literal
5573 ;; sequence, as above.
5574 (setq c (js2-get-char)
5575 escape-val (js2-x-digit-to-int c 0))
5576 (if (minusp escape-val)
5578 (js2-add-to-string ?x)
5579 (throw 'continue nil))
5582 escape-val (js2-x-digit-to-int c escape-val))
5583 (if (minusp escape-val)
5585 (js2-add-to-string ?x)
5586 (js2-add-to-string c1)
5587 (throw 'continue nil))
5589 (setq c escape-val))))
5591 ;; Remove line terminator after escape to follow
5592 ;; SpiderMonkey and C/C++
5593 (setq c (js2-get-char))
5594 (throw 'continue nil))
5596 (when (and (<= ?0 c) (< c ?8))
5599 (when (and (<= ?0 c) (< c ?8))
5600 (setq val (- (+ (* 8 val) c) ?0)
5602 (when (and (<= ?0 c)
5605 ;; c is 3rd char of octal sequence only
5606 ;; if the resulting val <= 0377
5607 (setq val (- (+ (* 8 val) c) ?0)
5611 (js2-add-to-string c)
5612 (setq c (js2-get-char)))))
5613 (setq js2-ts-string (js2-get-string-from-buffer))
5614 (throw 'return js2-STRING))
5617 (throw 'return js2-SEMI))
5619 (throw 'return js2-LB))
5621 (throw 'return js2-RB))
5623 (throw 'return js2-LC))
5625 (throw 'return js2-RC))
5627 (throw 'return js2-LP))
5629 (throw 'return js2-RP))
5631 (throw 'return js2-COMMA))
5633 (throw 'return js2-HOOK))
5635 (if (js2-match-char ?:)
5636 (js2-ts-return js2-COLONCOLON)
5637 (throw 'return js2-COLON)))
5639 (if (js2-match-char ?.)
5640 (js2-ts-return js2-DOTDOT)
5641 (if (js2-match-char ?\()
5642 (js2-ts-return js2-DOTQUERY)
5643 (throw 'return js2-DOT))))
5645 (if (js2-match-char ?|)
5646 (throw 'return js2-OR)
5647 (if (js2-match-char ?=)
5648 (js2-ts-return js2-ASSIGN_BITOR)
5649 (throw 'return js2-BITOR))))
5651 (if (js2-match-char ?=)
5652 (js2-ts-return js2-ASSIGN_BITOR)
5653 (throw 'return js2-BITXOR)))
5655 (if (js2-match-char ?&)
5656 (throw 'return js2-AND)
5657 (if (js2-match-char ?=)
5658 (js2-ts-return js2-ASSIGN_BITAND)
5659 (throw 'return js2-BITAND))))
5661 (if (js2-match-char ?=)
5662 (if (js2-match-char ?=)
5663 (js2-ts-return js2-SHEQ)
5664 (throw 'return js2-EQ))
5665 (throw 'return js2-ASSIGN)))
5667 (if (js2-match-char ?=)
5668 (if (js2-match-char ?=)
5669 (js2-ts-return js2-SHNE)
5670 (js2-ts-return js2-NE))
5671 (throw 'return js2-NOT)))
5673 ;; NB:treat HTML begin-comment as comment-till-eol
5674 (when (js2-match-char ?!)
5675 (when (js2-match-char ?-)
5676 (when (js2-match-char ?-)
5678 (setq js2-ts-comment-type 'html)
5679 (throw 'return js2-COMMENT)))
5681 (if (js2-match-char ?<)
5682 (if (js2-match-char ?=)
5683 (js2-ts-return js2-ASSIGN_LSH)
5684 (js2-ts-return js2-LSH))
5685 (if (js2-match-char ?=)
5686 (js2-ts-return js2-LE)
5687 (throw 'return js2-LT))))
5689 (if (js2-match-char ?>)
5690 (if (js2-match-char ?>)
5691 (if (js2-match-char ?=)
5692 (js2-ts-return js2-ASSIGN_URSH)
5693 (js2-ts-return js2-URSH))
5694 (if (js2-match-char ?=)
5695 (js2-ts-return js2-ASSIGN_RSH)
5696 (js2-ts-return js2-RSH)))
5697 (if (js2-match-char ?=)
5698 (js2-ts-return js2-GE)
5699 (throw 'return js2-GT))))
5701 (if (js2-match-char ?=)
5702 (js2-ts-return js2-ASSIGN_MUL)
5703 (throw 'return js2-MUL)))
5705 ;; is it a // comment?
5706 (when (js2-match-char ?/)
5707 (setq js2-token-beg (- js2-ts-cursor 2))
5709 (setq js2-ts-comment-type 'line)
5710 ;; include newline so highlighting goes to end of window
5711 (incf js2-token-end)
5712 (throw 'return js2-COMMENT))
5713 ;; is it a /* comment?
5714 (when (js2-match-char ?*)
5715 (setq look-for-slash nil
5716 js2-token-beg (- js2-ts-cursor 2)
5718 (if (js2-match-char ?*)
5720 (setq look-for-slash t)
5724 (setq c (js2-get-char))
5726 ((eq c js2-EOF_CHAR)
5727 (setq js2-token-end (1- js2-ts-cursor))
5728 (js2-report-error "msg.unterminated.comment")
5729 (throw 'return js2-COMMENT))
5731 (setq look-for-slash t))
5734 (js2-ts-return js2-COMMENT)))
5736 (setq look-for-slash nil
5737 js2-token-end js2-ts-cursor)))))
5738 (if (js2-match-char ?=)
5739 (js2-ts-return js2-ASSIGN_DIV)
5740 (throw 'return js2-DIV)))
5742 (when js2-skip-preprocessor-directives
5744 (setq js2-ts-comment-type 'preprocessor
5745 js2-token-end js2-ts-cursor)
5746 (throw 'return js2-COMMENT))
5747 (throw 'return js2-ERROR))
5749 (if (js2-match-char ?=)
5750 (js2-ts-return js2-ASSIGN_MOD)
5751 (throw 'return js2-MOD)))
5753 (throw 'return js2-BITNOT))
5755 (if (js2-match-char ?=)
5756 (js2-ts-return js2-ASSIGN_ADD)
5757 (if (js2-match-char ?+)
5758 (js2-ts-return js2-INC)
5759 (throw 'return js2-ADD))))
5762 ((js2-match-char ?=)
5763 (setq c js2-ASSIGN_SUB))
5764 ((js2-match-char ?-)
5765 (unless js2-ts-dirty-line
5766 ;; treat HTML end-comment after possible whitespace
5767 ;; after line start as comment-until-eol
5768 (when (js2-match-char ?>)
5770 (setq js2-ts-comment-type 'html)
5771 (throw 'return js2-COMMENT)))
5775 (setq js2-ts-dirty-line t)
5778 (js2-report-scan-error "msg.illegal.character")))))))
5780 (defun js2-read-regexp (start-token)
5781 "Called by parser when it gets / or /= in literal context."
5783 in-class ; inside a '[' .. ']' character-class
5786 (setq js2-token-beg js2-ts-cursor
5787 js2-ts-string-buffer nil
5788 js2-ts-regexp-flags nil)
5789 (if (eq start-token js2-ASSIGN_DIV)
5791 (js2-add-to-string ?=)
5792 (if (not (eq start-token js2-DIV))
5793 (error "failed assertion")))
5794 (while (and (not err)
5795 (or (/= (setq c (js2-get-char)) ?/)
5800 (setq js2-token-end (1- js2-ts-cursor)
5802 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5803 (js2-report-error "msg.unterminated.re.lit"))
5806 (js2-add-to-string c)
5807 (setq c (js2-get-char)))
5811 (setq in-class nil)))
5812 (js2-add-to-string c))))
5816 ((js2-match-char ?g)
5818 ((js2-match-char ?i)
5820 ((js2-match-char ?m)
5823 (setq continue nil))))
5824 (if (js2-alpha-p (js2-peek-char))
5825 (js2-report-scan-error "msg.invalid.re.flag" t
5827 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5828 js2-ts-regexp-flags (js2-collect-string flags)
5829 js2-token-end js2-ts-cursor)
5830 ;; tell `parse-partial-sexp' to ignore this range of chars
5831 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5833 (defun js2-get-first-xml-token ()
5834 (setq js2-ts-xml-open-tags-count 0
5835 js2-ts-is-xml-attribute nil
5836 js2-ts-xml-is-tag-content nil)
5838 (js2-get-next-xml-token))
5840 (defun js2-xml-discard-string ()
5841 "Throw away the string in progress and flag an XML parse error."
5842 (setq js2-ts-string-buffer nil
5844 (js2-report-scan-error "msg.XML.bad.form" t))
5846 (defun js2-get-next-xml-token ()
5847 (setq js2-ts-string-buffer nil ; for recording the XML
5848 js2-token-beg js2-ts-cursor)
5853 (setq c (js2-get-char))
5856 (throw 'return js2-ERROR))
5857 (js2-ts-xml-is-tag-content
5860 (js2-add-to-string c)
5861 (setq js2-ts-xml-is-tag-content nil
5862 js2-ts-is-xml-attribute nil))
5864 (js2-add-to-string c)
5865 (when (eq ?> (js2-peek-char))
5866 (setq c (js2-get-char))
5867 (js2-add-to-string c)
5868 (setq js2-ts-xml-is-tag-content nil)
5869 (decf js2-ts-xml-open-tags-count)))
5872 (setq js2-ts-string (js2-get-string-from-buffer))
5873 (throw 'return js2-XML))
5875 (js2-add-to-string c)
5876 (unless (js2-read-quoted-string c)
5877 (throw 'return js2-ERROR)))
5879 (js2-add-to-string c)
5880 (setq js2-ts-is-xml-attribute t))
5882 (js2-add-to-string c))
5884 (js2-add-to-string c)
5885 (setq js2-ts-is-xml-attribute nil)))
5886 (when (and (not js2-ts-xml-is-tag-content)
5887 (zerop js2-ts-xml-open-tags-count))
5888 (setq js2-ts-string (js2-get-string-from-buffer))
5889 (throw 'return js2-XMLEND)))
5891 ;; else not tag content
5894 (js2-add-to-string c)
5895 (setq c (js2-peek-char))
5898 (setq c (js2-get-char)) ;; skip !
5899 (js2-add-to-string c)
5900 (setq c (js2-peek-char))
5903 (setq c (js2-get-char)) ;; skip -
5904 (js2-add-to-string c)
5907 (js2-add-to-string c)
5908 (unless (js2-read-xml-comment)
5909 (throw 'return js2-ERROR)))
5910 (js2-xml-discard-string)
5911 (throw 'return js2-ERROR)))
5913 (setq c (js2-get-char)) ;; skip [
5914 (js2-add-to-string c)
5915 (if (and (= (js2-get-char) ?C)
5916 (= (js2-get-char) ?D)
5917 (= (js2-get-char) ?A)
5918 (= (js2-get-char) ?T)
5919 (= (js2-get-char) ?A)
5920 (= (js2-get-char) ?\[))
5922 (js2-add-to-string ?C)
5923 (js2-add-to-string ?D)
5924 (js2-add-to-string ?A)
5925 (js2-add-to-string ?T)
5926 (js2-add-to-string ?A)
5927 (js2-add-to-string ?\[)
5928 (unless (js2-read-cdata)
5929 (throw 'return js2-ERROR)))
5930 (js2-xml-discard-string)
5931 (throw 'return js2-ERROR)))
5933 (unless (js2-read-entity)
5934 (throw 'return js2-ERROR))))
5935 ;; Allow bare CDATA section, e.g.:
5936 ;; let xml = <![CDATA[ foo bar baz ]]>;
5937 (when (zerop js2-ts-xml-open-tags-count)
5938 (throw 'return js2-XMLEND)))
5940 (setq c (js2-get-char)) ;; skip ?
5941 (js2-add-to-string c)
5942 (unless (js2-read-PI)
5943 (throw 'return js2-ERROR)))
5946 (setq c (js2-get-char)) ;; skip /
5947 (js2-add-to-string c)
5948 (when (zerop js2-ts-xml-open-tags-count)
5949 (js2-xml-discard-string)
5950 (throw 'return js2-ERROR))
5951 (setq js2-ts-xml-is-tag-content t)
5952 (decf js2-ts-xml-open-tags-count))
5955 (setq js2-ts-xml-is-tag-content t)
5956 (incf js2-ts-xml-open-tags-count))))
5959 (setq js2-ts-string (js2-get-string-from-buffer))
5960 (throw 'return js2-XML))
5962 (js2-add-to-string c))))))))
5963 (setq js2-token-end js2-ts-cursor)
5966 (defun js2-read-quoted-string (quote)
5969 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5970 (js2-add-to-string c)
5973 (js2-xml-discard-string) ;; throw away string in progress
5976 (defun js2-read-xml-comment ()
5977 (let ((c (js2-get-char)))
5979 (while (/= c js2-EOF_CHAR)
5981 (js2-add-to-string c)
5982 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5983 (setq c (js2-get-char))
5984 (js2-add-to-string c)
5985 (if (eq (js2-peek-char) ?>)
5987 (setq c (js2-get-char)) ;; skip >
5988 (js2-add-to-string c)
5990 (throw 'continue nil)))
5991 (setq c (js2-get-char))))
5992 (js2-xml-discard-string)
5995 (defun js2-read-cdata ()
5996 (let ((c (js2-get-char)))
5998 (while (/= c js2-EOF_CHAR)
6000 (js2-add-to-string c)
6001 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6002 (setq c (js2-get-char))
6003 (js2-add-to-string c)
6004 (if (eq (js2-peek-char) ?>)
6006 (setq c (js2-get-char)) ;; Skip >
6007 (js2-add-to-string c)
6009 (throw 'continue nil)))
6010 (setq c (js2-get-char))))
6011 (js2-xml-discard-string)
6014 (defun js2-read-entity ()
6018 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6019 (js2-add-to-string c)
6025 (if (zerop decl-tags)
6026 (throw 'return t)))))
6027 (js2-xml-discard-string)
6030 (defun js2-read-PI ()
6031 "Scan an XML processing instruction."
6034 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6035 (js2-add-to-string c)
6036 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6037 (setq c (js2-get-char)) ;; Skip >
6038 (js2-add-to-string c)
6040 (js2-xml-discard-string)
6043 (defun js2-scanner-get-line ()
6044 "Return the text of the current scan line."
6045 (buffer-substring (point-at-bol) (point-at-eol)))
6049 (defun js2-set-face (beg end face &optional record)
6050 "Fontify a region. If RECORD is non-nil, record for later."
6051 (when (plusp js2-highlight-level)
6052 (setq beg (min (point-max) beg)
6053 beg (max (point-min) beg)
6054 end (min (point-max) end)
6055 end (max (point-min) end))
6057 (push (list beg end face) js2-mode-fontifications)
6058 (put-text-property beg end 'font-lock-face face))))
6060 (defun js2-set-kid-face (pos kid len face)
6061 "Set-face on a child node.
6062 POS is absolute buffer position of parent.
6063 KID is the child node.
6064 LEN is the length to fontify.
6065 FACE is the face to fontify with."
6066 (js2-set-face (+ pos (js2-node-pos kid))
6067 (+ pos (js2-node-pos kid) (js2-node-len kid))
6070 (defsubst js2-fontify-kwd (start length)
6071 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6073 (defsubst js2-clear-face (beg end)
6074 (remove-text-properties beg end '(font-lock-face nil
6079 (defconst js2-ecma-global-props
6082 '("Infinity" "NaN" "undefined" "arguments") t)
6084 "Value properties of the Ecma-262 Global Object.
6085 Shown at or above `js2-highlight-level' 2.")
6087 ;; might want to add the name "arguments" to this list?
6088 (defconst js2-ecma-object-props
6091 '("prototype" "__proto__" "__parent__") t)
6093 "Value properties of the Ecma-262 Object constructor.
6094 Shown at or above `js2-highlight-level' 2.")
6096 (defconst js2-ecma-global-funcs
6100 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6101 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6103 "Function properties of the Ecma-262 Global object.
6104 Shown at or above `js2-highlight-level' 2.")
6106 (defconst js2-ecma-number-props
6108 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6110 "POSITIVE_INFINITY") t)
6112 "Properties of the Ecma-262 Number constructor.
6113 Shown at or above `js2-highlight-level' 2.")
6115 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6116 "Properties of the Ecma-262 Date constructor.
6117 Shown at or above `js2-highlight-level' 2.")
6119 (defconst js2-ecma-math-props
6122 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6125 "Properties of the Ecma-262 Math object.
6126 Shown at or above `js2-highlight-level' 2.")
6128 (defconst js2-ecma-math-funcs
6131 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6132 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6134 "Function properties of the Ecma-262 Math object.
6135 Shown at or above `js2-highlight-level' 2.")
6137 (defconst js2-ecma-function-props
6141 '(;; properties of the Object prototype object
6142 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6143 "toLocaleString" "toString" "valueOf"
6144 ;; properties of the Function prototype object
6146 ;; properties of the Array prototype object
6147 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6149 ;; properties of the String prototype object
6150 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6151 "localeCompare" "match" "replace" "search" "split" "substring"
6152 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6154 ;; properties of the Number prototype object
6155 "toExponential" "toFixed" "toPrecision"
6156 ;; properties of the Date prototype object
6157 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6158 "getMinutes" "getMonth" "getSeconds" "getTime"
6159 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6160 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6161 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6162 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6163 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6164 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6165 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6166 "toTimeString" "toUTCString"
6167 ;; properties of the RegExp prototype object
6169 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6170 "toSource" "__defineGetter__" "__defineSetter__"
6171 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6172 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6175 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6176 Shown at or above `js2-highlight-level' 3.")
6178 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6179 (let ((target-name (and target
6180 (js2-name-node-p target)
6181 (js2-name-node-name target)))
6182 (prop-name (if prop (js2-name-node-name prop)))
6183 (level1 (>= js2-highlight-level 1))
6184 (level2 (>= js2-highlight-level 2))
6185 (level3 (>= js2-highlight-level 3))
6192 ((and level3 (string-match js2-ecma-function-props prop-name))
6193 (setq face 'font-lock-builtin-face))
6194 ((and target-name prop)
6196 ((string= target-name "Date")
6197 (if (string-match js2-ecma-date-props prop-name)
6198 (setq face 'font-lock-builtin-face)))
6199 ((string= target-name "Math")
6200 (if (string-match js2-ecma-math-funcs prop-name)
6201 (setq face 'font-lock-builtin-face)))))))
6203 (if (string-match js2-ecma-global-funcs prop-name)
6204 (setq face 'font-lock-builtin-face))))
6208 ((string= target-name "Number")
6209 (if (string-match js2-ecma-number-props prop-name)
6210 (setq face 'font-lock-constant-face)))
6211 ((string= target-name "Math")
6212 (if (string-match js2-ecma-math-props prop-name)
6213 (setq face 'font-lock-constant-face)))))
6215 (if (string-match js2-ecma-object-props prop-name)
6216 (setq face 'font-lock-constant-face)))))
6218 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6219 (js2-node-pos prop))) ; relative
6220 (+ pos (js2-node-len prop))
6223 (defun js2-parse-highlight-member-expr-node (node)
6224 "Perform syntax highlighting of EcmaScript built-in properties.
6225 The variable `js2-highlight-level' governs this highighting."
6226 (let (face target prop name pos end parent call-p callee)
6228 ;; case 1: simple name, e.g. foo
6229 ((js2-name-node-p node)
6230 (setq name (js2-name-node-name node))
6231 ;; possible for name to be nil in rare cases - saw it when
6232 ;; running js2-mode on an elisp buffer. Might as well try to
6233 ;; make it so js2-mode never barfs.
6235 (setq face (if (string-match js2-ecma-global-props name)
6236 'font-lock-constant-face))
6238 (setq pos (js2-node-pos node)
6239 end (+ pos (js2-node-len node)))
6240 (js2-set-face pos end face))))
6241 ;; case 2: property access or function call
6242 ((or (js2-prop-get-node-p node)
6243 ;; highlight function call if expr is a prop-get node
6244 ;; or a plain name (i.e. unqualified function call)
6245 (and (setq call-p (js2-call-node-p node))
6246 (setq callee (js2-call-node-target node)) ; separate setq!
6247 (or (js2-prop-get-node-p callee)
6248 (js2-name-node-p callee))))
6250 node (if call-p callee node))
6251 (if (and call-p (js2-name-node-p callee))
6253 (setq target (js2-prop-get-node-left node)
6254 prop (js2-prop-get-node-right node)))
6256 ((js2-name-node-p target)
6257 (if (js2-name-node-p prop)
6258 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6259 (js2-parse-highlight-prop-get parent target prop call-p)
6260 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6261 (js2-parse-highlight-prop-get parent target nil call-p)))
6262 ((js2-name-node-p prop)
6263 ;; case 2c: complex target, simple name, e.g. x[y].bar
6264 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6266 (defun js2-parse-highlight-member-expr-fn-name (expr)
6267 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6268 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6269 We currently only handle the case where the last component is a prop-get
6270 of a simple name. Called before EXPR has a parent node."
6272 (name (and (js2-prop-get-node-p expr)
6273 (js2-prop-get-node-right expr))))
6274 (when (js2-name-node-p name)
6275 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6276 (js2-node-pos name)))
6277 (+ pos (js2-node-len name))
6278 'font-lock-function-name-face
6281 ;; source: http://jsdoc.sourceforge.net/
6282 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6283 ;; allows type specifications, and needs work before entering the wild.
6285 (defconst js2-jsdoc-param-tag-regexp
6286 (concat "^\\s-*\\*+\\s-*\\(@"
6287 "\\(?:param\\|argument\\)"
6289 "\\s-*\\({[^}]+}\\)?" ; optional type
6290 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6292 "Matches jsdoc tags with optional type and optional param name.")
6294 (defconst js2-jsdoc-typed-tag-regexp
6295 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6309 "\\)\\)\\s-*\\({[^}]+}\\)?")
6310 "Matches jsdoc tags with optional type.")
6312 (defconst js2-jsdoc-arg-tag-regexp
6313 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6336 "\\)\\)\\s-+\\([^ \t]+\\)")
6337 "Matches jsdoc tags with a single argument.")
6339 (defconst js2-jsdoc-empty-tag-regexp
6340 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6380 "Matches empty jsdoc tags.")
6382 (defconst js2-jsdoc-link-tag-regexp
6383 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6384 "Matches a jsdoc link or code tag.")
6386 (defconst js2-jsdoc-see-tag-regexp
6387 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6388 "Matches a jsdoc @see tag.")
6390 (defconst js2-jsdoc-html-tag-regexp
6391 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6392 "Matches a simple (no attributes) html start- or end-tag.")
6394 (defun js2-jsdoc-highlight-helper ()
6395 (js2-set-face (match-beginning 1)
6398 (if (match-beginning 2)
6400 (goto-char (match-beginning 2))
6401 (= (char-after) ?{))
6402 (js2-set-face (1+ (match-beginning 2))
6405 (js2-set-face (match-beginning 2)
6408 (if (match-beginning 3)
6409 (js2-set-face (match-beginning 3)
6413 (defun js2-highlight-jsdoc (ast)
6414 "Highlight doc comment tags."
6415 (let ((comments (js2-ast-root-comments ast))
6418 (dolist (node comments)
6419 (when (eq (js2-comment-node-format node) 'jsdoc)
6420 (setq beg (js2-node-abs-pos node)
6421 end (+ beg (js2-node-len node)))
6423 (narrow-to-region beg end)
6424 (dolist (re (list js2-jsdoc-param-tag-regexp
6425 js2-jsdoc-typed-tag-regexp
6426 js2-jsdoc-arg-tag-regexp
6427 js2-jsdoc-link-tag-regexp
6428 js2-jsdoc-see-tag-regexp
6429 js2-jsdoc-empty-tag-regexp))
6431 (while (re-search-forward re nil t)
6432 (js2-jsdoc-highlight-helper)))
6433 ;; simple highlighting for html tags
6435 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6436 (js2-set-face (match-beginning 1)
6438 'js2-jsdoc-html-tag-delimiter)
6439 (js2-set-face (match-beginning 2)
6441 'js2-jsdoc-html-tag-name)
6442 (js2-set-face (match-beginning 3)
6444 'js2-jsdoc-html-tag-delimiter))))))))
6446 (defun js2-highlight-assign-targets (node left right)
6447 "Highlight function properties and external variables."
6448 (let (leftpos end name)
6449 ;; highlight vars and props assigned function values
6450 (when (js2-function-node-p right)
6452 ;; var foo = function() {...}
6453 ((js2-name-node-p left)
6455 ;; foo.bar.baz = function() {...}
6456 ((and (js2-prop-get-node-p left)
6457 (js2-name-node-p (js2-prop-get-node-right left)))
6458 (setq name (js2-prop-get-node-right left))))
6460 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6461 (+ leftpos (js2-node-len name))
6462 'font-lock-function-name-face
6465 (defun js2-record-name-node (node)
6466 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6467 later. NODE must be a name node."
6469 (push (list node js2-current-scope
6470 (setq leftpos (js2-node-abs-pos node))
6471 (setq end (+ leftpos (js2-node-len node))))
6472 js2-recorded-identifiers)))
6474 (defun js2-highlight-undeclared-vars ()
6475 "After entire parse is finished, look for undeclared variable references.
6476 We have to wait until entire buffer is parsed, since JavaScript permits var
6477 decls to occur after they're used.
6479 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6480 it is considered declared."
6482 (dolist (entry js2-recorded-identifiers)
6483 (destructuring-bind (name-node scope pos end) entry
6484 (setq name (js2-name-node-name name-node))
6485 (unless (or (member name js2-global-externs)
6486 (member name js2-default-externs)
6487 (member name js2-additional-externs)
6488 (js2-get-defining-scope scope name))
6489 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)))))
6490 (setq js2-recorded-identifiers nil)))
6494 ;; We currently only support imenu, but eventually should support speedbar and
6495 ;; possibly other browsing mechanisms.
6497 ;; The basic strategy is to identify function assignment targets of the form
6498 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6499 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6500 ;; for imenu after parsing is finished.
6502 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6503 ;; JavaScript, and the general problem is undecidable. However, several forms
6504 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6507 ;; function foo() -- function declaration
6508 ;; foo = function() -- function expression assigned to variable
6509 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6510 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6511 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6512 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6513 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6514 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6515 ;; function foo() {function bar() {...}} -- nested function
6516 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6518 ;; This list boils down to a few forms that can be combined recursively.
6519 ;; Top-level named function declarations include both the left-hand (name)
6520 ;; and the right-hand (function value) expressions needed to produce an imenu
6521 ;; entry. The other "right-hand" forms we need to look for are:
6522 ;; - functions declared as props/getters/setters in object literals
6523 ;; - nested named function declarations
6524 ;; The "left-hand" expressions that functions can be assigned to include:
6525 ;; - local/global variables
6526 ;; - nested property-get expressions like a.b.c.d
6527 ;; - element gets like foo[10] or foo['bar'] where the index
6528 ;; expression can be trivially converted to a property name. They
6529 ;; effectively then become property gets.
6531 ;; All the different definition types are canonicalized into the form
6532 ;; foo.bar.baz = position-of-function-keyword
6534 ;; We need to build a trie-like structure for imenu. As an example,
6535 ;; consider the following JavaScript code:
6537 ;; a = function() {...} // function at position 5
6538 ;; b = function() {...} // function at position 25
6539 ;; foo = function() {...} // function at position 100
6540 ;; foo.bar = function() {...} // function at position 200
6541 ;; foo.bar.baz = function() {...} // function at position 300
6542 ;; foo.bar.zab = function() {...} // function at position 400
6544 ;; During parsing we accumulate an entry for each definition in
6545 ;; the variable `js2-imenu-recorder', like so:
6551 ;; (fn foo bar baz 300)
6552 ;; (fn foo bar zab 400))
6554 ;; Where 'fn' is the respective function node.
6555 ;; After parsing these entries are merged into this alist-trie:
6559 ;; (foo (<definition> . 3)
6560 ;; (bar (<definition> . 6)
6564 ;; Note the wacky need for a <definition> name. The token can be anything
6565 ;; that isn't a valid JavaScript identifier, because you might make foo
6566 ;; a function and then start setting properties on it that are also functions.
6568 (defun js2-prop-node-name (node)
6569 "Return the name of a node that may be a property-get/property-name.
6570 If NODE is not a valid name-node, string-node or integral number-node,
6571 returns nil. Otherwise returns the string name/value of the node."
6573 ((js2-name-node-p node)
6574 (js2-name-node-name node))
6575 ((js2-string-node-p node)
6576 (js2-string-node-value node))
6577 ((and (js2-number-node-p node)
6578 (string-match "^[0-9]+$" (js2-number-node-value node)))
6579 (js2-number-node-value node))
6580 ((js2-this-node-p node)
6583 (defun js2-node-qname-component (node)
6584 "Return the name of this node, if it contributes to a qname.
6585 Returns nil if the node doesn't contribute."
6587 (or (js2-prop-node-name node)
6588 (if (and (js2-function-node-p node)
6589 (js2-function-node-name node))
6590 (js2-name-node-name (js2-function-node-name node))))))
6592 (defun js2-record-imenu-entry (fn-node qname pos)
6593 "Add an entry to `js2-imenu-recorder'.
6594 FN-NODE should be the current item's function node.
6596 Associate FN-NODE with its QNAME for later lookup.
6597 This is used in postprocessing the chain list. For each chain, we find
6598 the parent function, look up its qname, then prepend a copy of it to the chain."
6599 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6600 (unless js2-imenu-function-map
6601 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6602 (puthash fn-node qname js2-imenu-function-map))
6604 (defun js2-record-imenu-functions (node &optional var)
6605 "Record function definitions for imenu.
6606 NODE is a function node or an object literal.
6607 VAR, if non-nil, is the expression that NODE is being assigned to.
6608 When passed arguments of wrong type, does nothing."
6609 (when js2-parse-ide-mode
6610 (let ((fun-p (js2-function-node-p node))
6611 qname left fname-node pos)
6613 ;; non-anonymous function declaration?
6616 (setq fname-node (js2-function-node-name node)))
6617 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6618 ;; for remaining forms, compute left-side tree branch first
6619 ((and var (setq qname (js2-compute-nested-prop-get var)))
6621 ;; foo.bar.baz = function
6623 (js2-record-imenu-entry node qname (js2-node-pos node)))
6624 ;; foo.bar.baz = object-literal
6625 ;; look for nested functions: {a: {b: function() {...} }}
6626 ((js2-object-node-p node)
6627 ;; Node position here is still absolute, since the parser
6628 ;; passes the assignment target and value expressions
6629 ;; to us before they are added as children of the assignment node.
6630 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6632 (defun js2-compute-nested-prop-get (node)
6633 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6634 component nodes as a list. Otherwise return nil. Element-gets are treated
6635 as property-gets if the index expression is a string, or a positive integer."
6636 (let (left right head)
6638 ((or (js2-name-node-p node)
6639 (js2-this-node-p node))
6641 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6642 ((js2-prop-get-node-p node) ; foo.bar
6643 (setq left (js2-prop-get-node-left node)
6644 right (js2-prop-get-node-right node))
6645 (if (setq head (js2-compute-nested-prop-get left))
6646 (nconc head (list right))))
6647 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6648 (setq left (js2-elem-get-node-target node)
6649 right (js2-elem-get-node-element node))
6650 (if (or (js2-string-node-p right) ; ['bar']
6651 (and (js2-number-node-p right) ; [10]
6652 (string-match "^[0-9]+$"
6653 (js2-number-node-value right))))
6654 (if (setq head (js2-compute-nested-prop-get left))
6655 (nconc head (list right))))))))
6657 (defun js2-record-object-literal (node qname pos)
6658 "Recursively process an object literal looking for functions.
6659 NODE is an object literal that is the right-hand child of an assignment
6660 expression. QNAME is a list of nodes representing the assignment target,
6661 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6662 POS is the absolute position of the node.
6663 We do a depth-first traversal of NODE. For any functions we find,
6664 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6665 (let (left right prop-qname)
6666 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6667 (let ((left (js2-infix-node-left e))
6668 ;; Element positions are relative to the parent position.
6669 (pos (+ pos (js2-node-pos e))))
6671 ;; foo: function() {...}
6672 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6673 (when (js2-prop-node-name left)
6674 ;; As a policy decision, we record the position of the property,
6675 ;; not the position of the `function' keyword, since the property
6676 ;; is effectively the name of the function.
6677 (js2-record-imenu-entry right (append qname (list left)) pos)))
6678 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6679 ((js2-object-node-p right)
6680 (js2-record-object-literal right
6681 (append qname (list (js2-infix-node-left e)))
6682 (+ pos (js2-node-pos right)))))))))
6684 (defun js2-node-top-level-decl-p (node)
6685 "Return t if NODE's name is defined in the top-level scope.
6686 Also returns t if NODE's name is not defined in any scope, since it implies
6687 that it's an external variable, which must also be in the top-level scope."
6688 (let* ((name (js2-prop-node-name node))
6689 (this-scope (js2-node-get-enclosing-scope node))
6692 ((js2-this-node-p node)
6696 ((setq defining-scope (js2-get-defining-scope this-scope name))
6697 (js2-ast-root-p defining-scope))
6700 (defun js2-wrapper-function-p (node)
6701 "Returns t if NODE is a function expression that's immediately invoked.
6702 NODE must be `js2-function-node'."
6703 (let ((parent (js2-node-parent node)))
6705 ;; function(){...}();
6706 (js2-call-node-p parent)
6707 (and (js2-paren-node-p parent)
6708 ;; (function(){...})();
6709 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6710 ;; (function(){...}).call(this);
6711 (and (js2-prop-get-node-p parent)
6712 (member (js2-name-node-name (js2-prop-get-node-right parent))
6714 (js2-call-node-p (js2-node-parent parent))))))))
6716 (defun js2-browse-postprocess-chains (entries)
6717 "Modify function-declaration name chains after parsing finishes.
6718 Some of the information is only available after the parse tree is complete.
6719 For instance, processing a nested scope requires a parent function node."
6720 (let (result head fn current-fn parent-qname qname p elem)
6721 (dolist (entry entries)
6722 ;; function node goes first
6723 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6724 ;; Examine head's defining scope:
6725 ;; Pre-processed chain, or top-level/external, keep as-is.
6726 (if (or (stringp head) (js2-node-top-level-decl-p head))
6728 (when (js2-this-node-p head)
6729 (setq chain (cdr chain))) ; discard this-node
6730 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6731 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6732 (when (eq parent-qname 'not-found)
6733 ;; anonymous function expressions are not recorded
6734 ;; during the parse, so we need to handle this case here
6736 (if (js2-wrapper-function-p fn)
6737 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6738 (if (js2-ast-root-p grandparent)
6740 (gethash grandparent js2-imenu-function-map 'skip)))
6742 (puthash fn parent-qname js2-imenu-function-map))
6743 (unless (eq parent-qname 'skip)
6744 ;; prefix parent fn qname to this chain.
6745 (let ((qname (append parent-qname chain)))
6746 (puthash current-fn (butlast qname) js2-imenu-function-map)
6747 (push qname result)))))))
6748 ;; finally replace each node in each chain with its name.
6749 (dolist (chain result)
6752 (if (js2-node-p (setq elem (car p)))
6753 (setcar p (js2-node-qname-component elem)))
6757 ;; Merge name chains into a trie-like tree structure of nested lists.
6758 ;; To simplify construction of the trie, we first build it out using the rule
6759 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6760 ;; [key, num-or-list]. The second element can be a number; if so, this key
6761 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6762 ;; associated with the key at this level.) Otherwise the second element is
6763 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6764 ;; a simple recursive formulation.
6766 ;; js2-mode is building the data structure for imenu. The imenu documentation
6767 ;; claims that it's the structure above, but in practice it wants the children
6768 ;; at the same list level as the key for that level, which is how I've drawn
6769 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6770 ;; list wrapper around the children at each level.
6772 ;; A completed nested imenu-alist entry looks like this:
6774 ;; ("<definition>" . 7)
6779 ;; In particular, the documentation for `imenu--index-alist' says that
6780 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6781 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6783 (defun js2-treeify (lst)
6784 "Convert (a b c d) to (a ((b ((c d)))))."
6785 (if (null (cddr lst)) ; list length <= 2
6787 (list (car lst) (list (js2-treeify (cdr lst))))))
6789 (defun js2-build-alist-trie (chains trie)
6790 "Merge declaration name chains into a trie-like alist structure for imenu.
6791 CHAINS is the qname chain list produced during parsing. TRIE is a
6792 list of elements built up so far."
6793 (let (head tail pos branch kids)
6794 (dolist (chain chains)
6795 (setq head (car chain)
6797 pos (if (numberp (car tail)) (car tail))
6798 branch (js2-find-if (lambda (n)
6799 (string= (car n) head))
6801 kids (second branch))
6803 ;; case 1: this key isn't in the trie yet
6806 (setcdr (last trie) (list (js2-treeify chain)))
6807 (setq trie (list (js2-treeify chain)))))
6808 ;; case 2: key is present with a single number entry: replace w/ list
6809 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6810 ;; ("<definition>" 20)))
6812 (setcar (cdr branch)
6813 (list (list "<definition-1>" kids)
6815 (list "<definition-2>" pos)
6816 (js2-treeify tail)))))
6817 ;; case 3: key is there (with kids), and we're a number entry
6821 (list (format "<definition-%d>"
6822 (1+ (loop for kid in kids
6823 count (eq ?< (aref (car kid) 0)))))
6825 ;; case 4: key is there with kids, need to merge in our chain
6827 (js2-build-alist-trie (list tail) kids))))
6830 (defun js2-flatten-trie (trie)
6831 "Convert TRIE to imenu-format.
6832 Recurses through nodes, and for each one whose second element is a list,
6833 appends the list's flattened elements to the current element. Also
6834 changes the tails into conses. For instance, this pre-flattened trie
6846 Note that the root of the trie has no key, just a list of chains.
6847 This is also true for the value of any key with multiple children,
6848 e.g. key 'c' in the example above."
6851 (mapcar #'js2-flatten-trie trie))
6853 (if (numberp (second trie))
6854 (cons (car trie) (second trie))
6855 ;; else pop list and append its kids
6856 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6858 (defun js2-build-imenu-index ()
6859 "Turn `js2-imenu-recorder' into an imenu data structure."
6860 (unless (eq js2-imenu-recorder 'empty)
6861 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6862 (result (js2-build-alist-trie chains nil)))
6863 (js2-flatten-trie result))))
6865 (defun js2-test-print-chains (chains)
6866 "Print a list of qname chains.
6867 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6868 i.e. one or more nodes, and an integer position as the list tail."
6869 (mapconcat (lambda (chain)
6871 (mapconcat (lambda (elem)
6872 (if (js2-node-p elem)
6873 (or (js2-node-qname-component elem)
6875 (number-to-string elem)))
6884 (defconst js2-version "1.8.0"
6885 "Version of JavaScript supported, plus minor js2 version.")
6887 (defmacro js2-record-face (face)
6888 "Record a style run of FACE for the current token."
6889 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6891 (defsubst js2-node-end (n)
6892 "Computes the absolute end of node N.
6893 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6894 is only true until the node is added to its parent; i.e., while parsing."
6898 (defun js2-record-comment ()
6899 "Record a comment in `js2-scanned-comments'."
6900 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6901 :format js2-ts-comment-type)
6902 js2-scanned-comments)
6903 (when js2-parse-ide-mode
6904 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6906 'font-lock-comment-face))
6907 (when (memq js2-ts-comment-type '(html preprocessor))
6908 ;; Tell cc-engine the bounds of the comment.
6909 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6911 ;; This function is called depressingly often, so it should be fast.
6912 ;; Most of the time it's looking at the same token it peeked before.
6913 (defun js2-peek-token ()
6914 "Return the next token without consuming it.
6915 If previous token was consumed, calls scanner to get new token.
6916 If previous token was -not- consumed, returns it (idempotent).
6918 This function will not return a newline (js2-EOL) - instead, it
6919 gobbles newlines until it finds a non-newline token, and flags
6920 that token as appearing just after a newline.
6922 This function will also not return a js2-COMMENT. Instead, it
6923 records comments found in `js2-scanned-comments'. If the token
6924 returned by this function immediately follows a jsdoc comment,
6925 the token is flagged as such.
6927 Note that this function always returned the un-flagged token!
6928 The flags, if any, are saved in `js2-current-flagged-token'."
6929 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6930 js2-current-token ; most common case - return already-peeked token
6931 (let ((tt (js2-get-token)) ; call scanner
6934 ;; process comments and whitespace
6935 (while (or (= tt js2-EOL)
6940 (if js2-record-comments
6941 (js2-record-comment)))
6942 (setq tt (js2-get-token))) ; call scanner
6943 (setq js2-current-token tt
6944 js2-current-flagged-token (if saw-eol
6945 (logior tt js2-ti-after-eol)
6947 ;; perform lexical fontification as soon as token is scanned
6948 (when js2-parse-ide-mode
6951 (js2-record-face 'js2-error))
6952 ((setq face (aref js2-kwd-tokens tt))
6953 (js2-record-face face))
6954 ((and (= tt js2-NAME)
6955 (equal js2-ts-string "undefined"))
6956 (js2-record-face 'font-lock-constant-face))))
6957 tt))) ; return unflagged token
6959 (defun js2-peek-flagged-token ()
6960 "Returns the current token along with any flags set for it."
6962 js2-current-flagged-token)
6964 (defsubst js2-consume-token ()
6965 (setq js2-current-flagged-token js2-EOF))
6967 (defun js2-next-token ()
6970 (js2-consume-token)))
6972 (defun js2-next-flagged-token ()
6974 (prog1 js2-current-flagged-token
6975 (js2-consume-token)))
6977 (defun js2-match-token (match)
6978 "Consume and return t if next token matches MATCH, a bytecode.
6979 Returns nil and consumes nothing if MATCH is not the next token."
6980 (if (/= (js2-peek-token) match)
6985 (defun js2-valid-prop-name-token (tt)
6987 (and js2-allow-keywords-as-property-names
6989 (aref js2-kwd-tokens tt))))
6991 (defun js2-match-prop-name ()
6992 "Consume token and return t if next token is a valid property name.
6993 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
6994 is non-nil and it's a keyword token."
6995 (if (js2-valid-prop-name-token (js2-peek-token))
7001 (defun js2-must-match-prop-name (msg-id &optional pos len)
7002 (if (js2-match-prop-name)
7004 (js2-report-error msg-id nil pos len)
7007 (defun js2-peek-token-or-eol ()
7008 "Return js2-EOL if the current token immediately follows a newline.
7009 Else returns the current token. Used in situations where we don't
7010 consider certain token types valid if they are preceded by a newline.
7011 One example is the postfix ++ or -- operator, which has to be on the
7012 same line as its operand."
7013 (let ((tt (js2-peek-token)))
7014 ;; Check for last peeked token flags
7015 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7019 (defun js2-set-check-for-label ()
7020 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7021 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7023 (defun js2-must-match (token msg-id &optional pos len)
7024 "Match next token to token code TOKEN, or record a syntax error.
7025 MSG-ID is the error message to report if the match fails.
7026 Returns t on match, nil if no match."
7027 (if (js2-match-token token)
7029 (js2-report-error msg-id nil pos len)
7032 (defsubst js2-inside-function ()
7033 (plusp js2-nesting-of-function))
7035 (defun js2-set-requires-activation ()
7036 (if (js2-function-node-p js2-current-script-or-fn)
7037 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7039 (defun js2-check-activation-name (name token)
7040 (when (js2-inside-function)
7041 ;; skip language-version 1.2 check from Rhino
7042 (if (or (string= "arguments" name)
7043 (and js2-compiler-activation-names ; only used in codegen
7044 (gethash name js2-compiler-activation-names)))
7045 (js2-set-requires-activation))))
7047 (defun js2-set-is-generator ()
7048 (if (js2-function-node-p js2-current-script-or-fn)
7049 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7051 (defun js2-must-have-xml ()
7052 (unless js2-compiler-xml-available
7053 (js2-report-error "msg.XML.not.available")))
7055 (defun js2-push-scope (scope)
7056 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7057 (assert (js2-scope-p scope))
7058 (assert (null (js2-scope-parent-scope scope)))
7059 (assert (not (eq js2-current-scope scope)))
7060 (setf (js2-scope-parent-scope scope) js2-current-scope
7061 js2-current-scope scope))
7063 (defsubst js2-pop-scope ()
7064 (setq js2-current-scope
7065 (js2-scope-parent-scope js2-current-scope)))
7067 (defun js2-enter-loop (loop-node)
7068 (push loop-node js2-loop-set)
7069 (push loop-node js2-loop-and-switch-set)
7070 (js2-push-scope loop-node)
7071 ;; Tell the current labeled statement (if any) its statement,
7072 ;; and set the jump target of the first label to the loop.
7073 ;; These are used in `js2-parse-continue' to verify that the
7074 ;; continue target is an actual labeled loop. (And for codegen.)
7075 (when js2-labeled-stmt
7076 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7077 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7078 js2-labeled-stmt))) loop-node)))
7080 (defun js2-exit-loop ()
7082 (pop js2-loop-and-switch-set)
7085 (defsubst js2-enter-switch (switch-node)
7086 (push switch-node js2-loop-and-switch-set))
7088 (defsubst js2-exit-switch ()
7089 (pop js2-loop-and-switch-set))
7091 (defun js2-parse (&optional buf cb)
7092 "Tell the js2 parser to parse a region of JavaScript.
7094 BUF is a buffer or buffer name containing the code to parse.
7095 Call `narrow-to-region' first to parse only part of the buffer.
7097 The returned AST root node is given some additional properties:
7098 `node-count' - total number of nodes in the AST
7099 `buffer' - BUF. The buffer it refers to may change or be killed,
7100 so the value is not necessarily reliable.
7102 An optional callback CB can be specified to report parsing
7103 progress. If `(functionp CB)' returns t, it will be called with
7104 the current line number once before parsing begins, then again
7105 each time the lexer reaches a new line number.
7107 CB can also be a list of the form `(symbol cb ...)' to specify
7108 multiple callbacks with different criteria. Each symbol is a
7109 criterion keyword, and the following element is the callback to
7112 :line - called whenever the line number changes
7113 :token - called for each new token consumed
7115 The list of criteria could be extended to include entering or
7116 leaving a statement, an expression, or a function definition."
7117 (if (and cb (not (functionp cb)))
7118 (error "criteria callbacks not yet implemented"))
7119 (let ((inhibit-point-motion-hooks t)
7120 (js2-compiler-xml-available (>= js2-language-version 160))
7121 ;; This is a recursive-descent parser, so give it a big stack.
7122 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7123 (max-specpdl-size (max max-specpdl-size 3000))
7124 (case-fold-search nil)
7126 (message nil) ; clear any error message from previous parse
7127 (with-current-buffer (or buf (current-buffer))
7128 (setq js2-scanned-comments nil
7129 js2-parsed-errors nil
7130 js2-parsed-warnings nil
7131 js2-imenu-recorder nil
7132 js2-imenu-function-map nil
7135 (setq ast (with-silent-modifications
7137 (unless js2-ts-hit-eof
7138 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7139 (setf (js2-ast-root-errors ast) js2-parsed-errors
7140 (js2-ast-root-warnings ast) js2-parsed-warnings)
7141 ;; if we didn't find any declarations, put a dummy in this list so we
7142 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7143 (unless js2-imenu-recorder
7144 (setq js2-imenu-recorder 'empty))
7145 (run-hooks 'js2-parse-finished-hook)
7148 ;; Corresponds to Rhino's Parser.parse() method.
7149 (defun js2-do-parse ()
7150 "Parse current buffer starting from current point.
7151 Scanner should be initialized."
7152 (let ((pos js2-ts-cursor)
7153 (end js2-ts-cursor) ; in case file is empty
7155 ;; initialize buffer-local parsing vars
7156 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7157 js2-current-script-or-fn root
7158 js2-current-scope root
7159 js2-current-flagged-token js2-EOF
7160 js2-nesting-of-function 0
7161 js2-labeled-stmt nil
7162 js2-recorded-identifiers nil) ; for js2-highlight
7163 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7164 (if (= tt js2-FUNCTION)
7167 (setq n (js2-parse-function (if js2-called-by-compile-function
7168 'FUNCTION_EXPRESSION
7169 'FUNCTION_STATEMENT))))
7170 ;; not a function - parse a statement
7171 (setq n (js2-parse-statement)))
7172 ;; add function or statement to script
7173 (setq end (js2-node-end n))
7174 (js2-block-node-push root n))
7175 ;; add comments to root in lexical order
7176 (when js2-scanned-comments
7177 ;; if we find a comment beyond end of normal kids, use its end
7178 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7179 (dolist (comment js2-scanned-comments)
7180 (push comment (js2-ast-root-comments root))
7181 (js2-node-add-children root comment)))
7182 (setf (js2-node-len root) (- end pos))
7183 ;; Give extensions a chance to muck with things before highlighting starts.
7184 (let ((js2-additional-externs js2-additional-externs))
7186 (dolist (callback js2-post-parse-callbacks)
7187 (funcall callback)))
7188 (js2-highlight-undeclared-vars))
7191 (defun js2-function-parser ()
7193 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7195 (defun js2-parse-function-closure-body (fn-node)
7196 "Parse a JavaScript 1.8 function closure body."
7197 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7199 (js2-report-error "msg.no.brace.body" nil
7200 (js2-node-pos fn-node)
7201 (- js2-ts-cursor (js2-node-pos fn-node)))
7202 (js2-node-add-children fn-node
7203 (setf (js2-function-node-body fn-node)
7204 (js2-parse-expr t))))))
7206 (defun js2-parse-function-body (fn-node)
7207 (js2-must-match js2-LC "msg.no.brace.body"
7208 (js2-node-pos fn-node)
7209 (- js2-ts-cursor (js2-node-pos fn-node)))
7210 (let ((pos js2-token-beg) ; LC position
7211 (pn (make-js2-block-node)) ; starts at LC position
7214 (incf js2-nesting-of-function)
7216 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7219 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7220 (js2-parse-statement)
7222 (js2-parse-function 'FUNCTION_STATEMENT))))
7223 (decf js2-nesting-of-function))
7224 (setq end js2-token-end) ; assume no curly and leave at current token
7225 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7226 (setq end js2-token-end))
7227 (setf (js2-node-pos pn) pos
7228 (js2-node-len pn) (- end pos))
7229 (setf (js2-function-node-body fn-node) pn)
7230 (js2-node-add-children fn-node pn)
7233 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7234 "Declare and fontify destructuring parameters inside NODE.
7235 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7237 ((js2-name-node-p node)
7239 (js2-define-symbol decl-type (js2-name-node-name node)
7240 node ignore-not-in-block)
7242 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7243 (+ leftpos (js2-node-len node))
7245 ((js2-object-node-p node)
7246 (dolist (elem (js2-object-node-elems node))
7247 (js2-define-destruct-symbols
7248 (if (js2-object-prop-node-p elem)
7249 (js2-object-prop-node-right elem)
7250 ;; abbreviated destructuring {a, b}
7252 decl-type face ignore-not-in-block)))
7253 ((js2-array-node-p node)
7254 (dolist (elem (js2-array-node-elems node))
7256 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7257 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7258 (js2-node-len node)))))
7260 (defun js2-parse-function-params (fn-node pos)
7261 (if (js2-match-token js2-RP)
7262 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7263 (let (params len param)
7264 (loop for tt = (js2-peek-token)
7267 ;; destructuring param
7268 ((or (= tt js2-LB) (= tt js2-LC))
7269 (setq param (js2-parse-primary-expr-lhs))
7270 (js2-define-destruct-symbols param
7272 'js2-function-param)
7273 (push param params))
7276 (js2-must-match js2-NAME "msg.no.parm")
7277 (js2-record-face 'js2-function-param)
7278 (setq param (js2-create-name-node))
7279 (js2-define-symbol js2-LP js2-ts-string param)
7280 (push param params)))
7282 (js2-match-token js2-COMMA))
7283 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7284 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7286 (js2-node-add-children fn-node p)
7287 (push p (js2-function-node-params fn-node))))))
7289 (defun js2-check-inconsistent-return-warning (fn-node name)
7290 "Possibly show inconsistent-return warning.
7291 Last token scanned is the close-curly for the function body."
7292 (when (and js2-mode-show-strict-warnings
7293 js2-strict-inconsistent-return-warning
7294 (not (js2-has-consistent-return-usage
7295 (js2-function-node-body fn-node))))
7296 ;; Have it extend from close-curly to bol or beginning of block.
7297 (let ((pos (save-excursion
7298 (goto-char js2-token-end)
7299 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7301 (end js2-token-end))
7302 (if (plusp (js2-name-node-length name))
7303 (js2-add-strict-warning "msg.no.return.value"
7304 (js2-name-node-name name) pos end)
7305 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7307 (defun js2-parse-function (function-type)
7308 "Function parser. FUNCTION-TYPE is a symbol."
7309 (let ((pos js2-token-beg) ; start of 'function' keyword
7310 name name-beg name-end fn-node lp
7311 (synthetic-type function-type)
7313 ;; parse function name, expression, or non-name (anonymous)
7315 ;; function foo(...)
7316 ((js2-match-token js2-NAME)
7317 (setq name (js2-create-name-node t)
7318 name-beg js2-token-beg
7319 name-end js2-token-end)
7320 (unless (js2-match-token js2-LP)
7321 (when js2-allow-member-expr-as-function-name
7322 ;; function foo.bar(...)
7323 (setq member-expr-node name
7325 member-expr-node (js2-parse-member-expr-tail
7326 nil member-expr-node)))
7327 (js2-must-match js2-LP "msg.no.paren.parms")))
7328 ((js2-match-token js2-LP)
7329 nil) ; anonymous function: leave name as null
7331 ;; function random-member-expr(...)
7332 (when js2-allow-member-expr-as-function-name
7333 ;; Note that memberExpr can not start with '(' like
7334 ;; in function (1+2).toString(), because 'function (' already
7335 ;; processed as anonymous function
7336 (setq member-expr-node (js2-parse-member-expr)))
7337 (js2-must-match js2-LP "msg.no.paren.parms")))
7338 (if (= js2-current-token js2-LP) ; eventually matched LP?
7339 (setq lp js2-token-beg))
7340 (if member-expr-node
7342 (setq synthetic-type 'FUNCTION_EXPRESSION)
7343 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7345 (js2-set-face name-beg name-end
7346 'font-lock-function-name-face 'record)))
7347 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7348 (plusp (js2-name-node-length name)))
7349 ;; Function statements define a symbol in the enclosing scope
7350 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7351 (setf fn-node (make-js2-function-node :pos pos
7354 :lp (if lp (- lp pos))))
7355 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7356 ;; 1. Nested functions are not affected by the dynamic scope flag
7357 ;; as dynamic scope is already a parent of their scope.
7358 ;; 2. Functions defined under the with statement also immune to
7359 ;; this setup, in which case dynamic scope is ignored in favor
7360 ;; of the with object.
7361 (setf (js2-function-node-ignore-dynamic fn-node) t))
7362 ;; dynamically bind all the per-function variables
7363 (let ((js2-current-script-or-fn fn-node)
7364 (js2-current-scope fn-node)
7365 (js2-nesting-of-with 0)
7369 js2-loop-and-switch-set)
7370 (js2-parse-function-params fn-node pos)
7371 (if (and (>= js2-language-version 180)
7372 (/= (js2-peek-token) js2-LC))
7373 (js2-parse-function-closure-body fn-node)
7374 (js2-parse-function-body fn-node))
7376 (js2-node-add-children fn-node name))
7377 (js2-check-inconsistent-return-warning fn-node name)
7378 ;; Function expressions define a name only in the body of the
7379 ;; function, and only if not hidden by a parameter name
7381 (eq synthetic-type 'FUNCTION_EXPRESSION)
7382 (null (js2-scope-get-symbol js2-current-scope
7383 (js2-name-node-name name))))
7384 (js2-define-symbol js2-FUNCTION
7385 (js2-name-node-name name)
7388 (not (eq function-type 'FUNCTION_EXPRESSION)))
7389 (js2-record-imenu-functions fn-node)))
7390 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7391 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7392 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7393 ;; We wait until after parsing the function to set its parent scope,
7394 ;; since `js2-define-symbol' needs the defining-scope check to stop
7395 ;; at the function boundary when checking for redeclarations.
7396 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7399 (defun js2-parse-statements (&optional parent)
7400 "Parse a statement list. Last token consumed must be js2-LC.
7402 PARENT can be a `js2-block-node', in which case the statements are
7403 appended to PARENT. Otherwise a new `js2-block-node' is created
7406 This function does not match the closing js2-RC: the caller
7407 matches the RC so it can provide a suitable error message if not
7408 matched. This means it's up to the caller to set the length of
7409 the node to include the closing RC. The node start pos is set to
7410 the absolute buffer start position, and the caller should fix it
7411 up to be relative to the parent node. All children of this block
7412 node are given relative start positions and correct lengths."
7413 (let ((pn (or parent (make-js2-block-node)))
7415 (setf (js2-node-pos pn) js2-token-beg)
7416 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7418 (js2-block-node-push pn (js2-parse-statement)))
7421 (defun js2-parse-statement ()
7422 (let (tt pn beg end)
7423 ;; coarse-grained user-interrupt check - needs work
7424 (and js2-parse-interruptable-p
7425 (zerop (% (incf js2-parse-stmt-count)
7426 js2-statements-per-pause))
7428 (throw 'interrupted t))
7429 (setq pn (js2-statement-helper))
7430 ;; no-side-effects warning check
7431 (unless (js2-node-has-side-effects pn)
7432 (setq end (js2-node-end pn))
7435 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7436 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7439 ;; These correspond to the switch cases in Parser.statementHelper
7440 (defconst js2-parsers
7441 (let ((parsers (make-vector js2-num-tokens
7442 #'js2-parse-expr-stmt)))
7443 (aset parsers js2-BREAK #'js2-parse-break)
7444 (aset parsers js2-CONST #'js2-parse-const-var)
7445 (aset parsers js2-CONTINUE #'js2-parse-continue)
7446 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7447 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7448 (aset parsers js2-DO #'js2-parse-do)
7449 (aset parsers js2-FOR #'js2-parse-for)
7450 (aset parsers js2-FUNCTION #'js2-function-parser)
7451 (aset parsers js2-IF #'js2-parse-if)
7452 (aset parsers js2-LC #'js2-parse-block)
7453 (aset parsers js2-LET #'js2-parse-let-stmt)
7454 (aset parsers js2-NAME #'js2-parse-name-or-label)
7455 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7456 (aset parsers js2-SEMI #'js2-parse-semi)
7457 (aset parsers js2-SWITCH #'js2-parse-switch)
7458 (aset parsers js2-THROW #'js2-parse-throw)
7459 (aset parsers js2-TRY #'js2-parse-try)
7460 (aset parsers js2-VAR #'js2-parse-const-var)
7461 (aset parsers js2-WHILE #'js2-parse-while)
7462 (aset parsers js2-WITH #'js2-parse-with)
7463 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7465 "A vector mapping token types to parser functions.")
7467 (defun js2-parse-warn-missing-semi (beg end)
7468 (and js2-mode-show-strict-warnings
7469 js2-strict-missing-semi-warning
7470 (js2-add-strict-warning
7471 "msg.missing.semi" nil
7472 ;; back up to beginning of statement or line
7473 (max beg (save-excursion
7478 (defconst js2-no-semi-insertion
7490 "List of tokens that don't do automatic semicolon insertion.")
7492 (defconst js2-autoinsert-semi-and-warn
7493 (list js2-ERROR js2-EOF js2-RC))
7495 (defun js2-statement-helper ()
7496 (let* ((tt (js2-peek-token))
7499 (parser (if (= tt js2-ERROR)
7501 (aref js2-parsers tt)))
7504 ;; If the statement is set, then it's been told its label by now.
7505 (and js2-labeled-stmt
7506 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7507 (setq js2-labeled-stmt nil))
7508 (setq pn (funcall parser))
7509 ;; Don't do auto semi insertion for certain statement types.
7510 (unless (or (memq first-tt js2-no-semi-insertion)
7511 (js2-labeled-stmt-node-p pn))
7512 (js2-auto-insert-semicolon pn))
7515 (defun js2-auto-insert-semicolon (pn)
7516 (let* ((tt-flagged (js2-peek-flagged-token))
7517 (tt (logand tt-flagged js2-clear-ti-mask))
7518 (pos (js2-node-pos pn)))
7521 ;; Consume ';' as a part of expression
7523 ;; extend the node bounds to include the semicolon.
7524 (setf (js2-node-len pn) (- js2-token-end pos)))
7525 ((memq tt js2-autoinsert-semi-and-warn)
7527 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7529 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7530 ;; Report error if no EOL or autoinsert ';' otherwise
7531 (js2-report-error "msg.no.semi.stmt")
7532 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7534 (defun js2-parse-condition ()
7535 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7536 The parens are discarded and the expression node is returned.
7537 The `pos' field of the return value is set to an absolute position
7538 that must be fixed up by the caller.
7539 Return value is a list (EXPR LP RP), with absolute paren positions."
7541 (if (js2-must-match js2-LP "msg.no.paren.cond")
7542 (setq lp js2-token-beg))
7543 (setq pn (js2-parse-expr))
7544 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7545 (setq rp js2-token-beg))
7546 ;; Report strict warning on code like "if (a = 7) ..."
7547 (if (and js2-strict-cond-assign-warning
7548 (js2-assign-node-p pn))
7549 (js2-add-strict-warning "msg.equal.as.assign" nil
7551 (+ (js2-node-pos pn)
7552 (js2-node-len pn))))
7555 (defun js2-parse-if ()
7556 "Parser for if-statement. Last matched token must be js2-IF."
7557 (let ((pos js2-token-beg)
7558 cond if-true if-false else-pos end pn)
7560 (setq cond (js2-parse-condition)
7561 if-true (js2-parse-statement)
7562 if-false (if (js2-match-token js2-ELSE)
7564 (setq else-pos (- js2-token-beg pos))
7565 (js2-parse-statement)))
7566 end (js2-node-end (or if-false if-true))
7567 pn (make-js2-if-node :pos pos
7569 :condition (car cond)
7573 :lp (js2-relpos (second cond) pos)
7574 :rp (js2-relpos (third cond) pos)))
7575 (js2-node-add-children pn (car cond) if-true if-false)
7578 (defun js2-parse-switch ()
7579 "Parser for if-statement. Last matched token must be js2-SWITCH."
7580 (let ((pos js2-token-beg)
7581 tt pn discriminant has-default case-expr case-node
7582 case-pos cases stmt lp rp)
7584 (if (js2-must-match js2-LP "msg.no.paren.switch")
7585 (setq lp js2-token-beg))
7586 (setq discriminant (js2-parse-expr)
7587 pn (make-js2-switch-node :discriminant discriminant
7589 :lp (js2-relpos lp pos)))
7590 (js2-node-add-children pn discriminant)
7591 (js2-enter-switch pn)
7594 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7595 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7596 (js2-must-match js2-LC "msg.no.brace.switch")
7599 (setq tt (js2-next-token)
7600 case-pos js2-token-beg)
7603 (setf (js2-node-len pn) (- js2-token-end pos))
7604 (throw 'break nil)) ; done
7606 (setq case-expr (js2-parse-expr))
7607 (js2-must-match js2-COLON "msg.no.colon.case"))
7610 (js2-report-error "msg.double.switch.default"))
7613 (js2-must-match js2-COLON "msg.no.colon.case"))
7615 (js2-report-error "msg.bad.switch")
7616 (throw 'break nil)))
7617 (setq case-node (make-js2-case-node :pos case-pos
7618 :len (- js2-token-end case-pos)
7620 (js2-node-add-children case-node case-expr)
7621 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7625 (setf stmt (js2-parse-statement)
7626 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7627 (js2-block-node-push case-node stmt))
7628 (push case-node cases)))
7629 ;; add cases last, as pushing reverses the order to be correct
7631 (js2-node-add-children pn kid)
7632 (push kid (js2-switch-node-cases pn)))
7634 (js2-exit-switch))))
7636 (defun js2-parse-while ()
7637 "Parser for while-statement. Last matched token must be js2-WHILE."
7638 (let ((pos js2-token-beg)
7639 (pn (make-js2-while-node))
7645 (setf cond (js2-parse-condition)
7646 (js2-while-node-condition pn) (car cond)
7647 body (js2-parse-statement)
7648 (js2-while-node-body pn) body
7649 (js2-node-len pn) (- (js2-node-end body) pos)
7650 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7651 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7652 (js2-node-add-children pn body (car cond)))
7656 (defun js2-parse-do ()
7657 "Parser for do-statement. Last matched token must be js2-DO."
7658 (let ((pos js2-token-beg)
7659 (pn (make-js2-do-node))
7665 (setq body (js2-parse-statement))
7666 (js2-must-match js2-WHILE "msg.no.while.do")
7667 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7668 cond (js2-parse-condition)
7669 (js2-do-node-condition pn) (car cond)
7670 (js2-do-node-body pn) body
7672 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7673 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7674 (js2-node-add-children pn (car cond) body))
7676 ;; Always auto-insert semicolon to follow SpiderMonkey:
7677 ;; It is required by ECMAScript but is ignored by the rest of
7678 ;; world; see bug 238945
7679 (if (js2-match-token js2-SEMI)
7680 (setq end js2-ts-cursor))
7681 (setf (js2-node-len pn) (- end pos))
7684 (defun js2-parse-for ()
7685 "Parser for for-statement. Last matched token must be js2-FOR.
7686 Parses for, for-in, and for each-in statements."
7687 (let ((for-pos js2-token-beg)
7688 pn is-for-each is-for-in in-pos each-pos tmp-pos
7689 init ; Node init is also foo in 'foo in object'
7690 cond ; Node cond is also object in 'foo in object'
7691 incr ; 3rd section of for-loop initializer
7694 ;; See if this is a for each () instead of just a for ()
7695 (when (js2-match-token js2-NAME)
7696 (if (string= "each" js2-ts-string)
7699 each-pos (- js2-token-beg for-pos)) ; relative
7700 (js2-record-face 'font-lock-keyword-face))
7701 (js2-report-error "msg.no.paren.for")))
7702 (if (js2-must-match js2-LP "msg.no.paren.for")
7703 (setq lp (- js2-token-beg for-pos)))
7704 (setq tt (js2-peek-token))
7705 ;; 'for' makes local scope
7706 (js2-push-scope (make-js2-scope))
7708 ;; parse init clause
7709 (let ((js2-in-for-init t)) ; set as dynamic variable
7712 (setq init (make-js2-empty-expr-node)))
7713 ((or (= tt js2-VAR) (= tt js2-LET))
7715 (setq init (js2-parse-variables tt js2-token-beg)))
7717 (setq init (js2-parse-expr)))))
7718 (if (js2-match-token js2-IN)
7720 in-pos (- js2-token-beg for-pos)
7721 ;; scope of iteration target object is not the scope we've created above.
7722 ;; stash current scope temporary.
7723 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7724 (js2-parse-expr))) ; object over which we're iterating
7725 ;; else ordinary for loop - parse cond and incr
7726 (js2-must-match js2-SEMI "msg.no.semi.for")
7727 (setq cond (if (= (js2-peek-token) js2-SEMI)
7728 (make-js2-empty-expr-node) ; no loop condition
7730 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7731 (setq tmp-pos js2-token-end
7732 incr (if (= (js2-peek-token) js2-RP)
7733 (make-js2-empty-expr-node :pos tmp-pos)
7735 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7736 (setq rp (- js2-token-beg for-pos)))
7738 (setq pn (make-js2-for-node :init init
7743 ;; cond could be null if 'in obj' got eaten by the init node.
7744 (if (js2-infix-node-p init)
7745 ;; it was (foo in bar) instead of (var foo in bar)
7746 (setq cond (js2-infix-node-right init)
7747 init (js2-infix-node-left init))
7748 (if (and (js2-var-decl-node-p init)
7749 (> (length (js2-var-decl-node-kids init)) 1))
7750 (js2-report-error "msg.mult.index")))
7751 (setq pn (make-js2-for-in-node :iterator init
7754 :foreach-p is-for-each
7761 ;; We have to parse the body -after- creating the loop node,
7762 ;; so that the loop node appears in the js2-loop-set, allowing
7763 ;; break/continue statements to find the enclosing loop.
7764 (setf body (js2-parse-statement)
7765 (js2-loop-node-body pn) body
7766 (js2-node-pos pn) for-pos
7767 (js2-node-len pn) (- (js2-node-end body) for-pos))
7768 (js2-node-add-children pn init cond incr body))
7774 (defun js2-parse-try ()
7775 "Parser for try-statement. Last matched token must be js2-TRY."
7776 (let ((try-pos js2-token-beg)
7794 (if (/= (js2-peek-token) js2-LC)
7795 (js2-report-error "msg.no.brace.try"))
7796 (setq try-block (js2-parse-statement)
7797 try-end (js2-node-end try-block)
7798 peek (js2-peek-token))
7801 (while (js2-match-token js2-CATCH)
7802 (setq catch-pos js2-token-beg
7807 (if saw-default-catch
7808 (js2-report-error "msg.catch.unreachable"))
7809 (if (js2-must-match js2-LP "msg.no.paren.catch")
7810 (setq lp (- js2-token-beg catch-pos)))
7811 (js2-push-scope (make-js2-scope))
7812 (let ((tt (js2-peek-token)))
7814 ;; destructuring pattern
7815 ;; catch ({ message, file }) { ... }
7816 ((or (= tt js2-LB) (= tt js2-LC))
7818 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
7822 (js2-must-match js2-NAME "msg.bad.catchcond")
7823 (setq param (js2-create-name-node))
7824 (js2-define-symbol js2-LET js2-ts-string param))))
7826 (if (js2-match-token js2-IF)
7827 (setq guard-kwd (- js2-token-beg catch-pos)
7828 catch-cond (js2-parse-expr))
7829 (setq saw-default-catch t))
7830 (if (js2-must-match js2-RP "msg.bad.catchcond")
7831 (setq rp (- js2-token-beg catch-pos)))
7832 (js2-must-match js2-LC "msg.no.brace.catchblock")
7833 (setq block (js2-parse-statements)
7834 try-end (js2-node-end block)
7835 catch-node (make-js2-catch-node :pos catch-pos
7837 :guard-expr catch-cond
7838 :guard-kwd guard-kwd
7843 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7844 (setq try-end js2-token-beg))
7845 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7846 (js2-node-len catch-node) (- try-end catch-pos))
7847 (js2-node-add-children catch-node param catch-cond block)
7848 (push catch-node catch-blocks)))
7849 ((/= peek js2-FINALLY)
7850 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7851 (js2-node-pos try-block)
7852 (- (setq try-end (js2-node-end try-block))
7853 (js2-node-pos try-block)))))
7854 (when (js2-match-token js2-FINALLY)
7855 (setq finally-pos js2-token-beg
7856 block (js2-parse-statement)
7857 try-end (js2-node-end block)
7858 finally-block (make-js2-finally-node :pos finally-pos
7859 :len (- try-end finally-pos)
7861 (js2-node-add-children finally-block block))
7862 (setq pn (make-js2-try-node :pos try-pos
7863 :len (- try-end try-pos)
7864 :try-block try-block
7865 :finally-block finally-block))
7866 (js2-node-add-children pn try-block finally-block)
7867 ;; push them onto the try-node, which reverses and corrects their order
7868 (dolist (cb catch-blocks)
7869 (js2-node-add-children pn cb)
7870 (push cb (js2-try-node-catch-clauses pn)))
7873 (defun js2-parse-throw ()
7874 "Parser for throw-statement. Last matched token must be js2-THROW."
7875 (let ((pos js2-token-beg)
7878 (if (= (js2-peek-token-or-eol) js2-EOL)
7879 ;; ECMAScript does not allow new lines before throw expression,
7881 (js2-report-error "msg.bad.throw.eol"))
7882 (setq expr (js2-parse-expr)
7883 pn (make-js2-throw-node :pos pos
7884 :len (- (js2-node-end expr) pos)
7886 (js2-node-add-children pn expr)
7889 (defun js2-match-jump-label-name (label-name)
7890 "If break/continue specified a label, return that label's labeled stmt.
7891 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7892 does not match an existing label, reports an error and returns nil."
7893 (let ((bundle (cdr (assoc label-name js2-label-set))))
7895 (js2-report-error "msg.undef.label"))
7898 (defun js2-parse-break ()
7899 "Parser for break-statement. Last matched token must be js2-BREAK."
7900 (let ((pos js2-token-beg)
7902 break-target ; statement to break from
7903 break-label ; in "break foo", name-node representing the foo
7904 labels ; matching labeled statement to break to
7906 (js2-consume-token) ; `break'
7907 (when (eq (js2-peek-token-or-eol) js2-NAME)
7909 (setq break-label (js2-create-name-node)
7910 end (js2-node-end break-label)
7911 ;; matchJumpLabelName only matches if there is one
7912 labels (js2-match-jump-label-name js2-ts-string)
7913 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7914 (unless (or break-target break-label)
7915 ;; no break target specified - try for innermost enclosing loop/switch
7916 (if (null js2-loop-and-switch-set)
7918 (js2-report-error "msg.bad.break" nil pos (length "break")))
7919 (setq break-target (car js2-loop-and-switch-set))))
7920 (setq pn (make-js2-break-node :pos pos
7923 :target break-target))
7924 (js2-node-add-children pn break-label) ; but not break-target
7927 (defun js2-parse-continue ()
7928 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7929 (let ((pos js2-token-beg)
7931 label ; optional user-specified label, a `js2-name-node'
7932 labels ; current matching labeled stmt, if any
7933 target ; the `js2-loop-node' target of this continue stmt
7935 (js2-consume-token) ; `continue'
7936 (when (= (js2-peek-token-or-eol) js2-NAME)
7938 (setq label (js2-create-name-node)
7939 end (js2-node-end label)
7940 ;; matchJumpLabelName only matches if there is one
7941 labels (js2-match-jump-label-name js2-ts-string)))
7943 ((null labels) ; no current label to go to
7944 (if (null js2-loop-set) ; no loop to continue to
7945 (js2-report-error "msg.continue.outside" nil pos
7946 (length "continue"))
7947 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7949 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7950 (setq target (js2-labeled-stmt-node-stmt labels))
7951 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7952 (setq pn (make-js2-continue-node :pos pos
7956 (js2-node-add-children pn label) ; but not target - it's not our child
7959 (defun js2-parse-with ()
7960 "Parser for with-statement. Last matched token must be js2-WITH."
7962 (let ((pos js2-token-beg)
7964 (if (js2-must-match js2-LP "msg.no.paren.with")
7965 (setq lp js2-token-beg))
7966 (setq obj (js2-parse-expr))
7967 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7968 (setq rp js2-token-beg))
7969 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7970 (setq body (js2-parse-statement)))
7971 (setq pn (make-js2-with-node :pos pos
7972 :len (- (js2-node-end body) pos)
7975 :lp (js2-relpos lp pos)
7976 :rp (js2-relpos rp pos)))
7977 (js2-node-add-children pn obj body)
7980 (defun js2-parse-const-var ()
7981 "Parser for var- or const-statement.
7982 Last matched token must be js2-CONST or js2-VAR."
7983 (let ((tt (js2-peek-token))
7987 (setq expr (js2-parse-variables tt js2-token-beg)
7988 pn (make-js2-expr-stmt-node :pos pos
7989 :len (- (js2-node-end expr) pos)
7991 (js2-node-add-children pn expr)
7994 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
7995 (let ((pn (make-js2-expr-stmt-node :pos pos
7996 :len (js2-node-len expr)
7997 :type (if (js2-inside-function)
8002 (js2-node-add-children pn expr))
8005 (defun js2-parse-let-stmt ()
8006 "Parser for let-statement. Last matched token must be js2-LET."
8008 (let ((pos js2-token-beg)
8010 (if (= (js2-peek-token) js2-LP)
8011 ;; let expression in statement context
8012 (setq expr (js2-parse-let pos 'statement)
8013 pn (js2-wrap-with-expr-stmt pos expr t))
8014 ;; else we're looking at a statement like let x=6, y=7;
8015 (setf expr (js2-parse-variables js2-LET pos)
8016 pn (js2-wrap-with-expr-stmt pos expr t)
8017 (js2-node-type pn) js2-EXPR_RESULT))
8020 (defun js2-parse-ret-yield ()
8021 (js2-parse-return-or-yield (js2-peek-token) nil))
8023 (defconst js2-parse-return-stmt-enders
8024 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8026 (defsubst js2-now-all-set (before after mask)
8027 "Return whether or not the bits in the mask have changed to all set.
8028 BEFORE is bits before change, AFTER is bits after change, and MASK is
8029 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8031 (and (/= (logand before mask) mask)
8032 (= (logand after mask) mask)))
8034 (defun js2-parse-return-or-yield (tt expr-context)
8035 (let ((pos js2-token-beg)
8037 (before js2-end-flags)
8038 (inside-function (js2-inside-function))
8040 (unless inside-function
8041 (js2-report-error (if (eq tt js2-RETURN)
8045 ;; This is ugly, but we don't want to require a semicolon.
8046 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8047 (setq e (js2-parse-expr)
8048 end (js2-node-end e)))
8051 (js2-set-flag js2-end-flags (if (null e)
8053 js2-end-returns-value))
8054 (setq ret (make-js2-return-node :pos pos
8057 (js2-node-add-children ret e)
8058 ;; See if we need a strict mode warning.
8059 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8060 ;; more thorough and accurate than this before/after flag check.
8061 ;; E.g. if there's a finally-block that always returns, we shouldn't
8062 ;; show a warning generated by inconsistent returns in the catch blocks.
8063 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8064 ;; so we know which returns/yields to highlight, and we should get rid of
8065 ;; all the checking in `js2-parse-return-or-yield'.
8066 (if (and js2-strict-inconsistent-return-warning
8067 (js2-now-all-set before js2-end-flags
8068 (logior js2-end-returns js2-end-returns-value)))
8069 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8071 (unless (js2-inside-function)
8072 (js2-report-error "msg.bad.yield"))
8073 (js2-set-flag js2-end-flags js2-end-yields)
8074 (setq ret (make-js2-yield-node :pos pos
8077 (js2-node-add-children ret e)
8078 (unless expr-context
8080 ret (js2-wrap-with-expr-stmt pos e t))
8081 (js2-set-requires-activation)
8082 (js2-set-is-generator))))
8083 ;; see if we are mixing yields and value returns.
8084 (when (and inside-function
8085 (js2-now-all-set before js2-end-flags
8086 (logior js2-end-yields js2-end-returns-value)))
8087 (setq name (js2-function-name js2-current-script-or-fn))
8088 (if (zerop (length name))
8089 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8090 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8093 (defun js2-parse-debugger ()
8095 (make-js2-keyword-node :type js2-DEBUGGER))
8097 (defun js2-parse-block ()
8098 "Parser for a curly-delimited statement block.
8099 Last token matched must be `js2-LC'."
8100 (let ((pos js2-token-beg)
8101 (pn (make-js2-scope)))
8106 (js2-parse-statements pn)
8107 (js2-must-match js2-RC "msg.no.brace.block")
8108 (setf (js2-node-len pn) (- js2-token-end pos)))
8112 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8113 (defun js2-parse-semi ()
8114 "Parse a statement or handle an error.
8115 Last matched token is `js2-SEMI' or `js2-ERROR'."
8116 (let ((tt (js2-peek-token)) pos len)
8118 (if (eq tt js2-SEMI)
8119 (make-js2-empty-expr-node :len 1)
8120 (setq pos js2-token-beg
8121 len (- js2-token-beg pos))
8122 (js2-report-error "msg.syntax" nil pos len)
8123 (make-js2-error-node :pos pos :len len))))
8125 (defun js2-parse-default-xml-namespace ()
8126 "Parse a `default xml namespace = <expr>' e4x statement."
8127 (let ((pos js2-token-beg)
8128 end len expr unary es)
8131 (js2-set-requires-activation)
8132 (setq len (- js2-ts-cursor pos))
8133 (unless (and (js2-match-token js2-NAME)
8134 (string= js2-ts-string "xml"))
8135 (js2-report-error "msg.bad.namespace" nil pos len))
8136 (unless (and (js2-match-token js2-NAME)
8137 (string= js2-ts-string "namespace"))
8138 (js2-report-error "msg.bad.namespace" nil pos len))
8139 (unless (js2-match-token js2-ASSIGN)
8140 (js2-report-error "msg.bad.namespace" nil pos len))
8141 (setq expr (js2-parse-expr)
8142 end (js2-node-end expr)
8143 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8147 (js2-node-add-children unary expr)
8148 (make-js2-expr-stmt-node :pos pos
8152 (defun js2-record-label (label bundle)
8153 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8155 (let ((name (js2-label-node-name label))
8158 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8159 ;; flag both labels if possible when used in editing mode
8160 (if (and js2-parse-ide-mode
8161 (setq dup (js2-get-label-by-name labeled-stmt name)))
8162 (js2-report-error "msg.dup.label" nil
8163 (js2-node-abs-pos dup) (js2-node-len dup)))
8164 (js2-report-error "msg.dup.label" nil
8165 (js2-node-pos label) (js2-node-len label)))
8166 (js2-labeled-stmt-node-add-label bundle label)
8167 (js2-node-add-children bundle label)
8168 ;; Add one reference to the bundle per label in `js2-label-set'
8169 (push (cons name bundle) js2-label-set)))
8171 (defun js2-parse-name-or-label ()
8172 "Parser for identifier or label. Last token matched must be js2-NAME.
8173 Called when we found a name in a statement context. If it's a label, we gather
8174 up any following labels and the next non-label statement into a
8175 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8176 expression and return it wrapped in a `js2-expr-stmt-node'."
8177 (let ((pos js2-token-beg)
8181 ;; set check for label and call down to `js2-parse-primary-expr'
8182 (js2-set-check-for-label)
8183 (setq expr (js2-parse-expr))
8184 (if (/= (js2-node-type expr) js2-LABEL)
8185 ;; Parsed non-label expression - wrap with expression stmt.
8186 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8187 ;; else parsed a label
8188 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8189 (js2-record-label expr bundle)
8190 ;; look for more labels
8191 (while (and continue (= (js2-peek-token) js2-NAME))
8192 (js2-set-check-for-label)
8193 (setq expr (js2-parse-expr))
8194 (if (/= (js2-node-type expr) js2-LABEL)
8196 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8198 (js2-auto-insert-semicolon stmt))
8199 (js2-record-label expr bundle)))
8200 ;; no more labels; now parse the labeled statement
8203 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8204 (setq stmt (js2-statement-helper))))
8205 ;; remove the labels for this statement from the global set
8206 (dolist (label (js2-labeled-stmt-node-labels bundle))
8207 (setq js2-label-set (remove label js2-label-set))))
8208 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8209 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8210 (js2-node-add-children bundle stmt)
8213 (defun js2-parse-expr-stmt ()
8214 "Default parser in statement context, if no recognized statement found."
8215 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8217 (defun js2-parse-variables (decl-type pos)
8218 "Parse a comma-separated list of variable declarations.
8219 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8221 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8222 For 'var' or 'const', the keyword should be the token last scanned.
8224 POS is the position where the node should start. It's sometimes the
8225 var/const/let keyword, and other times the beginning of the first token
8226 in the first variable declaration.
8228 Returns the parsed `js2-var-decl-node' expression node."
8229 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8231 destructuring kid-pos tt init name end nbeg nend vi
8234 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8235 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8236 ;; var {a, b} = baz;
8238 (setq destructuring nil
8241 kid-pos js2-token-beg
8244 (if (or (= tt js2-LB) (= tt js2-LC))
8245 ;; Destructuring assignment, e.g., var [a, b] = ...
8246 (setq destructuring (js2-parse-primary-expr-lhs)
8247 end (js2-node-end destructuring))
8248 ;; Simple variable name
8249 (when (js2-must-match js2-NAME "msg.bad.var")
8250 (setq name (js2-create-name-node)
8254 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8255 (when (js2-match-token js2-ASSIGN)
8256 (setq init (js2-parse-assign-expr)
8257 end (js2-node-end init))
8258 (js2-record-imenu-functions init name))
8260 (js2-set-face nbeg nend (if (js2-function-node-p init)
8261 'font-lock-function-name-face
8262 'font-lock-variable-name-face)
8264 (setq vi (make-js2-var-init-node :pos kid-pos
8265 :len (- end kid-pos)
8269 (if (and (null init) (not js2-in-for-init))
8270 (js2-report-error "msg.destruct.assign.no.init"))
8271 (js2-define-destruct-symbols destructuring
8273 'font-lock-variable-name-face)
8274 (setf (js2-var-init-node-target vi) destructuring))
8275 (setf (js2-var-init-node-target vi) name))
8276 (setf (js2-var-init-node-initializer vi) init)
8277 (js2-node-add-children vi name destructuring init)
8278 (js2-block-node-push result vi)
8279 (unless (js2-match-token js2-COMMA)
8280 (setq continue nil)))
8281 (setf (js2-node-len result) (- end pos))
8284 (defun js2-parse-let (pos &optional stmt-p)
8285 "Parse a let expression or statement.
8286 A let-expression is of the form `let (vars) expr'.
8287 A let-statment is of the form `let (vars) {statements}'.
8288 The third form of let is a variable declaration list, handled
8289 by `js2-parse-variables'."
8290 (let ((pn (make-js2-let-node :pos pos))
8292 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8293 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8297 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8298 (if (js2-must-match js2-RP "msg.no.paren.let")
8299 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8300 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8304 (setf beg js2-token-beg ; position stmt at LC
8305 body (js2-parse-statements))
8306 (js2-must-match js2-RC "msg.no.curly.let")
8307 (setf (js2-node-len body) (- js2-token-end beg)
8308 (js2-node-len pn) (- js2-token-end pos)
8309 (js2-let-node-body pn) body
8310 (js2-node-type pn) js2-LET))
8312 (setf body (js2-parse-expr)
8313 (js2-node-len pn) (- (js2-node-end body) pos)
8314 (js2-let-node-body pn) body))
8315 (js2-node-add-children pn vars body))
8319 (defun js2-define-new-symbol (decl-type name node &optional scope)
8320 (js2-scope-put-symbol (or scope js2-current-scope)
8322 (make-js2-symbol decl-type name node)))
8324 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8325 "Define a symbol in the current scope.
8326 If NODE is non-nil, it is the AST node associated with the symbol."
8327 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8328 (symbol (if defining-scope
8329 (js2-scope-get-symbol defining-scope name)))
8330 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8332 ((and symbol ; already defined
8333 (or (= sdt js2-CONST) ; old version is const
8334 (= decl-type js2-CONST) ; new version is const
8335 ;; two let-bound vars in this block have same name
8336 (and (= sdt js2-LET)
8337 (eq defining-scope js2-current-scope))))
8340 ((= sdt js2-CONST) "msg.const.redecl")
8341 ((= sdt js2-LET) "msg.let.redecl")
8342 ((= sdt js2-VAR) "msg.var.redecl")
8343 ((= sdt js2-FUNCTION) "msg.function.redecl")
8344 (t "msg.parm.redecl"))
8346 ((= decl-type js2-LET)
8347 (if (and (not ignore-not-in-block)
8348 (or (= (js2-node-type js2-current-scope) js2-IF)
8349 (js2-loop-node-p js2-current-scope)))
8350 (js2-report-error "msg.let.decl.not.in.block")
8351 (js2-define-new-symbol decl-type name node)))
8352 ((or (= decl-type js2-VAR)
8353 (= decl-type js2-CONST)
8354 (= decl-type js2-FUNCTION))
8356 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8357 (js2-add-strict-warning "msg.var.redecl" name)
8358 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8359 (js2-add-strict-warning "msg.var.hides.arg" name)))
8360 (js2-define-new-symbol decl-type name node
8361 js2-current-script-or-fn)))
8362 ((= decl-type js2-LP)
8364 ;; must be duplicate parameter. Second parameter hides the
8365 ;; first, so go ahead and add the second pararameter
8366 (js2-report-warning "msg.dup.parms" name))
8367 (js2-define-new-symbol decl-type name node))
8368 (t (js2-code-bug)))))
8370 (defun js2-parse-expr (&optional oneshot)
8371 (let* ((pn (js2-parse-assign-expr))
8372 (pos (js2-node-pos pn))
8376 (while (and (not oneshot)
8377 (js2-match-token js2-COMMA))
8378 (setq op-pos (- js2-token-beg pos)) ; relative
8379 (if (= (js2-peek-token) js2-YIELD)
8380 (js2-report-error "msg.yield.parenthesized"))
8381 (setq right (js2-parse-assign-expr)
8383 pn (make-js2-infix-node :type js2-COMMA
8385 :len (- js2-ts-cursor pos)
8389 (js2-node-add-children pn left right))
8392 (defun js2-parse-assign-expr ()
8393 (let ((tt (js2-peek-token))
8395 pn left right op-pos)
8396 (if (= tt js2-YIELD)
8397 (js2-parse-return-or-yield tt t)
8398 ;; not yield - parse assignment expression
8399 (setq pn (js2-parse-cond-expr)
8400 tt (js2-peek-token))
8401 (when (and (<= js2-first-assign tt)
8402 (<= tt js2-last-assign))
8403 ;; tt express assignment (=, |=, ^=, ..., %=)
8405 (setq op-pos (- js2-token-beg pos) ; relative
8407 right (js2-parse-assign-expr)
8408 pn (make-js2-assign-node :type tt
8410 :len (- (js2-node-end right) pos)
8414 (when js2-parse-ide-mode
8415 (js2-highlight-assign-targets pn left right)
8416 (js2-record-imenu-functions right left))
8417 ;; do this last so ide checks above can use absolute positions
8418 (js2-node-add-children pn left right))
8421 (defun js2-parse-cond-expr ()
8422 (let ((pos js2-token-beg)
8423 (pn (js2-parse-or-expr))
8429 (when (js2-match-token js2-HOOK)
8430 (setq q-pos (- js2-token-beg pos)
8431 if-true (js2-parse-assign-expr))
8432 (js2-must-match js2-COLON "msg.no.colon.cond")
8433 (setq c-pos (- js2-token-beg pos)
8434 if-false (js2-parse-assign-expr)
8436 pn (make-js2-cond-node :pos pos
8437 :len (- (js2-node-end if-false) pos)
8438 :test-expr test-expr
8440 :false-expr if-false
8443 (js2-node-add-children pn test-expr if-true if-false))
8446 (defun js2-make-binary (type left parser)
8447 "Helper for constructing a binary-operator AST node.
8448 LEFT is the left-side-expression, already parsed, and the
8449 binary operator should have just been matched.
8450 PARSER is a function to call to parse the right operand,
8451 or a `js2-node' struct if it has already been parsed."
8452 (let* ((pos (js2-node-pos left))
8453 (op-pos (- js2-token-beg pos))
8454 (right (if (js2-node-p parser)
8457 (pn (make-js2-infix-node :type type
8459 :len (- (js2-node-end right) pos)
8463 (js2-node-add-children pn left right)
8466 (defun js2-parse-or-expr ()
8467 (let ((pn (js2-parse-and-expr)))
8468 (when (js2-match-token js2-OR)
8469 (setq pn (js2-make-binary js2-OR
8471 'js2-parse-or-expr)))
8474 (defun js2-parse-and-expr ()
8475 (let ((pn (js2-parse-bit-or-expr)))
8476 (when (js2-match-token js2-AND)
8477 (setq pn (js2-make-binary js2-AND
8479 'js2-parse-and-expr)))
8482 (defun js2-parse-bit-or-expr ()
8483 (let ((pn (js2-parse-bit-xor-expr)))
8484 (while (js2-match-token js2-BITOR)
8485 (setq pn (js2-make-binary js2-BITOR
8487 'js2-parse-bit-xor-expr)))
8490 (defun js2-parse-bit-xor-expr ()
8491 (let ((pn (js2-parse-bit-and-expr)))
8492 (while (js2-match-token js2-BITXOR)
8493 (setq pn (js2-make-binary js2-BITXOR
8495 'js2-parse-bit-and-expr)))
8498 (defun js2-parse-bit-and-expr ()
8499 (let ((pn (js2-parse-eq-expr)))
8500 (while (js2-match-token js2-BITAND)
8501 (setq pn (js2-make-binary js2-BITAND
8503 'js2-parse-eq-expr)))
8506 (defconst js2-parse-eq-ops
8507 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8509 (defun js2-parse-eq-expr ()
8510 (let ((pn (js2-parse-rel-expr))
8512 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8514 (setq pn (js2-make-binary tt
8516 'js2-parse-rel-expr)))
8519 (defconst js2-parse-rel-ops
8520 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8522 (defun js2-parse-rel-expr ()
8523 (let ((pn (js2-parse-shift-expr))
8527 (setq tt (js2-peek-token))
8529 ((and js2-in-for-init (= tt js2-IN))
8530 (setq continue nil))
8531 ((memq tt js2-parse-rel-ops)
8533 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8535 (setq continue nil))))
8538 (defconst js2-parse-shift-ops
8539 (list js2-LSH js2-URSH js2-RSH))
8541 (defun js2-parse-shift-expr ()
8542 (let ((pn (js2-parse-add-expr))
8546 (setq tt (js2-peek-token))
8547 (if (memq tt js2-parse-shift-ops)
8550 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8551 (setq continue nil)))
8554 (defun js2-parse-add-expr ()
8555 (let ((pn (js2-parse-mul-expr))
8559 (setq tt (js2-peek-token))
8560 (if (or (= tt js2-ADD) (= tt js2-SUB))
8563 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8564 (setq continue nil)))
8567 (defconst js2-parse-mul-ops
8568 (list js2-MUL js2-DIV js2-MOD))
8570 (defun js2-parse-mul-expr ()
8571 (let ((pn (js2-parse-unary-expr))
8575 (setq tt (js2-peek-token))
8576 (if (memq tt js2-parse-mul-ops)
8579 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8580 (setq continue nil)))
8583 (defun js2-make-unary (type parser &rest args)
8584 "Make a unary node of type TYPE.
8585 PARSER is either a node (for postfix operators) or a function to call
8586 to parse the operand (for prefix operators)."
8587 (let* ((pos js2-token-beg)
8588 (postfix (js2-node-p parser))
8591 (apply parser args)))
8594 (if postfix ; e.g. i++
8595 (setq pos (js2-node-pos expr)
8597 (setq end (js2-node-end expr)))
8598 (setq pn (make-js2-unary-node :type type
8602 (js2-node-add-children pn expr)
8605 (defconst js2-incrementable-node-types
8606 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8607 "Node types that can be the operand of a ++ or -- operator.")
8609 (defun js2-check-bad-inc-dec (tt beg end unary)
8610 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8611 js2-incrementable-node-types)
8612 (js2-report-error (if (= tt js2-INC)
8615 nil beg (- end beg))))
8617 (defun js2-parse-unary-expr ()
8618 (let ((tt (js2-peek-token))
8621 ((or (= tt js2-VOID)
8626 (js2-make-unary tt 'js2-parse-unary-expr))
8629 ;; Convert to special POS token in decompiler and parse tree
8630 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8633 ;; Convert to special NEG token in decompiler and parse tree
8634 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8639 (setq beg js2-token-beg
8641 expr (js2-make-unary tt 'js2-parse-member-expr t))
8642 (js2-check-bad-inc-dec tt beg end expr)))
8645 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8648 (make-js2-error-node)) ; try to continue
8650 js2-compiler-xml-available)
8651 ;; XML stream encountered in expression.
8653 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8655 (setq pn (js2-parse-member-expr t)
8656 ;; Don't look across a newline boundary for a postfix incop.
8657 tt (js2-peek-token-or-eol))
8658 (when (or (= tt js2-INC) (= tt js2-DEC))
8661 pn (js2-make-unary tt expr))
8662 (js2-node-set-prop pn 'postfix t)
8663 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8666 (defun js2-parse-xml-initializer ()
8667 "Parse an E4X XML initializer.
8668 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8669 Then I'll postprocess the result, depending on whether we're in IDE
8670 mode or codegen mode, and generate the appropriate rewritten AST.
8671 IDE mode uses a rich AST that models the XML structure. Codegen mode
8672 just concatenates everything and makes a new XML or XMLList out of it."
8673 (let ((tt (js2-get-first-xml-token))
8674 pn-xml pn expr kids expr-pos
8677 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8678 (js2-report-error "msg.syntax"))
8679 (setq pn-xml (make-js2-xml-node))
8682 (setq first-token nil)
8683 (setq tt (js2-get-next-xml-token)))
8685 ;; js2-XML means we found a {expr} in the XML stream.
8686 ;; The js2-ts-string is the XML up to the left-curly.
8688 (push (make-js2-string-node :pos js2-token-beg
8689 :len (- js2-ts-cursor js2-token-beg))
8691 (js2-must-match js2-LC "msg.syntax")
8692 (setq expr-pos js2-ts-cursor
8693 expr (if (eq (js2-peek-token) js2-RC)
8694 (make-js2-empty-expr-node :pos expr-pos)
8696 (js2-must-match js2-RC "msg.syntax")
8697 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8698 :len (js2-node-len expr)
8700 (js2-node-add-children pn expr)
8702 ;; a js2-XMLEND token means we hit the final close-tag.
8704 (push (make-js2-string-node :pos js2-token-beg
8705 :len (- js2-ts-cursor js2-token-beg))
8707 (dolist (kid (nreverse kids))
8708 (js2-block-node-push pn-xml kid))
8709 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8710 (js2-node-pos pn-xml))
8713 (js2-report-error "msg.syntax")
8714 (setq continue nil))))
8718 (defun js2-parse-argument-list ()
8719 "Parse an argument list and return it as a Lisp list of nodes.
8720 Returns the list in reverse order. Consumes the right-paren token."
8722 (unless (js2-match-token js2-RP)
8724 (if (= (js2-peek-token) js2-YIELD)
8725 (js2-report-error "msg.yield.parenthesized"))
8726 (push (js2-parse-assign-expr) result)
8728 (js2-match-token js2-COMMA))
8729 (js2-must-match js2-RP "msg.no.paren.arg")
8732 (defun js2-parse-member-expr (&optional allow-call-syntax)
8733 (let ((tt (js2-peek-token))
8734 pn pos target args beg end init tail)
8736 (setq pn (js2-parse-primary-expr))
8737 ;; parse a 'new' expression
8739 (setq pos js2-token-beg
8741 target (js2-parse-member-expr)
8742 end (js2-node-end target)
8743 pn (make-js2-new-node :pos pos
8746 (js2-node-add-children pn target)
8747 (when (js2-match-token js2-LP)
8748 ;; Add the arguments to pn, if any are supplied.
8749 (setf beg pos ; start of "new" keyword
8751 args (nreverse (js2-parse-argument-list))
8752 (js2-new-node-args pn) args
8754 (js2-new-node-lp pn) (- pos beg)
8755 (js2-new-node-rp pn) (- end 1 beg))
8756 (apply #'js2-node-add-children pn args))
8757 (when (and js2-allow-rhino-new-expr-initializer
8758 (js2-match-token js2-LC))
8759 (setf init (js2-parse-object-literal)
8760 end (js2-node-end init)
8761 (js2-new-node-initializer pn) init)
8762 (js2-node-add-children pn init))
8763 (setf (js2-node-len pn) (- end beg))) ; end outer if
8764 (js2-parse-member-expr-tail allow-call-syntax pn)))
8766 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8767 "Parse a chain of property/array accesses or function calls.
8768 Includes parsing for E4X operators like `..' and `.@'.
8769 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8770 Returns an expression tree that includes PN, the parent node."
8771 (let ((beg (js2-node-pos pn))
8775 (setq tt (js2-peek-token))
8777 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8778 (setq pn (js2-parse-property-access tt pn)))
8779 ((= tt js2-DOTQUERY)
8780 (setq pn (js2-parse-dot-query pn)))
8782 (setq pn (js2-parse-element-get pn)))
8784 (if allow-call-syntax
8785 (setq pn (js2-parse-function-call pn))
8786 (setq continue nil)))
8788 (setq continue nil))))
8789 (if (>= js2-highlight-level 2)
8790 (js2-parse-highlight-member-expr-node pn))
8793 (defun js2-parse-dot-query (pn)
8794 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8795 Last token parsed must be `js2-DOTQUERY'."
8796 (let ((pos (js2-node-pos pn))
8800 (js2-set-requires-activation)
8801 (setq op-pos js2-token-beg
8802 expr (js2-parse-expr)
8803 end (js2-node-end expr)
8804 pn (make-js2-xml-dot-query-node :left pn
8808 (js2-node-add-children pn
8809 (js2-xml-dot-query-node-left pn)
8810 (js2-xml-dot-query-node-right pn))
8811 (if (js2-must-match js2-RP "msg.no.paren")
8812 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8814 (setf (js2-node-len pn) (- end pos))
8817 (defun js2-parse-element-get (pn)
8818 "Parse an element-get expression, e.g. foo[bar].
8819 Last token parsed must be `js2-RB'."
8820 (let ((lb js2-token-beg)
8821 (pos (js2-node-pos pn))
8824 (setq expr (js2-parse-expr))
8825 (if (js2-must-match js2-RB "msg.no.bracket.index")
8826 (setq rb js2-token-beg))
8827 (setq pn (make-js2-elem-get-node :target pn
8830 :lb (js2-relpos lb pos)
8831 :rb (js2-relpos rb pos)
8832 :len (- js2-token-end pos)))
8833 (js2-node-add-children pn
8834 (js2-elem-get-node-target pn)
8835 (js2-elem-get-node-element pn))
8838 (defun js2-parse-function-call (pn)
8840 (pos (js2-node-pos pn)))
8842 (setq pn (make-js2-call-node :pos pos
8844 :lp (- js2-token-beg pos)))
8845 (js2-node-add-children pn (js2-call-node-target pn))
8846 ;; Add the arguments to pn, if any are supplied.
8847 (setf args (nreverse (js2-parse-argument-list))
8848 (js2-call-node-rp pn) (- js2-token-beg pos)
8849 (js2-call-node-args pn) args)
8850 (apply #'js2-node-add-children pn args)
8851 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8854 (defun js2-parse-property-access (tt pn)
8855 "Parse a property access, XML descendants access, or XML attr access."
8856 (let ((member-type-flags 0)
8857 (dot-pos js2-token-beg)
8858 (dot-len (if (= tt js2-DOTDOT) 2 1))
8860 ref ; right side of . or .. operator
8863 (when (= tt js2-DOTDOT)
8865 (setq member-type-flags js2-descendants-flag))
8866 (if (not js2-compiler-xml-available)
8868 (js2-must-match-prop-name "msg.no.name.after.dot")
8869 (setq name (js2-create-name-node t js2-GETPROP)
8870 result (make-js2-prop-get-node :left pn
8873 :len (- js2-token-end
8875 (js2-node-add-children result pn name)
8877 ;; otherwise look for XML operators
8878 (setf result (if (= tt js2-DOT)
8879 (make-js2-prop-get-node)
8880 (make-js2-infix-node :type js2-DOTDOT))
8881 (js2-node-pos result) (js2-node-pos pn)
8882 (js2-infix-node-op-pos result) dot-pos
8883 (js2-infix-node-left result) pn ; do this after setting position
8884 tt (js2-next-token))
8886 ;; needed for generator.throw()
8888 (js2-save-name-token-data js2-token-beg "throw")
8889 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8890 ;; handles: name, ns::name, ns::*, ns::[expr]
8891 ((js2-valid-prop-name-token tt)
8892 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8893 ;; handles: *, *::name, *::*, *::[expr]
8895 (js2-save-name-token-data js2-token-beg "*")
8896 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8897 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8899 (setq result (js2-parse-attribute-access)))
8901 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8903 (setf (js2-node-len result) (- (js2-node-end ref)
8904 (js2-node-pos result))
8905 (js2-infix-node-right result) ref))
8906 (if (js2-infix-node-p result)
8907 (js2-node-add-children result
8908 (js2-infix-node-left result)
8909 (js2-infix-node-right result)))
8912 (defun js2-parse-attribute-access ()
8913 "Parse an E4X XML attribute expression.
8914 This includes expressions of the forms:
8916 @attr @ns::attr @ns::*
8918 @[expr] @*::[expr] @ns::[expr]
8920 Called if we peeked an '@' token."
8921 (let ((tt (js2-next-token))
8922 (at-pos js2-token-beg))
8924 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8925 ((js2-valid-prop-name-token tt)
8926 (js2-parse-property-name at-pos js2-ts-string 0))
8927 ;; handles: @*, @*::name, @*::*, @*::[expr]
8929 (js2-save-name-token-data js2-token-beg "*")
8930 (js2-parse-property-name js2-token-beg "*" 0))
8933 (js2-parse-xml-elem-ref at-pos))
8935 (js2-report-error "msg.no.name.after.xmlAttr")
8936 ;; Avoid cascaded errors that happen if we make an error node here.
8937 (js2-save-name-token-data js2-token-beg "")
8938 (js2-parse-property-name js2-token-beg "" 0)))))
8940 (defun js2-parse-property-name (at-pos s member-type-flags)
8941 "Check if :: follows name in which case it becomes qualified name.
8943 AT-POS is a natural number if we just read an '@' token, else nil.
8944 S is the name or string that was matched: an identifier, 'throw' or '*'.
8945 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8947 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8948 operator, or the name is followed by ::. For a plain name, returns a
8949 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8950 (let ((pos (or at-pos js2-token-beg))
8952 (name (js2-create-name-node t js2-current-token))
8955 (when (js2-match-token js2-COLONCOLON)
8957 colon-pos js2-token-beg
8958 tt (js2-next-token))
8960 ;; handles name::name
8961 ((js2-valid-prop-name-token tt)
8962 (setq name (js2-create-name-node)))
8965 (js2-save-name-token-data js2-token-beg "*")
8966 (setq name (js2-create-name-node)))
8967 ;; handles name::[expr]
8969 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8971 (js2-report-error "msg.no.name.after.coloncolon"))))
8972 (if (and (null ns) (zerop member-type-flags))
8976 (make-js2-xml-prop-ref-node :pos pos
8977 :len (- (js2-node-end name) pos)
8979 :colon-pos colon-pos
8981 (js2-node-add-children pn name))))))
8983 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
8984 "Parse the [expr] portion of an xml element reference.
8985 For instance, @[expr], @*::[expr], or ns::[expr]."
8986 (let* ((lb js2-token-beg)
8987 (pos (or at-pos lb))
8989 (expr (js2-parse-expr))
8990 (end (js2-node-end expr))
8992 (if (js2-must-match js2-RB "msg.no.bracket.index")
8993 (setq rb js2-token-beg
8997 (make-js2-xml-elem-ref-node :pos pos
8999 :namespace namespace
9000 :colon-pos colon-pos
9003 :lb (js2-relpos lb pos)
9004 :rb (js2-relpos rb pos)))
9005 (js2-node-add-children pn namespace expr))))
9007 (defun js2-parse-primary-expr-lhs ()
9008 (let ((js2-is-in-lhs t))
9009 (js2-parse-primary-expr)))
9011 (defun js2-parse-primary-expr ()
9012 "Parse a literal (leaf) expression of some sort.
9013 Includes complex literals such as functions, object-literals,
9014 array-literals, array comprehensions and regular expressions."
9015 (let ((tt-flagged (js2-next-flagged-token))
9016 pn ; parent node (usually return value)
9018 px-pos ; paren-expr pos
9020 flags ; regexp flags
9022 (setq tt js2-current-token)
9024 ((= tt js2-FUNCTION)
9025 (js2-parse-function 'FUNCTION_EXPRESSION))
9027 (js2-parse-array-literal))
9029 (js2-parse-object-literal))
9031 (js2-parse-let js2-token-beg))
9033 (setq px-pos js2-token-beg
9034 expr (js2-parse-expr))
9035 (js2-must-match js2-RP "msg.no.paren")
9036 (setq pn (make-js2-paren-node :pos px-pos
9038 :len (- js2-token-end px-pos)))
9039 (js2-node-add-children pn (js2-paren-node-expr pn))
9043 (js2-parse-attribute-access))
9045 (js2-parse-name tt-flagged tt))
9047 (make-js2-number-node))
9050 (make-js2-string-node)
9051 (js2-record-face 'font-lock-string-face)))
9052 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9053 ;; Got / or /= which in this context means a regexp literal
9054 (setq px-pos js2-token-beg)
9055 (js2-read-regexp tt)
9056 (setq flags js2-ts-regexp-flags
9057 js2-ts-regexp-flags nil)
9059 (make-js2-regexp-node :pos px-pos
9060 :len (- js2-ts-cursor px-pos)
9061 :value js2-ts-string
9063 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9064 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9065 ((or (= tt js2-NULL)
9069 (make-js2-keyword-node :type tt))
9070 ((= tt js2-RESERVED)
9071 (js2-report-error "msg.reserved.id")
9072 (make-js2-name-node))
9074 ;; the scanner or one of its subroutines reported the error.
9075 (make-js2-error-node))
9077 (setq px-pos (point-at-bol)
9078 len (- js2-ts-cursor px-pos))
9079 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9080 (make-js2-error-node :pos px-pos :len len))
9082 (js2-report-error "msg.syntax")
9083 (make-js2-error-node)))))
9085 (defun js2-parse-name (tt-flagged tt)
9086 (let ((name js2-ts-string)
9087 (name-pos js2-token-beg)
9089 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9090 (= (js2-peek-token) js2-COLON))
9092 ;; Do not consume colon, it is used as unwind indicator
9093 ;; to return to statementHelper.
9094 (make-js2-label-node :pos name-pos
9095 :len (- js2-token-end name-pos)
9097 (js2-set-face name-pos
9099 'font-lock-variable-name-face 'record))
9100 ;; Otherwise not a label, just a name. Unfortunately peeking
9101 ;; the next token to check for a colon has biffed js2-token-beg
9102 ;; and js2-token-end. We store the name's bounds in buffer vars
9103 ;; and `js2-create-name-node' uses them.
9104 (js2-save-name-token-data name-pos name)
9105 (setq node (if js2-compiler-xml-available
9106 (js2-parse-property-name nil name 0)
9107 (js2-create-name-node 'check-activation)))
9108 (if js2-highlight-external-variables
9109 (js2-record-name-node node))
9112 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9113 (js2-add-strict-warning
9115 ;; back up from comma to beginning of line or array/objlit
9117 (js2-node-pos (car elems))
9120 (goto-char comma-pos)
9121 (back-to-indentation)
9125 (defun js2-parse-array-literal ()
9126 (let ((pos js2-token-beg)
9128 (after-lb-or-comma t)
9129 after-comma tt elems pn
9131 (unless js2-is-in-lhs
9132 (js2-push-scope (make-js2-scope))) ; for array comp
9134 (setq tt (js2-peek-token))
9139 (setq after-comma js2-token-end)
9140 (if (not after-lb-or-comma)
9141 (setq after-lb-or-comma t)
9145 (= tt js2-EOF)) ; prevent infinite loop
9147 (js2-report-error "msg.no.bracket.arg" nil pos)
9148 (js2-consume-token))
9151 pn (make-js2-array-node :pos pos
9152 :len (- js2-ts-cursor pos)
9153 :elems (nreverse elems)))
9154 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9155 (when (and after-comma (not js2-is-in-lhs))
9156 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9157 pos elems after-comma)))
9158 ;; destructuring binding
9160 (push (if (or (= tt js2-LC)
9163 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9164 (js2-parse-primary-expr-lhs)
9167 (js2-report-error "msg.bad.var")
9168 (make-js2-error-node))
9170 (setq after-lb-or-comma nil
9173 ((and (>= js2-language-version 170)
9174 (= tt js2-FOR) ; check for array comprehension
9175 (not after-lb-or-comma) ; "for" can't follow a comma
9176 elems ; must have at least 1 element
9177 (not (cdr elems))) ; but no 2nd element
9179 pn (js2-parse-array-comprehension (car elems) pos)))
9183 (unless after-lb-or-comma
9184 (js2-report-error "msg.no.bracket.arg"))
9185 (push (js2-parse-assign-expr) elems)
9186 (setq after-lb-or-comma nil
9188 (unless js2-is-in-lhs
9192 (defun js2-parse-array-comprehension (expr pos)
9193 "Parse a JavaScript 1.7 Array Comprehension.
9194 EXPR is the first expression after the opening left-bracket.
9195 POS is the beginning of the LB token preceding EXPR.
9196 We should have just parsed the 'for' keyword before calling this function."
9197 (let (loops loop first prev filter if-pos result)
9198 (while (= (js2-peek-token) js2-FOR)
9199 (let ((prev (car loops))) ; rearrange scope chain
9200 (push (setq loop (js2-parse-array-comp-loop)) loops)
9201 (if prev ; each loop is parent scope to the next one
9202 (setf (js2-scope-parent-scope loop) prev)
9203 ; first loop takes expr scope's parent
9204 (setf (js2-scope-parent-scope (setq first loop))
9205 (js2-scope-parent-scope js2-current-scope)))))
9206 ;; set expr scope's parent to the last loop
9207 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9208 (when (= (js2-peek-token) js2-IF)
9210 (setq if-pos (- js2-token-beg pos) ; relative
9211 filter (js2-parse-condition)))
9212 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9213 (setq result (make-js2-array-comp-node :pos pos
9214 :len (- js2-ts-cursor pos)
9216 :loops (nreverse loops)
9217 :filter (car filter)
9218 :lp (js2-relpos (second filter) pos)
9219 :rp (js2-relpos (third filter) pos)
9221 (apply #'js2-node-add-children result expr (car filter)
9222 (js2-array-comp-node-loops result))
9223 (setq js2-current-scope first) ; pop to the first loop
9226 (defun js2-parse-array-comp-loop ()
9227 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9228 Last token peeked should be the initial FOR."
9229 (let ((pos js2-token-beg)
9230 (pn (make-js2-array-comp-loop-node))
9231 tt iter obj foreach-p in-pos each-pos lp rp)
9232 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9236 (when (js2-match-token js2-NAME)
9237 (if (string= js2-ts-string "each")
9240 each-pos (- js2-token-beg pos)) ; relative
9241 (js2-record-face 'font-lock-keyword-face))
9242 (js2-report-error "msg.no.paren.for")))
9243 (if (js2-must-match js2-LP "msg.no.paren.for")
9244 (setq lp (- js2-token-beg pos)))
9245 (setq tt (js2-peek-token))
9249 ;; handle destructuring assignment
9250 (setq iter (js2-parse-primary-expr-lhs))
9251 (js2-define-destruct-symbols iter js2-LET
9252 'font-lock-variable-name-face t))
9253 ((js2-valid-prop-name-token tt)
9255 (setq iter (js2-create-name-node)))
9257 (js2-report-error "msg.bad.var")))
9258 ;; Define as a let since we want the scope of the variable to
9259 ;; be restricted to the array comprehension
9260 (if (js2-name-node-p iter)
9261 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9262 (if (js2-must-match js2-IN "msg.in.after.for.name")
9263 (setq in-pos (- js2-token-beg pos)))
9264 (setq obj (js2-parse-expr))
9265 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9266 (setq rp (- js2-token-beg pos)))
9267 (setf (js2-node-pos pn) pos
9268 (js2-node-len pn) (- js2-ts-cursor pos)
9269 (js2-array-comp-loop-node-iterator pn) iter
9270 (js2-array-comp-loop-node-object pn) obj
9271 (js2-array-comp-loop-node-in-pos pn) in-pos
9272 (js2-array-comp-loop-node-each-pos pn) each-pos
9273 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9274 (js2-array-comp-loop-node-lp pn) lp
9275 (js2-array-comp-loop-node-rp pn) rp)
9276 (js2-node-add-children pn iter obj))
9280 (defun js2-parse-object-literal ()
9281 (let ((pos js2-token-beg)
9282 tt elems result after-comma
9285 (setq tt (js2-peek-token))
9287 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9288 ;; {get foo() {...}}, or {set foo(x) {...}}
9289 ((or (js2-valid-prop-name-token tt)
9291 (setq after-comma nil
9292 result (js2-parse-named-prop tt))
9293 (if (and (null result)
9294 (not js2-recover-from-parse-errors))
9296 (push result elems)))
9297 ;; {12: x} or {10.7: x}
9300 (setq after-comma nil)
9301 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9306 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9307 pos elems after-comma)))
9309 (js2-report-error "msg.bad.prop")
9310 (unless js2-recover-from-parse-errors
9311 (setq continue nil)))) ; end switch
9312 (if (js2-match-token js2-COMMA)
9313 (setq after-comma js2-token-end)
9314 (setq continue nil))) ; end loop
9315 (js2-must-match js2-RC "msg.no.brace.prop")
9316 (setq result (make-js2-object-node :pos pos
9317 :len (- js2-ts-cursor pos)
9318 :elems (nreverse elems)))
9319 (apply #'js2-node-add-children result (js2-object-node-elems result))
9322 (defun js2-parse-named-prop (tt)
9323 "Parse a name, string, or getter/setter object property.
9324 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9326 (let ((string-prop (and (= tt js2-STRING)
9327 (make-js2-string-node)))
9329 (ppos js2-token-beg)
9330 (pend js2-token-end)
9331 (name (js2-create-name-node))
9332 (prop js2-ts-string))
9334 ;; getter/setter prop
9335 ((and (= tt js2-NAME)
9336 (= (js2-peek-token) js2-NAME)
9337 (or (string= prop "get")
9338 (string= prop "set")))
9340 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9341 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9342 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9343 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9344 ;; abbreviated destructuring bind e.g., {a, b} = c;
9345 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9346 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9347 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9348 ;; assignment but it's difficult because it requires looking ahead of expression.
9351 (let ((ctk (js2-peek-token)))
9352 (or (= ctk js2-COMMA)
9354 (js2-valid-prop-name-token ctk))))
9359 (setq expr (js2-parse-plain-property (or string-prop name)))
9360 (js2-set-face ppos pend
9361 (if (js2-function-node-p
9362 (js2-object-prop-node-right expr))
9363 'font-lock-function-name-face
9364 'font-lock-variable-name-face)
9367 (defun js2-parse-plain-property (prop)
9368 "Parse a non-getter/setter property in an object literal.
9369 PROP is the node representing the property: a number, name or string."
9370 (js2-must-match js2-COLON "msg.no.colon.prop")
9371 (let* ((pos (js2-node-pos prop))
9372 (colon (- js2-token-beg pos))
9373 (expr (js2-parse-assign-expr))
9374 (result (make-js2-object-prop-node
9376 ;; don't include last consumed token in length
9377 :len (- (+ (js2-node-pos expr)
9378 (js2-node-len expr))
9383 (js2-node-add-children result prop expr)
9386 (defun js2-parse-getter-setter-prop (pos prop get-p)
9387 "Parse getter or setter property in an object literal.
9388 JavaScript syntax is:
9390 { get foo() {...}, set foo(x) {...} }
9392 and expression closure style is also supported
9394 { get foo() x, set foo(x) _x = x }
9396 POS is the start position of the `get' or `set' keyword.
9397 PROP is the `js2-name-node' representing the property name.
9398 GET-P is non-nil if the keyword was `get'."
9399 (let ((type (if get-p js2-GET js2-SET))
9401 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9402 ;; it has to be an anonymous function, as we already parsed the name
9403 (if (/= (js2-node-type fn) js2-FUNCTION)
9404 (js2-report-error "msg.bad.prop")
9405 (if (plusp (length (js2-function-name fn)))
9406 (js2-report-error "msg.bad.prop")))
9407 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9408 (setq end (js2-node-end fn)
9409 result (make-js2-getter-setter-node :type type
9414 (js2-node-add-children result prop fn)
9417 (defun js2-create-name-node (&optional check-activation-p token)
9418 "Create a name node using the token info from last scanned name.
9419 In some cases we need to either synthesize a name node, or we lost
9420 the name token information by peeking. If the TOKEN parameter is
9421 not `js2-NAME', then we use the token info saved in instance vars."
9422 (let ((beg js2-token-beg)
9425 (when (/= js2-current-token js2-NAME)
9426 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9427 s js2-prev-name-token-string
9428 js2-prev-name-token-start nil
9429 js2-prev-name-token-string nil))
9430 (setq name (make-js2-name-node :pos beg
9433 (if check-activation-p
9434 (js2-check-activation-name s (or token js2-NAME)))
9437 ;;; Indentation support
9439 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9440 ;; Karl cleverly deduces that the desired indentation level is often a
9441 ;; function of paren/bracket/brace nesting depth, which can be determined
9442 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9443 ;; then does some equally clever checks to see if we're in the context of a
9444 ;; substatement of a possibly braceless statement keyword such as if, while,
9445 ;; or finally. This approach yields pretty good results.
9447 ;; The indenter is often "wrong", however, and needs to be overridden.
9448 ;; The right long-term solution is probably to emulate (or integrate
9449 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9450 ;; parse tree from `js2-parse' is present, which is not true at the
9451 ;; moment the user is typing, computing indentation is still thousands
9452 ;; of lines of code to handle every possible syntactic edge case.
9454 ;; In the meantime, the compromise solution is that we offer a "bounce
9455 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9456 ;; current line indent among various likely guess points. This approach
9457 ;; is far from perfect, but should at least make it slightly easier to
9458 ;; move the line towards its desired indentation when manually
9459 ;; overriding Karl's heuristic nesting guesser.
9461 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9462 ;; extensions such as `let' and Array comprehensions. Major kudos to
9463 ;; Karl for coming up with the initial approach, which packs a lot of
9464 ;; punch for so little code.
9466 (defconst js2-possibly-braceless-keywords-re
9467 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9468 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9469 "try" "while" "with" "let")))
9470 "Regular expression matching keywords that are optionally
9471 followed by an opening brace.")
9473 (defconst js2-indent-operator-re
9474 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9475 (regexp-opt '("in" "instanceof") 'words))
9476 "Regular expression matching operators that affect indentation
9477 of continued expressions.")
9479 (defconst js2-declaration-keyword-re
9480 (regexp-opt '("var" "let" "const") 'words)
9481 "Regular expression matching variable declaration keywords.")
9483 ;; This function has horrible results if you're typing an array
9484 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9485 ;; in conjunction with electric-indent, so just disabling it.
9486 (defsubst js2-code-at-bol-p ()
9487 "Return t if the first character on line is non-whitespace."
9490 (defun js2-insert-and-indent (key)
9491 "Run command bound to KEY and indent current line.
9492 Runs the command bound to KEY in the global keymap and indents
9494 (interactive (list (this-command-keys)))
9495 (let ((cmd (lookup-key (current-global-map) key)))
9497 (call-interactively cmd)))
9498 ;; don't do the electric keys inside comments or strings,
9499 ;; and don't do bounce-indent with them.
9500 (let ((parse-state (syntax-ppss (point)))
9501 (js2-bounce-indent-p (js2-code-at-bol-p)))
9502 (unless (or (nth 3 parse-state)
9503 (nth 4 parse-state))
9504 (indent-according-to-mode))))
9506 (defun js2-re-search-forward-inner (regexp &optional bound count)
9507 "Auxiliary function for `js2-re-search-forward'."
9508 (let (parse saved-point)
9510 (re-search-forward regexp bound)
9511 (setq parse (if saved-point
9512 (parse-partial-sexp saved-point (point))
9513 (syntax-ppss (point))))
9514 (cond ((nth 3 parse)
9516 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9517 (save-excursion (end-of-line) (point)) t))
9521 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9522 (re-search-forward "\\*/"))
9524 (setq count (1- count))))
9525 (setq saved-point (point))))
9528 (defun js2-re-search-forward (regexp &optional bound noerror count)
9529 "Search forward but ignore strings and comments.
9530 Invokes `re-search-forward' but treats the buffer as if strings
9531 and comments have been removed."
9532 (let ((saved-point (point))
9535 '(js2-re-search-forward-inner regexp bound 1))
9537 '(js2-re-search-backward-inner regexp bound (- count)))
9539 '(js2-re-search-forward-inner regexp bound count)))))
9543 (goto-char saved-point)
9545 (error (error-message-string err)))))))
9547 (defun js2-re-search-backward-inner (regexp &optional bound count)
9548 "Auxiliary function for `js2-re-search-backward'."
9551 (re-search-backward regexp bound)
9552 (setq parse (syntax-ppss (point)))
9553 (cond ((nth 3 parse)
9555 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9556 (line-beginning-position) t))
9558 (goto-char (nth 8 parse)))
9560 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9561 (re-search-backward "/\\*"))
9563 (setq count (1- count))))))
9566 (defun js2-re-search-backward (regexp &optional bound noerror count)
9567 "Search backward but ignore strings and comments.
9568 Invokes `re-search-backward' but treats the buffer as if strings
9569 and comments have been removed."
9570 (let ((saved-point (point))
9573 '(js2-re-search-backward-inner regexp bound 1))
9575 '(js2-re-search-forward-inner regexp bound (- count)))
9577 '(js2-re-search-backward-inner regexp bound count)))))
9581 (goto-char saved-point)
9583 (error (error-message-string err)))))))
9585 (defun js2-looking-at-operator-p ()
9586 "Return non-nil if text after point is a non-comma operator."
9587 (and (looking-at js2-indent-operator-re)
9588 (or (not (looking-at ":"))
9590 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9591 (looking-at "?"))))))
9593 (defun js2-continued-expression-p ()
9594 "Return non-nil if the current line continues an expression."
9596 (back-to-indentation)
9597 (or (js2-looking-at-operator-p)
9598 (when (js2-re-search-backward "\n" nil t) ;; skip comments
9599 (skip-chars-backward " \t")
9600 (unless (bolp) ;; previous line is empty
9602 (when (js2-looking-at-operator-p)
9604 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))
9606 (defun js2-end-of-do-while-loop-p ()
9607 "Return non-nil if word after point is `while' of a do-while
9608 statement, else returns nil. A braceless do-while statement
9609 spanning several lines requires that the start of the loop is
9610 indented to the same column as the current line."
9613 (when (looking-at "\\s-*\\<while\\>")
9615 (skip-chars-backward "[ \t\n]*}")
9616 (looking-at "[ \t\n]*}"))
9618 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9619 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9620 (or (looking-at "\\<do\\>")
9621 (let ((saved-indent (current-indentation)))
9622 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9623 (/= (current-indentation) saved-indent)))
9624 (and (looking-at "[ \t]*\\<do\\>")
9625 (not (js2-re-search-forward
9626 "\\<while\\>" (point-at-eol) t))
9627 (= (current-indentation) saved-indent))))))))
9629 (defun js2-multiline-decl-indentation ()
9630 "Returns the declaration indentation column if the current line belongs
9631 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9632 (let (forward-sexp-function ; use Lisp version
9635 (back-to-indentation)
9636 (when (not (looking-at js2-declaration-keyword-re))
9637 (when (looking-at js2-indent-operator-re)
9638 (goto-char (match-end 0))) ; continued expressions are ok
9639 (while (and (not at-opening-bracket)
9641 (let ((pos (point)))
9644 (or (eq (char-before) ?,)
9645 (and (not (eq (char-before) ?\;))
9647 (prog2 (skip-chars-backward "[[:punct:]]")
9648 (looking-at js2-indent-operator-re)
9650 (not (eq (char-before) ?\;))))
9651 (js2-same-line pos)))))
9654 (scan-error (setq at-opening-bracket t))))
9655 (when (looking-at js2-declaration-keyword-re)
9656 (- (1+ (match-end 0)) (point-at-bol)))))))
9658 (defun js2-ctrl-statement-indentation ()
9659 "Return the proper indentation of current line if it is a control statement.
9660 Returns an indentation if this line starts the body of a control
9661 statement without braces, else returns nil."
9662 (let (forward-sexp-function)
9664 (back-to-indentation)
9665 (when (and (not (js2-same-line (point-min)))
9666 (not (looking-at "{"))
9667 (js2-re-search-backward "[[:graph:]]" nil t)
9668 (not (looking-at "[{([]"))
9671 (when (= (char-before) ?\))
9672 ;; scan-sexps sometimes throws an error
9673 (ignore-errors (backward-sexp))
9674 (skip-chars-backward " \t" (point-at-bol)))
9676 (back-to-indentation)
9677 (and (looking-at js2-possibly-braceless-keywords-re)
9678 (= (match-end 0) pt)
9679 (not (js2-end-of-do-while-loop-p))))))
9680 (+ (current-indentation) js2-basic-offset)))))
9682 (defun js2-indent-in-array-comp (parse-status)
9683 "Return non-nil if we think we're in an array comprehension.
9684 In particular, return the buffer position of the first `for' kwd."
9685 (let ((bracket (nth 1 parse-status))
9690 (when (looking-at "\\[")
9693 (if (looking-at "[[{]")
9694 (let (forward-sexp-function) ; use Lisp version
9695 (forward-sexp) ; skip destructuring form
9697 (if (and (/= (char-after) ?,) ; regular array
9699 (match-beginning 0)))
9700 ;; to skip arbitrary expressions we need the parser,
9701 ;; so we'll just guess at it.
9702 (if (and (> end (point)) ; not empty literal
9703 (re-search-forward "[^,]]* \\(for\\) " end t)
9704 ;; not inside comment or string literal
9705 (let ((state (parse-partial-sexp bracket (point))))
9706 (not (or (nth 3 state) (nth 4 state)))))
9707 (match-beginning 1))))))))
9709 (defun js2-array-comp-indentation (parse-status for-kwd)
9710 (if (js2-same-line for-kwd)
9711 ;; first continuation line
9713 (goto-char (nth 1 parse-status))
9715 (skip-chars-forward " \t")
9721 (defun js2-proper-indentation (parse-status)
9722 "Return the proper indentation for the current line."
9724 (back-to-indentation)
9725 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9726 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9727 (continued-expr-p (js2-continued-expression-p))
9728 (declaration-indent (and js2-pretty-multiline-declarations
9729 (js2-multiline-decl-indentation)))
9730 (bracket (nth 1 parse-status))
9733 ;; indent array comprehension continuation lines specially
9735 (>= js2-language-version 170)
9736 (not (js2-same-line bracket))
9737 (setq beg (js2-indent-in-array-comp parse-status))
9738 (>= (point) (save-excursion
9740 (point-at-bol)))) ; at or after first loop?
9741 (js2-array-comp-indentation parse-status beg))
9745 ((and declaration-indent continued-expr-p)
9746 (+ declaration-indent js2-basic-offset))
9748 (declaration-indent)
9753 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9754 (when (save-excursion (skip-chars-backward " \t)")
9757 (back-to-indentation)
9758 (and (eq js2-pretty-multiline-declarations 'all)
9759 (looking-at js2-declaration-keyword-re)
9760 (goto-char (1+ (match-end 0))))
9761 (cond (same-indent-p
9764 (+ (current-column) (* 2 js2-basic-offset)))
9766 (+ (current-column) js2-basic-offset))))
9768 (unless same-indent-p
9770 (skip-chars-forward " \t"))
9773 (continued-expr-p js2-basic-offset)
9777 (defun js2-lineup-comment (parse-status)
9778 "Indent a multi-line block comment continuation line."
9779 (let* ((beg (nth 8 parse-status))
9780 (first-line (js2-same-line beg))
9781 (offset (save-excursion
9783 (if (looking-at "/\\*")
9784 (+ 1 (current-column))
9787 (indent-line-to offset))))
9789 (defun js2-backward-sws ()
9790 "Move backward through whitespace and comments."
9792 (while (forward-comment -1)))
9794 (defun js2-forward-sws ()
9795 "Move forward through whitespace and comments."
9797 (while (forward-comment 1)))
9799 (defun js2-current-indent (&optional pos)
9800 "Return column of indentation on current line.
9801 If POS is non-nil, go to that point and return indentation for that line."
9805 (back-to-indentation)
9808 (defun js2-arglist-close ()
9809 "Return non-nil if we're on a line beginning with a close-paren/brace."
9811 (goto-char (point-at-bol))
9813 (looking-at "[])}]")))
9815 (defun js2-indent-looks-like-label-p ()
9816 (goto-char (point-at-bol))
9818 (looking-at (concat js2-mode-identifier-re ":")))
9820 (defun js2-indent-in-objlit-p (parse-status)
9821 "Return non-nil if this looks like an object-literal entry."
9822 (let ((start (nth 1 parse-status)))
9826 (and (zerop (forward-line -1))
9827 (not (< (point) start)) ; crossed a {} boundary
9828 (js2-indent-looks-like-label-p)))
9830 (js2-indent-looks-like-label-p)))))
9832 ;; If prev line looks like foobar({ then we're passing an object
9833 ;; literal to a function call, and people pretty much always want to
9834 ;; de-dent back to the previous line, so move the 'basic-offset'
9835 ;; position to the front.
9836 (defun js2-indent-objlit-arg-p (parse-status)
9838 (back-to-indentation)
9840 (and (eq (1- (point)) (nth 1 parse-status))
9841 (eq (char-before) ?{)
9844 (skip-chars-backward " \t")
9845 (eq (char-before) ?\()))))
9847 (defun js2-indent-case-block-p ()
9849 (back-to-indentation)
9851 (goto-char (point-at-bol))
9852 (skip-chars-forward " \t")
9853 (looking-at "case\\s-.+:")))
9855 (defun js2-syntax-bol ()
9856 "Return the point at the first non-whitespace char on the line.
9857 Returns `point-at-bol' if the line is empty."
9860 (skip-chars-forward " \t")
9863 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9864 "Cycle among alternate computed indentation positions.
9865 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9866 of the buffer to the current point. NORMAL-COL is the indentation
9867 column computed by the heuristic guesser based on current paren,
9868 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9870 (let ((cur-indent (js2-current-indent))
9871 (old-buffer-undo-list buffer-undo-list)
9872 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9873 (current-line (save-excursion
9874 (forward-line 0) ; move to bol
9875 (1+ (count-lines (point-min) (point)))))
9876 positions pos main-pos anchor arglist-cont same-indent
9877 prev-line-col basic-offset computed-pos)
9878 ;; temporarily don't record undo info, if user requested this
9879 (when js2-mode-indent-inhibit-undo
9880 (setq buffer-undo-list t))
9883 ;; First likely point: indent from beginning of previous code line
9884 (push (setq basic-offset
9886 (back-to-indentation)
9888 (back-to-indentation)
9889 (setq prev-line-col (current-column)))
9893 ;; (First + epsilon) likely point: indent 2x from beginning of
9894 ;; previous code line. Google does it this way.
9895 (push (setq basic-offset
9897 (back-to-indentation)
9899 (back-to-indentation)
9900 (setq prev-line-col (current-column)))
9901 (* 2 js2-basic-offset)))
9904 ;; Second likely point: indent from assign-expr RHS. This
9905 ;; is just a crude guess based on finding " = " on the previous
9906 ;; line containing actual code.
9907 (setq pos (save-excursion
9909 (goto-char (point-at-bol))
9910 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9912 (goto-char (match-end 1))
9913 (skip-chars-forward " \t\r\n")
9916 (incf pos js2-basic-offset)
9917 (push pos positions))
9919 ;; Third likely point: same indent as previous line of code.
9920 ;; Make it the first likely point if we're not on an
9921 ;; arglist-close line and previous line ends in a comma, or
9922 ;; both this line and prev line look like object-literal
9924 (setq pos (save-excursion
9925 (goto-char (point-at-bol))
9927 (back-to-indentation)
9930 ;; while we're here, look for trailing comma
9932 (goto-char (point-at-eol))
9934 (eq (char-before) ?,))
9935 (setq arglist-cont (1- (point)))))))
9937 (if (and (or arglist-cont
9938 (js2-indent-in-objlit-p parse-status))
9939 (not (js2-arglist-close)))
9940 (setq same-indent pos))
9941 (push pos positions))
9943 ;; Fourth likely point: first preceding code with less indentation.
9944 ;; than the immediately preceding code line.
9945 (setq pos (save-excursion
9946 (back-to-indentation)
9948 (back-to-indentation)
9949 (setq anchor (current-column))
9950 (while (and (zerop (forward-line -1))
9952 (back-to-indentation)
9955 (setq pos (current-column))))
9956 (push pos positions)
9958 ;; nesting-heuristic position, main by default
9959 (push (setq main-pos normal-col) positions)
9961 ;; delete duplicates and sort positions list
9962 (setq positions (sort (delete-dups positions) '<))
9964 ;; comma-list continuation lines: prev line indent takes precedence
9966 (setq main-pos same-indent))
9968 ;; common special cases where we want to indent in from previous line
9969 (if (or (js2-indent-case-block-p)
9970 (js2-indent-objlit-arg-p parse-status))
9971 (setq main-pos basic-offset))
9973 ;; if bouncing backwards, reverse positions list
9975 (setq positions (reverse positions)))
9977 ;; record whether we're already sitting on one of the alternatives
9978 (setq pos (member cur-indent positions))
9981 ;; case 0: we're one one of the alternatives and this is the
9982 ;; first time they've pressed TAB on this line (best-guess).
9983 ((and js2-mode-indent-ignore-first-tab
9985 ;; first time pressing TAB on this line?
9986 (not (eq js2-mode-last-indented-line current-line)))
9988 (setq computed-pos nil))
9989 ;; case 1: only one computed position => use it
9990 ((null (cdr positions))
9991 (setq computed-pos 0))
9992 ;; case 2: not on any of the computed spots => use main spot
9994 (setq computed-pos (js2-position main-pos positions)))
9995 ;; case 3: on last position: cycle to first position
9997 (setq computed-pos 0))
9998 ;; case 4: on intermediate position: cycle to next position
10000 (setq computed-pos (js2-position (second pos) positions))))
10002 ;; see if any hooks want to indent; otherwise we do it
10003 (loop with result = nil
10004 for hook in js2-indent-hook
10005 while (null result)
10007 (setq result (funcall hook positions computed-pos))
10009 (unless (or result (null computed-pos))
10010 (indent-line-to (nth computed-pos positions)))))
10013 (if js2-mode-indent-inhibit-undo
10014 (setq buffer-undo-list old-buffer-undo-list))
10015 ;; see commentary for `js2-mode-last-indented-line'
10016 (setq js2-mode-last-indented-line current-line))))
10018 (defun js2-indent-bounce-backwards ()
10019 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10020 cycles between the computed indentation positions in reverse order."
10022 (js2-indent-line t))
10024 (defun js2-1-line-comment-continuation-p ()
10025 "Return t if we're in a 1-line comment continuation.
10026 If so, we don't ever want to use bounce-indent."
10030 (looking-at "\\s-*//"))
10034 (when (looking-at "\\s-*$")
10037 (looking-at "\\s-*//")))))
10039 (defun js2-indent-line (&optional bounce-backwards)
10040 "Indent the current line as JavaScript source text."
10042 (let (parse-status current-indent offset indent-col moved
10043 ;; Don't whine about errors/warnings when we're indenting.
10044 ;; This has to be set before calling parse-partial-sexp below.
10045 (inhibit-point-motion-hooks t))
10046 (setq parse-status (save-excursion
10047 (syntax-ppss (point-at-bol)))
10048 offset (- (point) (save-excursion
10049 (back-to-indentation)
10051 (js2-with-underscore-as-word-syntax
10052 (if (nth 4 parse-status)
10053 (js2-lineup-comment parse-status)
10054 (setq indent-col (js2-proper-indentation parse-status))
10055 ;; See comments below about `js2-mode-last-indented-line'.
10057 ;; bounce-indenting is disabled during electric-key indent.
10058 ;; It doesn't work well on first line of buffer.
10059 ((and js2-bounce-indent-p
10060 (not (js2-same-line (point-min)))
10061 (not (js2-1-line-comment-continuation-p)))
10062 (js2-bounce-indent indent-col parse-status bounce-backwards))
10063 ;; just indent to the guesser's likely spot
10064 (t (indent-line-to indent-col)))
10065 (when (plusp offset)
10066 (forward-char offset))))))
10068 (defun js2-indent-region (start end)
10069 "Indent the region, but don't use bounce indenting."
10070 (let ((js2-bounce-indent-p nil)
10071 (indent-region-function nil)
10072 (after-change-functions (remq 'js2-mode-edit
10073 after-change-functions)))
10074 (indent-region start end nil) ; nil for byte-compiler
10075 (js2-mode-edit start end (- end start))))
10077 (defvar js2-minor-mode-map
10078 (let ((map (make-sparse-keymap)))
10079 (define-key map (kbd "C-c C-`") #'js2-next-error)
10080 (define-key map [mouse-1] #'js2-mode-show-node)
10082 "Keymap used when `js2-minor-mode' is active.")
10085 (define-minor-mode js2-minor-mode
10086 "Minor mode for running js2 as a background linter.
10087 This allows you to use a different major mode for JavaScript editing,
10088 such as `espresso-mode', while retaining the asynchronous error/warning
10089 highlighting features of `js2-mode'."
10091 :lighter " js-lint"
10093 (js2-minor-mode-enter)
10094 (js2-minor-mode-exit)))
10096 (defun js2-minor-mode-enter ()
10097 "Initialization for `js2-minor-mode'."
10098 (set (make-local-variable 'max-lisp-eval-depth)
10099 (max max-lisp-eval-depth 3000))
10100 (setq next-error-function #'js2-next-error)
10101 (setq js2-default-externs
10102 (append js2-ecma-262-externs
10103 (if js2-include-browser-externs js2-browser-externs)
10104 (if js2-include-gears-externs js2-gears-externs)
10105 (if js2-include-rhino-externs js2-rhino-externs)))
10106 ;; Experiment: make reparse-delay longer for longer files.
10107 (if (plusp js2-dynamic-idle-timer-adjust)
10108 (setq js2-idle-timer-delay
10109 (* js2-idle-timer-delay
10110 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10111 (setq js2-mode-buffer-dirty-p t
10112 js2-mode-parsing nil)
10113 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10114 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10115 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10118 (defun js2-minor-mode-exit ()
10119 "Turn off `js2-minor-mode'."
10120 (setq next-error-function nil)
10121 (remove-hook 'after-change-functions #'js2-mode-edit t)
10122 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10123 (when js2-mode-node-overlay
10124 (delete-overlay js2-mode-node-overlay)
10125 (setq js2-mode-node-overlay nil))
10126 (js2-remove-overlays)
10127 (setq js2-mode-ast nil))
10129 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10130 (make-variable-buffer-local 'js2-source-buffer)
10132 (defun* js2-display-error-list ()
10133 "Display a navigable buffer listing parse errors/warnings."
10135 (unless (js2-have-errors-p)
10136 (message "No errors")
10137 (return-from js2-display-error-list))
10138 (labels ((annotate-list
10140 "Add diagnostic TYPE and line number to errs list"
10141 (mapcar (lambda (err)
10142 (append err (list type
10143 (line-number-at-pos (nth 1 err)))))
10145 (let* ((srcbuf (current-buffer))
10146 (errbuf (get-buffer-create "*js-lint*"))
10147 (errors (annotate-list
10148 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10149 'js2-error)) ; must be a valid face name
10150 (warnings (annotate-list
10151 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10152 'js2-warning)) ; must be a valid face name
10153 (all-errs (sort (append errors warnings)
10155 (funcall '< (nth 1 e1) (nth 1 e2))))))
10156 (with-current-buffer errbuf
10157 (let ((inhibit-read-only t))
10159 (dolist (err all-errs)
10160 (destructuring-bind (msg-key beg end type line) err
10161 (insert-text-button
10162 (format "line %d: %s" line (js2-get-msg msg-key))
10164 'follow-link "\C-m"
10165 'action 'js2-error-buffer-jump
10166 'js2-msg (js2-get-msg msg-key)
10169 (js2-error-buffer-mode)
10170 (setq js2-source-buffer srcbuf)
10171 (pop-to-buffer errbuf)
10172 (goto-char (point-min))
10174 (js2-error-buffer-view))))))
10176 (defvar js2-error-buffer-mode-map
10177 (let ((map (make-sparse-keymap)))
10178 (define-key map "n" #'js2-error-buffer-next)
10179 (define-key map "p" #'js2-error-buffer-prev)
10180 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10181 (define-key map "o" #'js2-error-buffer-view)
10182 (define-key map "q" #'js2-error-buffer-quit)
10184 "Keymap used for js2 diagnostics buffers.")
10186 (defun js2-error-buffer-mode ()
10187 "Major mode for js2 diagnostics buffers.
10188 Selecting an error will jump it to the corresponding source-buffer error.
10189 \\{js2-error-buffer-mode-map}"
10191 (setq major-mode 'js2-error-buffer-mode
10192 mode-name "JS Lint Diagnostics")
10193 (use-local-map js2-error-buffer-mode-map)
10194 (setq truncate-lines t)
10195 (set-buffer-modified-p nil)
10196 (setq buffer-read-only t)
10197 (run-hooks 'js2-error-buffer-mode-hook))
10199 (defun js2-error-buffer-next ()
10200 "Move to next error and view it."
10202 (when (zerop (forward-line 1))
10203 (js2-error-buffer-view)))
10205 (defun js2-error-buffer-prev ()
10206 "Move to previous error and view it."
10208 (when (zerop (forward-line -1))
10209 (js2-error-buffer-view)))
10211 (defun js2-error-buffer-quit ()
10212 "Kill the current buffer."
10216 (defun js2-error-buffer-jump (&rest ignored)
10217 "Jump cursor to current error in source buffer."
10219 (when (js2-error-buffer-view)
10220 (pop-to-buffer js2-source-buffer)))
10222 (defun js2-error-buffer-view ()
10223 "Scroll source buffer to show error at current line."
10226 ((not (eq major-mode 'js2-error-buffer-mode))
10227 (message "Not in a js2 errors buffer"))
10228 ((not (buffer-live-p js2-source-buffer))
10229 (message "Source buffer has been killed"))
10230 ((not (wholenump (get-text-property (point) 'js2-pos)))
10231 (message "There does not seem to be an error here"))
10233 (let ((pos (get-text-property (point) 'js2-pos))
10234 (msg (get-text-property (point) 'js2-msg)))
10235 (save-selected-window
10236 (pop-to-buffer js2-source-buffer)
10241 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10242 ;; FIXME: Should derive from js-mode.
10243 "Major mode for editing JavaScript code."
10244 (setq comment-start "//" ; used by comment-region; don't change it
10246 (set (make-local-variable 'max-lisp-eval-depth)
10247 (max max-lisp-eval-depth 3000))
10248 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10249 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10250 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10251 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10252 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10253 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10254 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10255 ;; for characters inside regexp literals.
10256 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10257 ;; this is necessary to make `show-paren-function' work properly
10258 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10259 ;; needed for M-x rgrep, among other things
10260 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10262 (set (make-local-variable 'electric-indent-chars)
10263 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10264 electric-indent-chars))
10265 (set (make-local-variable 'electric-layout-rules)
10266 '((?\; . after) (?\{ . after) (?\} . before)))
10268 ;; some variables needed by cc-engine for paragraph-fill, etc.
10269 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10270 c-comment-start-regexp "/[*/]\\|\\s|"
10271 c-line-comment-starter "//"
10272 c-paragraph-start js2-paragraph-start
10273 c-paragraph-separate "$"
10274 comment-start-skip js2-comment-start-skip
10275 c-syntactic-ws-start js2-syntactic-ws-start
10276 c-syntactic-ws-end js2-syntactic-ws-end
10277 c-syntactic-eol js2-syntactic-eol)
10279 (let ((c-buffer-is-cc-mode t))
10280 ;; Copied from `js-mode'. Also see Bug#6071.
10281 (make-local-variable 'paragraph-start)
10282 (make-local-variable 'paragraph-separate)
10283 (make-local-variable 'paragraph-ignore-fill-prefix)
10284 (make-local-variable 'adaptive-fill-mode)
10285 (make-local-variable 'adaptive-fill-regexp)
10286 (c-setup-paragraph-variables))
10288 (setq js2-default-externs
10289 (append js2-ecma-262-externs
10290 (if js2-include-browser-externs js2-browser-externs)
10291 (if js2-include-gears-externs js2-gears-externs)
10292 (if js2-include-rhino-externs js2-rhino-externs)))
10294 (setq font-lock-defaults '(nil t))
10296 ;; Experiment: make reparse-delay longer for longer files.
10297 (when (plusp js2-dynamic-idle-timer-adjust)
10298 (setq js2-idle-timer-delay
10299 (* js2-idle-timer-delay
10300 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10302 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10303 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10304 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10305 (setq next-error-function #'js2-next-error)
10306 (imenu-add-to-menubar (concat "IM-" mode-name))
10307 (add-to-invisibility-spec '(js2-outline . t))
10308 (set (make-local-variable 'line-move-ignore-invisible) t)
10309 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10311 (if (fboundp 'run-mode-hooks)
10312 (run-mode-hooks 'js2-mode-hook)
10313 (run-hooks 'js2-mode-hook))
10315 (setq js2-mode-functions-hidden nil
10316 js2-mode-comments-hidden nil
10317 js2-mode-buffer-dirty-p t
10318 js2-mode-parsing nil)
10321 (defun js2-mode-exit ()
10322 "Exit `js2-mode' and clean up."
10324 (when js2-mode-node-overlay
10325 (delete-overlay js2-mode-node-overlay)
10326 (setq js2-mode-node-overlay nil))
10327 (js2-remove-overlays)
10328 (setq js2-mode-ast nil)
10329 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10330 (remove-from-invisibility-spec '(js2-outline . t))
10331 (js2-mode-show-all)
10332 (with-silent-modifications
10333 (js2-clear-face (point-min) (point-max))))
10335 (defun js2-mode-reset-timer ()
10336 "Cancel any existing parse timer and schedule a new one."
10337 (if js2-mode-parse-timer
10338 (cancel-timer js2-mode-parse-timer))
10339 (setq js2-mode-parsing nil)
10340 (setq js2-mode-parse-timer
10341 (run-with-idle-timer js2-idle-timer-delay nil
10342 #'js2-mode-idle-reparse (current-buffer))))
10344 (defun js2-mode-idle-reparse (buffer)
10345 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10346 it to be reparsed when the buffer is selected."
10347 (if (eq buffer (current-buffer))
10349 ;; reparse when the buffer is selected again
10350 (with-current-buffer buffer
10351 (add-hook 'window-configuration-change-hook
10352 #'js2-mode-idle-reparse-inner
10355 (defun js2-mode-idle-reparse-inner ()
10356 (remove-hook 'window-configuration-change-hook
10357 #'js2-mode-idle-reparse-inner
10361 (defun js2-mode-edit (beg end len)
10362 "Schedule a new parse after buffer is edited.
10363 Buffer edit spans from BEG to END and is of length LEN."
10364 (setq js2-mode-buffer-dirty-p t)
10365 (js2-mode-hide-overlay)
10366 (js2-mode-reset-timer))
10368 (defun js2-minor-mode-edit (beg end len)
10369 "Callback for buffer edits in `js2-mode'.
10370 Schedules a new parse after buffer is edited.
10371 Buffer edit spans from BEG to END and is of length LEN."
10372 (setq js2-mode-buffer-dirty-p t)
10373 (js2-mode-hide-overlay)
10374 (js2-mode-reset-timer))
10376 (defun js2-reparse (&optional force)
10377 "Re-parse current buffer after user finishes some data entry.
10378 If we get any user input while parsing, including cursor motion,
10379 we discard the parse and reschedule it. If FORCE is nil, then the
10380 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10383 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10384 (unless js2-mode-parsing
10385 (setq js2-mode-parsing t)
10387 (when (or js2-mode-buffer-dirty-p force)
10388 (js2-remove-overlays)
10389 (with-silent-modifications
10390 (setq js2-mode-buffer-dirty-p nil
10391 js2-mode-fontifications nil
10392 js2-mode-deferred-properties nil)
10393 (if js2-mode-verbose-parse-p
10394 (message "parsing..."))
10397 (setq interrupted-p
10398 (catch 'interrupted
10399 (setq js2-mode-ast (js2-parse))
10400 ;; if parsing is interrupted, comments and regex
10401 ;; literals stay ignored by `parse-partial-sexp'
10402 (remove-text-properties (point-min) (point-max)
10404 (js2-mode-apply-deferred-properties)
10405 (js2-mode-remove-suppressed-warnings)
10406 (js2-mode-show-warnings)
10407 (js2-mode-show-errors)
10408 (if (>= js2-highlight-level 1)
10409 (js2-highlight-jsdoc js2-mode-ast))
10413 ;; unfinished parse => try again
10414 (setq js2-mode-buffer-dirty-p t)
10415 (js2-mode-reset-timer))
10416 (if js2-mode-verbose-parse-p
10417 (message "Parse time: %s" time)))))
10418 (setq js2-mode-parsing nil)
10419 (unless interrupted-p
10420 (setq js2-mode-parse-timer nil))))))
10422 (defun js2-mode-show-node ()
10423 "Debugging aid: highlight selected AST node on mouse click."
10425 (let ((node (js2-node-at-point))
10427 (when js2-mode-show-overlay
10429 (message "No node found at location %s" (point))
10430 (setq beg (js2-node-abs-pos node)
10431 end (+ beg (js2-node-len node)))
10432 (if js2-mode-node-overlay
10433 (move-overlay js2-mode-node-overlay beg end)
10434 (setq js2-mode-node-overlay (make-overlay beg end))
10435 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10436 (with-silent-modifications
10437 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10438 (message "%s, parent: %s"
10439 (js2-node-short-name node)
10440 (if (js2-node-parent node)
10441 (js2-node-short-name (js2-node-parent node))
10444 (defun js2-mode-hide-overlay (&optional p1 p2)
10445 "Remove the debugging overlay when the point moves.
10446 P1 and P2 are the old and new values of point, respectively."
10447 (when js2-mode-node-overlay
10448 (let ((beg (overlay-start js2-mode-node-overlay))
10449 (end (overlay-end js2-mode-node-overlay)))
10450 ;; Sometimes we're called spuriously.
10454 (with-silent-modifications
10455 (remove-text-properties beg end '(point-left nil)))
10456 (delete-overlay js2-mode-node-overlay)
10457 (setq js2-mode-node-overlay nil)))))
10459 (defun js2-mode-reset ()
10460 "Debugging helper: reset everything."
10465 (defun js2-mode-show-warn-or-err (e face)
10466 "Highlight a warning or error E with FACE.
10467 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10468 (let* ((key (first e))
10470 (end (+ beg (third e)))
10471 ;; Don't inadvertently go out of bounds.
10472 (beg (max (point-min) (min beg (point-max))))
10473 (end (max (point-min) (min end (point-max))))
10474 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10475 (ovl (make-overlay beg end)))
10476 (overlay-put ovl 'font-lock-face face)
10477 (overlay-put ovl 'js2-error t)
10478 (put-text-property beg end 'help-echo (js2-get-msg key))
10479 (put-text-property beg end 'point-entered #'js2-echo-error)))
10481 (defun js2-remove-overlays ()
10482 "Remove overlays from buffer that have a `js2-error' property."
10483 (let ((beg (point-min))
10486 (dolist (o (overlays-in beg end))
10487 (when (overlay-get o 'js2-error)
10488 (delete-overlay o))))))
10490 (defun js2-error-at-point (&optional pos)
10491 "Return non-nil if there's an error overlay at POS.
10492 Defaults to point."
10493 (loop with pos = (or pos (point))
10494 for o in (overlays-at pos)
10495 thereis (overlay-get o 'js2-error)))
10497 (defun js2-mode-apply-deferred-properties ()
10498 "Apply fontifications and other text properties recorded during parsing."
10499 (when (plusp js2-highlight-level)
10500 ;; We defer clearing faces as long as possible to eliminate flashing.
10501 (js2-clear-face (point-min) (point-max))
10502 ;; Have to reverse the recorded fontifications list so that errors
10503 ;; and warnings overwrite the normal fontifications.
10504 (dolist (f (nreverse js2-mode-fontifications))
10505 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10506 (setq js2-mode-fontifications nil))
10507 (dolist (p js2-mode-deferred-properties)
10508 (apply #'put-text-property p))
10509 (setq js2-mode-deferred-properties nil))
10511 (defun js2-mode-show-errors ()
10512 "Highlight syntax errors."
10513 (when js2-mode-show-parse-errors
10514 (dolist (e (js2-ast-root-errors js2-mode-ast))
10515 (js2-mode-show-warn-or-err e 'js2-error))))
10517 (defun js2-mode-remove-suppressed-warnings ()
10518 "Take suppressed warnings out of the AST warnings list.
10519 This ensures that the counts and `next-error' are correct."
10520 (setf (js2-ast-root-warnings js2-mode-ast)
10523 (let ((key (caar e)))
10525 (and (not js2-strict-trailing-comma-warning)
10526 (string-match "trailing\\.comma" key))
10527 (and (not js2-strict-cond-assign-warning)
10528 (string= key "msg.equal.as.assign"))
10529 (and js2-missing-semi-one-line-override
10530 (string= key "msg.missing.semi")
10531 (let* ((beg (second e))
10532 (node (js2-node-at-point beg))
10533 (fn (js2-mode-find-parent-fn node))
10534 (body (and fn (js2-function-node-body fn)))
10535 (lc (and body (js2-node-abs-pos body)))
10536 (rc (and lc (+ lc (js2-node-len body)))))
10541 (and (js2-same-line lc)
10542 (js2-same-line rc))))))))))
10543 (js2-ast-root-warnings js2-mode-ast))))
10545 (defun js2-mode-show-warnings ()
10546 "Highlight strict-mode warnings."
10547 (when js2-mode-show-strict-warnings
10548 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10549 (js2-mode-show-warn-or-err e 'js2-warning))))
10551 (defun js2-echo-error (old-point new-point)
10552 "Called by point-motion hooks."
10553 (let ((msg (get-text-property new-point 'help-echo)))
10554 (when (and (stringp msg) (or (not (current-message))
10555 (string= (current-message) "Quit")))
10558 (defalias #'js2-echo-help #'js2-echo-error)
10560 (defun js2-line-break (&optional soft)
10561 "Break line at point."
10562 (let ((parse-status (syntax-ppss)))
10564 ;; Check if we're inside a string.
10565 ((nth 3 parse-status)
10566 (if js2-concat-multiline-strings
10567 (js2-mode-split-string parse-status)
10569 ;; Check if inside a block comment.
10570 ((nth 4 parse-status)
10571 (js2-mode-extend-comment))
10575 (defun js2-mode-split-string (parse-status)
10576 "Turn a newline in mid-string into a string concatenation.
10577 PARSE-STATUS is as documented in `parse-partial-sexp'."
10578 (let* ((col (current-column))
10579 (quote-char (nth 3 parse-status))
10580 (quote-string (string quote-char))
10581 (string-beg (nth 8 parse-status))
10582 (at-eol (eq js2-concat-multiline-strings 'eol))
10585 (back-to-indentation)
10586 (if (looking-at "\\+")
10589 (goto-char string-beg)
10590 (if (looking-back "\\+\\s-+")
10591 (goto-char (match-beginning 0)))
10592 (current-column)))))
10593 (insert quote-char)
10597 ;; FIXME: This does not match the behavior of `js2-indent-line'.
10601 (insert quote-string)
10603 (insert quote-string)
10604 (backward-char 1))))
10606 (defun js2-mode-extend-comment ()
10607 "Indent the line and, when inside a comment block, add comment prefix."
10608 (let (star single col first-line needs-close)
10610 (back-to-indentation)
10612 ((looking-at "\\*[^/]")
10614 col (current-column)))
10615 ((looking-at "/\\*")
10618 col (1+ (current-column))))
10621 col (current-column)))))
10622 ;; Heuristic for whether we need to close the comment:
10623 ;; if we've got a parse error here, assume it's an unterminated
10627 (eq (get-text-property (1- (point)) 'point-entered)
10629 ;; The heuristic above doesn't work well when we're
10630 ;; creating a comment and there's another one downstream,
10631 ;; as our parser thinks this one ends at the end of the
10632 ;; next one. (You can have a /* inside a js block comment.)
10633 ;; So just close it if the next non-ws char isn't a *.
10637 (skip-chars-forward " \t\r\n")
10638 (not (eq (char-after) ?*))))))
10644 (if (and first-line needs-close)
10651 (and (zerop (forward-line 1))
10652 (looking-at "\\s-*//"))))
10655 ;; don't need to extend the comment after all
10656 (js2-enter-indents-newline
10657 (js2-indent-line)))))
10659 (defun js2-beginning-of-line ()
10660 "Toggles point between bol and first non-whitespace char in line.
10661 Also moves past comment delimiters when inside comments."
10666 (back-to-indentation))
10668 (skip-chars-forward "/ \t"))
10669 ((and (eq (char-after) ?*)
10670 (setq node (js2-comment-at-point))
10671 (memq (js2-comment-node-format node) '(jsdoc block))
10673 (skip-chars-backward " \t")
10675 (skip-chars-forward "\* \t"))
10677 (goto-char (point-at-bol))))))
10679 (defun js2-end-of-line ()
10680 "Toggles point between eol and last non-whitespace char in line."
10683 (skip-chars-backward " \t")
10684 (goto-char (point-at-eol))))
10686 (defsubst js2-mode-inside-string ()
10687 "Return non-nil if inside a string.
10688 Actually returns the quote character that begins the string."
10689 (nth 3 (syntax-ppss)))
10691 (defun js2-mode-inside-comment-or-string ()
10692 "Return non-nil if inside a comment or string."
10694 (let ((comment-start
10696 (goto-char (point-at-bol))
10697 (if (re-search-forward "//" (point-at-eol) t)
10698 (match-beginning 0)))))
10700 (<= comment-start (point))))
10701 (let ((parse-state (syntax-ppss)))
10702 (or (nth 3 parse-state)
10703 (nth 4 parse-state)))))
10706 (defun js2-insert-catch-skel (try-pos)
10707 "Complete a try/catch block after inserting a { following a try keyword.
10708 Rationale is that a try always needs a catch or a finally, and the catch is
10709 the more likely of the two.
10711 TRY-POS is the buffer position of the try keyword. The open-curly should
10712 already have been inserted."
10714 (let ((try-col (save-excursion
10715 (goto-char try-pos)
10716 (current-column))))
10719 (js2-indent-line) ;; indent the blank line where cursor will end up
10722 (indent-to try-col)
10723 (insert "} catch (x) {\n\n")
10724 (indent-to try-col)
10728 (defun js2-mode-wait-for-parse (callback)
10729 "Invoke CALLBACK when parsing is finished.
10730 If parsing is already finished, calls CALLBACK immediately."
10731 (if (not js2-mode-buffer-dirty-p)
10733 (push callback js2-mode-pending-parse-callbacks)
10734 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10736 (defun js2-mode-parse-finished ()
10737 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10738 ;; We can't let errors propagate up, since it prevents the
10739 ;; `js2-parse' method from completing normally and returning
10740 ;; the ast, which makes things mysteriously not work right.
10742 (dolist (cb js2-mode-pending-parse-callbacks)
10743 (condition-case err
10745 (error (message "%s" err))))
10746 (setq js2-mode-pending-parse-callbacks nil)))
10748 (defun js2-mode-flag-region (from to flag)
10749 "Hide or show text from FROM to TO, according to FLAG.
10750 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10751 Returns the created overlay if FLAG is non-nil."
10752 (remove-overlays from to 'invisible 'js2-outline)
10754 (let ((o (make-overlay from to)))
10755 (overlay-put o 'invisible 'js2-outline)
10756 (overlay-put o 'isearch-open-invisible
10757 'js2-isearch-open-invisible)
10760 ;; Function to be set as an outline-isearch-open-invisible' property
10761 ;; to the overlay that makes the outline invisible (see
10762 ;; `js2-mode-flag-region').
10763 (defun js2-isearch-open-invisible (overlay)
10764 ;; We rely on the fact that isearch places point on the matched text.
10765 (js2-mode-show-element))
10767 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10768 "Return cons cell of bounds of folding overlay at POS.
10769 Returns nil if not found."
10770 (let ((overlays (overlays-at (or pos (point))))
10772 (while (and overlays
10774 (if (overlay-get (car overlays) 'invisible)
10775 (setq o (car overlays))
10776 (setq overlays (cdr overlays))))
10778 (cons (overlay-start o) (overlay-end o)))))
10780 (defun js2-mode-function-at-point (&optional pos)
10781 "Return the innermost function node enclosing current point.
10782 Returns nil if point is not in a function."
10783 (let ((node (js2-node-at-point pos)))
10784 (while (and node (not (js2-function-node-p node)))
10785 (setq node (js2-node-parent node)))
10786 (if (js2-function-node-p node)
10789 (defun js2-mode-toggle-element ()
10790 "Hide or show the foldable element at the point."
10792 (let (comment fn pos)
10795 ;; /* ... */ comment?
10796 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10797 (if (js2-mode-invisible-overlay-bounds
10798 (setq pos (+ 3 (js2-node-abs-pos comment))))
10801 (js2-mode-show-element))
10802 (js2-mode-hide-element)))
10805 (back-to-indentation)
10806 (looking-at js2-mode-//-comment-re))
10807 (js2-mode-toggle-//-comment))
10809 ((setq fn (js2-mode-function-at-point))
10810 (setq pos (and (js2-function-node-body fn)
10811 (js2-node-abs-pos (js2-function-node-body fn))))
10812 (goto-char (1+ pos))
10813 (if (js2-mode-invisible-overlay-bounds)
10814 (js2-mode-show-element)
10815 (js2-mode-hide-element)))
10817 (message "Nothing at point to hide or show"))))))
10819 (defun js2-mode-hide-element ()
10820 "Fold/hide contents of a block, showing ellipses.
10821 Show the hidden text with \\[js2-mode-show-element]."
10823 (if js2-mode-buffer-dirty-p
10824 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10825 (let (node body beg end)
10827 ((js2-mode-invisible-overlay-bounds)
10828 (message "already hidden"))
10830 (setq node (js2-node-at-point))
10832 ((js2-block-comment-p node)
10833 (js2-mode-hide-comment node))
10835 (while (and node (not (js2-function-node-p node)))
10836 (setq node (js2-node-parent node)))
10838 (setq body (js2-function-node-body node)))
10840 (setq beg (js2-node-abs-pos body)
10841 end (+ beg (js2-node-len body)))
10842 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10843 (message "No collapsable element found at point"))))))))
10845 (defun js2-mode-show-element ()
10846 "Show the hidden element at current point."
10848 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10850 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10851 (message "Nothing to un-hide"))))
10853 (defun js2-mode-show-all ()
10854 "Show all of the text in the buffer."
10856 (js2-mode-flag-region (point-min) (point-max) nil))
10858 (defun js2-mode-toggle-hide-functions ()
10860 (if js2-mode-functions-hidden
10861 (js2-mode-show-functions)
10862 (js2-mode-hide-functions)))
10864 (defun js2-mode-hide-functions ()
10865 "Hides all non-nested function bodies in the buffer.
10866 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10867 to open an individual entry."
10869 (if js2-mode-buffer-dirty-p
10870 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10871 (if (null js2-mode-ast)
10872 (message "Oops - parsing failed")
10873 (setq js2-mode-functions-hidden t)
10874 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10876 (defun js2-mode-function-hider (n endp)
10878 (let ((tt (js2-node-type n))
10881 ((and (= tt js2-FUNCTION)
10882 (setq body (js2-function-node-body n)))
10883 (setq beg (js2-node-abs-pos body)
10884 end (+ beg (js2-node-len body)))
10885 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10886 nil) ; don't process children of function
10888 t))))) ; keep processing other AST nodes
10890 (defun js2-mode-show-functions ()
10891 "Un-hide any folded function bodies in the buffer."
10893 (setq js2-mode-functions-hidden nil)
10895 (goto-char (point-min))
10896 (while (/= (goto-char (next-overlay-change (point)))
10898 (dolist (o (overlays-at (point)))
10899 (when (and (overlay-get o 'invisible)
10900 (not (overlay-get o 'comment)))
10901 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10903 (defun js2-mode-hide-comment (n)
10904 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10907 (beg (+ (js2-node-abs-pos n) head))
10908 (end (- (+ beg (js2-node-len n)) head 2))
10909 (o (js2-mode-flag-region beg end 'hide)))
10910 (overlay-put o 'comment t)))
10912 (defun js2-mode-toggle-hide-comments ()
10913 "Folds all block comments in the buffer.
10914 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10915 to open an individual entry."
10917 (if js2-mode-comments-hidden
10918 (js2-mode-show-comments)
10919 (js2-mode-hide-comments)))
10921 (defun js2-mode-hide-comments ()
10923 (if js2-mode-buffer-dirty-p
10924 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10925 (if (null js2-mode-ast)
10926 (message "Oops - parsing failed")
10927 (setq js2-mode-comments-hidden t)
10928 (dolist (n (js2-ast-root-comments js2-mode-ast))
10929 (let ((format (js2-comment-node-format n)))
10930 (when (js2-block-comment-p n)
10931 (js2-mode-hide-comment n))))
10932 (js2-mode-hide-//-comments)))
10934 (defun js2-mode-extend-//-comment (direction)
10935 "Find start or end of a block of similar //-comment lines.
10936 DIRECTION is -1 to look back, 1 to look forward.
10937 INDENT is the indentation level to match.
10938 Returns the end-of-line position of the furthest adjacent
10939 //-comment line with the same indentation as the current line.
10940 If there is no such matching line, returns current end of line."
10941 (let ((pos (point-at-eol))
10942 (indent (current-indentation)))
10944 (while (and (zerop (forward-line direction))
10945 (looking-at js2-mode-//-comment-re)
10946 (eq indent (length (match-string 1))))
10947 (setq pos (point-at-eol))
10950 (defun js2-mode-hide-//-comments ()
10951 "Fold adjacent 1-line comments, showing only snippet of first one."
10954 (goto-char (point-min))
10955 (while (re-search-forward js2-mode-//-comment-re nil t)
10957 end (js2-mode-extend-//-comment 1))
10958 (unless (eq beg end)
10959 (overlay-put (js2-mode-flag-region beg end 'hide)
10962 (forward-char 1)))))
10964 (defun js2-mode-toggle-//-comment ()
10965 "Fold or un-fold any multi-line //-comment at point.
10966 Caller should have determined that this line starts with a //-comment."
10967 (let* ((beg (point-at-eol))
10971 (if (js2-mode-invisible-overlay-bounds)
10972 (js2-mode-show-element)
10973 ;; else hide the comment
10974 (setq beg (js2-mode-extend-//-comment -1)
10975 end (js2-mode-extend-//-comment 1))
10976 (unless (eq beg end)
10977 (overlay-put (js2-mode-flag-region beg end 'hide)
10980 (defun js2-mode-show-comments ()
10981 "Un-hide any hidden comments, leaving other hidden elements alone."
10983 (setq js2-mode-comments-hidden nil)
10985 (goto-char (point-min))
10986 (while (/= (goto-char (next-overlay-change (point)))
10988 (dolist (o (overlays-at (point)))
10989 (when (overlay-get o 'comment)
10990 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10992 (defun js2-mode-display-warnings-and-errors ()
10993 "Turn on display of warnings and errors."
10995 (setq js2-mode-show-parse-errors t
10996 js2-mode-show-strict-warnings t)
10997 (js2-reparse 'force))
10999 (defun js2-mode-hide-warnings-and-errors ()
11000 "Turn off display of warnings and errors."
11002 (setq js2-mode-show-parse-errors nil
11003 js2-mode-show-strict-warnings nil)
11004 (js2-reparse 'force))
11006 (defun js2-mode-toggle-warnings-and-errors ()
11007 "Toggle the display of warnings and errors.
11008 Some users don't like having warnings/errors reported while they type."
11010 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11011 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11012 (if (called-interactively-p 'any)
11013 (message "warnings and errors %s"
11014 (if js2-mode-show-parse-errors
11017 (js2-reparse 'force))
11019 (defun js2-mode-customize ()
11021 (customize-group 'js2-mode))
11023 (defun js2-mode-forward-sexp (&optional arg)
11024 "Move forward across one statement or balanced expression.
11025 With ARG, do it that many times. Negative arg -N means
11026 move backward across N balanced expressions."
11028 (setq arg (or arg 1))
11029 (let (node end (start (point)))
11032 ;; could probably make this better for some cases:
11033 ;; - if in statement block (e.g. function body), go to parent
11034 ;; - infix exprs like (foo in bar) - maybe go to beginning
11035 ;; of infix expr if in the right-side expression?
11036 ((and arg (minusp arg))
11037 (dotimes (i (- arg))
11039 (forward-char -1) ; enter the node we backed up to
11040 (setq node (js2-node-at-point (point) t))
11041 (goto-char (if node
11042 (js2-node-abs-pos node)
11049 (setq node (js2-node-at-point (point) t)
11050 end (if node (+ (js2-node-abs-pos node)
11051 (js2-node-len node))))
11052 (goto-char (or end (point-max))))))))
11054 (defun js2-errors ()
11055 "Return a list of errors found."
11057 (js2-ast-root-errors js2-mode-ast)))
11059 (defun js2-warnings ()
11060 "Return a list of warnings found."
11062 (js2-ast-root-warnings js2-mode-ast)))
11064 (defun js2-have-errors-p ()
11065 "Return non-nil if any parse errors or warnings were found."
11066 (or (js2-errors) (js2-warnings)))
11068 (defun js2-errors-and-warnings ()
11069 "Return a copy of the concatenated errors and warnings lists.
11070 They are appended: first the errors, then the warnings.
11071 Entries are of the form (MSG BEG END)."
11073 (append (js2-ast-root-errors js2-mode-ast)
11074 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11076 (defun js2-next-error (&optional arg reset)
11077 "Move to next parse error.
11078 Typically invoked via \\[next-error].
11079 ARG is the number of errors, forward or backward, to move.
11080 RESET means start over from the beginning."
11082 (if (not (or (js2-errors) (js2-warnings)))
11083 (message "No errors")
11085 (goto-char (point-min)))
11086 (let* ((errs (js2-errors-and-warnings))
11090 (backward (minusp count))
11091 (sorter (if backward '> '<))
11092 (stopper (if backward '< '>))
11093 (count (abs count))
11095 ;; Sort by start position.
11096 (setq errs (sort errs (lambda (e1 e2)
11097 (funcall sorter (second e1) (second e2))))
11099 ;; Find nth error with pos > start.
11100 (while (and errs continue)
11101 (when (funcall stopper (cadar errs) start)
11102 (setq err (car errs))
11103 (if (zerop (decf count))
11104 (setq continue nil)))
11105 (setq errs (cdr errs)))
11107 (goto-char (second err))
11108 ;; Wrap around to first error.
11109 (goto-char (second (car all-errs)))
11110 ;; If we were already on it, echo msg again.
11111 (if (= (point) start)
11112 (js2-echo-error (point) (point)))))))
11114 (defun js2-down-mouse-3 ()
11115 "Make right-click move the point to the click location.
11116 This makes right-click context menu operations a bit more intuitive.
11117 The point will not move if the region is active, however, to avoid
11118 destroying the region selection."
11120 (when (and js2-move-point-on-right-click
11122 (let ((e last-input-event))
11124 (goto-char (cadadr e))))))
11126 (defun js2-mode-create-imenu-index ()
11127 "Return an alist for `imenu--index-alist'."
11128 ;; This is built up in `js2-parse-record-imenu' during parsing.
11130 ;; if we have an ast but no recorder, they're requesting a rescan
11131 (unless js2-imenu-recorder
11132 (js2-reparse 'force))
11134 (js2-build-imenu-index)
11135 (setq js2-imenu-recorder nil
11136 js2-imenu-function-map nil))))
11138 (defun js2-mode-find-tag ()
11139 "Replacement for `find-tag-default'.
11140 `find-tag-default' returns a ridiculous answer inside comments."
11142 (js2-with-underscore-as-word-syntax
11144 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11145 (looking-back "[A-Za-z0-9_$]"))
11146 (setq beg (progn (forward-word -1) (point))
11147 end (progn (forward-word 1) (point)))
11148 (setq beg (progn (forward-word 1) (point))
11149 end (progn (forward-word -1) (point))))
11150 (replace-regexp-in-string
11152 (buffer-substring-no-properties beg end))))))
11154 (defun js2-mode-forward-sibling ()
11155 "Move to the end of the sibling following point in parent.
11156 Returns non-nil if successful, or nil if there was no following sibling."
11157 (let* ((node (js2-node-at-point))
11158 (parent (js2-mode-find-enclosing-fn node))
11160 (when (setq sib (js2-node-find-child-after (point) parent))
11161 (goto-char (+ (js2-node-abs-pos sib)
11162 (js2-node-len sib))))))
11164 (defun js2-mode-backward-sibling ()
11165 "Move to the beginning of the sibling node preceding point in parent.
11166 Parent is defined as the enclosing script or function."
11167 (let* ((node (js2-node-at-point))
11168 (parent (js2-mode-find-enclosing-fn node))
11170 (when (setq sib (js2-node-find-child-before (point) parent))
11171 (goto-char (js2-node-abs-pos sib)))))
11173 (defun js2-beginning-of-defun (&optional arg)
11174 "Go to line on which current function starts, and return t on success.
11175 If we're not in a function or already at the beginning of one, go
11176 to beginning of previous script-level element.
11177 With ARG N, do that N times. If N is negative, move forward."
11178 (setq arg (or arg 1))
11180 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11182 ((js2-function-node-p parent)
11183 (goto-char (js2-node-abs-pos parent)))
11185 (js2-mode-backward-sibling)))
11187 (js2-beginning-of-defun (1- arg))
11189 (when (js2-end-of-defun)
11191 (js2-beginning-of-defun 1)
11192 (js2-beginning-of-defun (1+ arg))))))
11194 (defun js2-end-of-defun ()
11195 "Go to the char after the last position of the current function
11196 or script-level element."
11197 (let* ((node (js2-node-at-point))
11198 (parent (or (and (js2-function-node-p node) node)
11199 (js2-node-parent-script-or-fn node)))
11201 (unless (js2-function-node-p parent)
11202 ;; Use current script-level node, or, if none, the next one.
11203 (setq script (or parent node)
11204 parent (js2-node-find-child-before (point) script))
11205 (when (or (null parent)
11206 (>= (point) (+ (js2-node-abs-pos parent)
11207 (js2-node-len parent))))
11208 (setq parent (js2-node-find-child-after (point) script))))
11210 (goto-char (+ (js2-node-abs-pos parent)
11211 (js2-node-len parent))))))
11213 (defun js2-mark-defun (&optional allow-extend)
11214 "Put mark at end of this function, point at beginning.
11215 The function marked is the one that contains point.
11217 Interactively, if this command is repeated,
11218 or (in Transient Mark mode) if the mark is active,
11219 it marks the next defun after the ones already marked."
11222 (when (and allow-extend
11223 (or (and (eq last-command this-command) (mark t))
11224 (and transient-mark-mode mark-active)))
11225 (let ((sib (save-excursion
11227 (if (js2-mode-forward-sibling)
11234 ;; no more siblings - try extending to enclosing node
11235 (goto-char (mark t)))))
11236 (when (not extended)
11237 (let ((node (js2-node-at-point (point) t)) ; skip comments
11238 ast fn stmt parent beg end)
11239 (when (js2-ast-root-p node)
11241 node (or (js2-node-find-child-after (point) node)
11242 (js2-node-find-child-before (point) node))))
11243 ;; only mark whole buffer if we can't find any children
11246 (if (js2-function-node-p node)
11248 (setq fn (js2-mode-find-enclosing-fn node)
11249 stmt (if (or (null fn)
11250 (js2-ast-root-p fn))
11251 (js2-mode-find-first-stmt node))
11252 parent (or stmt fn)))
11253 (setq beg (js2-node-abs-pos parent)
11254 end (+ beg (js2-node-len parent)))
11257 (exchange-point-and-mark)))))
11259 (defun js2-narrow-to-defun ()
11260 "Narrow to the function enclosing point."
11262 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11263 (fn (if (js2-script-node-p node)
11265 (js2-mode-find-enclosing-fn node)))
11266 (beg (js2-node-abs-pos fn)))
11267 (unless (js2-ast-root-p fn)
11268 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11270 (provide 'js2-mode)
11272 ;;; js2-mode.el ends here