1 ;;; js2-mode.el --- Improved JavaScript editing mode
3 ;; Copyright (C) 2009, 2011-2013 Free Software Foundation, Inc.
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; URL: https://github.com/mooz/js2-mode/
9 ;; http://code.google.com/p/js2-mode/
11 ;; Keywords: languages, javascript
12 ;; Package-Requires: ((emacs "24.1"))
14 ;; This file is part of GNU Emacs.
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
31 ;; This JavaScript editing mode supports:
33 ;; - strict recognition of the Ecma-262 language standard
34 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
35 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
36 ;; - accurate syntax highlighting using a recursive-descent parser
37 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
38 ;; - undeclared-variable warnings using a configurable externs framework
39 ;; - "bouncing" line indentation to choose among alternate indentation points
40 ;; - smart line-wrapping within comments and strings
42 ;; - show some or all function bodies as {...}
43 ;; - show some or all block comments as /*...*/
44 ;; - context-sensitive menu bar and popup menus
45 ;; - code browsing using the `imenu' package
46 ;; - many customization options
50 ;; To install it as your major mode for JavaScript editing:
52 ;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
54 ;; Alternately, to install it as a minor mode just for JavaScript linting,
55 ;; you must add it to the appropriate major-mode hook. Normally this would be:
57 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
59 ;; To customize how it works:
60 ;; M-x customize-group RET js2-mode RET
64 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
65 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
66 ;; `js2-mode' current as the EcmaScript language standard evolves.
68 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
69 ;; customizable. It is a surprising amount of work to support customizable
70 ;; indentation. The current compromise is that the tab key lets you cycle among
71 ;; various likely indentation points, similar to the behavior of python-mode.
73 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
74 ;; and `mumamo', although it could be made to do so with some effort.
75 ;; This means that `js2-mode' is currently only useful for editing JavaScript
76 ;; files, and not for editing JavaScript within <script> tags or templates.
78 ;; The project page on GitHub is used for development and issue tracking.
79 ;; The original homepage at Google Code is mentioned here for posterity, it has
80 ;; outdated information and is mostly unmaintained.
88 (require 'cc-cmds) ; for `c-fill-paragraph'
91 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
92 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
94 (defvar electric-layout-rules)
96 ;;; Externs (variables presumed to be defined by the host system)
98 (defvar js2-ecma-262-externs
100 '(Array Boolean Date Error EvalError Function Infinity JSON
101 Math NaN Number Object RangeError ReferenceError RegExp
102 String SyntaxError TypeError URIError arguments
103 decodeURI decodeURIComponent encodeURI
104 encodeURIComponent escape eval isFinite isNaN
105 parseFloat parseInt undefined unescape))
106 "Ecma-262 externs. Included in `js2-externs' by default.")
108 (defvar js2-browser-externs
111 Attr CDATASection CharacterData Comment DOMException
112 DOMImplementation Document DocumentFragment
113 DocumentType Element Entity EntityReference
114 ExceptionCode NamedNodeMap Node NodeList Notation
115 ProcessingInstruction Text
118 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
119 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
120 HTMLBodyElement HTMLButtonElement HTMLCollection
121 HTMLDListElement HTMLDirectoryElement HTMLDivElement
122 HTMLDocument HTMLElement HTMLFieldSetElement
123 HTMLFontElement HTMLFormElement HTMLFrameElement
124 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
125 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
126 HTMLImageElement HTMLInputElement HTMLIsIndexElement
127 HTMLLIElement HTMLLabelElement HTMLLegendElement
128 HTMLLinkElement HTMLMapElement HTMLMenuElement
129 HTMLMetaElement HTMLModElement HTMLOListElement
130 HTMLObjectElement HTMLOptGroupElement
131 HTMLOptionElement HTMLOptionsCollection
132 HTMLParagraphElement HTMLParamElement HTMLPreElement
133 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
134 HTMLStyleElement HTMLTableCaptionElement
135 HTMLTableCellElement HTMLTableColElement
136 HTMLTableElement HTMLTableRowElement
137 HTMLTableSectionElement HTMLTextAreaElement
138 HTMLTitleElement HTMLUListElement
141 DOMConfiguration DOMError DOMException
142 DOMImplementationList DOMImplementationSource
143 DOMLocator DOMStringList NameList TypeInfo
147 window alert confirm document java navigator prompt screen
151 CSSCharsetRule CSSFontFace CSSFontFaceRule
152 CSSImportRule CSSMediaRule CSSPageRule
153 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
154 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
155 CSSValue CSSValueList Counter DOMImplementationCSS
156 DocumentCSS DocumentStyle ElementCSSInlineStyle
157 LinkStyle MediaList RGBColor Rect StyleSheet
158 StyleSheetList ViewCSS
161 EventListener EventTarget Event DocumentEvent UIEvent
162 MouseEvent MutationEvent KeyboardEvent
165 DocumentRange Range RangeException
168 XPathResult XMLHttpRequest
170 ;; Khronos Typed Array Specification
171 ArrayBuffer ArrayBufferView TypedArray Uint8ClampedArray DataView
172 Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
173 Float32Array Float64Array
175 ;; console object. Provided by at least Chrome and Firefox.
178 You can cause these to be included or excluded with the custom
179 variable `js2-include-browser-externs'.")
181 (defvar js2-rhino-externs
183 '(Packages importClass importPackage com org java
184 ;; Global object (shell) externs.
185 defineClass deserialize doctest gc help load
186 loadClass print quit readFile readUrl runCommand seal
187 serialize spawn sync toint32 version))
188 "Mozilla Rhino externs.
189 Set `js2-include-rhino-externs' to t to include them.")
191 (defvar js2-node-externs
193 '(__dirname __filename Buffer clearInterval clearTimeout require
194 console exports global module process setInterval setTimeout))
196 Set `js2-include-node-externs' to t to include them.")
200 (defun js2-mark-safe-local (name pred)
201 "Make the variable NAME buffer-local and mark it as safe file-local
202 variable with predicate PRED."
203 (make-variable-buffer-local name)
204 (put name 'safe-local-variable pred))
206 (defcustom js2-highlight-level 2
207 "Amount of syntax highlighting to perform.
208 0 or a negative value means none.
209 1 adds basic syntax highlighting.
210 2 adds highlighting of some Ecma built-in properties.
211 3 adds highlighting of many Ecma built-in functions."
213 :type '(choice (const :tag "None" 0)
214 (const :tag "Basic" 1)
215 (const :tag "Include Properties" 2)
216 (const :tag "Include Functions" 3)))
218 (defvar js2-mode-dev-mode-p nil
219 "Non-nil if running in development mode. Normally nil.")
221 (defgroup js2-mode nil
222 "An improved JavaScript mode."
225 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
226 (numberp c-basic-offset))
229 "Number of spaces to indent nested statements.
230 Similar to `c-basic-offset'."
233 (js2-mark-safe-local 'js2-basic-offset 'integerp)
235 (defcustom js2-bounce-indent-p nil
236 "Non-nil to have indent-line function choose among alternatives.
237 If nil, the indent-line function will indent to a predetermined column
238 based on heuristic guessing. If non-nil, then if the current line is
239 already indented to that predetermined column, indenting will choose
240 another likely column and indent to that spot. Repeated invocation of
241 the indent-line function will cycle among the computed alternatives.
242 See the function `js2-bounce-indent' for details. When it is non-nil,
243 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
247 (defcustom js2-pretty-multiline-declarations t
248 "Non-nil to line up multiline declarations vertically:
254 If the value is not `all', and the first assigned value in
255 declaration is a function/array/object literal spanning several
256 lines, it won't be indented additionally:
258 var o = { var bar = 2,
264 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
266 (defcustom js2-idle-timer-delay 0.2
267 "Delay in secs before re-parsing after user makes changes.
268 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
271 (make-variable-buffer-local 'js2-idle-timer-delay)
273 (defcustom js2-dynamic-idle-timer-adjust 0
274 "Positive to adjust `js2-idle-timer-delay' based on file size.
275 The idea is that for short files, parsing is faster so we can be
276 more responsive to user edits without interfering with editing.
277 The buffer length in characters (typically bytes) is divided by
278 this value and used to multiply `js2-idle-timer-delay' for the
279 buffer. For example, a 21k file and 10k adjust yields 21k/10k
280 == 2, so js2-idle-timer-delay is multiplied by 2.
281 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
282 `js2-idle-timer-delay' is not dependent on the file size."
286 (defcustom js2-concat-multiline-strings t
287 "Non-nil to automatically turn a newline in mid-string into a
288 string concatenation. When `eol', the '+' will be inserted at the
289 end of the line, otherwise, at the beginning of the next line."
290 :type '(choice (const t) (const eol) (const nil))
293 (defcustom js2-mode-show-parse-errors t
294 "True to highlight parse errors."
298 (defcustom js2-mode-show-strict-warnings t
299 "Non-nil to emit Ecma strict-mode warnings.
300 Some of the warnings can be individually disabled by other flags,
301 even if this flag is non-nil."
305 (defcustom js2-strict-trailing-comma-warning t
306 "Non-nil to warn about trailing commas in array literals.
307 Ecma-262-5.1 allows them, but older versions of IE raise an error."
311 (defcustom js2-strict-missing-semi-warning t
312 "Non-nil to warn about semicolon auto-insertion after statement.
313 Technically this is legal per Ecma-262, but some style guides disallow
318 (defcustom js2-missing-semi-one-line-override nil
319 "Non-nil to permit missing semicolons in one-line functions.
320 In one-liner functions such as `function identity(x) {return x}'
321 people often omit the semicolon for a cleaner look. If you are
322 such a person, you can suppress the missing-semicolon warning
323 by setting this variable to t."
327 (defcustom js2-strict-inconsistent-return-warning t
328 "Non-nil to warn about mixing returns with value-returns.
329 It's perfectly legal to have a `return' and a `return foo' in the
330 same function, but it's often an indicator of a bug, and it also
331 interferes with type inference (in systems that support it.)"
335 (defcustom js2-strict-cond-assign-warning t
336 "Non-nil to warn about expressions like if (a = b).
337 This often should have been '==' instead of '='. If the warning
338 is enabled, you can suppress it on a per-expression basis by
339 parenthesizing the expression, e.g. if ((a = b)) ..."
343 (defcustom js2-strict-var-redeclaration-warning t
344 "Non-nil to warn about redeclaring variables in a script or function."
348 (defcustom js2-strict-var-hides-function-arg-warning t
349 "Non-nil to warn about a var decl hiding a function argument."
353 (defcustom js2-skip-preprocessor-directives nil
354 "Non-nil to treat lines beginning with # as comments.
355 Useful for viewing Mozilla JavaScript source code."
359 (defcustom js2-language-version 200
360 "Configures what JavaScript language version to recognize.
361 Currently versions 150, 160, 170, 180 and 200 are supported,
362 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
363 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
364 yield, and Array comprehensions, and 1.8 adds function closures."
368 (defcustom js2-allow-keywords-as-property-names t
369 "If non-nil, you can use JavaScript keywords as object property names.
372 var foo = {int: 5, while: 6, continue: 7};
375 Ecma-262 5.1 allows this syntax, but some engines still don't."
379 (defcustom js2-instanceof-has-side-effects nil
380 "If non-nil, treats the instanceof operator as having side effects.
381 This is useful for xulrunner apps."
385 (defcustom js2-move-point-on-right-click t
386 "Non-nil to move insertion point when you right-click.
387 This makes right-click context menu behavior a bit more intuitive,
388 since menu operations generally apply to the point. The exception
389 is if there is a region selection, in which case the point does -not-
390 move, so cut/copy/paste can work properly.
392 Note that IntelliJ moves the point, and Eclipse leaves it alone,
393 so this behavior is customizable."
397 (defcustom js2-allow-rhino-new-expr-initializer t
398 "Non-nil to support a Rhino's experimental syntactic construct.
400 Rhino supports the ability to follow a `new' expression with an object
401 literal, which is used to set additional properties on the new object
402 after calling its constructor. Syntax:
404 new <expr> [ ( arglist ) ] [initializer]
406 Hence, this expression:
408 new Object {a: 1, b: 2}
410 results in an Object with properties a=1 and b=2. This syntax is
411 apparently not configurable in Rhino - it's currently always enabled,
412 as of Rhino version 1.7R2."
416 (defcustom js2-allow-member-expr-as-function-name nil
417 "Non-nil to support experimental Rhino syntax for function names.
419 Rhino supports an experimental syntax configured via the Rhino Context
420 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
422 function <member-expr> ( [ arg-list ] ) { <body> }
424 Where member-expr is a non-parenthesized 'member expression', which
425 is anything at the grammar level of a new-expression or lower, meaning
426 any expression that does not involve infix or unary operators.
428 When <member-expr> is not a simple identifier, then it is syntactic
429 sugar for assigning the anonymous function to the <member-expr>. Hence,
432 function a.b().c[2] (x, y) { ... }
436 a.b().c[2] = function(x, y) {...}
438 which doesn't seem particularly useful, but Rhino permits it."
444 (defmacro js2-deflocal (name value &optional comment)
445 "Define a buffer-local variable NAME with VALUE and COMMENT."
447 (defvar ,name ,value ,comment)
448 (make-variable-buffer-local ',name)))
450 ;; We record the start and end position of each token.
451 (js2-deflocal js2-token-beg 1)
452 (js2-deflocal js2-token-end -1)
454 (defvar js2-EOF_CHAR -1
455 "Represents end of stream. Distinct from js2-EOF token type.")
457 ;; I originally used symbols to represent tokens, but Rhino uses
458 ;; ints and then sets various flag bits in them, so ints it is.
459 ;; The upshot is that we need a `js2-' prefix in front of each name.
460 (defvar js2-ERROR -1)
463 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
464 (defvar js2-LEAVEWITH 3)
465 (defvar js2-RETURN 4)
469 (defvar js2-SETNAME 8)
471 (defvar js2-BITXOR 10)
472 (defvar js2-BITAND 11)
482 (defvar js2-ADD 21) ; infix plus
483 (defvar js2-SUB 22) ; infix minus
488 (defvar js2-BITNOT 27)
489 (defvar js2-POS 28) ; unary plus
490 (defvar js2-NEG 29) ; unary minus
492 (defvar js2-DELPROP 31)
493 (defvar js2-TYPEOF 32)
494 (defvar js2-GETPROP 33)
495 (defvar js2-GETPROPNOWARN 34)
496 (defvar js2-SETPROP 35)
497 (defvar js2-GETELEM 36)
498 (defvar js2-SETELEM 37)
500 (defvar js2-NAME 39) ; an identifier
501 (defvar js2-NUMBER 40)
502 (defvar js2-STRING 41)
505 (defvar js2-FALSE 44)
507 (defvar js2-SHEQ 46) ; shallow equality (===)
508 (defvar js2-SHNE 47) ; shallow inequality (!==)
509 (defvar js2-REGEXP 48)
510 (defvar js2-BINDNAME 49)
511 (defvar js2-THROW 50)
512 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
514 (defvar js2-INSTANCEOF 53)
515 (defvar js2-LOCAL_LOAD 54)
516 (defvar js2-GETVAR 55)
517 (defvar js2-SETVAR 56)
518 (defvar js2-CATCH_SCOPE 57)
519 (defvar js2-ENUM_INIT_KEYS 58)
520 (defvar js2-ENUM_INIT_VALUES 59)
521 (defvar js2-ENUM_INIT_ARRAY 60)
522 (defvar js2-ENUM_NEXT 61)
523 (defvar js2-ENUM_ID 62)
524 (defvar js2-THISFN 63)
525 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
526 (defvar js2-ARRAYLIT 65) ; array literal
527 (defvar js2-OBJECTLIT 66) ; object literal
528 (defvar js2-GET_REF 67) ; *reference
529 (defvar js2-SET_REF 68) ; *reference = something
530 (defvar js2-DEL_REF 69) ; delete reference
531 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
532 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
533 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
536 (defvar js2-DEFAULTNAMESPACE 73)
537 (defvar js2-ESCXMLATTR 74)
538 (defvar js2-ESCXMLTEXT 75)
539 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
540 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
541 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
542 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
544 (defvar js2-first-bytecode js2-ENTERWITH)
545 (defvar js2-last-bytecode js2-REF_NS_NAME)
548 (defvar js2-SEMI 81) ; semicolon
549 (defvar js2-LB 82) ; left and right brackets
551 (defvar js2-LC 84) ; left and right curly-braces
553 (defvar js2-LP 86) ; left and right parens
555 (defvar js2-COMMA 88) ; comma operator
557 (defvar js2-ASSIGN 89) ; simple assignment (=)
558 (defvar js2-ASSIGN_BITOR 90) ; |=
559 (defvar js2-ASSIGN_BITXOR 91) ; ^=
560 (defvar js2-ASSIGN_BITAND 92) ; &=
561 (defvar js2-ASSIGN_LSH 93) ; <<=
562 (defvar js2-ASSIGN_RSH 94) ; >>=
563 (defvar js2-ASSIGN_URSH 95) ; >>>=
564 (defvar js2-ASSIGN_ADD 96) ; +=
565 (defvar js2-ASSIGN_SUB 97) ; -=
566 (defvar js2-ASSIGN_MUL 98) ; *=
567 (defvar js2-ASSIGN_DIV 99) ; /=
568 (defvar js2-ASSIGN_MOD 100) ; %=
570 (defvar js2-first-assign js2-ASSIGN)
571 (defvar js2-last-assign js2-ASSIGN_MOD)
573 (defvar js2-HOOK 101) ; conditional (?:)
574 (defvar js2-COLON 102)
575 (defvar js2-OR 103) ; logical or (||)
576 (defvar js2-AND 104) ; logical and (&&)
577 (defvar js2-INC 105) ; increment/decrement (++ --)
579 (defvar js2-DOT 107) ; member operator (.)
580 (defvar js2-FUNCTION 108) ; function keyword
581 (defvar js2-EXPORT 109) ; export keyword
582 (defvar js2-IMPORT 110) ; import keyword
583 (defvar js2-IF 111) ; if keyword
584 (defvar js2-ELSE 112) ; else keyword
585 (defvar js2-SWITCH 113) ; switch keyword
586 (defvar js2-CASE 114) ; case keyword
587 (defvar js2-DEFAULT 115) ; default keyword
588 (defvar js2-WHILE 116) ; while keyword
589 (defvar js2-DO 117) ; do keyword
590 (defvar js2-FOR 118) ; for keyword
591 (defvar js2-BREAK 119) ; break keyword
592 (defvar js2-CONTINUE 120) ; continue keyword
593 (defvar js2-VAR 121) ; var keyword
594 (defvar js2-WITH 122) ; with keyword
595 (defvar js2-CATCH 123) ; catch keyword
596 (defvar js2-FINALLY 124) ; finally keyword
597 (defvar js2-VOID 125) ; void keyword
598 (defvar js2-RESERVED 126) ; reserved keywords
600 (defvar js2-EMPTY 127)
602 ;; Types used for the parse tree - never returned by scanner.
604 (defvar js2-BLOCK 128) ; statement block
605 (defvar js2-LABEL 129) ; label
606 (defvar js2-TARGET 130)
607 (defvar js2-LOOP 131)
608 (defvar js2-EXPR_VOID 132) ; expression statement in functions
609 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
611 (defvar js2-SCRIPT 135) ; top-level node for entire script
612 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
613 (defvar js2-USE_STACK 137)
614 (defvar js2-SETPROP_OP 138) ; x.y op= something
615 (defvar js2-SETELEM_OP 139) ; x[y] op= something
616 (defvar js2-LOCAL_BLOCK 140)
617 (defvar js2-SET_REF_OP 141) ; *reference op= something
620 (defvar js2-DOTDOT 142) ; member operator (..)
621 (defvar js2-COLONCOLON 143) ; namespace::name
622 (defvar js2-XML 144) ; XML type
623 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
624 (defvar js2-XMLATTR 146) ; @
625 (defvar js2-XMLEND 147)
627 ;; Optimizer-only tokens
628 (defvar js2-TO_OBJECT 148)
629 (defvar js2-TO_DOUBLE 149)
631 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
632 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
633 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
634 (defvar js2-CONST 153)
635 (defvar js2-SETCONST 154)
636 (defvar js2-SETCONSTVAR 155)
637 (defvar js2-ARRAYCOMP 156)
638 (defvar js2-LETEXPR 157)
639 (defvar js2-WITHEXPR 158)
640 (defvar js2-DEBUGGER 159)
642 (defvar js2-COMMENT 160)
643 (defvar js2-ENUM 161) ; for "enum" reserved word
644 (defvar js2-TRIPLEDOT 162) ; for rest parameter
646 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
648 (defconst js2-debug-print-trees nil)
650 ;; Rhino accepts any string or stream as input. Emacs character
651 ;; processing works best in buffers, so we'll assume the input is a
652 ;; buffer. JavaScript strings can be copied into temp buffers before
655 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
656 ;; They're the Emacs equivalent of instance variables, more or less.
658 (js2-deflocal js2-ts-dirty-line nil
659 "Token stream buffer-local variable.
660 Indicates stuff other than whitespace since start of line.")
662 (js2-deflocal js2-ts-regexp-flags nil
663 "Token stream buffer-local variable.")
665 (js2-deflocal js2-ts-string ""
666 "Token stream buffer-local variable.
667 Last string scanned.")
669 (js2-deflocal js2-ts-number nil
670 "Token stream buffer-local variable.
671 Last literal number scanned.")
673 (js2-deflocal js2-ts-hit-eof nil
674 "Token stream buffer-local variable.")
676 (js2-deflocal js2-ts-line-start 0
677 "Token stream buffer-local variable.")
679 (js2-deflocal js2-ts-lineno 1
680 "Token stream buffer-local variable.")
682 (js2-deflocal js2-ts-line-end-char -1
683 "Token stream buffer-local variable.")
685 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
686 "Token stream buffer-local variable.
687 Current scan position.")
689 (js2-deflocal js2-ts-is-xml-attribute nil
690 "Token stream buffer-local variable.")
692 (js2-deflocal js2-ts-xml-is-tag-content nil
693 "Token stream buffer-local variable.")
695 (js2-deflocal js2-ts-xml-open-tags-count 0
696 "Token stream buffer-local variable.")
698 (js2-deflocal js2-ts-string-buffer nil
699 "Token stream buffer-local variable.
700 List of chars built up while scanning various tokens.")
702 (js2-deflocal js2-ts-comment-type nil
703 "Token stream buffer-local variable.")
707 (js2-deflocal js2-parsed-errors nil
708 "List of errors produced during scanning/parsing.")
710 (js2-deflocal js2-parsed-warnings nil
711 "List of warnings produced during scanning/parsing.")
713 (js2-deflocal js2-recover-from-parse-errors t
714 "Non-nil to continue parsing after a syntax error.
716 In recovery mode, the AST will be built in full, and any error
717 nodes will be flagged with appropriate error information. If
718 this flag is nil, a syntax error will result in an error being
721 The variable is automatically buffer-local, because different
722 modes that use the parser will need different settings.")
724 (js2-deflocal js2-parse-hook nil
725 "List of callbacks for receiving parsing progress.")
727 (defvar js2-parse-finished-hook nil
728 "List of callbacks to notify when parsing finishes.
729 Not called if parsing was interrupted.")
731 (js2-deflocal js2-is-eval-code nil
732 "True if we're evaluating code in a string.
733 If non-nil, the tokenizer will record the token text, and the AST nodes
734 will record their source text. Off by default for IDE modes, since the
735 text is available in the buffer.")
737 (defvar js2-parse-ide-mode t
738 "Non-nil if the parser is being used for `js2-mode'.
739 If non-nil, the parser will set text properties for fontification
740 and the syntax table. The value should be nil when using the
741 parser as a frontend to an interpreter or byte compiler.")
743 ;;; Parser instance variables (buffer-local vars for js2-parse)
745 (defconst js2-clear-ti-mask #xFFFF
746 "Mask to clear token information bits.")
748 (defconst js2-ti-after-eol (lsh 1 16)
749 "Flag: first token of the source line.")
751 (defconst js2-ti-check-label (lsh 1 17)
752 "Flag: indicates to check for label.")
754 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
756 (js2-deflocal js2-compiler-generate-debug-info t)
757 (js2-deflocal js2-compiler-use-dynamic-scope nil)
758 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
759 (js2-deflocal js2-compiler-xml-available t)
760 (js2-deflocal js2-compiler-optimization-level 0)
761 (js2-deflocal js2-compiler-generating-source t)
762 (js2-deflocal js2-compiler-strict-mode nil)
763 (js2-deflocal js2-compiler-report-warning-as-error nil)
764 (js2-deflocal js2-compiler-generate-observer-count nil)
765 (js2-deflocal js2-compiler-activation-names nil)
769 ;; There's a compileFunction method in Context.java - may need it.
770 (js2-deflocal js2-called-by-compile-function nil
771 "True if `js2-parse' was called by `js2-compile-function'.
772 Will only be used when we finish implementing the interpreter.")
774 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
776 (js2-deflocal js2-current-flagged-token js2-EOF)
777 (js2-deflocal js2-current-token js2-EOF)
779 ;; SKIP: node factory - we're going to just call functions directly,
780 ;; and eventually go to a unified AST format.
782 (js2-deflocal js2-nesting-of-function 0)
784 (js2-deflocal js2-recorded-identifiers nil
785 "Tracks identifiers found during parsing.")
787 (js2-deflocal js2-is-in-destructuring nil
788 "True while parsing destructuring expression.")
790 (defcustom js2-global-externs nil
791 "A list of any extern names you'd like to consider always declared.
792 This list is global and is used by all `js2-mode' files.
793 You can create buffer-local externs list using `js2-additional-externs'.
795 There is also a buffer-local variable `js2-default-externs',
796 which is initialized by default to include the Ecma-262 externs
797 and the standard browser externs. The three lists are all
798 checked during highlighting."
802 (js2-deflocal js2-default-externs nil
803 "Default external declarations.
805 These are currently only used for highlighting undeclared variables,
806 which only worries about top-level (unqualified) references.
807 As js2-mode's processing improves, we will flesh out this list.
809 The initial value is set to `js2-ecma-262-externs', unless some
810 of the `js2-include-?-externs' variables are set to t, in which
811 case the browser, Rhino and/or Node.js externs are also included.
813 See `js2-additional-externs' for more information.")
815 (defcustom js2-include-browser-externs t
816 "Non-nil to include browser externs in the master externs list.
817 If you work on JavaScript files that are not intended for browsers,
818 such as Mozilla Rhino server-side JavaScript, set this to nil.
819 See `js2-additional-externs' for more information about externs."
823 (defcustom js2-include-rhino-externs nil
824 "Non-nil to include Mozilla Rhino externs in the master externs list.
825 See `js2-additional-externs' for more information about externs."
829 (defcustom js2-include-node-externs nil
830 "Non-nil to include Node.js externs in the master externs list.
831 See `js2-additional-externs' for more information about externs."
835 (js2-deflocal js2-additional-externs nil
836 "A buffer-local list of additional external declarations.
837 It is used to decide whether variables are considered undeclared
838 for purposes of highlighting.
840 Each entry is a Lisp string. The string should be the fully qualified
841 name of an external entity. All externs should be added to this list,
842 so that as js2-mode's processing improves it can take advantage of them.
844 You may want to declare your externs in three ways.
845 First, you can add externs that are valid for all your JavaScript files.
846 You should probably do this by adding them to `js2-global-externs', which
847 is a global list used for all js2-mode files.
849 Next, you can add a function to `js2-mode-hook' that adds additional
850 externs appropriate for the specific file, perhaps based on its path.
851 These should go in `js2-additional-externs', which is buffer-local.
853 Finally, you can add a function to `js2-post-parse-callbacks',
854 which is called after parsing completes, and `js2-mode-ast' is bound to
855 the root of the parse tree. At this stage you can set up an AST
856 node visitor using `js2-visit-ast' and examine the parse tree
857 for specific import patterns that may imply the existence of
858 other externs, possibly tied to your build system. These should also
859 be added to `js2-additional-externs'.
861 Your post-parse callback may of course also use the simpler and
862 faster (but perhaps less robust) approach of simply scanning the
863 buffer text for your imports, using regular expressions.")
866 ;; SKIP: encoded-source
868 ;;; The following variables are per-function and should be saved/restored
869 ;;; during function parsing...
871 (js2-deflocal js2-current-script-or-fn nil)
872 (js2-deflocal js2-current-scope nil)
873 (js2-deflocal js2-nesting-of-with 0)
874 (js2-deflocal js2-label-set nil
875 "An alist mapping label names to nodes.")
877 (js2-deflocal js2-loop-set nil)
878 (js2-deflocal js2-loop-and-switch-set nil)
879 (js2-deflocal js2-has-return-value nil)
880 (js2-deflocal js2-end-flags 0)
882 ;;; ...end of per function variables
884 ;; Without 2-token lookahead, labels are a problem.
885 ;; These vars store the token info of the last matched name,
886 ;; iff it wasn't the last matched token. Only valid in some contexts.
887 (defvar js2-prev-name-token-start nil)
888 (defvar js2-prev-name-token-string nil)
890 (defsubst js2-save-name-token-data (pos name)
891 (setq js2-prev-name-token-start pos
892 js2-prev-name-token-string name))
894 ;; These flags enumerate the possible ways a statement/function can
895 ;; terminate. These flags are used by endCheck() and by the Parser to
896 ;; detect inconsistent return usage.
898 ;; END_UNREACHED is reserved for code paths that are assumed to always be
899 ;; able to execute (example: throw, continue)
901 ;; END_DROPS_OFF indicates if the statement can transfer control to the
902 ;; next one. Statement such as return dont. A compound statement may have
903 ;; some branch that drops off control to the next statement.
905 ;; END_RETURNS indicates that the statement can return (without arguments)
906 ;; END_RETURNS_VALUE indicates that the statement can return a value.
908 ;; A compound statement such as
912 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
914 (defconst js2-end-unreached #x0)
915 (defconst js2-end-drops-off #x1)
916 (defconst js2-end-returns #x2)
917 (defconst js2-end-returns-value #x4)
918 (defconst js2-end-yields #x8)
920 ;; Rhino awkwardly passes a statementLabel parameter to the
921 ;; statementHelper() function, the main statement parser, which
922 ;; is then used by quite a few of the sub-parsers. We just make
923 ;; it a buffer-local variable and make sure it's cleaned up properly.
924 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
926 ;; Similarly, Rhino passes an inForInit boolean through about half
927 ;; the expression parsers. We use a dynamically-scoped variable,
928 ;; which makes it easier to funcall the parsers individually without
929 ;; worrying about whether they take the parameter or not.
930 (js2-deflocal js2-in-for-init nil)
931 (js2-deflocal js2-temp-name-counter 0)
932 (js2-deflocal js2-parse-stmt-count 0)
934 (defsubst js2-get-next-temp-name ()
935 (format "$%d" (incf js2-temp-name-counter)))
937 (defvar js2-parse-interruptable-p t
938 "Set this to nil to force parse to continue until finished.
939 This will mostly be useful for interpreters.")
941 (defvar js2-statements-per-pause 50
942 "Pause after this many statements to check for user input.
943 If user input is pending, stop the parse and discard the tree.
944 This makes for a smoother user experience for large files.
945 You may have to wait a second or two before the highlighting
946 and error-reporting appear, but you can always type ahead if
947 you wish. This appears to be more or less how Eclipse, IntelliJ
948 and other editors work.")
950 (js2-deflocal js2-record-comments t
951 "Instructs the scanner to record comments in `js2-scanned-comments'.")
953 (js2-deflocal js2-scanned-comments nil
954 "List of all comments from the current parse.")
956 (defcustom js2-mode-indent-inhibit-undo nil
957 "Non-nil to disable collection of Undo information when indenting lines.
958 Some users have requested this behavior. It's nil by default because
959 other Emacs modes don't work this way."
963 (defcustom js2-mode-indent-ignore-first-tab nil
964 "If non-nil, ignore first TAB keypress if we look indented properly.
965 It's fairly common for users to navigate to an already-indented line
966 and press TAB for reassurance that it's been indented. For this class
967 of users, we want the first TAB press on a line to be ignored if the
968 line is already indented to one of the precomputed alternatives.
970 This behavior is only partly implemented. If you TAB-indent a line,
971 navigate to another line, and then navigate back, it fails to clear
972 the last-indented variable, so it thinks you've already hit TAB once,
973 and performs the indent. A full solution would involve getting on the
974 point-motion hooks for the entire buffer. If we come across another
975 use cases that requires watching point motion, I'll consider doing it.
977 If you set this variable to nil, then the TAB key will always change
978 the indentation of the current line, if more than one alternative
979 indentation spot exists."
983 (defvar js2-indent-hook nil
984 "A hook for user-defined indentation rules.
986 Functions on this hook should expect two arguments: (LIST INDEX)
987 The LIST argument is the list of computed indentation points for
988 the current line. INDEX is the list index of the indentation point
989 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
990 indent function is not going to change the current line indentation.
992 If a hook function on this list returns a non-nil value, then
993 `js2-bounce-indent' assumes the hook function has performed its own
994 indentation, and will do nothing. If all hook functions on the list
995 return nil, then `js2-bounce-indent' will use its computed indentation
996 and reindent the line.
998 When hook functions on this hook list are called, the variable
999 `js2-mode-ast' may or may not be set, depending on whether the
1000 parse tree is available. If the variable is nil, you can pass a
1001 callback to `js2-mode-wait-for-parse', and your callback will be
1002 called after the new parse tree is built. This can take some time
1005 (defface js2-warning
1006 `((((class color) (background light))
1007 (:underline "orange"))
1008 (((class color) (background dark))
1009 (:underline "orange"))
1011 "Face for JavaScript warnings."
1015 `((((class color) (background light))
1016 (:foreground "red"))
1017 (((class color) (background dark))
1018 (:foreground "red"))
1019 (t (:foreground "red")))
1020 "Face for JavaScript errors."
1023 (defface js2-jsdoc-tag
1024 '((t :foreground "SlateGray"))
1025 "Face used to highlight @whatever tags in jsdoc comments."
1028 (defface js2-jsdoc-type
1029 '((t :foreground "SteelBlue"))
1030 "Face used to highlight {FooBar} types in jsdoc comments."
1033 (defface js2-jsdoc-value
1034 '((t :foreground "PeachPuff3"))
1035 "Face used to highlight tag values in jsdoc comments."
1038 (defface js2-function-param
1039 '((t :foreground "SeaGreen"))
1040 "Face used to highlight function parameters in javascript."
1043 (defface js2-instance-member
1044 '((t :foreground "DarkOrchid"))
1045 "Face used to highlight instance variables in javascript.
1046 Not currently used."
1049 (defface js2-private-member
1050 '((t :foreground "PeachPuff3"))
1051 "Face used to highlight calls to private methods in javascript.
1052 Not currently used."
1055 (defface js2-private-function-call
1056 '((t :foreground "goldenrod"))
1057 "Face used to highlight calls to private functions in javascript.
1058 Not currently used."
1061 (defface js2-jsdoc-html-tag-name
1062 '((((class color) (min-colors 88) (background light))
1063 (:foreground "rosybrown"))
1064 (((class color) (min-colors 8) (background dark))
1065 (:foreground "yellow"))
1066 (((class color) (min-colors 8) (background light))
1067 (:foreground "magenta")))
1068 "Face used to highlight jsdoc html tag names"
1071 (defface js2-jsdoc-html-tag-delimiter
1072 '((((class color) (min-colors 88) (background light))
1073 (:foreground "dark khaki"))
1074 (((class color) (min-colors 8) (background dark))
1075 (:foreground "green"))
1076 (((class color) (min-colors 8) (background light))
1077 (:foreground "green")))
1078 "Face used to highlight brackets in jsdoc html tags."
1081 (defface js2-external-variable
1082 '((t :foreground "orange"))
1083 "Face used to highlight undeclared variable identifiers.")
1085 (defcustom js2-post-parse-callbacks nil
1086 "A list of callback functions invoked after parsing finishes.
1087 Currently, the main use for this function is to add synthetic
1088 declarations to `js2-recorded-identifiers', which see."
1092 (defcustom js2-highlight-external-variables t
1093 "Non-nil to highlight undeclared variable identifiers.
1094 An undeclared variable is any variable not declared with var or let
1095 in the current scope or any lexically enclosing scope. If you use
1096 such a variable, then you are either expecting it to originate from
1097 another file, or you've got a potential bug."
1101 (defcustom js2-auto-insert-catch-block t
1102 "Non-nil to insert matching catch block on open-curly after `try'."
1106 (defvar js2-mode-map
1107 (let ((map (make-sparse-keymap))
1109 (define-key map [mouse-1] #'js2-mode-show-node)
1110 (define-key map (kbd "M-j") #'js2-line-break)
1111 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1112 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1113 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1114 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1115 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1116 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1117 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1118 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1119 (when js2-bounce-indent-p
1120 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1122 (define-key map [menu-bar javascript]
1123 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1125 (define-key map [menu-bar javascript customize-js2-mode]
1126 '(menu-item "Customize js2-mode" js2-mode-customize
1127 :help "Customize the behavior of this mode"))
1129 (define-key map [menu-bar javascript js2-force-refresh]
1130 '(menu-item "Force buffer refresh" js2-mode-reset
1131 :help "Re-parse the buffer from scratch"))
1133 (define-key map [menu-bar javascript separator-2]
1136 (define-key map [menu-bar javascript next-error]
1137 '(menu-item "Next warning or error" next-error
1138 :enabled (and js2-mode-ast
1139 (or (js2-ast-root-errors js2-mode-ast)
1140 (js2-ast-root-warnings js2-mode-ast)))
1141 :help "Move to next warning or error"))
1143 (define-key map [menu-bar javascript display-errors]
1144 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1145 :visible (not js2-mode-show-parse-errors)
1146 :help "Turn on display of warnings and errors"))
1148 (define-key map [menu-bar javascript hide-errors]
1149 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1150 :visible js2-mode-show-parse-errors
1151 :help "Turn off display of warnings and errors"))
1153 (define-key map [menu-bar javascript separator-1]
1156 (define-key map [menu-bar javascript js2-toggle-function]
1157 '(menu-item "Show/collapse element" js2-mode-toggle-element
1158 :help "Hide or show function body or comment"))
1160 (define-key map [menu-bar javascript show-comments]
1161 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1162 :visible js2-mode-comments-hidden
1163 :help "Expand all hidden block comments"))
1165 (define-key map [menu-bar javascript hide-comments]
1166 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1167 :visible (not js2-mode-comments-hidden)
1168 :help "Show block comments as /*...*/"))
1170 (define-key map [menu-bar javascript show-all-functions]
1171 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1172 :visible js2-mode-functions-hidden
1173 :help "Expand all hidden function bodies"))
1175 (define-key map [menu-bar javascript hide-all-functions]
1176 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1177 :visible (not js2-mode-functions-hidden)
1178 :help "Show {...} for all top-level function bodies"))
1181 "Keymap used in `js2-mode' buffers.")
1183 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1185 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1186 "Matches a //-comment line. Must be first non-whitespace on line.
1187 First match-group is the leading whitespace.")
1189 (defvar js2-mode-hook nil)
1191 (js2-deflocal js2-mode-ast nil "Private variable.")
1192 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1193 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1194 (js2-deflocal js2-mode-parsing nil "Private variable.")
1195 (js2-deflocal js2-mode-node-overlay nil)
1197 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1198 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1200 (js2-deflocal js2-mode-fontifications nil "Private variable")
1201 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1202 (js2-deflocal js2-imenu-recorder nil "Private variable")
1203 (js2-deflocal js2-imenu-function-map nil "Private variable")
1205 (defvar js2-paragraph-start
1206 "\\(@[a-zA-Z]+\\>\\|$\\)")
1208 ;; Note that we also set a 'c-in-sws text property in html comments,
1209 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1210 (defvar js2-syntactic-ws-start
1211 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1213 (defvar js2-syntactic-ws-end
1214 "\\s \\|[\n\r/]\\|\\s!")
1216 (defvar js2-syntactic-eol
1217 (concat "\\s *\\(/\\*[^*\n\r]*"
1218 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1220 "\\(//\\|/\\*[^*\n\r]*"
1221 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1223 "Copied from `java-mode'. Needed for some cc-engine functions.")
1225 (defvar js2-comment-prefix-regexp
1228 (defvar js2-comment-start-skip
1229 "\\(//+\\|/\\*+\\)\\s *")
1231 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1232 "Non-nil to emit status messages during parsing.")
1234 (defvar js2-mode-functions-hidden nil "Private variable.")
1235 (defvar js2-mode-comments-hidden nil "Private variable.")
1237 (defvar js2-mode-syntax-table
1238 (let ((table (make-syntax-table)))
1239 (c-populate-syntax-table table)
1241 "Syntax table used in `js2-mode' buffers.")
1243 (defvar js2-mode-abbrev-table nil
1244 "Abbrev table in use in `js2-mode' buffers.")
1245 (define-abbrev-table 'js2-mode-abbrev-table ())
1247 (defvar js2-mode-pending-parse-callbacks nil
1248 "List of functions waiting to be notified that parse is finished.")
1250 (defvar js2-mode-last-indented-line -1)
1252 ;;; Localizable error and warning messages
1254 ;; Messages are copied from Rhino's Messages.properties.
1255 ;; Many of the Java-specific messages have been elided.
1256 ;; Add any js2-specific ones at the end, so we can keep
1257 ;; this file synced with changes to Rhino's.
1259 (defvar js2-message-table
1260 (make-hash-table :test 'equal :size 250)
1261 "Contains localized messages for `js2-mode'.")
1263 ;; TODO(stevey): construct this table at compile-time.
1264 (defmacro js2-msg (key &rest strings)
1265 `(puthash ,key (concat ,@strings)
1268 (defun js2-get-msg (msg-key)
1269 "Look up a localized message.
1270 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1271 the correct number of ARGS must be provided."
1272 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1273 (args (if (listp msg-key) (cdr msg-key)))
1274 (msg (gethash key js2-message-table)))
1276 (apply #'format msg args)
1277 key))) ; default to showing the key
1279 (js2-msg "msg.dup.parms"
1280 "Duplicate parameter name '%s'.")
1282 (js2-msg "msg.too.big.jump"
1283 "Program too complex: jump offset too big.")
1285 (js2-msg "msg.too.big.index"
1286 "Program too complex: internal index exceeds 64K limit.")
1288 (js2-msg "msg.while.compiling.fn"
1289 "Encountered code generation error while compiling function '%s': %s")
1291 (js2-msg "msg.while.compiling.script"
1292 "Encountered code generation error while compiling script: %s")
1295 (js2-msg "msg.ctor.not.found"
1296 "Constructor for '%s' not found.")
1298 (js2-msg "msg.not.ctor"
1299 "'%s' is not a constructor.")
1302 (js2-msg "msg.varargs.ctor"
1303 "Method or constructor '%s' must be static "
1304 "with the signature (Context cx, Object[] args, "
1305 "Function ctorObj, boolean inNewExpr) "
1306 "to define a variable arguments constructor.")
1308 (js2-msg "msg.varargs.fun"
1309 "Method '%s' must be static with the signature "
1310 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1311 "to define a variable arguments function.")
1313 (js2-msg "msg.incompat.call"
1314 "Method '%s' called on incompatible object.")
1316 (js2-msg "msg.bad.parms"
1317 "Unsupported parameter type '%s' in method '%s'.")
1319 (js2-msg "msg.bad.method.return"
1320 "Unsupported return type '%s' in method '%s'.")
1322 (js2-msg "msg.bad.ctor.return"
1323 "Construction of objects of type '%s' is not supported.")
1325 (js2-msg "msg.no.overload"
1326 "Method '%s' occurs multiple times in class '%s'.")
1328 (js2-msg "msg.method.not.found"
1329 "Method '%s' not found in '%s'.")
1333 (js2-msg "msg.bad.for.in.lhs"
1334 "Invalid left-hand side of for..in loop.")
1336 (js2-msg "msg.mult.index"
1337 "Only one variable allowed in for..in loop.")
1339 (js2-msg "msg.bad.for.in.destruct"
1340 "Left hand side of for..in loop must be an array of "
1341 "length 2 to accept key/value pair.")
1343 (js2-msg "msg.cant.convert"
1344 "Can't convert to type '%s'.")
1346 (js2-msg "msg.bad.assign.left"
1347 "Invalid assignment left-hand side.")
1349 (js2-msg "msg.bad.decr"
1350 "Invalid decerement operand.")
1352 (js2-msg "msg.bad.incr"
1353 "Invalid increment operand.")
1355 (js2-msg "msg.bad.yield"
1356 "yield must be in a function.")
1358 (js2-msg "msg.yield.parenthesized"
1359 "yield expression must be parenthesized.")
1362 (js2-msg "msg.cant.call.indirect"
1363 "Function '%s' must be called directly, and not by way of a "
1364 "function of another name.")
1366 (js2-msg "msg.eval.nonstring"
1367 "Calling eval() with anything other than a primitive "
1368 "string value will simply return the value. "
1369 "Is this what you intended?")
1371 (js2-msg "msg.eval.nonstring.strict"
1372 "Calling eval() with anything other than a primitive "
1373 "string value is not allowed in strict mode.")
1375 (js2-msg "msg.bad.destruct.op"
1376 "Invalid destructuring assignment operator")
1379 (js2-msg "msg.only.from.new"
1380 "'%s' may only be invoked from a `new' expression.")
1382 (js2-msg "msg.deprec.ctor"
1383 "The '%s' constructor is deprecated.")
1386 (js2-msg "msg.no.function.ref.found"
1387 "no source found to decompile function reference %s")
1389 (js2-msg "msg.arg.isnt.array"
1390 "second argument to Function.prototype.apply must be an array")
1393 (js2-msg "msg.bad.esc.mask"
1394 "invalid string escape mask")
1397 (js2-msg "msg.bad.quant"
1398 "Invalid quantifier %s")
1400 (js2-msg "msg.overlarge.backref"
1401 "Overly large back reference %s")
1403 (js2-msg "msg.overlarge.min"
1404 "Overly large minimum %s")
1406 (js2-msg "msg.overlarge.max"
1407 "Overly large maximum %s")
1409 (js2-msg "msg.zero.quant"
1410 "Zero quantifier %s")
1412 (js2-msg "msg.max.lt.min"
1413 "Maximum %s less than minimum")
1415 (js2-msg "msg.unterm.quant"
1416 "Unterminated quantifier %s")
1418 (js2-msg "msg.unterm.paren"
1419 "Unterminated parenthetical %s")
1421 (js2-msg "msg.unterm.class"
1422 "Unterminated character class %s")
1424 (js2-msg "msg.bad.range"
1425 "Invalid range in character class.")
1427 (js2-msg "msg.trail.backslash"
1428 "Trailing \\ in regular expression.")
1430 (js2-msg "msg.re.unmatched.right.paren"
1431 "unmatched ) in regular expression.")
1433 (js2-msg "msg.no.regexp"
1434 "Regular expressions are not available.")
1436 (js2-msg "msg.bad.backref"
1437 "back-reference exceeds number of capturing parentheses.")
1439 (js2-msg "msg.bad.regexp.compile"
1440 "Only one argument may be specified if the first "
1441 "argument to RegExp.prototype.compile is a RegExp object.")
1444 (js2-msg "msg.got.syntax.errors"
1445 "Compilation produced %s syntax errors.")
1447 (js2-msg "msg.var.redecl"
1448 "TypeError: redeclaration of var %s.")
1450 (js2-msg "msg.const.redecl"
1451 "TypeError: redeclaration of const %s.")
1453 (js2-msg "msg.let.redecl"
1454 "TypeError: redeclaration of variable %s.")
1456 (js2-msg "msg.parm.redecl"
1457 "TypeError: redeclaration of formal parameter %s.")
1459 (js2-msg "msg.fn.redecl"
1460 "TypeError: redeclaration of function %s.")
1462 (js2-msg "msg.let.decl.not.in.block"
1463 "SyntaxError: let declaration not directly within block")
1466 (js2-msg "msg.dup.label"
1469 (js2-msg "msg.undef.label"
1472 (js2-msg "msg.bad.break"
1473 "unlabelled break must be inside loop or switch")
1475 (js2-msg "msg.continue.outside"
1476 "continue must be inside loop")
1478 (js2-msg "msg.continue.nonloop"
1479 "continue can only use labels of iteration statements")
1481 (js2-msg "msg.bad.throw.eol"
1482 "Line terminator is not allowed between the throw "
1483 "keyword and throw expression.")
1485 (js2-msg "msg.no.paren.parms"
1486 "missing ( before function parameters.")
1488 (js2-msg "msg.no.parm"
1489 "missing formal parameter")
1491 (js2-msg "msg.no.paren.after.parms"
1492 "missing ) after formal parameters")
1494 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1495 "parameter without default follows parameter with default")
1497 (js2-msg "msg.param.after.rest" ; added by js2-mode
1498 "parameter after rest parameter")
1500 (js2-msg "msg.no.brace.body"
1501 "missing '{' before function body")
1503 (js2-msg "msg.no.brace.after.body"
1504 "missing } after function body")
1506 (js2-msg "msg.no.paren.cond"
1507 "missing ( before condition")
1509 (js2-msg "msg.no.paren.after.cond"
1510 "missing ) after condition")
1512 (js2-msg "msg.no.semi.stmt"
1513 "missing ; before statement")
1515 (js2-msg "msg.missing.semi"
1516 "missing ; after statement")
1518 (js2-msg "msg.no.name.after.dot"
1519 "missing name after . operator")
1521 (js2-msg "msg.no.name.after.coloncolon"
1522 "missing name after :: operator")
1524 (js2-msg "msg.no.name.after.dotdot"
1525 "missing name after .. operator")
1527 (js2-msg "msg.no.name.after.xmlAttr"
1528 "missing name after .@")
1530 (js2-msg "msg.no.bracket.index"
1531 "missing ] in index expression")
1533 (js2-msg "msg.no.paren.switch"
1534 "missing ( before switch expression")
1536 (js2-msg "msg.no.paren.after.switch"
1537 "missing ) after switch expression")
1539 (js2-msg "msg.no.brace.switch"
1540 "missing '{' before switch body")
1542 (js2-msg "msg.bad.switch"
1543 "invalid switch statement")
1545 (js2-msg "msg.no.colon.case"
1546 "missing : after case expression")
1548 (js2-msg "msg.double.switch.default"
1549 "double default label in the switch statement")
1551 (js2-msg "msg.no.while.do"
1552 "missing while after do-loop body")
1554 (js2-msg "msg.no.paren.for"
1555 "missing ( after for")
1557 (js2-msg "msg.no.semi.for"
1558 "missing ; after for-loop initializer")
1560 (js2-msg "msg.no.semi.for.cond"
1561 "missing ; after for-loop condition")
1563 (js2-msg "msg.in.after.for.name"
1564 "missing in or of after for")
1566 (js2-msg "msg.no.paren.for.ctrl"
1567 "missing ) after for-loop control")
1569 (js2-msg "msg.no.paren.with"
1570 "missing ( before with-statement object")
1572 (js2-msg "msg.no.paren.after.with"
1573 "missing ) after with-statement object")
1575 (js2-msg "msg.no.paren.after.let"
1576 "missing ( after let")
1578 (js2-msg "msg.no.paren.let"
1579 "missing ) after variable list")
1581 (js2-msg "msg.no.curly.let"
1582 "missing } after let statement")
1584 (js2-msg "msg.bad.return"
1587 (js2-msg "msg.no.brace.block"
1588 "missing } in compound statement")
1590 (js2-msg "msg.bad.label"
1593 (js2-msg "msg.bad.var"
1594 "missing variable name")
1596 (js2-msg "msg.bad.var.init"
1597 "invalid variable initialization")
1599 (js2-msg "msg.no.colon.cond"
1600 "missing : in conditional expression")
1602 (js2-msg "msg.no.paren.arg"
1603 "missing ) after argument list")
1605 (js2-msg "msg.no.bracket.arg"
1606 "missing ] after element list")
1608 (js2-msg "msg.bad.prop"
1609 "invalid property id")
1611 (js2-msg "msg.no.colon.prop"
1612 "missing : after property id")
1614 (js2-msg "msg.no.brace.prop"
1615 "missing } after property list")
1617 (js2-msg "msg.no.paren"
1618 "missing ) in parenthetical")
1620 (js2-msg "msg.reserved.id"
1621 "identifier is a reserved word")
1623 (js2-msg "msg.no.paren.catch"
1624 "missing ( before catch-block condition")
1626 (js2-msg "msg.bad.catchcond"
1627 "invalid catch block condition")
1629 (js2-msg "msg.catch.unreachable"
1630 "any catch clauses following an unqualified catch are unreachable")
1632 (js2-msg "msg.no.brace.try"
1633 "missing '{' before try block")
1635 (js2-msg "msg.no.brace.catchblock"
1636 "missing '{' before catch-block body")
1638 (js2-msg "msg.try.no.catchfinally"
1639 "'try' without 'catch' or 'finally'")
1641 (js2-msg "msg.no.return.value"
1642 "function %s does not always return a value")
1644 (js2-msg "msg.anon.no.return.value"
1645 "anonymous function does not always return a value")
1647 (js2-msg "msg.return.inconsistent"
1648 "return statement is inconsistent with previous usage")
1650 (js2-msg "msg.generator.returns"
1651 "TypeError: generator function '%s' returns a value")
1653 (js2-msg "msg.anon.generator.returns"
1654 "TypeError: anonymous generator function returns a value")
1656 (js2-msg "msg.syntax"
1659 (js2-msg "msg.unexpected.eof"
1660 "Unexpected end of file")
1662 (js2-msg "msg.XML.bad.form"
1663 "illegally formed XML syntax")
1665 (js2-msg "msg.XML.not.available"
1666 "XML runtime not available")
1668 (js2-msg "msg.too.deep.parser.recursion"
1669 "Too deep recursion while parsing")
1671 (js2-msg "msg.no.side.effects"
1672 "Code has no side effects")
1674 (js2-msg "msg.extra.trailing.comma"
1675 "Trailing comma is not supported in some browsers")
1677 (js2-msg "msg.array.trailing.comma"
1678 "Trailing comma yields different behavior across browsers")
1680 (js2-msg "msg.equal.as.assign"
1681 (concat "Test for equality (==) mistyped as assignment (=)?"
1682 " (parenthesize to suppress warning)"))
1684 (js2-msg "msg.var.hides.arg"
1685 "Variable %s hides argument")
1687 (js2-msg "msg.destruct.assign.no.init"
1688 "Missing = in destructuring declaration")
1691 (js2-msg "msg.no.properties"
1692 "%s has no properties.")
1694 (js2-msg "msg.invalid.iterator"
1695 "Invalid iterator value")
1697 (js2-msg "msg.iterator.primitive"
1698 "__iterator__ returned a primitive value")
1700 (js2-msg "msg.assn.create.strict"
1701 "Assignment to undeclared variable %s")
1703 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1704 "Undeclared variable or function '%s'")
1706 (js2-msg "msg.ref.undefined.prop"
1707 "Reference to undefined property '%s'")
1709 (js2-msg "msg.prop.not.found"
1710 "Property %s not found.")
1712 (js2-msg "msg.invalid.type"
1713 "Invalid JavaScript value of type %s")
1715 (js2-msg "msg.primitive.expected"
1716 "Primitive type expected (had %s instead)")
1718 (js2-msg "msg.namespace.expected"
1719 "Namespace object expected to left of :: (found %s instead)")
1721 (js2-msg "msg.null.to.object"
1722 "Cannot convert null to an object.")
1724 (js2-msg "msg.undef.to.object"
1725 "Cannot convert undefined to an object.")
1727 (js2-msg "msg.cyclic.value"
1728 "Cyclic %s value not allowed.")
1730 (js2-msg "msg.is.not.defined"
1731 "'%s' is not defined.")
1733 (js2-msg "msg.undef.prop.read"
1734 "Cannot read property '%s' from %s")
1736 (js2-msg "msg.undef.prop.write"
1737 "Cannot set property '%s' of %s to '%s'")
1739 (js2-msg "msg.undef.prop.delete"
1740 "Cannot delete property '%s' of %s")
1742 (js2-msg "msg.undef.method.call"
1743 "Cannot call method '%s' of %s")
1745 (js2-msg "msg.undef.with"
1746 "Cannot apply 'with' to %s")
1748 (js2-msg "msg.isnt.function"
1749 "%s is not a function, it is %s.")
1751 (js2-msg "msg.isnt.function.in"
1752 "Cannot call property %s in object %s. "
1753 "It is not a function, it is '%s'.")
1755 (js2-msg "msg.function.not.found"
1756 "Cannot find function %s.")
1758 (js2-msg "msg.function.not.found.in"
1759 "Cannot find function %s in object %s.")
1761 (js2-msg "msg.isnt.xml.object"
1762 "%s is not an xml object.")
1764 (js2-msg "msg.no.ref.to.get"
1765 "%s is not a reference to read reference value.")
1767 (js2-msg "msg.no.ref.to.set"
1768 "%s is not a reference to set reference value to %s.")
1770 (js2-msg "msg.no.ref.from.function"
1771 "Function %s can not be used as the left-hand "
1772 "side of assignment or as an operand of ++ or -- operator.")
1774 (js2-msg "msg.bad.default.value"
1775 "Object's getDefaultValue() method returned an object.")
1777 (js2-msg "msg.instanceof.not.object"
1778 "Can't use instanceof on a non-object.")
1780 (js2-msg "msg.instanceof.bad.prototype"
1781 "'prototype' property of %s is not an object.")
1783 (js2-msg "msg.bad.radix"
1784 "illegal radix %s.")
1787 (js2-msg "msg.default.value"
1788 "Cannot find default value for object.")
1790 (js2-msg "msg.zero.arg.ctor"
1791 "Cannot load class '%s' which has no zero-parameter constructor.")
1793 (js2-msg "msg.ctor.multiple.parms"
1794 "Can't define constructor or class %s since more than "
1795 "one constructor has multiple parameters.")
1797 (js2-msg "msg.extend.scriptable"
1798 "%s must extend ScriptableObject in order to define property %s.")
1800 (js2-msg "msg.bad.getter.parms"
1801 "In order to define a property, getter %s must have zero "
1802 "parameters or a single ScriptableObject parameter.")
1804 (js2-msg "msg.obj.getter.parms"
1805 "Expected static or delegated getter %s to take "
1806 "a ScriptableObject parameter.")
1808 (js2-msg "msg.getter.static"
1809 "Getter and setter must both be static or neither be static.")
1811 (js2-msg "msg.setter.return"
1812 "Setter must have void return type: %s")
1814 (js2-msg "msg.setter2.parms"
1815 "Two-parameter setter must take a ScriptableObject as "
1816 "its first parameter.")
1818 (js2-msg "msg.setter1.parms"
1819 "Expected single parameter setter for %s")
1821 (js2-msg "msg.setter2.expected"
1822 "Expected static or delegated setter %s to take two parameters.")
1824 (js2-msg "msg.setter.parms"
1825 "Expected either one or two parameters for setter.")
1827 (js2-msg "msg.setter.bad.type"
1828 "Unsupported parameter type '%s' in setter '%s'.")
1830 (js2-msg "msg.add.sealed"
1831 "Cannot add a property to a sealed object: %s.")
1833 (js2-msg "msg.remove.sealed"
1834 "Cannot remove a property from a sealed object: %s.")
1836 (js2-msg "msg.modify.sealed"
1837 "Cannot modify a property of a sealed object: %s.")
1839 (js2-msg "msg.modify.readonly"
1840 "Cannot modify readonly property: %s.")
1843 (js2-msg "msg.missing.exponent"
1846 (js2-msg "msg.caught.nfe"
1847 "number format error")
1849 (js2-msg "msg.unterminated.string.lit"
1850 "unterminated string literal")
1852 (js2-msg "msg.unterminated.comment"
1853 "unterminated comment")
1855 (js2-msg "msg.unterminated.re.lit"
1856 "unterminated regular expression literal")
1858 (js2-msg "msg.invalid.re.flag"
1859 "invalid flag after regular expression")
1861 (js2-msg "msg.no.re.input.for"
1864 (js2-msg "msg.illegal.character"
1865 "illegal character")
1867 (js2-msg "msg.invalid.escape"
1868 "invalid Unicode escape sequence")
1870 (js2-msg "msg.bad.namespace"
1871 "not a valid default namespace statement. "
1872 "Syntax is: default xml namespace = EXPRESSION;")
1874 ;; TokensStream warnings
1875 (js2-msg "msg.bad.octal.literal"
1876 "illegal octal literal digit %s; "
1877 "interpreting it as a decimal digit")
1879 (js2-msg "msg.reserved.keyword"
1880 "illegal usage of future reserved keyword %s; "
1881 "interpreting it as ordinary identifier")
1883 (js2-msg "msg.script.is.not.constructor"
1884 "Script objects are not constructors.")
1887 (js2-msg "msg.arraylength.bad"
1888 "Inappropriate array length.")
1891 (js2-msg "msg.arraylength.too.big"
1892 "Array length %s exceeds supported capacity limit.")
1895 (js2-msg "msg.bad.uri"
1896 "Malformed URI sequence.")
1899 (js2-msg "msg.bad.precision"
1900 "Precision %s out of range.")
1903 (js2-msg "msg.send.newborn"
1904 "Attempt to send value to newborn generator")
1906 (js2-msg "msg.already.exec.gen"
1907 "Already executing generator")
1909 (js2-msg "msg.StopIteration.invalid"
1910 "StopIteration may not be changed to an arbitrary object.")
1913 (js2-msg "msg.yield.closing"
1914 "Yield from closing generator")
1918 (defun js2-delete-if (predicate list)
1919 "Remove all items satisfying PREDICATE in LIST."
1920 (loop for item in list
1921 if (not (funcall predicate item))
1924 (defun js2-position (element list)
1925 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1926 Returns nil if element is not found in the list."
1929 (while (and list (not found))
1930 (if (eq element (car list))
1932 (setq count (1+ count)
1936 (defun js2-find-if (predicate list)
1937 "Find first item satisfying PREDICATE in LIST."
1939 (while (and list (not result))
1940 (if (funcall predicate (car list))
1941 (setq result (car list)))
1942 (setq list (cdr list)))
1945 (defmacro js2-time (form)
1946 "Evaluate FORM, discard result, and return elapsed time in sec."
1948 (let ((beg (make-symbol "--js2-time-beg--"))
1949 (delta (make-symbol "--js2-time-end--")))
1950 `(let ((,beg (current-time))
1953 (/ (truncate (* (- (float-time (current-time))
1958 (defsubst js2-same-line (pos)
1959 "Return t if POS is on the same line as current point."
1960 (and (>= pos (point-at-bol))
1961 (<= pos (point-at-eol))))
1963 (defun js2-code-bug ()
1964 "Signal an error when we encounter an unexpected code path."
1965 (error "failed assertion"))
1967 (defsubst js2-record-text-property (beg end prop value)
1968 "Record a text property to set when parsing finishes."
1969 (push (list beg end prop value) js2-mode-deferred-properties))
1971 ;; I'd like to associate errors with nodes, but for now the
1972 ;; easiest thing to do is get the context info from the last token.
1973 (defun js2-record-parse-error (msg &optional arg pos len)
1974 (push (list (list msg arg)
1975 (or pos js2-token-beg)
1976 (or len (- js2-token-end js2-token-beg)))
1979 (defun js2-report-error (msg &optional msg-arg pos len)
1980 "Signal a syntax error or record a parse error."
1981 (if js2-recover-from-parse-errors
1982 (js2-record-parse-error msg msg-arg pos len)
1983 (signal 'js2-syntax-error
1987 (goto-char js2-ts-cursor)
1991 (defun js2-report-warning (msg &optional msg-arg pos len face)
1992 (if js2-compiler-report-warning-as-error
1993 (js2-report-error msg msg-arg pos len)
1994 (push (list (list msg msg-arg)
1995 (or pos js2-token-beg)
1996 (or len (- js2-token-end js2-token-beg))
1998 js2-parsed-warnings)))
2000 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2001 (if js2-compiler-strict-mode
2002 (js2-report-warning msg-id msg-arg beg
2003 (and beg end (- end beg)))))
2005 (put 'js2-syntax-error 'error-conditions
2006 '(error syntax-error js2-syntax-error))
2007 (put 'js2-syntax-error 'error-message "Syntax error")
2009 (put 'js2-parse-error 'error-conditions
2010 '(error parse-error js2-parse-error))
2011 (put 'js2-parse-error 'error-message "Parse error")
2013 (defmacro js2-clear-flag (flags flag)
2014 `(setq ,flags (logand ,flags (lognot ,flag))))
2016 (defmacro js2-set-flag (flags flag)
2017 "Logical-or FLAG into FLAGS."
2018 `(setq ,flags (logior ,flags ,flag)))
2020 (defsubst js2-flag-set-p (flags flag)
2021 (/= 0 (logand flags flag)))
2023 (defsubst js2-flag-not-set-p (flags flag)
2024 (zerop (logand flags flag)))
2026 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2027 "Evaluate BODY with the _ character set to be word-syntax."
2028 (declare (indent 0) (debug t))
2029 (let ((old-syntax (make-symbol "old-syntax")))
2030 `(let ((,old-syntax (string (char-syntax ?_))))
2033 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2035 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2037 (defsubst js2-char-uppercase-p (c)
2038 "Return t if C is an uppercase character.
2039 Handles unicode and latin chars properly."
2040 (/= c (downcase c)))
2042 (defsubst js2-char-lowercase-p (c)
2043 "Return t if C is an uppercase character.
2044 Handles unicode and latin chars properly."
2047 ;;; AST struct and function definitions
2049 ;; flags for ast node property 'member-type (used for e4x operators)
2050 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2051 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2052 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2054 (defsubst js2-relpos (pos anchor)
2055 "Convert POS to be relative to ANCHOR.
2056 If POS is nil, returns nil."
2057 (and pos (- pos anchor)))
2059 (defun js2-make-pad (indent)
2062 (make-string (* indent js2-basic-offset) ? )))
2064 (defun js2-visit-ast (node callback)
2065 "Visit every node in ast NODE with visitor CALLBACK.
2067 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2068 called twice: once to visit the node, and again after all the node's
2069 children have been processed. The END-P argument is nil on the first
2070 call and non-nil on the second call. The return value of the callback
2071 affects the traversal: if non-nil, the children of NODE are processed.
2072 If the callback returns nil, or if the node has no children, then the
2073 callback is called immediately with a non-nil END-P argument.
2075 The node traversal is approximately lexical-order, although there
2076 are currently no guarantees around this."
2078 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2080 (when (funcall callback node nil)
2083 ((eq vfunc 'js2-visit-none)
2084 nil) ; don't even bother calling it
2085 ;; Each AST node type has to define a `js2-visitor' function
2086 ;; that takes a node and a callback, and calls `js2-visit-ast'
2087 ;; on each child of the node.
2089 (funcall vfunc node callback))
2091 (error "%s does not define a visitor-traversal function"
2093 ;; call the end-visit
2094 (funcall callback node t))))
2096 (defstruct (js2-node
2097 (:constructor nil)) ; abstract
2098 "Base AST node type."
2099 (type -1) ; token type
2100 (pos -1) ; start position of this AST node in parsed input
2101 (len 1) ; num characters spanned by the node
2102 props ; optional node property list (an alist)
2103 parent) ; link to parent node; null for root
2105 (defsubst js2-node-get-prop (node prop &optional default)
2106 (or (cadr (assoc prop (js2-node-props node))) default))
2108 (defsubst js2-node-set-prop (node prop value)
2109 (setf (js2-node-props node)
2110 (cons (list prop value) (js2-node-props node))))
2112 (defun js2-fixup-starts (n nodes)
2113 "Adjust the start positions of NODES to be relative to N.
2114 Any node in the list may be nil, for convenience."
2115 (dolist (node nodes)
2117 (setf (js2-node-pos node) (- (js2-node-pos node)
2118 (js2-node-pos n))))))
2120 (defun js2-node-add-children (parent &rest nodes)
2121 "Set parent node of NODES to PARENT, and return PARENT.
2122 Does nothing if we're not recording parent links.
2123 If any given node in NODES is nil, doesn't record that link."
2124 (js2-fixup-starts parent nodes)
2125 (dolist (node nodes)
2127 (setf (js2-node-parent node) parent))))
2129 ;; Non-recursive since it's called a frightening number of times.
2130 (defun js2-node-abs-pos (n)
2131 (let ((pos (js2-node-pos n)))
2132 (while (setq n (js2-node-parent n))
2133 (setq pos (+ pos (js2-node-pos n))))
2136 (defsubst js2-node-abs-end (n)
2137 "Return absolute buffer position of end of N."
2138 (+ (js2-node-abs-pos n) (js2-node-len n)))
2140 ;; It's important to make sure block nodes have a Lisp list for the
2141 ;; child nodes, to limit printing recursion depth in an AST that
2142 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2143 ;; a sufficiently large vector tree.
2145 (defstruct (js2-block-node
2148 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2153 "A block of statements."
2154 kids) ; a Lisp list of the child statement nodes
2156 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2157 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2159 (defun js2-visit-block (ast callback)
2160 "Visit the `js2-block-node' children of AST."
2161 (dolist (kid (js2-block-node-kids ast))
2162 (js2-visit-ast kid callback)))
2164 (defun js2-print-block (n i)
2165 (let ((pad (js2-make-pad i)))
2167 (dolist (kid (js2-block-node-kids n))
2168 (js2-print-ast kid (1+ i)))
2171 (defstruct (js2-scope
2172 (:include js2-block-node)
2174 (:constructor make-js2-scope (&key (type js2-BLOCK)
2178 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2179 ;; I don't have one of those handy, so I'll use an alist for now.
2180 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2181 ;; and is much lighter-weight to construct (both CPU and mem).
2182 ;; The keys are interned strings (symbols) for faster lookup.
2183 ;; Should switch to hybrid alist/hashtable eventually.
2184 symbol-table ; an alist of (symbol . js2-symbol)
2185 parent-scope ; a `js2-scope'
2186 top) ; top-level `js2-scope' (script/function)
2188 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2189 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2191 (defun js2-node-get-enclosing-scope (node)
2192 "Return the innermost `js2-scope' node surrounding NODE.
2193 Returns nil if there is no enclosing scope node."
2194 (let ((parent (js2-node-parent node)))
2195 (while (not (js2-scope-p parent))
2196 (setq parent (js2-node-parent parent)))
2199 (defun js2-get-defining-scope (scope name)
2200 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2201 Returns `js2-scope' in which NAME is defined, or nil if not found."
2202 (let ((sym (if (symbolp name)
2208 (while (and scope continue)
2209 (if (and (setq table (js2-scope-symbol-table scope))
2213 (setq scope (js2-scope-parent-scope scope))))
2216 (defun js2-scope-get-symbol (scope name)
2217 "Return symbol table entry for NAME in SCOPE.
2218 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2219 (and (js2-scope-symbol-table scope)
2220 (cdr (assq (if (symbolp name)
2223 (js2-scope-symbol-table scope)))))
2225 (defun js2-scope-put-symbol (scope name symbol)
2226 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2227 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2228 (let* ((table (js2-scope-symbol-table scope))
2229 (sym (if (symbolp name) name (intern name)))
2230 (entry (assq sym table)))
2232 (setcdr entry symbol)
2233 (push (cons sym symbol)
2234 (js2-scope-symbol-table scope)))))
2236 (defstruct (js2-symbol
2238 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2239 "A symbol table entry."
2240 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2241 ;; js2-LET, or js2-CONST
2244 ast-node) ; a `js2-node'
2246 (defstruct (js2-error-node
2248 (:constructor nil) ; silence emacs21 byte-compiler
2249 (:constructor make-js2-error-node (&key (type js2-ERROR)
2252 "AST node representing a parse error.")
2254 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2255 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2257 (defstruct (js2-script-node
2258 (:include js2-scope)
2260 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2265 functions ; Lisp list of nested functions
2266 regexps ; Lisp list of (string . flags)
2267 symbols ; alist (every symbol gets unique index)
2269 var-names ; vector of string names
2270 consts ; bool-vector matching var-decls
2271 (temp-number 0)) ; for generating temp variables
2273 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2274 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2276 (defun js2-print-script (node indent)
2277 (dolist (kid (js2-block-node-kids node))
2278 (js2-print-ast kid indent)))
2280 (defstruct (js2-ast-root
2281 (:include js2-script-node)
2283 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2287 "The root node of a js2 AST."
2288 buffer ; the source buffer from which the code was parsed
2289 comments ; a Lisp list of comments, ordered by start position
2290 errors ; a Lisp list of errors found during parsing
2291 warnings ; a Lisp list of warnings found during parsing
2292 node-count) ; number of nodes in the tree, including the root
2294 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2295 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2297 (defun js2-visit-ast-root (ast callback)
2298 (dolist (kid (js2-ast-root-kids ast))
2299 (js2-visit-ast kid callback))
2300 (dolist (comment (js2-ast-root-comments ast))
2301 (js2-visit-ast comment callback)))
2303 (defstruct (js2-comment-node
2306 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2309 (format js2-ts-comment-type))))
2310 format) ; 'line, 'block, 'jsdoc or 'html
2312 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2313 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2315 (defun js2-print-comment (n i)
2316 ;; We really ought to link end-of-line comments to their nodes.
2317 ;; Or maybe we could add a new comment type, 'endline.
2318 (insert (js2-make-pad i)
2319 (js2-node-string n)))
2321 (defstruct (js2-expr-stmt-node
2324 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2328 "An expression statement."
2331 (defsubst js2-expr-stmt-node-set-has-result (node)
2332 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2333 (setf (js2-node-type node) js2-EXPR_RESULT))
2335 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2336 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2338 (defun js2-visit-expr-stmt-node (n v)
2339 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2341 (defun js2-print-expr-stmt-node (n indent)
2342 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2345 (defstruct (js2-loop-node
2346 (:include js2-scope)
2348 "Abstract supertype of loop nodes."
2349 body ; a `js2-block-node'
2350 lp ; position of left-paren, nil if omitted
2351 rp) ; position of right-paren, nil if omitted
2353 (defstruct (js2-do-node
2354 (:include js2-loop-node)
2356 (:constructor make-js2-do-node (&key (type js2-DO)
2364 "AST node for do-loop."
2365 condition ; while (expression)
2366 while-pos) ; buffer position of 'while' keyword
2368 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2369 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2371 (defun js2-visit-do-node (n v)
2372 (js2-visit-ast (js2-do-node-body n) v)
2373 (js2-visit-ast (js2-do-node-condition n) v))
2375 (defun js2-print-do-node (n i)
2376 (let ((pad (js2-make-pad i)))
2377 (insert pad "do {\n")
2378 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2379 (js2-print-ast kid (1+ i)))
2380 (insert pad "} while (")
2381 (js2-print-ast (js2-do-node-condition n) 0)
2384 (defstruct (js2-while-node
2385 (:include js2-loop-node)
2387 (:constructor make-js2-while-node (&key (type js2-WHILE)
2392 "AST node for while-loop."
2393 condition) ; while-condition
2395 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2396 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2398 (defun js2-visit-while-node (n v)
2399 (js2-visit-ast (js2-while-node-condition n) v)
2400 (js2-visit-ast (js2-while-node-body n) v))
2402 (defun js2-print-while-node (n i)
2403 (let ((pad (js2-make-pad i)))
2404 (insert pad "while (")
2405 (js2-print-ast (js2-while-node-condition n) 0)
2407 (js2-print-body (js2-while-node-body n) (1+ i))
2408 (insert pad "}\n")))
2410 (defstruct (js2-for-node
2411 (:include js2-loop-node)
2413 (:constructor make-js2-for-node (&key (type js2-FOR)
2418 "AST node for a C-style for-loop."
2419 init ; initialization expression
2420 condition ; loop condition
2421 update) ; update clause
2423 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2424 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2426 (defun js2-visit-for-node (n v)
2427 (js2-visit-ast (js2-for-node-init n) v)
2428 (js2-visit-ast (js2-for-node-condition n) v)
2429 (js2-visit-ast (js2-for-node-update n) v)
2430 (js2-visit-ast (js2-for-node-body n) v))
2432 (defun js2-print-for-node (n i)
2433 (let ((pad (js2-make-pad i)))
2434 (insert pad "for (")
2435 (js2-print-ast (js2-for-node-init n) 0)
2437 (js2-print-ast (js2-for-node-condition n) 0)
2439 (js2-print-ast (js2-for-node-update n) 0)
2441 (js2-print-body (js2-for-node-body n) (1+ i))
2442 (insert pad "}\n")))
2444 (defstruct (js2-for-in-node
2445 (:include js2-loop-node)
2447 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2456 "AST node for a for..in loop."
2457 iterator ; [var] foo in ...
2458 object ; object over which we're iterating
2459 in-pos ; buffer position of 'in' keyword
2460 each-pos ; buffer position of 'each' keyword, if foreach-p
2461 foreach-p ; t if it's a for-each loop
2462 forof-p) ; t if it's a for-of loop
2464 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2465 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2467 (defun js2-visit-for-in-node (n v)
2468 (js2-visit-ast (js2-for-in-node-iterator n) v)
2469 (js2-visit-ast (js2-for-in-node-object n) v)
2470 (js2-visit-ast (js2-for-in-node-body n) v))
2472 (defun js2-print-for-in-node (n i)
2473 (let ((pad (js2-make-pad i))
2474 (foreach (js2-for-in-node-foreach-p n))
2475 (forof (js2-for-in-node-forof-p n)))
2480 (js2-print-ast (js2-for-in-node-iterator n) 0)
2484 (js2-print-ast (js2-for-in-node-object n) 0)
2486 (js2-print-body (js2-for-in-node-body n) (1+ i))
2487 (insert pad "}\n")))
2489 (defstruct (js2-return-node
2492 (:constructor make-js2-return-node (&key (type js2-RETURN)
2496 "AST node for a return statement."
2497 retval) ; expression to return, or 'undefined
2499 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2500 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2502 (defun js2-visit-return-node (n v)
2503 (js2-visit-ast (js2-return-node-retval n) v))
2505 (defun js2-print-return-node (n i)
2506 (insert (js2-make-pad i) "return")
2507 (when (js2-return-node-retval n)
2509 (js2-print-ast (js2-return-node-retval n) 0))
2512 (defstruct (js2-if-node
2515 (:constructor make-js2-if-node (&key (type js2-IF)
2522 "AST node for an if-statement."
2523 condition ; expression
2524 then-part ; statement or block
2525 else-pos ; optional buffer position of 'else' keyword
2526 else-part ; optional statement or block
2527 lp ; position of left-paren, nil if omitted
2528 rp) ; position of right-paren, nil if omitted
2530 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2531 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2533 (defun js2-visit-if-node (n v)
2534 (js2-visit-ast (js2-if-node-condition n) v)
2535 (js2-visit-ast (js2-if-node-then-part n) v)
2536 (js2-visit-ast (js2-if-node-else-part n) v))
2538 (defun js2-print-if-node (n i)
2539 (let ((pad (js2-make-pad i))
2540 (then-part (js2-if-node-then-part n))
2541 (else-part (js2-if-node-else-part n)))
2543 (js2-print-ast (js2-if-node-condition n) 0)
2545 (js2-print-body then-part (1+ i))
2550 ((js2-if-node-p else-part)
2552 (js2-print-body else-part i))
2554 (insert " else {\n")
2555 (js2-print-body else-part (1+ i))
2556 (insert pad "}\n")))))
2558 (defstruct (js2-try-node
2561 (:constructor make-js2-try-node (&key (type js2-TRY)
2567 "AST node for a try-statement."
2569 catch-clauses ; a Lisp list of `js2-catch-node'
2570 finally-block) ; a `js2-finally-node'
2572 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2573 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2575 (defun js2-visit-try-node (n v)
2576 (js2-visit-ast (js2-try-node-try-block n) v)
2577 (dolist (clause (js2-try-node-catch-clauses n))
2578 (js2-visit-ast clause v))
2579 (js2-visit-ast (js2-try-node-finally-block n) v))
2581 (defun js2-print-try-node (n i)
2582 (let ((pad (js2-make-pad i))
2583 (catches (js2-try-node-catch-clauses n))
2584 (finally (js2-try-node-finally-block n)))
2585 (insert pad "try {\n")
2586 (js2-print-body (js2-try-node-try-block n) (1+ i))
2589 (dolist (catch catches)
2590 (js2-print-ast catch i)))
2592 (js2-print-ast finally i)
2595 (defstruct (js2-catch-node
2598 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2606 "AST node for a catch clause."
2607 param ; destructuring form or simple name node
2608 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2609 guard-expr ; catch condition, a `js2-node'
2610 block ; statements, a `js2-block-node'
2611 lp ; buffer position of left-paren, nil if omitted
2612 rp) ; buffer position of right-paren, nil if omitted
2614 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2615 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2617 (defun js2-visit-catch-node (n v)
2618 (js2-visit-ast (js2-catch-node-param n) v)
2619 (when (js2-catch-node-guard-kwd n)
2620 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2621 (js2-visit-ast (js2-catch-node-block n) v))
2623 (defun js2-print-catch-node (n i)
2624 (let ((pad (js2-make-pad i))
2625 (guard-kwd (js2-catch-node-guard-kwd n))
2626 (guard-expr (js2-catch-node-guard-expr n)))
2628 (js2-print-ast (js2-catch-node-param n) 0)
2631 (js2-print-ast guard-expr 0))
2633 (js2-print-body (js2-catch-node-block n) (1+ i))
2636 (defstruct (js2-finally-node
2639 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2642 "AST node for a finally clause."
2643 body) ; a `js2-node', often but not always a block node
2645 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2646 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2648 (defun js2-visit-finally-node (n v)
2649 (js2-visit-ast (js2-finally-node-body n) v))
2651 (defun js2-print-finally-node (n i)
2652 (let ((pad (js2-make-pad i)))
2653 (insert " finally {\n")
2654 (js2-print-body (js2-finally-node-body n) (1+ i))
2655 (insert pad "}\n")))
2657 (defstruct (js2-switch-node
2660 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2666 "AST node for a switch statement."
2667 discriminant ; a `js2-node' (switch expression)
2668 cases ; a Lisp list of `js2-case-node'
2669 lp ; position of open-paren for discriminant, nil if omitted
2670 rp) ; position of close-paren for discriminant, nil if omitted
2672 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2673 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2675 (defun js2-visit-switch-node (n v)
2676 (js2-visit-ast (js2-switch-node-discriminant n) v)
2677 (dolist (c (js2-switch-node-cases n))
2678 (js2-visit-ast c v)))
2680 (defun js2-print-switch-node (n i)
2681 (let ((pad (js2-make-pad i))
2682 (cases (js2-switch-node-cases n)))
2683 (insert pad "switch (")
2684 (js2-print-ast (js2-switch-node-discriminant n) 0)
2686 (dolist (case cases)
2687 (js2-print-ast case i))
2688 (insert pad "}\n")))
2690 (defstruct (js2-case-node
2691 (:include js2-block-node)
2693 (:constructor make-js2-case-node (&key (type js2-CASE)
2696 "AST node for a case clause of a switch statement."
2697 expr) ; the case expression (nil for default)
2699 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2700 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2702 (defun js2-visit-case-node (n v)
2703 (js2-visit-ast (js2-case-node-expr n) v)
2704 (js2-visit-block n v))
2706 (defun js2-print-case-node (n i)
2707 (let ((pad (js2-make-pad i))
2708 (expr (js2-case-node-expr n)))
2711 (insert "default:\n")
2713 (js2-print-ast expr 0)
2715 (dolist (kid (js2-case-node-kids n))
2716 (js2-print-ast kid (1+ i)))))
2718 (defstruct (js2-throw-node
2721 (:constructor make-js2-throw-node (&key (type js2-THROW)
2724 "AST node for a throw statement."
2725 expr) ; the expression to throw
2727 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2728 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2730 (defun js2-visit-throw-node (n v)
2731 (js2-visit-ast (js2-throw-node-expr n) v))
2733 (defun js2-print-throw-node (n i)
2734 (insert (js2-make-pad i) "throw ")
2735 (js2-print-ast (js2-throw-node-expr n) 0)
2738 (defstruct (js2-with-node
2741 (:constructor make-js2-with-node (&key (type js2-WITH)
2745 "AST node for a with-statement."
2748 lp ; buffer position of left-paren around object, nil if omitted
2749 rp) ; buffer position of right-paren around object, nil if omitted
2751 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2752 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2754 (defun js2-visit-with-node (n v)
2755 (js2-visit-ast (js2-with-node-object n) v)
2756 (js2-visit-ast (js2-with-node-body n) v))
2758 (defun js2-print-with-node (n i)
2759 (let ((pad (js2-make-pad i)))
2760 (insert pad "with (")
2761 (js2-print-ast (js2-with-node-object n) 0)
2763 (js2-print-body (js2-with-node-body n) (1+ i))
2764 (insert pad "}\n")))
2766 (defstruct (js2-label-node
2769 (:constructor make-js2-label-node (&key (type js2-LABEL)
2772 "AST node for a statement label or case label."
2774 loop) ; for validating and code-generating continue-to-label
2776 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2777 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2779 (defun js2-print-label (n i)
2780 (insert (js2-make-pad i)
2781 (js2-label-node-name n)
2784 (defstruct (js2-labeled-stmt-node
2787 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2788 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2789 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2792 "AST node for a statement with one or more labels.
2793 Multiple labels for a statement are collapsed into the labels field."
2794 labels ; Lisp list of `js2-label-node'
2795 stmt) ; the statement these labels are for
2797 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2798 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2800 (defun js2-get-label-by-name (lbl-stmt name)
2801 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2802 Returns nil if no such label is in the list."
2803 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2805 (while (and label-list (not result))
2806 (if (string= (js2-label-node-name (car label-list)) name)
2807 (setq result (car label-list))
2808 (setq label-list (cdr label-list))))
2811 (defun js2-visit-labeled-stmt (n v)
2812 (dolist (label (js2-labeled-stmt-node-labels n))
2813 (js2-visit-ast label v))
2814 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2816 (defun js2-print-labeled-stmt (n i)
2817 (dolist (label (js2-labeled-stmt-node-labels n))
2818 (js2-print-ast label i))
2819 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2821 (defun js2-labeled-stmt-node-contains (node label)
2822 "Return t if NODE contains LABEL in its label set.
2823 NODE is a `js2-labels-node'. LABEL is an identifier."
2824 (loop for nl in (js2-labeled-stmt-node-labels node)
2825 if (string= label (js2-label-node-name nl))
2827 finally return nil))
2829 (defsubst js2-labeled-stmt-node-add-label (node label)
2830 "Add a `js2-label-node' to the label set for this statement."
2831 (setf (js2-labeled-stmt-node-labels node)
2832 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2834 (defstruct (js2-jump-node
2837 "Abstract supertype of break and continue nodes."
2838 label ; `js2-name-node' for location of label identifier, if present
2839 target) ; target js2-labels-node or loop/switch statement
2841 (defun js2-visit-jump-node (n v)
2842 ;; We don't visit the target, since it's a back-link.
2843 (js2-visit-ast (js2-jump-node-label n) v))
2845 (defstruct (js2-break-node
2846 (:include js2-jump-node)
2848 (:constructor make-js2-break-node (&key (type js2-BREAK)
2851 "AST node for a break statement.
2852 The label field is a `js2-name-node', possibly nil, for the named label
2853 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2854 is the target of the break - a label node or enclosing loop/switch statement.")
2856 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2857 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2859 (defun js2-print-break-node (n i)
2860 (insert (js2-make-pad i) "break")
2861 (when (js2-break-node-label n)
2863 (js2-print-ast (js2-break-node-label n) 0))
2866 (defstruct (js2-continue-node
2867 (:include js2-jump-node)
2869 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2872 "AST node for a continue statement.
2873 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2874 It is nil if continue specifies no label. The target field is the jump target:
2875 a `js2-label-node' or the innermost enclosing loop.")
2877 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2878 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2880 (defun js2-print-continue-node (n i)
2881 (insert (js2-make-pad i) "continue")
2882 (when (js2-continue-node-label n)
2884 (js2-print-ast (js2-continue-node-label n) 0))
2887 (defstruct (js2-function-node
2888 (:include js2-script-node)
2890 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2894 (form 'FUNCTION_STATEMENT)
2899 "AST node for a function declaration.
2900 The `params' field is a Lisp list of nodes. Each node is either a simple
2901 `js2-name-node', or if it's a destructuring-assignment parameter, a
2902 `js2-array-node' or `js2-object-node'."
2903 ftype ; FUNCTION, GETTER or SETTER
2904 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2905 name ; function name (a `js2-name-node', or nil if anonymous)
2906 params ; a Lisp list of destructuring forms or simple name nodes
2907 rest-p ; if t, the last parameter is rest parameter
2908 body ; a `js2-block-node' or expression node (1.8 only)
2909 lp ; position of arg-list open-paren, or nil if omitted
2910 rp ; position of arg-list close-paren, or nil if omitted
2911 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2912 needs-activation ; t if we need an activation object for this frame
2913 is-generator ; t if this function contains a yield
2914 member-expr) ; nonstandard Ecma extension from Rhino
2916 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2917 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2919 (defun js2-visit-function-node (n v)
2920 (js2-visit-ast (js2-function-node-name n) v)
2921 (dolist (p (js2-function-node-params n))
2922 (js2-visit-ast p v))
2923 (js2-visit-ast (js2-function-node-body n) v))
2925 (defun js2-print-function-node (n i)
2926 (let ((pad (js2-make-pad i))
2927 (getter (js2-node-get-prop n 'GETTER_SETTER))
2928 (name (js2-function-node-name n))
2929 (params (js2-function-node-params n))
2930 (rest-p (js2-function-node-rest-p n))
2931 (body (js2-function-node-body n))
2932 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2934 (insert pad "function"))
2937 (js2-print-ast name 0))
2939 (loop with len = (length params)
2943 (when (and rest-p (= count len))
2945 (js2-print-ast param 0)
2951 ;; TODO: fix this to be smarter about indenting, etc.
2952 (js2-print-body body (1+ i))
2957 (defun js2-function-name (node)
2958 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2959 (and (js2-function-node-name node)
2960 (js2-name-node-name (js2-function-node-name node))))
2962 ;; Having this be an expression node makes it more flexible.
2963 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2964 ;; that work better if you assume it's an expression. Whenever we have
2965 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2966 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2967 (defstruct (js2-var-decl-node
2970 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2974 "AST node for a variable declaration list (VAR, CONST or LET).
2975 The node bounds differ depending on the declaration type. For VAR or
2976 CONST declarations, the bounds include the var/const keyword. For LET
2977 declarations, the node begins at the position of the first child."
2978 kids ; a Lisp list of `js2-var-init-node' structs.
2979 decl-type) ; js2-VAR, js2-CONST or js2-LET
2981 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
2982 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
2984 (defun js2-visit-var-decl (n v)
2985 (dolist (kid (js2-var-decl-node-kids n))
2986 (js2-visit-ast kid v)))
2988 (defun js2-print-var-decl (n i)
2989 (let ((pad (js2-make-pad i))
2990 (tt (js2-var-decl-node-decl-type n)))
2993 ((= tt js2-VAR) "var ")
2994 ((= tt js2-LET) "let ")
2995 ((= tt js2-CONST) "const ")
2997 (error "malformed var-decl node"))))
2998 (loop with kids = (js2-var-decl-node-kids n)
2999 with len = (length kids)
3003 (js2-print-ast kid 0)
3007 (defstruct (js2-var-init-node
3010 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3014 "AST node for a variable declaration.
3015 The type field will be js2-CONST for a const decl."
3016 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3017 initializer) ; initializer expression, a `js2-node'
3019 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3020 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3022 (defun js2-visit-var-init-node (n v)
3023 (js2-visit-ast (js2-var-init-node-target n) v)
3024 (js2-visit-ast (js2-var-init-node-initializer n) v))
3026 (defun js2-print-var-init-node (n i)
3027 (let ((pad (js2-make-pad i))
3028 (name (js2-var-init-node-target n))
3029 (init (js2-var-init-node-initializer n)))
3031 (js2-print-ast name 0)
3034 (js2-print-ast init 0))))
3036 (defstruct (js2-cond-node
3039 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3046 "AST node for the ternary operator"
3050 q-pos ; buffer position of ?
3051 c-pos) ; buffer position of :
3053 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3054 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3056 (defun js2-visit-cond-node (n v)
3057 (js2-visit-ast (js2-cond-node-test-expr n) v)
3058 (js2-visit-ast (js2-cond-node-true-expr n) v)
3059 (js2-visit-ast (js2-cond-node-false-expr n) v))
3061 (defun js2-print-cond-node (n i)
3062 (let ((pad (js2-make-pad i)))
3064 (js2-print-ast (js2-cond-node-test-expr n) 0)
3066 (js2-print-ast (js2-cond-node-true-expr n) 0)
3068 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3070 (defstruct (js2-infix-node
3073 (:constructor make-js2-infix-node (&key type
3077 "Represents infix expressions.
3078 Includes assignment ops like `|=', and the comma operator.
3079 The type field inherited from `js2-node' holds the operator."
3080 op-pos ; buffer position where operator begins
3081 left ; any `js2-node'
3082 right) ; any `js2-node'
3084 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3085 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3087 (defun js2-visit-infix-node (n v)
3088 (js2-visit-ast (js2-infix-node-left n) v)
3089 (js2-visit-ast (js2-infix-node-right n) v))
3091 (defconst js2-operator-tokens
3092 (let ((table (make-hash-table :test 'eq))
3094 (list (cons js2-IN "in")
3095 (cons js2-TYPEOF "typeof")
3096 (cons js2-INSTANCEOF "instanceof")
3097 (cons js2-DELPROP "delete")
3098 (cons js2-COMMA ",")
3099 (cons js2-COLON ":")
3104 (cons js2-BITOR "|")
3105 (cons js2-BITXOR "^")
3106 (cons js2-BITAND "&")
3115 (cons js2-URSH ">>>")
3116 (cons js2-ADD "+") ; infix plus
3117 (cons js2-SUB "-") ; infix minus
3122 (cons js2-BITNOT "~")
3123 (cons js2-POS "+") ; unary plus
3124 (cons js2-NEG "-") ; unary minus
3125 (cons js2-SHEQ "===") ; shallow equality
3126 (cons js2-SHNE "!==") ; shallow inequality
3127 (cons js2-ASSIGN "=")
3128 (cons js2-ASSIGN_BITOR "|=")
3129 (cons js2-ASSIGN_BITXOR "^=")
3130 (cons js2-ASSIGN_BITAND "&=")
3131 (cons js2-ASSIGN_LSH "<<=")
3132 (cons js2-ASSIGN_RSH ">>=")
3133 (cons js2-ASSIGN_URSH ">>>=")
3134 (cons js2-ASSIGN_ADD "+=")
3135 (cons js2-ASSIGN_SUB "-=")
3136 (cons js2-ASSIGN_MUL "*=")
3137 (cons js2-ASSIGN_DIV "/=")
3138 (cons js2-ASSIGN_MOD "%="))))
3139 (loop for (k . v) in tokens do
3140 (puthash k v table))
3143 (defun js2-print-infix-node (n i)
3144 (let* ((tt (js2-node-type n))
3145 (op (gethash tt js2-operator-tokens)))
3147 (error "unrecognized infix operator %s" (js2-node-type n)))
3148 (insert (js2-make-pad i))
3149 (js2-print-ast (js2-infix-node-left n) 0)
3150 (unless (= tt js2-COMMA)
3154 (js2-print-ast (js2-infix-node-right n) 0)))
3156 (defstruct (js2-assign-node
3157 (:include js2-infix-node)
3159 (:constructor make-js2-assign-node (&key type
3163 "Represents any assignment.
3164 The type field holds the actual assignment operator.")
3166 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3167 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3169 (defstruct (js2-unary-node
3172 (:constructor make-js2-unary-node (&key type ; required
3175 "AST node type for unary operator nodes.
3176 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3177 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3178 property is added if the operator follows the operand."
3179 operand) ; a `js2-node' expression
3181 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3182 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3184 (defun js2-visit-unary-node (n v)
3185 (js2-visit-ast (js2-unary-node-operand n) v))
3187 (defun js2-print-unary-node (n i)
3188 (let* ((tt (js2-node-type n))
3189 (op (gethash tt js2-operator-tokens))
3190 (postfix (js2-node-get-prop n 'postfix)))
3192 (error "unrecognized unary operator %s" tt))
3193 (insert (js2-make-pad i))
3196 (if (or (= tt js2-TYPEOF)
3199 (js2-print-ast (js2-unary-node-operand n) 0)
3203 (defstruct (js2-let-node
3204 (:include js2-scope)
3206 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3210 "AST node for a let expression or a let statement.
3211 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3212 vars ; a `js2-var-decl-node'
3213 body ; a `js2-node' representing the expression or body block
3217 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3218 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3220 (defun js2-visit-let-node (n v)
3221 (js2-visit-ast (js2-let-node-vars n) v)
3222 (js2-visit-ast (js2-let-node-body n) v))
3224 (defun js2-print-let-node (n i)
3225 (insert (js2-make-pad i) "let (")
3226 (js2-print-ast (js2-let-node-vars n) 0)
3228 (js2-print-ast (js2-let-node-body n) i))
3230 (defstruct (js2-keyword-node
3233 (:constructor make-js2-keyword-node (&key type
3235 (len (- js2-ts-cursor pos)))))
3236 "AST node representing a literal keyword such as `null'.
3237 Used for `null', `this', `true', `false' and `debugger'.
3238 The node type is set to js2-NULL, js2-THIS, etc.")
3240 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3241 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3243 (defun js2-print-keyword-node (n i)
3244 (insert (js2-make-pad i)
3245 (let ((tt (js2-node-type n)))
3247 ((= tt js2-THIS) "this")
3248 ((= tt js2-NULL) "null")
3249 ((= tt js2-TRUE) "true")
3250 ((= tt js2-FALSE) "false")
3251 ((= tt js2-DEBUGGER) "debugger")
3252 (t (error "Invalid keyword literal type: %d" tt))))))
3254 (defsubst js2-this-node-p (node)
3255 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3256 (eq (js2-node-type node) js2-THIS))
3258 (defstruct (js2-new-node
3261 (:constructor make-js2-new-node (&key (type js2-NEW)
3266 "AST node for new-expression such as new Foo()."
3267 target ; an identifier or reference
3268 args ; a Lisp list of argument nodes
3269 lp ; position of left-paren, nil if omitted
3270 rp ; position of right-paren, nil if omitted
3271 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3273 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3274 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3276 (defun js2-visit-new-node (n v)
3277 (js2-visit-ast (js2-new-node-target n) v)
3278 (dolist (arg (js2-new-node-args n))
3279 (js2-visit-ast arg v))
3280 (js2-visit-ast (js2-new-node-initializer n) v))
3282 (defun js2-print-new-node (n i)
3283 (insert (js2-make-pad i) "new ")
3284 (js2-print-ast (js2-new-node-target n))
3286 (js2-print-list (js2-new-node-args n))
3288 (when (js2-new-node-initializer n)
3290 (js2-print-ast (js2-new-node-initializer n))))
3292 (defstruct (js2-name-node
3295 (:constructor make-js2-name-node (&key (type js2-NAME)
3297 (len (- js2-ts-cursor
3299 (name js2-ts-string))))
3300 "AST node for a JavaScript identifier"
3302 scope) ; a `js2-scope' (optional, used for codegen)
3304 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3305 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3307 (defun js2-print-name-node (n i)
3308 (insert (js2-make-pad i)
3309 (js2-name-node-name n)))
3311 (defsubst js2-name-node-length (node)
3312 "Return identifier length of NODE, a `js2-name-node'.
3313 Returns 0 if NODE is nil or its identifier field is nil."
3315 (length (js2-name-node-name node))
3318 (defstruct (js2-number-node
3321 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3323 (len (- js2-ts-cursor
3325 (value js2-ts-string)
3326 (num-value js2-ts-number))))
3327 "AST node for a number literal."
3328 value ; the original string, e.g. "6.02e23"
3329 num-value) ; the parsed number value
3331 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3332 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3334 (defun js2-print-number-node (n i)
3335 (insert (js2-make-pad i)
3336 (number-to-string (js2-number-node-num-value n))))
3338 (defstruct (js2-regexp-node
3341 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3343 (len (- js2-ts-cursor
3346 "AST node for a regular expression literal."
3347 value ; the regexp string, without // delimiters
3348 flags) ; a string of flags, e.g. `mi'.
3350 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3351 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3353 (defun js2-print-regexp (n i)
3354 (insert (js2-make-pad i)
3356 (js2-regexp-node-value n)
3358 (if (js2-regexp-node-flags n)
3359 (insert (js2-regexp-node-flags n))))
3361 (defstruct (js2-string-node
3364 (:constructor make-js2-string-node (&key (type js2-STRING)
3366 (len (- js2-ts-cursor
3368 (value js2-ts-string))))
3370 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3371 You can tell the quote type by looking at the first character."
3372 value) ; the characters of the string, including the quotes
3374 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3375 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3377 (defun js2-print-string-node (n i)
3378 (insert (js2-make-pad i)
3379 (js2-node-string n)))
3381 (defstruct (js2-array-node
3384 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3387 "AST node for an array literal."
3388 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3390 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3391 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3393 (defun js2-visit-array-node (n v)
3394 (dolist (e (js2-array-node-elems n))
3395 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3397 (defun js2-print-array-node (n i)
3398 (insert (js2-make-pad i) "[")
3399 (js2-print-list (js2-array-node-elems n))
3402 (defstruct (js2-object-node
3405 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3409 "AST node for an object literal expression.
3410 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3411 The latter represents abbreviation in destructuring expressions."
3414 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3415 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3417 (defun js2-visit-object-node (n v)
3418 (dolist (e (js2-object-node-elems n))
3419 (js2-visit-ast e v)))
3421 (defun js2-print-object-node (n i)
3422 (insert (js2-make-pad i) "{")
3423 (js2-print-list (js2-object-node-elems n))
3426 (defstruct (js2-object-prop-node
3427 (:include js2-infix-node)
3429 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3433 "AST node for an object literal prop:value entry.
3434 The `left' field is the property: a name node, string node or number node.
3435 The `right' field is a `js2-node' representing the initializer value.")
3437 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3438 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3440 (defun js2-print-object-prop-node (n i)
3441 (insert (js2-make-pad i))
3442 (js2-print-ast (js2-object-prop-node-left n) 0)
3444 (js2-print-ast (js2-object-prop-node-right n) 0))
3446 (defstruct (js2-getter-setter-node
3447 (:include js2-infix-node)
3449 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3452 "AST node for a getter/setter property in an object literal.
3453 The `left' field is the `js2-name-node' naming the getter/setter prop.
3454 The `right' field is always an anonymous `js2-function-node' with a node
3455 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3457 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3458 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3460 (defun js2-print-getter-setter (n i)
3461 (let ((pad (js2-make-pad i))
3462 (left (js2-getter-setter-node-left n))
3463 (right (js2-getter-setter-node-right n)))
3465 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3466 (js2-print-ast left 0)
3467 (js2-print-ast right 0)))
3469 (defstruct (js2-prop-get-node
3470 (:include js2-infix-node)
3472 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3475 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3477 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3478 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3480 (defun js2-visit-prop-get-node (n v)
3481 (js2-visit-ast (js2-prop-get-node-left n) v)
3482 (js2-visit-ast (js2-prop-get-node-right n) v))
3484 (defun js2-print-prop-get-node (n i)
3485 (insert (js2-make-pad i))
3486 (js2-print-ast (js2-prop-get-node-left n) 0)
3488 (js2-print-ast (js2-prop-get-node-right n) 0))
3490 (defstruct (js2-elem-get-node
3493 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3497 "AST node for an array index expression such as foo[bar]."
3498 target ; a `js2-node' - the expression preceding the "."
3499 element ; a `js2-node' - the expression in brackets
3500 lb ; position of left-bracket, nil if omitted
3501 rb) ; position of right-bracket, nil if omitted
3503 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3504 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3506 (defun js2-visit-elem-get-node (n v)
3507 (js2-visit-ast (js2-elem-get-node-target n) v)
3508 (js2-visit-ast (js2-elem-get-node-element n) v))
3510 (defun js2-print-elem-get-node (n i)
3511 (insert (js2-make-pad i))
3512 (js2-print-ast (js2-elem-get-node-target n) 0)
3514 (js2-print-ast (js2-elem-get-node-element n) 0)
3517 (defstruct (js2-call-node
3520 (:constructor make-js2-call-node (&key (type js2-CALL)
3524 "AST node for a JavaScript function call."
3525 target ; a `js2-node' evaluating to the function to call
3526 args ; a Lisp list of `js2-node' arguments
3527 lp ; position of open-paren, or nil if missing
3528 rp) ; position of close-paren, or nil if missing
3530 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3531 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3533 (defun js2-visit-call-node (n v)
3534 (js2-visit-ast (js2-call-node-target n) v)
3535 (dolist (arg (js2-call-node-args n))
3536 (js2-visit-ast arg v)))
3538 (defun js2-print-call-node (n i)
3539 (insert (js2-make-pad i))
3540 (js2-print-ast (js2-call-node-target n) 0)
3542 (js2-print-list (js2-call-node-args n))
3545 (defstruct (js2-yield-node
3548 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3551 "AST node for yield statement or expression."
3552 value) ; optional: value to be yielded
3554 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3555 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3557 (defun js2-visit-yield-node (n v)
3558 (js2-visit-ast (js2-yield-node-value n) v))
3560 (defun js2-print-yield-node (n i)
3561 (insert (js2-make-pad i))
3563 (when (js2-yield-node-value n)
3565 (js2-print-ast (js2-yield-node-value n) 0)))
3567 (defstruct (js2-paren-node
3570 (:constructor make-js2-paren-node (&key (type js2-LP)
3573 "AST node for a parenthesized expression.
3574 In particular, used when the parens are syntactically optional,
3575 as opposed to required parens such as those enclosing an if-conditional."
3578 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3579 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3581 (defun js2-visit-paren-node (n v)
3582 (js2-visit-ast (js2-paren-node-expr n) v))
3584 (defun js2-print-paren-node (n i)
3585 (insert (js2-make-pad i))
3587 (js2-print-ast (js2-paren-node-expr n) 0)
3590 (defstruct (js2-array-comp-node
3591 (:include js2-scope)
3593 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3598 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3599 result ; result expression (just after left-bracket)
3600 loops ; a Lisp list of `js2-array-comp-loop-node'
3601 filter ; guard/filter expression
3602 if-pos ; buffer pos of 'if' keyword, if present, else nil
3603 lp ; buffer position of if-guard left-paren, or nil if not present
3604 rp) ; buffer position of if-guard right-paren, or nil if not present
3606 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3607 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3609 (defun js2-visit-array-comp-node (n v)
3610 (js2-visit-ast (js2-array-comp-node-result n) v)
3611 (dolist (l (js2-array-comp-node-loops n))
3612 (js2-visit-ast l v))
3613 (js2-visit-ast (js2-array-comp-node-filter n) v))
3615 (defun js2-print-array-comp-node (n i)
3616 (let ((pad (js2-make-pad i))
3617 (result (js2-array-comp-node-result n))
3618 (loops (js2-array-comp-node-loops n))
3619 (filter (js2-array-comp-node-filter n)))
3621 (js2-print-ast result 0)
3624 (js2-print-ast l 0))
3627 (js2-print-ast filter 0)
3631 (defstruct (js2-array-comp-loop-node
3632 (:include js2-for-in-node)
3634 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3642 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3644 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3645 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3647 (defun js2-visit-array-comp-loop (n v)
3648 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3649 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3651 (defun js2-print-array-comp-loop (n i)
3653 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3655 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3656 (if (js2-array-comp-loop-node-forof-p n)
3659 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3662 (defstruct (js2-empty-expr-node
3665 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3668 "AST node for an empty expression.")
3670 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3671 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3673 (defstruct (js2-xml-node
3674 (:include js2-block-node)
3676 (:constructor make-js2-xml-node (&key (type js2-XML)
3679 "AST node for initial parse of E4X literals.
3680 The kids field is a list of XML fragments, each a `js2-string-node' or
3681 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3683 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3684 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3686 (defun js2-print-xml-node (n i)
3687 (dolist (kid (js2-xml-node-kids n))
3688 (js2-print-ast kid i)))
3690 (defstruct (js2-xml-js-expr-node
3691 (:include js2-xml-node)
3693 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3696 "AST node for an embedded JavaScript {expression} in an E4X literal.
3697 The start and end fields correspond to the curly-braces."
3698 expr) ; a `js2-expr-node' of some sort
3700 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3701 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3703 (defun js2-visit-xml-js-expr (n v)
3704 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3706 (defun js2-print-xml-js-expr (n i)
3707 (insert (js2-make-pad i))
3709 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3712 (defstruct (js2-xml-dot-query-node
3713 (:include js2-infix-node)
3715 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3719 "AST node for an E4X foo.(bar) filter expression.
3720 Note that the left-paren is automatically the character immediately
3721 following the dot (.) in the operator. No whitespace is permitted
3722 between the dot and the lp by the scanner."
3725 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3726 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3728 (defun js2-print-xml-dot-query (n i)
3729 (insert (js2-make-pad i))
3730 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3732 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3735 (defstruct (js2-xml-ref-node
3737 (:constructor nil)) ; abstract
3738 "Base type for E4X XML attribute-access or property-get expressions.
3739 Such expressions can take a variety of forms. The general syntax has
3742 - (optional) an @ (specifying an attribute access)
3743 - (optional) a namespace (a `js2-name-node') and double-colon
3744 - (required) either a `js2-name-node' or a bracketed [expression]
3746 The property-name expressions (examples: ns::name, @name) are
3747 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3748 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3750 This node type (or more specifically, its subclasses) will sometimes
3751 be the right-hand child of a `js2-prop-get-node' or a
3752 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3753 The `js2-xml-ref-node' may also be a standalone primary expression with
3754 no explicit target, which is valid in certain expression contexts such as
3756 company..employee.(@id < 100)
3758 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3759 expression whose parent is a `js2-xml-dot-query-node'."
3764 (defsubst js2-xml-ref-node-attr-access-p (node)
3765 "Return non-nil if this expression began with an @-token."
3766 (and (numberp (js2-xml-ref-node-at-pos node))
3767 (plusp (js2-xml-ref-node-at-pos node))))
3769 (defstruct (js2-xml-prop-ref-node
3770 (:include js2-xml-ref-node)
3772 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3777 "AST node for an E4X XML [expr] property-ref expression.
3778 The JavaScript syntax is an optional @, an optional ns::, and a name.
3780 [ '@' ] [ name '::' ] name
3782 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3783 @ns::*, @*::attr, @*::*, and @*.
3785 The node starts at the @ token, if present. Otherwise it starts at the
3786 namespace name. The node bounds extend through the closing right-bracket,
3787 or if it is missing due to a syntax error, through the end of the index
3791 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3792 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3794 (defun js2-visit-xml-prop-ref-node (n v)
3795 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3796 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3798 (defun js2-print-xml-prop-ref-node (n i)
3799 (insert (js2-make-pad i))
3800 (if (js2-xml-ref-node-attr-access-p n)
3802 (when (js2-xml-prop-ref-node-namespace n)
3803 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3805 (if (js2-xml-prop-ref-node-propname n)
3806 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3808 (defstruct (js2-xml-elem-ref-node
3809 (:include js2-xml-ref-node)
3811 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3816 "AST node for an E4X XML [expr] member-ref expression.
3819 [ '@' ] [ name '::' ] '[' expr ']'
3821 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3823 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3824 is not a legal E4X XML element-ref expression, since it's already used
3825 for standard JavaScript element-get array indexing. Hence, a
3826 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3827 non-nil namespace node, or both.
3829 The node starts at the @ token, if present. Otherwise it starts
3830 at the namespace name. The node bounds extend through the closing
3831 right-bracket, or if it is missing due to a syntax error, through the
3832 end of the index expression."
3833 expr ; the bracketed index expression
3837 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3838 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3840 (defun js2-visit-xml-elem-ref-node (n v)
3841 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3842 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3844 (defun js2-print-xml-elem-ref-node (n i)
3845 (insert (js2-make-pad i))
3846 (if (js2-xml-ref-node-attr-access-p n)
3848 (when (js2-xml-elem-ref-node-namespace n)
3849 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3852 (if (js2-xml-elem-ref-node-expr n)
3853 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3856 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3858 (defstruct (js2-xml-start-tag-node
3859 (:include js2-xml-node)
3861 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3865 "AST node for an XML start-tag. Not currently used.
3866 The `kids' field is a Lisp list of child content nodes."
3867 name ; a `js2-xml-name-node'
3868 attrs ; a Lisp list of `js2-xml-attr-node'
3869 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3871 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3872 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3874 (defun js2-visit-xml-start-tag (n v)
3875 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3876 (dolist (attr (js2-xml-start-tag-node-attrs n))
3877 (js2-visit-ast attr v))
3878 (js2-visit-block n v))
3880 (defun js2-print-xml-start-tag (n i)
3881 (insert (js2-make-pad i) "<")
3882 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3883 (when (js2-xml-start-tag-node-attrs n)
3885 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3888 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3889 ;; and add the end-tag to the kids list of the parent as well.
3890 (defstruct (js2-xml-end-tag-node
3891 (:include js2-xml-node)
3893 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3896 "AST node for an XML end-tag. Not currently used."
3897 name) ; a `js2-xml-name-node'
3899 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3900 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3902 (defun js2-visit-xml-end-tag (n v)
3903 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3905 (defun js2-print-xml-end-tag (n i)
3906 (insert (js2-make-pad i))
3908 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3911 (defstruct (js2-xml-name-node
3912 (:include js2-xml-node)
3914 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3916 len namespace kids)))
3917 "AST node for an E4X XML name. Not currently used.
3918 Any XML name can be qualified with a namespace, hence the namespace field.
3919 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3920 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3921 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3922 namespace) ; a `js2-string-node'
3924 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3925 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3927 (defun js2-visit-xml-name-node (n v)
3928 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3930 (defun js2-print-xml-name-node (n i)
3931 (insert (js2-make-pad i))
3932 (when (js2-xml-name-node-namespace n)
3933 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3935 (dolist (kid (js2-xml-name-node-kids n))
3936 (js2-print-ast kid 0)))
3938 (defstruct (js2-xml-pi-node
3939 (:include js2-xml-node)
3941 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3944 "AST node for an E4X XML processing instruction. Not currently used."
3945 name ; a `js2-xml-name-node'
3946 attrs) ; a list of `js2-xml-attr-node'
3948 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3949 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3951 (defun js2-visit-xml-pi-node (n v)
3952 (js2-visit-ast (js2-xml-pi-node-name n) v)
3953 (dolist (attr (js2-xml-pi-node-attrs n))
3954 (js2-visit-ast attr v)))
3956 (defun js2-print-xml-pi-node (n i)
3957 (insert (js2-make-pad i) "<?")
3958 (js2-print-ast (js2-xml-pi-node-name n))
3959 (when (js2-xml-pi-node-attrs n)
3961 (js2-print-list (js2-xml-pi-node-attrs n)))
3964 (defstruct (js2-xml-cdata-node
3965 (:include js2-xml-node)
3967 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3970 "AST node for a CDATA escape section. Not currently used."
3971 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3973 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3974 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3976 (defun js2-visit-xml-cdata-node (n v)
3977 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3979 (defun js2-print-xml-cdata-node (n i)
3980 (insert (js2-make-pad i))
3981 (js2-print-ast (js2-xml-cdata-node-content n)))
3983 (defstruct (js2-xml-attr-node
3984 (:include js2-xml-node)
3986 (:constructor make-js2-attr-node (&key (type js2-XML)
3989 eq-pos quote-type)))
3990 "AST node representing a foo='bar' XML attribute value. Not yet used."
3991 name ; a `js2-xml-name-node'
3992 value ; a `js2-xml-name-node'
3993 eq-pos ; buffer position of "=" sign
3994 quote-type) ; 'single or 'double
3996 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
3997 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
3999 (defun js2-visit-xml-attr-node (n v)
4000 (js2-visit-ast (js2-xml-attr-node-name n) v)
4001 (js2-visit-ast (js2-xml-attr-node-value n) v))
4003 (defun js2-print-xml-attr-node (n i)
4004 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4007 (insert (js2-make-pad i))
4008 (js2-print-ast (js2-xml-attr-node-name n) 0)
4010 (js2-print-ast (js2-xml-attr-node-value n) 0)
4013 (defstruct (js2-xml-text-node
4014 (:include js2-xml-node)
4016 (:constructor make-js2-text-node (&key (type js2-XML)
4019 "AST node for an E4X XML text node. Not currently used."
4020 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4022 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4023 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4025 (defun js2-visit-xml-text-node (n v)
4026 (js2-visit-ast (js2-xml-text-node-content n) v))
4028 (defun js2-print-xml-text-node (n i)
4029 (insert (js2-make-pad i))
4030 (dolist (kid (js2-xml-text-node-content n))
4031 (js2-print-ast kid)))
4033 (defstruct (js2-xml-comment-node
4034 (:include js2-xml-node)
4036 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4039 "AST node for E4X XML comment. Not currently used.")
4041 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4042 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4044 (defun js2-print-xml-comment (n i)
4045 (insert (js2-make-pad i)
4046 (js2-node-string n)))
4050 (defsubst js2-node-line (n)
4051 "Fetch the source line number at the start of node N.
4052 This is O(n) in the length of the source buffer; use prudently."
4053 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4055 (defsubst js2-block-node-kid (n i)
4056 "Return child I of node N, or nil if there aren't that many."
4057 (nth i (js2-block-node-kids n)))
4059 (defsubst js2-block-node-first (n)
4060 "Return first child of block node N, or nil if there is none."
4061 (first (js2-block-node-kids n)))
4063 (defun js2-node-root (n)
4064 "Return the root of the AST containing N.
4065 If N has no parent pointer, returns N."
4066 (let ((parent (js2-node-parent n)))
4068 (js2-node-root parent)
4071 (defsubst js2-node-short-name (n)
4072 "Return the short name of node N as a string, e.g. `js2-if-node'."
4073 (substring (symbol-name (aref n 0))
4074 (length "cl-struct-")))
4076 (defun js2-node-child-list (node)
4077 "Return the child list for NODE, a Lisp list of nodes.
4078 Works for block nodes, array nodes, obj literals, funarg lists,
4079 var decls and try nodes (for catch clauses). Note that you should call
4080 `js2-block-node-kids' on the function body for the body statements.
4081 Returns nil for zero-length child lists or unsupported nodes."
4083 ((js2-function-node-p node)
4084 (js2-function-node-params node))
4085 ((js2-block-node-p node)
4086 (js2-block-node-kids node))
4087 ((js2-try-node-p node)
4088 (js2-try-node-catch-clauses node))
4089 ((js2-array-node-p node)
4090 (js2-array-node-elems node))
4091 ((js2-object-node-p node)
4092 (js2-object-node-elems node))
4093 ((js2-call-node-p node)
4094 (js2-call-node-args node))
4095 ((js2-new-node-p node)
4096 (js2-new-node-args node))
4097 ((js2-var-decl-node-p node)
4098 (js2-var-decl-node-kids node))
4102 (defun js2-node-set-child-list (node kids)
4103 "Set the child list for NODE to KIDS."
4105 ((js2-function-node-p node)
4106 (setf (js2-function-node-params node) kids))
4107 ((js2-block-node-p node)
4108 (setf (js2-block-node-kids node) kids))
4109 ((js2-try-node-p node)
4110 (setf (js2-try-node-catch-clauses node) kids))
4111 ((js2-array-node-p node)
4112 (setf (js2-array-node-elems node) kids))
4113 ((js2-object-node-p node)
4114 (setf (js2-object-node-elems node) kids))
4115 ((js2-call-node-p node)
4116 (setf (js2-call-node-args node) kids))
4117 ((js2-new-node-p node)
4118 (setf (js2-new-node-args node) kids))
4119 ((js2-var-decl-node-p node)
4120 (setf (js2-var-decl-node-kids node) kids))
4122 (error "Unsupported node type: %s" (js2-node-short-name node))))
4125 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4126 (defconst js2-paren-expr-nodes
4127 '(cl-struct-js2-array-comp-loop-node
4128 cl-struct-js2-array-comp-node
4129 cl-struct-js2-call-node
4130 cl-struct-js2-catch-node
4131 cl-struct-js2-do-node
4132 cl-struct-js2-elem-get-node
4133 cl-struct-js2-for-in-node
4134 cl-struct-js2-for-node
4135 cl-struct-js2-function-node
4136 cl-struct-js2-if-node
4137 cl-struct-js2-let-node
4138 cl-struct-js2-new-node
4139 cl-struct-js2-paren-node
4140 cl-struct-js2-switch-node
4141 cl-struct-js2-while-node
4142 cl-struct-js2-with-node
4143 cl-struct-js2-xml-dot-query-node)
4144 "Node types that can have a parenthesized child expression.
4145 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4147 (defsubst js2-paren-expr-node-p (node)
4148 "Return t for nodes that typically have a parenthesized child expression.
4149 Useful for computing the indentation anchors for arg-lists and conditions.
4150 Note that it may return a false positive, for instance when NODE is
4151 a `js2-new-node' and there are no arguments or parentheses."
4152 (memq (aref node 0) js2-paren-expr-nodes))
4154 ;; Fake polymorphism... yech.
4155 (defun js2-node-lp (node)
4156 "Return relative left-paren position for NODE, if applicable.
4157 For `js2-elem-get-node' structs, returns left-bracket position.
4158 Note that the position may be nil in the case of a parse error."
4160 ((js2-elem-get-node-p node)
4161 (js2-elem-get-node-lb node))
4162 ((js2-loop-node-p node)
4163 (js2-loop-node-lp node))
4164 ((js2-function-node-p node)
4165 (js2-function-node-lp node))
4166 ((js2-if-node-p node)
4167 (js2-if-node-lp node))
4168 ((js2-new-node-p node)
4169 (js2-new-node-lp node))
4170 ((js2-call-node-p node)
4171 (js2-call-node-lp node))
4172 ((js2-paren-node-p node)
4174 ((js2-switch-node-p node)
4175 (js2-switch-node-lp node))
4176 ((js2-catch-node-p node)
4177 (js2-catch-node-lp node))
4178 ((js2-let-node-p node)
4179 (js2-let-node-lp node))
4180 ((js2-array-comp-node-p node)
4181 (js2-array-comp-node-lp node))
4182 ((js2-with-node-p node)
4183 (js2-with-node-lp node))
4184 ((js2-xml-dot-query-node-p node)
4185 (1+ (js2-infix-node-op-pos node)))
4187 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4189 ;; Fake polymorphism... blech.
4190 (defun js2-node-rp (node)
4191 "Return relative right-paren position for NODE, if applicable.
4192 For `js2-elem-get-node' structs, returns right-bracket position.
4193 Note that the position may be nil in the case of a parse error."
4195 ((js2-elem-get-node-p node)
4196 (js2-elem-get-node-rb node))
4197 ((js2-loop-node-p node)
4198 (js2-loop-node-rp node))
4199 ((js2-function-node-p node)
4200 (js2-function-node-rp node))
4201 ((js2-if-node-p node)
4202 (js2-if-node-rp node))
4203 ((js2-new-node-p node)
4204 (js2-new-node-rp node))
4205 ((js2-call-node-p node)
4206 (js2-call-node-rp node))
4207 ((js2-paren-node-p node)
4208 (1- (js2-node-len node)))
4209 ((js2-switch-node-p node)
4210 (js2-switch-node-rp node))
4211 ((js2-catch-node-p node)
4212 (js2-catch-node-rp node))
4213 ((js2-let-node-p node)
4214 (js2-let-node-rp node))
4215 ((js2-array-comp-node-p node)
4216 (js2-array-comp-node-rp node))
4217 ((js2-with-node-p node)
4218 (js2-with-node-rp node))
4219 ((js2-xml-dot-query-node-p node)
4220 (1+ (js2-xml-dot-query-node-rp node)))
4222 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4224 (defsubst js2-node-first-child (node)
4225 "Return the first element of `js2-node-child-list' for NODE."
4226 (car (js2-node-child-list node)))
4228 (defsubst js2-node-last-child (node)
4229 "Return the last element of `js2-node-last-child' for NODE."
4230 (car (last (js2-node-child-list node))))
4232 (defun js2-node-prev-sibling (node)
4233 "Return the previous statement in parent.
4234 Works for parents supported by `js2-node-child-list'.
4235 Returns nil if NODE is not in the parent, or PARENT is
4236 not a supported node, or if NODE is the first child."
4237 (let* ((p (js2-node-parent node))
4238 (kids (js2-node-child-list p))
4241 (not (eq node (cadr kids))))
4242 (setq kids (cdr kids)
4246 (defun js2-node-next-sibling (node)
4247 "Return the next statement in parent block.
4248 Returns nil if NODE is not in the block, or PARENT is not
4249 a block node, or if NODE is the last statement."
4250 (let* ((p (js2-node-parent node))
4251 (kids (js2-node-child-list p)))
4253 (not (eq node (car kids))))
4254 (setq kids (cdr kids)))
4257 (defun js2-node-find-child-before (pos parent &optional after)
4258 "Find the last child that starts before POS in parent.
4259 If AFTER is non-nil, returns first child starting after POS.
4260 POS is an absolute buffer position. PARENT is any node
4261 supported by `js2-node-child-list'.
4262 Returns nil if no applicable child is found."
4263 (let ((kids (if (js2-function-node-p parent)
4264 (js2-block-node-kids (js2-function-node-body parent))
4265 (js2-node-child-list parent)))
4266 (beg (if (js2-function-node-p parent)
4267 (js2-node-abs-pos (js2-function-node-body parent))
4268 (js2-node-abs-pos parent)))
4271 (setq fn (if after '>= '<))
4272 (while (and kids continue)
4273 (setq kid (car kids))
4274 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4276 continue (if after nil t))
4277 (setq continue (if after t nil)))
4278 (setq kids (cdr kids)))
4281 (defun js2-node-find-child-after (pos parent)
4282 "Find first child that starts after POS in parent.
4283 POS is an absolute buffer position. PARENT is any node
4284 supported by `js2-node-child-list'.
4285 Returns nil if no applicable child is found."
4286 (js2-node-find-child-before pos parent 'after))
4288 (defun js2-node-replace-child (pos parent new-node)
4289 "Replace node at index POS in PARENT with NEW-NODE.
4290 Only works for parents supported by `js2-node-child-list'."
4291 (let ((kids (js2-node-child-list parent))
4294 (setq kids (cdr kids)
4296 (setcar kids new-node)
4297 (js2-node-add-children parent new-node)))
4299 (defun js2-node-buffer (n)
4300 "Return the buffer associated with AST N.
4301 Returns nil if the buffer is not set as a property on the root
4302 node, or if parent links were not recorded during parsing."
4303 (let ((root (js2-node-root n)))
4305 (js2-ast-root-p root)
4306 (js2-ast-root-buffer root))))
4308 (defun js2-block-node-push (n kid)
4309 "Push js2-node KID onto the end of js2-block-node N's child list.
4310 KID is always added to the -end- of the kids list.
4311 Function also calls `js2-node-add-children' to add the parent link."
4312 (let ((kids (js2-node-child-list n)))
4314 (setcdr kids (nconc (cdr kids) (list kid)))
4315 (js2-node-set-child-list n (list kid)))
4316 (js2-node-add-children n kid)))
4318 (defun js2-node-string (node)
4319 (with-current-buffer (or (js2-node-buffer node)
4320 (error "No buffer available for node %s" node))
4321 (let ((pos (js2-node-abs-pos node)))
4322 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4324 ;; Container for storing the node we're looking for in a traversal.
4325 (js2-deflocal js2-discovered-node nil)
4327 ;; Keep track of absolute node position during traversals.
4328 (js2-deflocal js2-visitor-offset nil)
4330 (js2-deflocal js2-node-search-point nil)
4332 (when js2-mode-dev-mode-p
4333 (defun js2-find-node-at-point ()
4335 (let ((node (js2-node-at-point)))
4336 (message "%s" (or node "No node found at point"))))
4337 (defun js2-node-name-at-point ()
4339 (let ((node (js2-node-at-point)))
4340 (message "%s" (if node
4341 (js2-node-short-name node)
4342 "No node found at point.")))))
4344 (defun js2-node-at-point (&optional pos skip-comments)
4345 "Return AST node at POS, a buffer position, defaulting to current point.
4346 The `js2-mode-ast' variable must be set to the current parse tree.
4347 Signals an error if the AST (`js2-mode-ast') is nil.
4348 Always returns a node - if it can't find one, it returns the root.
4349 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4350 (let ((ast js2-mode-ast)
4353 (error "No JavaScript AST available"))
4354 ;; Look through comments first, since they may be inside nodes that
4355 ;; would otherwise report a match.
4356 (setq pos (or pos (point))
4357 result (if (> pos (js2-node-abs-end ast))
4359 (if (not skip-comments)
4360 (js2-comment-at-point pos))))
4362 (setq js2-discovered-node nil
4363 js2-visitor-offset 0
4364 js2-node-search-point pos)
4366 (catch 'js2-visit-done
4367 (js2-visit-ast ast #'js2-node-at-point-visitor))
4368 (setq js2-visitor-offset nil
4369 js2-node-search-point nil))
4370 (setq result js2-discovered-node))
4371 ;; may have found a comment beyond end of last child node,
4372 ;; since visiting the ast-root looks at the comment-list last.
4373 (if (and skip-comments
4374 (js2-comment-node-p result))
4376 (or result js2-mode-ast)))
4378 (defun js2-node-at-point-visitor (node end-p)
4379 (let ((rel-pos (js2-node-pos node))
4382 (point js2-node-search-point))
4385 ;; this evaluates to a non-nil return value, even if it's zero
4386 (decf js2-visitor-offset rel-pos))
4387 ;; we already looked for comments before visiting, and don't want them now
4388 ((js2-comment-node-p node)
4391 (setq abs-pos (incf js2-visitor-offset rel-pos)
4392 ;; we only want to use the node if the point is before
4393 ;; the last character position in the node, so we decrement
4394 ;; the absolute end by 1.
4395 abs-end (+ abs-pos (js2-node-len node) -1))
4397 ;; If this node starts after search-point, stop the search.
4399 (throw 'js2-visit-done nil))
4400 ;; If this node ends before the search-point, don't check kids.
4404 ;; Otherwise point is within this node, possibly in a child.
4405 (setq js2-discovered-node node)
4406 t)))))) ; keep processing kids to look for more specific match
4408 (defsubst js2-block-comment-p (node)
4409 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4410 (and (js2-comment-node-p node)
4411 (memq (js2-comment-node-format node) '(jsdoc block))))
4413 ;; TODO: put the comments in a vector and binary-search them instead
4414 (defun js2-comment-at-point (&optional pos)
4415 "Look through scanned comment nodes for one containing POS.
4416 POS is a buffer position that defaults to current point.
4417 Function returns nil if POS was not in any comment node."
4418 (let ((ast js2-mode-ast)
4419 (x (or pos (point)))
4422 (error "No JavaScript AST available"))
4424 ;; Comments are stored in lexical order.
4425 (dolist (comment (js2-ast-root-comments ast) nil)
4426 (setq beg (js2-node-abs-pos comment)
4427 end (+ beg (js2-node-len comment)))
4430 (throw 'done comment))))))
4432 (defun js2-mode-find-parent-fn (node)
4433 "Find function enclosing NODE.
4434 Returns nil if NODE is not inside a function."
4435 (setq node (js2-node-parent node))
4436 (while (and node (not (js2-function-node-p node)))
4437 (setq node (js2-node-parent node)))
4438 (and (js2-function-node-p node) node))
4440 (defun js2-mode-find-enclosing-fn (node)
4441 "Find function or root enclosing NODE."
4442 (if (js2-ast-root-p node)
4444 (setq node (js2-node-parent node))
4445 (while (not (or (js2-ast-root-p node)
4446 (js2-function-node-p node)))
4447 (setq node (js2-node-parent node)))
4450 (defun js2-mode-find-enclosing-node (beg end)
4451 "Find script or function fully enclosing BEG and END."
4452 (let ((node (js2-node-at-point beg))
4456 (if (or (js2-ast-root-p node)
4457 (and (js2-function-node-p node)
4458 (<= (setq pos (js2-node-abs-pos node)) beg)
4459 (>= (+ pos (js2-node-len node)) end)))
4461 (setq node (js2-node-parent node))))
4464 (defun js2-node-parent-script-or-fn (node)
4465 "Find script or function immediately enclosing NODE.
4466 If NODE is the ast-root, returns nil."
4467 (if (js2-ast-root-p node)
4469 (setq node (js2-node-parent node))
4470 (while (and node (not (or (js2-function-node-p node)
4471 (js2-script-node-p node))))
4472 (setq node (js2-node-parent node)))
4475 (defun js2-node-is-descendant (node ancestor)
4476 "Return t if NODE is a descendant of ANCESTOR."
4478 (not (eq node ancestor)))
4479 (setq node (js2-node-parent node)))
4482 ;;; visitor infrastructure
4484 (defun js2-visit-none (node callback)
4485 "Visitor for AST node that have no node children."
4488 (defun js2-print-none (node indent)
4489 "Visitor for AST node with no printed representation.")
4491 (defun js2-print-body (node indent)
4492 "Print a statement, or a block without braces."
4493 (if (js2-block-node-p node)
4494 (dolist (kid (js2-block-node-kids node))
4495 (js2-print-ast kid indent))
4496 (js2-print-ast node indent)))
4498 (defun js2-print-list (args &optional delimiter)
4499 (loop with len = (length args)
4503 (when arg (js2-print-ast arg 0))
4505 (insert (or delimiter ", ")))))
4507 (defun js2-print-tree (ast)
4508 "Prints an AST to the current buffer.
4509 Makes `js2-ast-parent-nodes' available to the printer functions."
4510 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4511 (js2-print-ast ast)))
4513 (defun js2-print-ast (node &optional indent)
4514 "Helper function for printing AST nodes.
4515 Requires `js2-ast-parent-nodes' to be non-nil.
4516 You should use `js2-print-tree' instead of this function."
4517 (let ((printer (get (aref node 0) 'js2-printer))
4519 (pos (js2-node-abs-pos node)))
4520 ;; TODO: wedge comments in here somewhere
4522 (funcall printer node i))))
4524 (defconst js2-side-effecting-tokens
4525 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4526 (dolist (tt (list js2-ASSIGN
4595 (if js2-instanceof-has-side-effects
4596 (aset tokens js2-INSTANCEOF t))
4599 (defun js2-node-has-side-effects (node)
4600 "Return t if NODE has side effects."
4601 (when node ; makes it easier to handle malformed expressions
4602 (let ((tt (js2-node-type node)))
4604 ;; This doubtless needs some work, since EXPR_VOID is used
4605 ;; in several ways in Rhino and I may not have caught them all.
4606 ;; I'll wait for people to notice incorrect warnings.
4607 ((and (= tt js2-EXPR_VOID)
4608 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4609 (let ((expr (js2-expr-stmt-node-expr node)))
4610 (or (js2-node-has-side-effects expr)
4611 (when (js2-string-node-p expr)
4612 (member (js2-string-node-value expr) '("use strict" "use asm"))))))
4614 (js2-node-has-side-effects (js2-infix-node-right node)))
4617 (or (js2-node-has-side-effects (js2-infix-node-right node))
4618 (js2-node-has-side-effects (js2-infix-node-left node))))
4620 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4621 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4622 ((js2-paren-node-p node)
4623 (js2-node-has-side-effects (js2-paren-node-expr node)))
4624 ((= tt js2-ERROR) ; avoid cascaded error messages
4627 (aref js2-side-effecting-tokens tt))))))
4629 (defconst js2-stmt-node-types
4633 js2-DEFAULT ; e4x "default xml namespace" statement
4645 "Node types that only appear in statement contexts.
4646 The list does not include nodes that always appear as the child
4647 of another specific statement type, such as switch-cases,
4648 catch and finally blocks, and else-clauses. The list also excludes
4649 nodes like yield, let and var, which may appear in either expression
4650 or statement context, and in the latter context always have a
4651 `js2-expr-stmt-node' parent. Finally, the list does not include
4652 functions or scripts, which are treated separately from statements
4653 by the JavaScript parser and runtime.")
4655 (defun js2-stmt-node-p (node)
4656 "Heuristic for figuring out if NODE is a statement.
4657 Some node types can appear in either an expression context or a
4658 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4659 For these node types in a statement context, the parent will be a
4660 `js2-expr-stmt-node'.
4661 Functions aren't included in the check."
4662 (memq (js2-node-type node) js2-stmt-node-types))
4664 (defun js2-mode-find-first-stmt (node)
4665 "Search upward starting from NODE looking for a statement.
4666 For purposes of this function, a `js2-function-node' counts."
4667 (while (not (or (js2-stmt-node-p node)
4668 (js2-function-node-p node)))
4669 (setq node (js2-node-parent node)))
4672 (defun js2-node-parent-stmt (node)
4673 "Return the node's first ancestor that is a statement.
4674 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4675 appearing in a statement context will have a parent that is a
4676 `js2-expr-stmt-node' that will be returned by this function."
4677 (let ((parent (js2-node-parent node)))
4678 (if (or (null parent)
4679 (js2-stmt-node-p parent)
4680 (and (js2-function-node-p parent)
4681 (not (eq (js2-function-node-form parent)
4682 'FUNCTION_EXPRESSION))))
4684 (js2-node-parent-stmt parent))))
4686 ;; In the Mozilla Rhino sources, Roshan James writes:
4687 ;; Does consistent-return analysis on the function body when strict mode is
4690 ;; function (x) { return (x+1) }
4694 ;; function (x) { if (x < 0) return (x+1); }
4696 ;; is not because the function can potentially return a value when the
4697 ;; condition is satisfied and if not, the function does not explicitly
4700 ;; This extends to checking mismatches such as "return" and "return <value>"
4701 ;; used in the same function. Warnings are not emitted if inconsistent
4702 ;; returns exist in code that can be statically shown to be unreachable.
4704 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4706 ;; emits no warning. However if the loop had a break statement, then a
4707 ;; warning would be emitted.
4709 ;; The consistency analysis looks at control structures such as loops, ifs,
4710 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4711 ;; warns the user about an inconsistent set of termination possibilities.
4713 ;; These flags enumerate the possible ways a statement/function can
4714 ;; terminate. These flags are used by endCheck() and by the Parser to
4715 ;; detect inconsistent return usage.
4717 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4718 ;; able to execute (example: throw, continue)
4720 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4721 ;; next one. Statement such as return dont. A compound statement may have
4722 ;; some branch that drops off control to the next statement.
4724 ;; END_RETURNS indicates that the statement can return with no value.
4725 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4727 ;; A compound statement such as
4731 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4733 (defconst js2-END_UNREACHED 0)
4734 (defconst js2-END_DROPS_OFF 1)
4735 (defconst js2-END_RETURNS 2)
4736 (defconst js2-END_RETURNS_VALUE 4)
4737 (defconst js2-END_YIELDS 8)
4739 (defun js2-has-consistent-return-usage (node)
4740 "Check that every return usage in a function body is consistent.
4741 Returns t if the function satisfies strict mode requirement."
4742 (let ((n (js2-end-check node)))
4743 ;; either it doesn't return a value in any branch...
4744 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4745 ;; or it returns a value (or is unreached) at every branch
4746 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4750 (defun js2-end-check-if (node)
4751 "Ensure that return usage in then/else blocks is consistent.
4752 If there is no else block, then the return statement can fall through.
4753 Returns logical OR of END_* flags"
4754 (let ((th (js2-if-node-then-part node))
4755 (el (js2-if-node-else-part node)))
4758 (logior (js2-end-check th) (if el
4760 js2-END_DROPS_OFF)))))
4762 (defun js2-end-check-switch (node)
4763 "Consistency of return statements is checked between the case statements.
4764 If there is no default, then the switch can fall through. If there is a
4765 default, we check to see if all code paths in the default return or if
4766 there is a code path that can fall through.
4767 Returns logical OR of END_* flags."
4768 (let ((rv js2-END_UNREACHED)
4770 ;; examine the cases
4772 (dolist (c (js2-switch-node-cases node))
4773 (if (js2-case-node-expr c)
4774 (js2-set-flag rv (js2-end-check-block c))
4775 (setq default-case c)
4776 (throw 'break nil))))
4777 ;; we don't care how the cases drop into each other
4778 (js2-clear-flag rv js2-END_DROPS_OFF)
4779 ;; examine the default
4780 (js2-set-flag rv (if default-case
4781 (js2-end-check default-case)
4785 (defun js2-end-check-try (node)
4786 "If the block has a finally, return consistency is checked in the
4787 finally block. If all code paths in the finally return, then the
4788 returns in the try-catch blocks don't matter. If there is a code path
4789 that does not return or if there is no finally block, the returns
4790 of the try and catch blocks are checked for mismatch.
4791 Returns logical OR of END_* flags."
4792 (let ((finally (js2-try-node-finally-block node))
4794 ;; check the finally if it exists
4795 (setq rv (if finally
4796 (js2-end-check (js2-finally-node-body finally))
4798 ;; If the finally block always returns, then none of the returns
4799 ;; in the try or catch blocks matter.
4800 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4801 (js2-clear-flag rv js2-END_DROPS_OFF)
4802 ;; examine the try block
4803 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4804 ;; check each catch block
4805 (dolist (cb (js2-try-node-catch-clauses node))
4806 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4809 (defun js2-end-check-loop (node)
4810 "Return statement in the loop body must be consistent.
4811 The default assumption for any kind of a loop is that it will eventually
4812 terminate. The only exception is a loop with a constant true condition.
4813 Code that follows such a loop is examined only if one can determine
4814 statically that there is a break out of the loop.
4816 for(... ; ... ; ...) {}
4821 Returns logical OR of END_* flags."
4822 (let ((rv (js2-end-check (js2-loop-node-body node)))
4824 ((js2-while-node-p node)
4825 (js2-while-node-condition node))
4826 ((js2-do-node-p node)
4827 (js2-do-node-condition node))
4828 ((js2-for-node-p node)
4829 (js2-for-node-condition node)))))
4831 ;; check to see if the loop condition is always true
4833 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4834 (js2-clear-flag rv js2-END_DROPS_OFF))
4836 ;; look for effect of breaks
4837 (js2-set-flag rv (js2-node-get-prop node
4842 (defun js2-end-check-block (node)
4843 "A general block of code is examined statement by statement.
4844 If any statement (even a compound one) returns in all branches, then
4845 subsequent statements are not examined.
4846 Returns logical OR of END_* flags."
4847 (let* ((rv js2-END_DROPS_OFF)
4848 (kids (js2-block-node-kids node))
4850 ;; Check each statment. If the statement can continue onto the next
4851 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4852 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4853 (js2-clear-flag rv js2-END_DROPS_OFF)
4854 (js2-set-flag rv (js2-end-check n))
4855 (setq kids (cdr kids)
4859 (defun js2-end-check-label (node)
4860 "A labeled statement implies that there may be a break to the label.
4861 The function processes the labeled statement and then checks the
4862 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4864 Returns logical OR of END_* flags."
4865 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4866 (logior rv (js2-node-get-prop node
4868 js2-END_UNREACHED))))
4870 (defun js2-end-check-break (node)
4871 "When a break is encountered annotate the statement being broken
4872 out of by setting its CONTROL_BLOCK_PROP property.
4873 Returns logical OR of END_* flags."
4874 (and (js2-break-node-target node)
4875 (js2-node-set-prop (js2-break-node-target node)
4880 (defun js2-end-check (node)
4881 "Examine the body of a function, doing a basic reachability analysis.
4882 Returns a combination of flags END_* flags that indicate
4883 how the function execution can terminate. These constitute only the
4884 pessimistic set of termination conditions. It is possible that at
4885 runtime certain code paths will never be actually taken. Hence this
4886 analysis will flag errors in cases where there may not be errors.
4887 Returns logical OR of END_* flags"
4890 ((js2-break-node-p node)
4891 (js2-end-check-break node))
4892 ((js2-expr-stmt-node-p node)
4893 (if (setq kid (js2-expr-stmt-node-expr node))
4896 ((or (js2-continue-node-p node)
4897 (js2-throw-node-p node))
4899 ((js2-return-node-p node)
4900 (if (setq kid (js2-return-node-retval node))
4901 js2-END_RETURNS_VALUE
4903 ((js2-loop-node-p node)
4904 (js2-end-check-loop node))
4905 ((js2-switch-node-p node)
4906 (js2-end-check-switch node))
4907 ((js2-labeled-stmt-node-p node)
4908 (js2-end-check-label node))
4909 ((js2-if-node-p node)
4910 (js2-end-check-if node))
4911 ((js2-try-node-p node)
4912 (js2-end-check-try node))
4913 ((js2-block-node-p node)
4914 (if (null (js2-block-node-kids node))
4916 (js2-end-check-block node)))
4917 ((js2-yield-node-p node)
4920 js2-END_DROPS_OFF))))
4922 (defun js2-always-defined-boolean-p (node)
4923 "Check if NODE always evaluates to true or false in boolean context.
4924 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4926 (let ((tt (js2-node-type node))
4929 ((or (= tt js2-FALSE) (= tt js2-NULL))
4934 (setq num (js2-number-node-num-value node))
4935 (if (and (not (eq num 0.0e+NaN))
4942 ;;; Scanner -- a port of Mozilla Rhino's lexer.
4943 ;; Corresponds to Rhino files Token.java and TokenStream.java.
4945 (defvar js2-tokens nil
4946 "List of all defined token names.") ; initialized in `js2-token-names'
4948 (defconst js2-token-names
4949 (let* ((names (make-vector js2-num-tokens -1))
4950 (case-fold-search nil) ; only match js2-UPPER_CASE
4951 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
4952 (loop for sym in syms
4955 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
4957 (aset names (symbol-value sym) ; code, e.g. 152
4959 (substring (symbol-name sym) 4))) ; name, e.g. "let"
4960 (push sym js2-tokens)))
4962 "Vector mapping int values to token string names, sans `js2-' prefix.")
4964 (defun js2-token-name (tok)
4965 "Return a string name for TOK, a token symbol or code.
4966 Signals an error if it's not a recognized token."
4969 (setq code (symbol-value tok)))
4972 (if (and (numberp code)
4974 (< code js2-num-tokens))
4975 (aref js2-token-names code)
4976 (error "Invalid token: %s" code)))))
4978 (defsubst js2-token-sym (tok)
4979 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
4980 (intern (js2-token-name tok)))
4982 (defconst js2-token-codes
4983 (let ((table (make-hash-table :test 'eq :size 256)))
4984 (loop for name across js2-token-names
4985 for sym = (intern (concat "js2-" (upcase name)))
4987 (puthash sym (symbol-value sym) table))
4988 ;; clean up a few that are "wrong" in Rhino's token codes
4989 (puthash 'js2-DELETE js2-DELPROP table)
4991 "Hashtable mapping token symbols to their bytecodes.")
4993 (defsubst js2-token-code (sym)
4994 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
4995 (or (gethash sym js2-token-codes)
4996 (error "Invalid token symbol: %s " sym))) ; signal code bug
4998 (defun js2-report-scan-error (msg &optional no-throw beg len)
4999 (setq js2-token-end js2-ts-cursor)
5000 (js2-report-error msg nil
5001 (or beg js2-token-beg)
5002 (or len (- js2-token-end js2-token-beg)))
5004 (throw 'return js2-ERROR)))
5006 (defun js2-get-string-from-buffer ()
5007 "Reverse the char accumulator and return it as a string."
5008 (setq js2-token-end js2-ts-cursor)
5009 (if js2-ts-string-buffer
5010 (apply #'string (nreverse js2-ts-string-buffer))
5013 ;; TODO: could potentially avoid a lot of consing by allocating a
5014 ;; char buffer the way Rhino does.
5015 (defsubst js2-add-to-string (c)
5016 (push c js2-ts-string-buffer))
5018 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5019 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5020 ;; any other character: when it's not part of the current token, we
5021 ;; unget it, allowing it to be read again by the following call.
5022 (defsubst js2-unget-char ()
5023 (decf js2-ts-cursor))
5025 ;; Rhino distinguishes \r and \n line endings. We don't need to
5026 ;; because we only scan from Emacs buffers, which always use \n.
5027 (defun js2-get-char ()
5028 "Read and return the next character from the input buffer.
5029 Increments `js2-ts-lineno' if the return value is a newline char.
5030 Updates `js2-ts-cursor' to the point after the returned char.
5031 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5032 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5034 ;; check for end of buffer
5035 (if (>= js2-ts-cursor (point-max))
5036 (setq js2-ts-hit-eof t
5037 js2-ts-cursor (1+ js2-ts-cursor)
5038 c js2-EOF_CHAR) ; return value
5039 ;; otherwise read next char
5040 (setq c (char-before (incf js2-ts-cursor)))
5041 ;; if we read a newline, update counters
5043 (setq js2-ts-line-start js2-ts-cursor
5044 js2-ts-lineno (1+ js2-ts-lineno)))
5045 ;; TODO: skip over format characters
5048 (defun js2-read-unicode-escape ()
5049 "Read a \\uNNNN sequence from the input.
5050 Assumes the ?\ and ?u have already been read.
5051 Returns the unicode character, or nil if it wasn't a valid character.
5052 Doesn't change the values of any scanner variables."
5053 ;; I really wish I knew a better way to do this, but I can't
5054 ;; find the Emacs function that takes a 16-bit int and converts
5055 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5056 ;; Have to first check that it's 4 hex characters or it may stop
5059 (let ((s (buffer-substring-no-properties js2-ts-cursor
5060 (+ 4 js2-ts-cursor))))
5061 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5062 (read (concat "?\\u" s))))))
5064 (defun js2-match-char (test)
5065 "Consume and return next character if it matches TEST, a character.
5066 Returns nil and consumes nothing if TEST is not the next character."
5067 (let ((c (js2-get-char)))
5073 (defun js2-peek-char ()
5078 (defun js2-java-identifier-start-p (c)
5081 (js2-char-uppercase-p c)
5082 (js2-char-lowercase-p c)))
5084 (defun js2-java-identifier-part-p (c)
5085 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5086 ;; TODO: make me Unicode-friendly. See comments above.
5089 (js2-char-uppercase-p c)
5090 (js2-char-lowercase-p c)
5091 (and (>= c ?0) (<= c ?9))))
5093 (defun js2-alpha-p (c)
5094 (cond ((and (<= ?A c) (<= c ?Z)) t)
5095 ((and (<= ?a c) (<= c ?z)) t)
5098 (defsubst js2-digit-p (c)
5099 (and (<= ?0 c) (<= c ?9)))
5101 (defun js2-js-space-p (c)
5103 (memq c '(#x20 #x9 #xB #xC #xD))
5106 ;; TODO: change this nil to check for Unicode space character
5109 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5111 (defun js2-skip-line ()
5112 "Skip to end of line."
5114 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5116 (setq js2-token-end js2-ts-cursor)))
5118 (defun js2-init-scanner (&optional buf line)
5119 "Create token stream for BUF starting on LINE.
5120 BUF defaults to `current-buffer' and LINE defaults to 1.
5122 A buffer can only have one scanner active at a time, which yields
5123 dramatically simpler code than using a defstruct. If you need to
5124 have simultaneous scanners in a buffer, copy the regions to scan
5126 (with-current-buffer (or buf (current-buffer))
5127 (setq js2-ts-dirty-line nil
5128 js2-ts-regexp-flags nil
5133 js2-ts-lineno (or line 1)
5134 js2-ts-line-end-char -1
5135 js2-ts-cursor (point-min)
5136 js2-ts-is-xml-attribute nil
5137 js2-ts-xml-is-tag-content nil
5138 js2-ts-xml-open-tags-count 0
5139 js2-ts-string-buffer nil)))
5141 ;; This function uses the cached op, string and number fields in
5142 ;; TokenStream; if getToken has been called since the passed token
5143 ;; was scanned, the op or string printed may be incorrect.
5144 (defun js2-token-to-string (token)
5145 ;; Not sure where this function is used in Rhino. Not tested.
5146 (if (not js2-debug-print-trees)
5148 (let ((name (js2-token-name token)))
5150 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5151 (concat name " `" js2-ts-string "'"))
5152 ((eq token js2-NUMBER)
5153 (format "NUMBER %g" js2-ts-number))
5157 (defconst js2-keywords
5159 case catch const continue
5160 debugger default delete do
5162 false finally for function
5163 if in instanceof import
5168 this throw true try typeof
5173 ;; Token names aren't exactly the same as the keywords, unfortunately.
5174 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5175 (defconst js2-kwd-tokens
5176 (let ((table (make-vector js2-num-tokens nil))
5179 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5180 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5182 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5183 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5188 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5193 (aset table i 'font-lock-keyword-face))
5194 (aset table js2-STRING 'font-lock-string-face)
5195 (aset table js2-REGEXP 'font-lock-string-face)
5196 (aset table js2-COMMENT 'font-lock-comment-face)
5197 (aset table js2-THIS 'font-lock-builtin-face)
5198 (aset table js2-VOID 'font-lock-constant-face)
5199 (aset table js2-NULL 'font-lock-constant-face)
5200 (aset table js2-TRUE 'font-lock-constant-face)
5201 (aset table js2-FALSE 'font-lock-constant-face)
5203 "Vector whose values are non-nil for tokens that are keywords.
5204 The values are default faces to use for highlighting the keywords.")
5206 (defconst js2-reserved-words
5214 implements import int interface
5217 package private protected public
5218 short static super synchronized
5222 (defconst js2-keyword-names
5223 (let ((table (make-hash-table :test 'equal)))
5224 (loop for k in js2-keywords
5226 (symbol-name k) ; instanceof
5227 (intern (concat "js2-"
5228 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5231 "JavaScript keywords by name, mapped to their symbols.")
5233 (defconst js2-reserved-word-names
5234 (let ((table (make-hash-table :test 'equal)))
5235 (loop for k in js2-reserved-words
5237 (puthash (symbol-name k) 'js2-RESERVED table))
5239 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5241 (defun js2-collect-string (buf)
5242 "Convert BUF, a list of chars, to a string.
5243 Reverses BUF before converting."
5247 ((null buf) ; for emacs21 compat
5251 (apply #'string (nreverse buf))
5254 (defun js2-string-to-keyword (s)
5255 "Return token for S, a string, if S is a keyword or reserved word.
5256 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5257 (or (gethash s js2-keyword-names)
5258 (gethash s js2-reserved-word-names)))
5260 (defsubst js2-ts-set-char-token-bounds ()
5261 "Used when next token is one character."
5262 (setq js2-token-beg (1- js2-ts-cursor)
5263 js2-token-end js2-ts-cursor))
5265 (defsubst js2-ts-return (token)
5266 "Return an N-character TOKEN from `js2-get-token'.
5267 Updates `js2-token-end' accordingly."
5268 (setq js2-token-end js2-ts-cursor)
5269 (throw 'return token))
5271 (defun js2-x-digit-to-int (c accumulator)
5272 "Build up a hex number.
5273 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5274 corresponding number. Otherwise return -1."
5277 ;; Use 0..9 < A..Z < a..z
5282 (throw 'check nil)))
5286 (throw 'check nil)))
5290 (throw 'check nil))))
5292 (logior c (lsh accumulator 4))))
5294 (defun js2-get-token ()
5295 "Return next JavaScript token, an int such as js2-RETURN."
5296 (let (c c1 identifier-start is-unicode-escape-start
5297 contains-escape escape-val escape-start str result base
5298 is-integer quote-char val look-for-slash continue)
5301 ;; Eat whitespace, possibly sensitive to newlines.
5304 (setq c (js2-get-char))
5306 ((eq c js2-EOF_CHAR)
5307 (js2-ts-set-char-token-bounds)
5308 (throw 'return js2-EOF))
5310 (js2-ts-set-char-token-bounds)
5311 (setq js2-ts-dirty-line nil)
5312 (throw 'return js2-EOL))
5313 ((not (js2-js-space-p c))
5314 (if (/= c ?-) ; in case end of HTML comment
5315 (setq js2-ts-dirty-line t))
5316 (setq continue nil))))
5317 ;; Assume the token will be 1 char - fixed up below.
5318 (js2-ts-set-char-token-bounds)
5320 (throw 'return js2-XMLATTR))
5321 ;; identifier/keyword/instanceof?
5322 ;; watch out for starting with a <backslash>
5325 (setq c (js2-get-char))
5327 (setq identifier-start t
5328 is-unicode-escape-start t
5329 js2-ts-string-buffer nil)
5330 (setq identifier-start nil)
5334 (when (setq identifier-start (js2-java-identifier-start-p c))
5335 (setq js2-ts-string-buffer nil)
5336 (js2-add-to-string c))))
5337 (when identifier-start
5338 (setq contains-escape is-unicode-escape-start)
5341 (if is-unicode-escape-start
5342 ;; strictly speaking we should probably push-back
5343 ;; all the bad characters if the <backslash>uXXXX
5344 ;; sequence is malformed. But since there isn't a
5345 ;; correct context(is there?) for a bad Unicode
5346 ;; escape sequence in an identifier, we can report
5351 (setq c (js2-get-char)
5352 escape-val (js2-x-digit-to-int c escape-val))
5353 ;; Next check takes care of c < 0 and bad escape
5354 (if (minusp escape-val)
5355 (throw 'break nil)))
5356 (if (minusp escape-val)
5357 (js2-report-scan-error "msg.invalid.escape" t))
5358 (js2-add-to-string escape-val)
5359 (setq is-unicode-escape-start nil))
5360 (setq c (js2-get-char))
5363 (setq c (js2-get-char))
5365 (setq is-unicode-escape-start t
5367 (js2-report-scan-error "msg.illegal.character" t)))
5369 (if (or (eq c js2-EOF_CHAR)
5370 (not (js2-java-identifier-part-p c)))
5372 (js2-add-to-string c))))))
5374 (setq str (js2-get-string-from-buffer))
5375 (unless contains-escape
5376 ;; OPT we shouldn't have to make a string (object!) to
5377 ;; check if it's a keyword.
5378 ;; Return the corresponding token if it's a keyword
5379 (when (setq result (js2-string-to-keyword str))
5380 (if (and (< js2-language-version 170)
5381 (memq result '(js2-LET js2-YIELD)))
5382 ;; LET and YIELD are tokens only in 1.7 and later
5383 (setq result 'js2-NAME))
5384 (if (not (eq result 'js2-RESERVED))
5385 (throw 'return (js2-token-code result)))
5386 (js2-report-warning "msg.reserved.keyword" str)))
5387 ;; If we want to intern these as Rhino does, just use (intern str)
5388 (setq js2-ts-string str)
5389 (throw 'return js2-NAME)) ; end identifier/kwd check
5391 (when (or (js2-digit-p c)
5392 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5393 (setq js2-ts-string-buffer nil
5396 (setq c (js2-get-char))
5398 ((or (eq c ?x) (eq c ?X))
5400 (setq c (js2-get-char)))
5404 (js2-add-to-string ?0))))
5406 (while (<= 0 (js2-x-digit-to-int c 0))
5407 (js2-add-to-string c)
5408 (setq c (js2-get-char)))
5409 (while (and (<= ?0 c) (<= c ?9))
5410 ;; We permit 08 and 09 as decimal numbers, which
5411 ;; makes our behavior a superset of the ECMA
5412 ;; numeric grammar. We might not always be so
5413 ;; permissive, so we warn about it.
5414 (when (and (eq base 8) (>= c ?8))
5415 (js2-report-warning "msg.bad.octal.literal"
5416 (if (eq c ?8) "8" "9"))
5418 (js2-add-to-string c)
5419 (setq c (js2-get-char))))
5421 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5422 (setq is-integer nil)
5425 (js2-add-to-string c)
5426 (setq c (js2-get-char))
5427 while (js2-digit-p c)))
5428 (when (memq c '(?e ?E))
5429 (js2-add-to-string c)
5430 (setq c (js2-get-char))
5431 (when (memq c '(?+ ?-))
5432 (js2-add-to-string c)
5433 (setq c (js2-get-char)))
5434 (unless (js2-digit-p c)
5435 (js2-report-scan-error "msg.missing.exponent" t))
5437 (js2-add-to-string c)
5438 (setq c (js2-get-char))
5439 while (js2-digit-p c))))
5441 (setq js2-ts-string (js2-get-string-from-buffer)
5443 (if (and (eq base 10) (not is-integer))
5444 (string-to-number js2-ts-string)
5445 ;; TODO: call runtime number-parser. Some of it is in
5446 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5447 (string-to-number js2-ts-string)))
5448 (throw 'return js2-NUMBER))
5450 (when (memq c '(?\" ?\'))
5451 ;; We attempt to accumulate a string the fast way, by
5452 ;; building it directly out of the reader. But if there
5453 ;; are any escaped characters in the string, we revert to
5454 ;; building it out of a string buffer.
5456 js2-ts-string-buffer nil
5459 (while (/= c quote-char)
5461 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5463 (setq js2-token-end js2-ts-cursor)
5464 (js2-report-error "msg.unterminated.string.lit")
5465 (throw 'return js2-STRING))
5467 ;; We've hit an escaped character
5468 (setq c (js2-get-char))
5477 (setq c1 (js2-read-unicode-escape))
5478 (if js2-parse-ide-mode
5481 ;; just copy the string in IDE-mode
5482 (js2-add-to-string ?\\)
5483 (js2-add-to-string ?u)
5485 (js2-add-to-string (js2-get-char)))
5486 (setq c (js2-get-char))) ; added at end of loop
5487 ;; flag it as an invalid escape
5488 (js2-report-warning "msg.invalid.escape"
5489 nil (- js2-ts-cursor 2) 6))
5490 ;; Get 4 hex digits; if the u escape is not
5491 ;; followed by 4 hex digits, use 'u' + the
5492 ;; literal character sequence that follows.
5493 (js2-add-to-string ?u)
5496 (setq c (js2-get-char)
5497 escape-val (js2-x-digit-to-int c escape-val))
5498 (if (minusp escape-val)
5499 (throw 'continue nil))
5500 (js2-add-to-string c))
5501 ;; prepare for replace of stored 'u' sequence by escape value
5502 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5505 ;; Get 2 hex digits, defaulting to 'x'+literal
5506 ;; sequence, as above.
5507 (setq c (js2-get-char)
5508 escape-val (js2-x-digit-to-int c 0))
5509 (if (minusp escape-val)
5511 (js2-add-to-string ?x)
5512 (throw 'continue nil))
5515 escape-val (js2-x-digit-to-int c escape-val))
5516 (if (minusp escape-val)
5518 (js2-add-to-string ?x)
5519 (js2-add-to-string c1)
5520 (throw 'continue nil))
5522 (setq c escape-val))))
5524 ;; Remove line terminator after escape to follow
5525 ;; SpiderMonkey and C/C++
5526 (setq c (js2-get-char))
5527 (throw 'continue nil))
5529 (when (and (<= ?0 c) (< c ?8))
5532 (when (and (<= ?0 c) (< c ?8))
5533 (setq val (- (+ (* 8 val) c) ?0)
5535 (when (and (<= ?0 c)
5538 ;; c is 3rd char of octal sequence only
5539 ;; if the resulting val <= 0377
5540 (setq val (- (+ (* 8 val) c) ?0)
5544 (js2-add-to-string c)
5545 (setq c (js2-get-char)))))
5546 (setq js2-ts-string (js2-get-string-from-buffer))
5547 (throw 'return js2-STRING))
5550 (throw 'return js2-SEMI))
5552 (throw 'return js2-LB))
5554 (throw 'return js2-RB))
5556 (throw 'return js2-LC))
5558 (throw 'return js2-RC))
5560 (throw 'return js2-LP))
5562 (throw 'return js2-RP))
5564 (throw 'return js2-COMMA))
5566 (throw 'return js2-HOOK))
5568 (if (js2-match-char ?:)
5569 (js2-ts-return js2-COLONCOLON)
5570 (throw 'return js2-COLON)))
5572 (if (js2-match-char ?.)
5573 (if (js2-match-char ?.)
5574 (js2-ts-return js2-TRIPLEDOT)
5575 (js2-ts-return js2-DOTDOT))
5576 (if (js2-match-char ?\()
5577 (js2-ts-return js2-DOTQUERY)
5578 (throw 'return js2-DOT))))
5580 (if (js2-match-char ?|)
5581 (throw 'return js2-OR)
5582 (if (js2-match-char ?=)
5583 (js2-ts-return js2-ASSIGN_BITOR)
5584 (throw 'return js2-BITOR))))
5586 (if (js2-match-char ?=)
5587 (js2-ts-return js2-ASSIGN_BITOR)
5588 (throw 'return js2-BITXOR)))
5590 (if (js2-match-char ?&)
5591 (throw 'return js2-AND)
5592 (if (js2-match-char ?=)
5593 (js2-ts-return js2-ASSIGN_BITAND)
5594 (throw 'return js2-BITAND))))
5596 (if (js2-match-char ?=)
5597 (if (js2-match-char ?=)
5598 (js2-ts-return js2-SHEQ)
5599 (throw 'return js2-EQ))
5600 (throw 'return js2-ASSIGN)))
5602 (if (js2-match-char ?=)
5603 (if (js2-match-char ?=)
5604 (js2-ts-return js2-SHNE)
5605 (js2-ts-return js2-NE))
5606 (throw 'return js2-NOT)))
5608 ;; NB:treat HTML begin-comment as comment-till-eol
5609 (when (js2-match-char ?!)
5610 (when (js2-match-char ?-)
5611 (when (js2-match-char ?-)
5613 (setq js2-ts-comment-type 'html)
5614 (throw 'return js2-COMMENT)))
5616 (if (js2-match-char ?<)
5617 (if (js2-match-char ?=)
5618 (js2-ts-return js2-ASSIGN_LSH)
5619 (js2-ts-return js2-LSH))
5620 (if (js2-match-char ?=)
5621 (js2-ts-return js2-LE)
5622 (throw 'return js2-LT))))
5624 (if (js2-match-char ?>)
5625 (if (js2-match-char ?>)
5626 (if (js2-match-char ?=)
5627 (js2-ts-return js2-ASSIGN_URSH)
5628 (js2-ts-return js2-URSH))
5629 (if (js2-match-char ?=)
5630 (js2-ts-return js2-ASSIGN_RSH)
5631 (js2-ts-return js2-RSH)))
5632 (if (js2-match-char ?=)
5633 (js2-ts-return js2-GE)
5634 (throw 'return js2-GT))))
5636 (if (js2-match-char ?=)
5637 (js2-ts-return js2-ASSIGN_MUL)
5638 (throw 'return js2-MUL)))
5640 ;; is it a // comment?
5641 (when (js2-match-char ?/)
5642 (setq js2-token-beg (- js2-ts-cursor 2))
5644 (setq js2-ts-comment-type 'line)
5645 ;; include newline so highlighting goes to end of window
5646 (incf js2-token-end)
5647 (throw 'return js2-COMMENT))
5648 ;; is it a /* comment?
5649 (when (js2-match-char ?*)
5650 (setq look-for-slash nil
5651 js2-token-beg (- js2-ts-cursor 2)
5653 (if (js2-match-char ?*)
5655 (setq look-for-slash t)
5659 (setq c (js2-get-char))
5661 ((eq c js2-EOF_CHAR)
5662 (setq js2-token-end (1- js2-ts-cursor))
5663 (js2-report-error "msg.unterminated.comment")
5664 (throw 'return js2-COMMENT))
5666 (setq look-for-slash t))
5669 (js2-ts-return js2-COMMENT)))
5671 (setq look-for-slash nil
5672 js2-token-end js2-ts-cursor)))))
5673 (if (js2-match-char ?=)
5674 (js2-ts-return js2-ASSIGN_DIV)
5675 (throw 'return js2-DIV)))
5677 (when js2-skip-preprocessor-directives
5679 (setq js2-ts-comment-type 'preprocessor
5680 js2-token-end js2-ts-cursor)
5681 (throw 'return js2-COMMENT))
5682 (throw 'return js2-ERROR))
5684 (if (js2-match-char ?=)
5685 (js2-ts-return js2-ASSIGN_MOD)
5686 (throw 'return js2-MOD)))
5688 (throw 'return js2-BITNOT))
5690 (if (js2-match-char ?=)
5691 (js2-ts-return js2-ASSIGN_ADD)
5692 (if (js2-match-char ?+)
5693 (js2-ts-return js2-INC)
5694 (throw 'return js2-ADD))))
5697 ((js2-match-char ?=)
5698 (setq c js2-ASSIGN_SUB))
5699 ((js2-match-char ?-)
5700 (unless js2-ts-dirty-line
5701 ;; treat HTML end-comment after possible whitespace
5702 ;; after line start as comment-until-eol
5703 (when (js2-match-char ?>)
5705 (setq js2-ts-comment-type 'html)
5706 (throw 'return js2-COMMENT)))
5710 (setq js2-ts-dirty-line t)
5713 (js2-report-scan-error "msg.illegal.character")))))))
5715 (defun js2-read-regexp (start-token)
5716 "Called by parser when it gets / or /= in literal context."
5718 in-class ; inside a '[' .. ']' character-class
5721 (setq js2-token-beg js2-ts-cursor
5722 js2-ts-string-buffer nil
5723 js2-ts-regexp-flags nil)
5724 (if (eq start-token js2-ASSIGN_DIV)
5726 (js2-add-to-string ?=)
5727 (if (not (eq start-token js2-DIV))
5728 (error "failed assertion")))
5729 (while (and (not err)
5730 (or (/= (setq c (js2-get-char)) ?/)
5735 (setq js2-token-end (1- js2-ts-cursor)
5737 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5738 (js2-report-error "msg.unterminated.re.lit"))
5741 (js2-add-to-string c)
5742 (setq c (js2-get-char)))
5746 (setq in-class nil)))
5747 (js2-add-to-string c))))
5751 ((js2-match-char ?g)
5753 ((js2-match-char ?i)
5755 ((js2-match-char ?m)
5758 (setq continue nil))))
5759 (if (js2-alpha-p (js2-peek-char))
5760 (js2-report-scan-error "msg.invalid.re.flag" t
5762 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5763 js2-ts-regexp-flags (js2-collect-string flags)
5764 js2-token-end js2-ts-cursor)
5765 ;; tell `parse-partial-sexp' to ignore this range of chars
5766 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5768 (defun js2-get-first-xml-token ()
5769 (setq js2-ts-xml-open-tags-count 0
5770 js2-ts-is-xml-attribute nil
5771 js2-ts-xml-is-tag-content nil)
5773 (js2-get-next-xml-token))
5775 (defun js2-xml-discard-string ()
5776 "Throw away the string in progress and flag an XML parse error."
5777 (setq js2-ts-string-buffer nil
5779 (js2-report-scan-error "msg.XML.bad.form" t))
5781 (defun js2-get-next-xml-token ()
5782 (setq js2-ts-string-buffer nil ; for recording the XML
5783 js2-token-beg js2-ts-cursor)
5788 (setq c (js2-get-char))
5791 (throw 'return js2-ERROR))
5792 (js2-ts-xml-is-tag-content
5795 (js2-add-to-string c)
5796 (setq js2-ts-xml-is-tag-content nil
5797 js2-ts-is-xml-attribute nil))
5799 (js2-add-to-string c)
5800 (when (eq ?> (js2-peek-char))
5801 (setq c (js2-get-char))
5802 (js2-add-to-string c)
5803 (setq js2-ts-xml-is-tag-content nil)
5804 (decf js2-ts-xml-open-tags-count)))
5807 (setq js2-ts-string (js2-get-string-from-buffer))
5808 (throw 'return js2-XML))
5810 (js2-add-to-string c)
5811 (unless (js2-read-quoted-string c)
5812 (throw 'return js2-ERROR)))
5814 (js2-add-to-string c)
5815 (setq js2-ts-is-xml-attribute t))
5817 (js2-add-to-string c))
5819 (js2-add-to-string c)
5820 (setq js2-ts-is-xml-attribute nil)))
5821 (when (and (not js2-ts-xml-is-tag-content)
5822 (zerop js2-ts-xml-open-tags-count))
5823 (setq js2-ts-string (js2-get-string-from-buffer))
5824 (throw 'return js2-XMLEND)))
5826 ;; else not tag content
5829 (js2-add-to-string c)
5830 (setq c (js2-peek-char))
5833 (setq c (js2-get-char)) ;; skip !
5834 (js2-add-to-string c)
5835 (setq c (js2-peek-char))
5838 (setq c (js2-get-char)) ;; skip -
5839 (js2-add-to-string c)
5842 (js2-add-to-string c)
5843 (unless (js2-read-xml-comment)
5844 (throw 'return js2-ERROR)))
5845 (js2-xml-discard-string)
5846 (throw 'return js2-ERROR)))
5848 (setq c (js2-get-char)) ;; skip [
5849 (js2-add-to-string c)
5850 (if (and (= (js2-get-char) ?C)
5851 (= (js2-get-char) ?D)
5852 (= (js2-get-char) ?A)
5853 (= (js2-get-char) ?T)
5854 (= (js2-get-char) ?A)
5855 (= (js2-get-char) ?\[))
5857 (js2-add-to-string ?C)
5858 (js2-add-to-string ?D)
5859 (js2-add-to-string ?A)
5860 (js2-add-to-string ?T)
5861 (js2-add-to-string ?A)
5862 (js2-add-to-string ?\[)
5863 (unless (js2-read-cdata)
5864 (throw 'return js2-ERROR)))
5865 (js2-xml-discard-string)
5866 (throw 'return js2-ERROR)))
5868 (unless (js2-read-entity)
5869 (throw 'return js2-ERROR))))
5870 ;; Allow bare CDATA section, e.g.:
5871 ;; let xml = <![CDATA[ foo bar baz ]]>;
5872 (when (zerop js2-ts-xml-open-tags-count)
5873 (throw 'return js2-XMLEND)))
5875 (setq c (js2-get-char)) ;; skip ?
5876 (js2-add-to-string c)
5877 (unless (js2-read-PI)
5878 (throw 'return js2-ERROR)))
5881 (setq c (js2-get-char)) ;; skip /
5882 (js2-add-to-string c)
5883 (when (zerop js2-ts-xml-open-tags-count)
5884 (js2-xml-discard-string)
5885 (throw 'return js2-ERROR))
5886 (setq js2-ts-xml-is-tag-content t)
5887 (decf js2-ts-xml-open-tags-count))
5890 (setq js2-ts-xml-is-tag-content t)
5891 (incf js2-ts-xml-open-tags-count))))
5894 (setq js2-ts-string (js2-get-string-from-buffer))
5895 (throw 'return js2-XML))
5897 (js2-add-to-string c))))))))
5898 (setq js2-token-end js2-ts-cursor)
5901 (defun js2-read-quoted-string (quote)
5904 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5905 (js2-add-to-string c)
5908 (js2-xml-discard-string) ;; throw away string in progress
5911 (defun js2-read-xml-comment ()
5912 (let ((c (js2-get-char)))
5914 (while (/= c js2-EOF_CHAR)
5916 (js2-add-to-string c)
5917 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5918 (setq c (js2-get-char))
5919 (js2-add-to-string c)
5920 (if (eq (js2-peek-char) ?>)
5922 (setq c (js2-get-char)) ;; skip >
5923 (js2-add-to-string c)
5925 (throw 'continue nil)))
5926 (setq c (js2-get-char))))
5927 (js2-xml-discard-string)
5930 (defun js2-read-cdata ()
5931 (let ((c (js2-get-char)))
5933 (while (/= c js2-EOF_CHAR)
5935 (js2-add-to-string c)
5936 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
5937 (setq c (js2-get-char))
5938 (js2-add-to-string c)
5939 (if (eq (js2-peek-char) ?>)
5941 (setq c (js2-get-char)) ;; Skip >
5942 (js2-add-to-string c)
5944 (throw 'continue nil)))
5945 (setq c (js2-get-char))))
5946 (js2-xml-discard-string)
5949 (defun js2-read-entity ()
5953 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5954 (js2-add-to-string c)
5960 (if (zerop decl-tags)
5961 (throw 'return t)))))
5962 (js2-xml-discard-string)
5965 (defun js2-read-PI ()
5966 "Scan an XML processing instruction."
5969 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
5970 (js2-add-to-string c)
5971 (when (and (eq c ??) (eq (js2-peek-char) ?>))
5972 (setq c (js2-get-char)) ;; Skip >
5973 (js2-add-to-string c)
5975 (js2-xml-discard-string)
5980 (defun js2-set-face (beg end face &optional record)
5981 "Fontify a region. If RECORD is non-nil, record for later."
5982 (when (plusp js2-highlight-level)
5983 (setq beg (min (point-max) beg)
5984 beg (max (point-min) beg)
5985 end (min (point-max) end)
5986 end (max (point-min) end))
5988 (push (list beg end face) js2-mode-fontifications)
5989 (put-text-property beg end 'font-lock-face face))))
5991 (defsubst js2-clear-face (beg end)
5992 (remove-text-properties beg end '(font-lock-face nil
5997 (defconst js2-ecma-global-props
6000 '("Infinity" "NaN" "undefined" "arguments") t)
6002 "Value properties of the Ecma-262 Global Object.
6003 Shown at or above `js2-highlight-level' 2.")
6005 ;; might want to add the name "arguments" to this list?
6006 (defconst js2-ecma-object-props
6009 '("prototype" "__proto__" "__parent__") t)
6011 "Value properties of the Ecma-262 Object constructor.
6012 Shown at or above `js2-highlight-level' 2.")
6014 (defconst js2-ecma-global-funcs
6018 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6019 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6021 "Function properties of the Ecma-262 Global object.
6022 Shown at or above `js2-highlight-level' 2.")
6024 (defconst js2-ecma-number-props
6026 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6028 "POSITIVE_INFINITY") t)
6030 "Properties of the Ecma-262 Number constructor.
6031 Shown at or above `js2-highlight-level' 2.")
6033 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6034 "Properties of the Ecma-262 Date constructor.
6035 Shown at or above `js2-highlight-level' 2.")
6037 (defconst js2-ecma-math-props
6040 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6043 "Properties of the Ecma-262 Math object.
6044 Shown at or above `js2-highlight-level' 2.")
6046 (defconst js2-ecma-math-funcs
6049 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6050 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6052 "Function properties of the Ecma-262 Math object.
6053 Shown at or above `js2-highlight-level' 2.")
6055 (defconst js2-ecma-function-props
6059 '(;; properties of the Object prototype object
6060 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6061 "toLocaleString" "toString" "valueOf"
6062 ;; properties of the Function prototype object
6064 ;; properties of the Array prototype object
6065 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6067 ;; properties of the String prototype object
6068 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6069 "localeCompare" "match" "replace" "search" "split" "substring"
6070 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6072 ;; properties of the Number prototype object
6073 "toExponential" "toFixed" "toPrecision"
6074 ;; properties of the Date prototype object
6075 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6076 "getMinutes" "getMonth" "getSeconds" "getTime"
6077 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6078 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6079 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6080 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6081 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6082 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6083 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6084 "toTimeString" "toUTCString"
6085 ;; properties of the RegExp prototype object
6087 ;; properties of the JSON prototype object
6089 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6090 "toSource" "__defineGetter__" "__defineSetter__"
6091 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6092 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6095 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6096 Shown at or above `js2-highlight-level' 3.")
6098 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6099 (let ((target-name (and target
6100 (js2-name-node-p target)
6101 (js2-name-node-name target)))
6102 (prop-name (if prop (js2-name-node-name prop)))
6103 (level1 (>= js2-highlight-level 1))
6104 (level2 (>= js2-highlight-level 2))
6105 (level3 (>= js2-highlight-level 3))
6112 ((and level3 (string-match js2-ecma-function-props prop-name))
6113 (setq face 'font-lock-builtin-face))
6114 ((and target-name prop)
6116 ((string= target-name "Date")
6117 (if (string-match js2-ecma-date-props prop-name)
6118 (setq face 'font-lock-builtin-face)))
6119 ((string= target-name "Math")
6120 (if (string-match js2-ecma-math-funcs prop-name)
6121 (setq face 'font-lock-builtin-face)))))))
6123 (if (string-match js2-ecma-global-funcs prop-name)
6124 (setq face 'font-lock-builtin-face))))
6128 ((string= target-name "Number")
6129 (if (string-match js2-ecma-number-props prop-name)
6130 (setq face 'font-lock-constant-face)))
6131 ((string= target-name "Math")
6132 (if (string-match js2-ecma-math-props prop-name)
6133 (setq face 'font-lock-constant-face)))))
6135 (if (string-match js2-ecma-object-props prop-name)
6136 (setq face 'font-lock-constant-face)))))
6138 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6139 (js2-node-pos prop))) ; relative
6140 (+ pos (js2-node-len prop))
6143 (defun js2-parse-highlight-member-expr-node (node)
6144 "Perform syntax highlighting of EcmaScript built-in properties.
6145 The variable `js2-highlight-level' governs this highighting."
6146 (let (face target prop name pos end parent call-p callee)
6148 ;; case 1: simple name, e.g. foo
6149 ((js2-name-node-p node)
6150 (setq name (js2-name-node-name node))
6151 ;; possible for name to be nil in rare cases - saw it when
6152 ;; running js2-mode on an elisp buffer. Might as well try to
6153 ;; make it so js2-mode never barfs.
6155 (setq face (if (string-match js2-ecma-global-props name)
6156 'font-lock-constant-face))
6158 (setq pos (js2-node-pos node)
6159 end (+ pos (js2-node-len node)))
6160 (js2-set-face pos end face 'record))))
6161 ;; case 2: property access or function call
6162 ((or (js2-prop-get-node-p node)
6163 ;; highlight function call if expr is a prop-get node
6164 ;; or a plain name (i.e. unqualified function call)
6165 (and (setq call-p (js2-call-node-p node))
6166 (setq callee (js2-call-node-target node)) ; separate setq!
6167 (or (js2-prop-get-node-p callee)
6168 (js2-name-node-p callee))))
6170 node (if call-p callee node))
6171 (if (and call-p (js2-name-node-p callee))
6173 (setq target (js2-prop-get-node-left node)
6174 prop (js2-prop-get-node-right node)))
6176 ((js2-name-node-p target)
6177 (if (js2-name-node-p prop)
6178 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6179 (js2-parse-highlight-prop-get parent target prop call-p)
6180 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6181 (js2-parse-highlight-prop-get parent target nil call-p)))
6182 ((js2-name-node-p prop)
6183 ;; case 2c: complex target, simple name, e.g. x[y].bar
6184 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6186 (defun js2-parse-highlight-member-expr-fn-name (expr)
6187 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6188 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6189 We currently only handle the case where the last component is a prop-get
6190 of a simple name. Called before EXPR has a parent node."
6192 (name (and (js2-prop-get-node-p expr)
6193 (js2-prop-get-node-right expr))))
6194 (when (js2-name-node-p name)
6195 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6196 (js2-node-pos name)))
6197 (+ pos (js2-node-len name))
6198 'font-lock-function-name-face
6201 ;; source: http://jsdoc.sourceforge.net/
6202 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6203 ;; allows type specifications, and needs work before entering the wild.
6205 (defconst js2-jsdoc-param-tag-regexp
6206 (concat "^\\s-*\\*+\\s-*\\(@"
6207 "\\(?:param\\|argument\\)"
6209 "\\s-*\\({[^}]+}\\)?" ; optional type
6210 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6212 "Matches jsdoc tags with optional type and optional param name.")
6214 (defconst js2-jsdoc-typed-tag-regexp
6215 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6229 "\\)\\)\\s-*\\({[^}]+}\\)?")
6230 "Matches jsdoc tags with optional type.")
6232 (defconst js2-jsdoc-arg-tag-regexp
6233 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6256 "\\)\\)\\s-+\\([^ \t]+\\)")
6257 "Matches jsdoc tags with a single argument.")
6259 (defconst js2-jsdoc-empty-tag-regexp
6260 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6300 "Matches empty jsdoc tags.")
6302 (defconst js2-jsdoc-link-tag-regexp
6303 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6304 "Matches a jsdoc link or code tag.")
6306 (defconst js2-jsdoc-see-tag-regexp
6307 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6308 "Matches a jsdoc @see tag.")
6310 (defconst js2-jsdoc-html-tag-regexp
6311 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6312 "Matches a simple (no attributes) html start- or end-tag.")
6314 (defun js2-jsdoc-highlight-helper ()
6315 (js2-set-face (match-beginning 1)
6318 (if (match-beginning 2)
6320 (goto-char (match-beginning 2))
6321 (= (char-after) ?{))
6322 (js2-set-face (1+ (match-beginning 2))
6325 (js2-set-face (match-beginning 2)
6328 (if (match-beginning 3)
6329 (js2-set-face (match-beginning 3)
6333 (defun js2-highlight-jsdoc (ast)
6334 "Highlight doc comment tags."
6335 (let ((comments (js2-ast-root-comments ast))
6338 (dolist (node comments)
6339 (when (eq (js2-comment-node-format node) 'jsdoc)
6340 (setq beg (js2-node-abs-pos node)
6341 end (+ beg (js2-node-len node)))
6343 (narrow-to-region beg end)
6344 (dolist (re (list js2-jsdoc-param-tag-regexp
6345 js2-jsdoc-typed-tag-regexp
6346 js2-jsdoc-arg-tag-regexp
6347 js2-jsdoc-link-tag-regexp
6348 js2-jsdoc-see-tag-regexp
6349 js2-jsdoc-empty-tag-regexp))
6351 (while (re-search-forward re nil t)
6352 (js2-jsdoc-highlight-helper)))
6353 ;; simple highlighting for html tags
6355 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6356 (js2-set-face (match-beginning 1)
6358 'js2-jsdoc-html-tag-delimiter)
6359 (js2-set-face (match-beginning 2)
6361 'js2-jsdoc-html-tag-name)
6362 (js2-set-face (match-beginning 3)
6364 'js2-jsdoc-html-tag-delimiter))))))))
6366 (defun js2-highlight-assign-targets (node left right)
6367 "Highlight function properties and external variables."
6368 (let (leftpos end name)
6369 ;; highlight vars and props assigned function values
6370 (when (js2-function-node-p right)
6372 ;; var foo = function() {...}
6373 ((js2-name-node-p left)
6375 ;; foo.bar.baz = function() {...}
6376 ((and (js2-prop-get-node-p left)
6377 (js2-name-node-p (js2-prop-get-node-right left)))
6378 (setq name (js2-prop-get-node-right left))))
6380 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6381 (+ leftpos (js2-node-len name))
6382 'font-lock-function-name-face
6385 (defun js2-record-name-node (node)
6386 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6387 later. NODE must be a name node."
6389 (push (list node js2-current-scope
6390 (setq leftpos (js2-node-abs-pos node))
6391 (setq end (+ leftpos (js2-node-len node))))
6392 js2-recorded-identifiers)))
6394 (defun js2-highlight-undeclared-vars ()
6395 "After entire parse is finished, look for undeclared variable references.
6396 We have to wait until entire buffer is parsed, since JavaScript permits var
6397 decls to occur after they're used.
6399 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6400 it is considered declared."
6402 (dolist (entry js2-recorded-identifiers)
6403 (destructuring-bind (name-node scope pos end) entry
6404 (setq name (js2-name-node-name name-node))
6405 (unless (or (member name js2-global-externs)
6406 (member name js2-default-externs)
6407 (member name js2-additional-externs)
6408 (js2-get-defining-scope scope name))
6409 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6410 'js2-external-variable))))
6411 (setq js2-recorded-identifiers nil)))
6415 ;; We currently only support imenu, but eventually should support speedbar and
6416 ;; possibly other browsing mechanisms.
6418 ;; The basic strategy is to identify function assignment targets of the form
6419 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6420 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6421 ;; for imenu after parsing is finished.
6423 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6424 ;; JavaScript, and the general problem is undecidable. However, several forms
6425 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6428 ;; function foo() -- function declaration
6429 ;; foo = function() -- function expression assigned to variable
6430 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6431 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6432 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6433 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6434 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6435 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6436 ;; function foo() {function bar() {...}} -- nested function
6437 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6439 ;; This list boils down to a few forms that can be combined recursively.
6440 ;; Top-level named function declarations include both the left-hand (name)
6441 ;; and the right-hand (function value) expressions needed to produce an imenu
6442 ;; entry. The other "right-hand" forms we need to look for are:
6443 ;; - functions declared as props/getters/setters in object literals
6444 ;; - nested named function declarations
6445 ;; The "left-hand" expressions that functions can be assigned to include:
6446 ;; - local/global variables
6447 ;; - nested property-get expressions like a.b.c.d
6448 ;; - element gets like foo[10] or foo['bar'] where the index
6449 ;; expression can be trivially converted to a property name. They
6450 ;; effectively then become property gets.
6452 ;; All the different definition types are canonicalized into the form
6453 ;; foo.bar.baz = position-of-function-keyword
6455 ;; We need to build a trie-like structure for imenu. As an example,
6456 ;; consider the following JavaScript code:
6458 ;; a = function() {...} // function at position 5
6459 ;; b = function() {...} // function at position 25
6460 ;; foo = function() {...} // function at position 100
6461 ;; foo.bar = function() {...} // function at position 200
6462 ;; foo.bar.baz = function() {...} // function at position 300
6463 ;; foo.bar.zab = function() {...} // function at position 400
6465 ;; During parsing we accumulate an entry for each definition in
6466 ;; the variable `js2-imenu-recorder', like so:
6472 ;; (fn foo bar baz 300)
6473 ;; (fn foo bar zab 400))
6475 ;; Where 'fn' is the respective function node.
6476 ;; After parsing these entries are merged into this alist-trie:
6480 ;; (foo (<definition> . 3)
6481 ;; (bar (<definition> . 6)
6485 ;; Note the wacky need for a <definition> name. The token can be anything
6486 ;; that isn't a valid JavaScript identifier, because you might make foo
6487 ;; a function and then start setting properties on it that are also functions.
6489 (defun js2-prop-node-name (node)
6490 "Return the name of a node that may be a property-get/property-name.
6491 If NODE is not a valid name-node, string-node or integral number-node,
6492 returns nil. Otherwise returns the string name/value of the node."
6494 ((js2-name-node-p node)
6495 (js2-name-node-name node))
6496 ((js2-string-node-p node)
6497 (js2-string-node-value node))
6498 ((and (js2-number-node-p node)
6499 (string-match "^[0-9]+$" (js2-number-node-value node)))
6500 (js2-number-node-value node))
6501 ((js2-this-node-p node)
6504 (defun js2-node-qname-component (node)
6505 "Return the name of this node, if it contributes to a qname.
6506 Returns nil if the node doesn't contribute."
6508 (or (js2-prop-node-name node)
6509 (if (and (js2-function-node-p node)
6510 (js2-function-node-name node))
6511 (js2-name-node-name (js2-function-node-name node))))))
6513 (defun js2-record-imenu-entry (fn-node qname pos)
6514 "Add an entry to `js2-imenu-recorder'.
6515 FN-NODE should be the current item's function node.
6517 Associate FN-NODE with its QNAME for later lookup.
6518 This is used in postprocessing the chain list. For each chain, we find
6519 the parent function, look up its qname, then prepend a copy of it to the chain."
6520 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6521 (unless js2-imenu-function-map
6522 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6523 (puthash fn-node qname js2-imenu-function-map))
6525 (defun js2-record-imenu-functions (node &optional var)
6526 "Record function definitions for imenu.
6527 NODE is a function node or an object literal.
6528 VAR, if non-nil, is the expression that NODE is being assigned to.
6529 When passed arguments of wrong type, does nothing."
6530 (when js2-parse-ide-mode
6531 (let ((fun-p (js2-function-node-p node))
6532 qname left fname-node pos)
6534 ;; non-anonymous function declaration?
6537 (setq fname-node (js2-function-node-name node)))
6538 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6539 ;; for remaining forms, compute left-side tree branch first
6540 ((and var (setq qname (js2-compute-nested-prop-get var)))
6542 ;; foo.bar.baz = function
6544 (js2-record-imenu-entry node qname (js2-node-pos node)))
6545 ;; foo.bar.baz = object-literal
6546 ;; look for nested functions: {a: {b: function() {...} }}
6547 ((js2-object-node-p node)
6548 ;; Node position here is still absolute, since the parser
6549 ;; passes the assignment target and value expressions
6550 ;; to us before they are added as children of the assignment node.
6551 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6553 (defun js2-compute-nested-prop-get (node)
6554 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6555 component nodes as a list. Otherwise return nil. Element-gets are treated
6556 as property-gets if the index expression is a string, or a positive integer."
6557 (let (left right head)
6559 ((or (js2-name-node-p node)
6560 (js2-this-node-p node))
6562 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6563 ((js2-prop-get-node-p node) ; foo.bar
6564 (setq left (js2-prop-get-node-left node)
6565 right (js2-prop-get-node-right node))
6566 (if (setq head (js2-compute-nested-prop-get left))
6567 (nconc head (list right))))
6568 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6569 (setq left (js2-elem-get-node-target node)
6570 right (js2-elem-get-node-element node))
6571 (if (or (js2-string-node-p right) ; ['bar']
6572 (and (js2-number-node-p right) ; [10]
6573 (string-match "^[0-9]+$"
6574 (js2-number-node-value right))))
6575 (if (setq head (js2-compute-nested-prop-get left))
6576 (nconc head (list right))))))))
6578 (defun js2-record-object-literal (node qname pos)
6579 "Recursively process an object literal looking for functions.
6580 NODE is an object literal that is the right-hand child of an assignment
6581 expression. QNAME is a list of nodes representing the assignment target,
6582 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6583 POS is the absolute position of the node.
6584 We do a depth-first traversal of NODE. For any functions we find,
6585 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6586 (let (left right prop-qname)
6587 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6588 (let ((left (js2-infix-node-left e))
6589 ;; Element positions are relative to the parent position.
6590 (pos (+ pos (js2-node-pos e))))
6592 ;; foo: function() {...}
6593 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6594 (when (js2-prop-node-name left)
6595 ;; As a policy decision, we record the position of the property,
6596 ;; not the position of the `function' keyword, since the property
6597 ;; is effectively the name of the function.
6598 (js2-record-imenu-entry right (append qname (list left)) pos)))
6599 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6600 ((js2-object-node-p right)
6601 (js2-record-object-literal right
6602 (append qname (list (js2-infix-node-left e)))
6603 (+ pos (js2-node-pos right)))))))))
6605 (defun js2-node-top-level-decl-p (node)
6606 "Return t if NODE's name is defined in the top-level scope.
6607 Also returns t if NODE's name is not defined in any scope, since it implies
6608 that it's an external variable, which must also be in the top-level scope."
6609 (let* ((name (js2-prop-node-name node))
6610 (this-scope (js2-node-get-enclosing-scope node))
6613 ((js2-this-node-p node)
6617 ((setq defining-scope (js2-get-defining-scope this-scope name))
6618 (js2-ast-root-p defining-scope))
6621 (defun js2-wrapper-function-p (node)
6622 "Return t if NODE is a function expression that's immediately invoked.
6623 NODE must be `js2-function-node'."
6624 (let ((parent (js2-node-parent node)))
6626 ;; function(){...}();
6627 (js2-call-node-p parent)
6628 (and (js2-paren-node-p parent)
6629 ;; (function(){...})();
6630 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6631 ;; (function(){...}).call(this);
6632 (and (js2-prop-get-node-p parent)
6633 (member (js2-name-node-name (js2-prop-get-node-right parent))
6635 (js2-call-node-p (js2-node-parent parent))))))))
6637 (defun js2-browse-postprocess-chains (entries)
6638 "Modify function-declaration name chains after parsing finishes.
6639 Some of the information is only available after the parse tree is complete.
6640 For instance, processing a nested scope requires a parent function node."
6641 (let (result head fn current-fn parent-qname qname p elem)
6642 (dolist (entry entries)
6643 ;; function node goes first
6644 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6645 ;; Examine head's defining scope:
6646 ;; Pre-processed chain, or top-level/external, keep as-is.
6647 (if (or (stringp head) (js2-node-top-level-decl-p head))
6649 (when (js2-this-node-p head)
6650 (setq chain (cdr chain))) ; discard this-node
6651 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6652 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6653 (when (eq parent-qname 'not-found)
6654 ;; anonymous function expressions are not recorded
6655 ;; during the parse, so we need to handle this case here
6657 (if (js2-wrapper-function-p fn)
6658 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6659 (if (js2-ast-root-p grandparent)
6661 (gethash grandparent js2-imenu-function-map 'skip)))
6663 (puthash fn parent-qname js2-imenu-function-map))
6664 (unless (eq parent-qname 'skip)
6665 ;; prefix parent fn qname to this chain.
6666 (let ((qname (append parent-qname chain)))
6667 (puthash current-fn (butlast qname) js2-imenu-function-map)
6668 (push qname result)))))))
6669 ;; finally replace each node in each chain with its name.
6670 (dolist (chain result)
6673 (if (js2-node-p (setq elem (car p)))
6674 (setcar p (js2-node-qname-component elem)))
6678 ;; Merge name chains into a trie-like tree structure of nested lists.
6679 ;; To simplify construction of the trie, we first build it out using the rule
6680 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6681 ;; [key, num-or-list]. The second element can be a number; if so, this key
6682 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6683 ;; associated with the key at this level.) Otherwise the second element is
6684 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6685 ;; a simple recursive formulation.
6687 ;; js2-mode is building the data structure for imenu. The imenu documentation
6688 ;; claims that it's the structure above, but in practice it wants the children
6689 ;; at the same list level as the key for that level, which is how I've drawn
6690 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6691 ;; list wrapper around the children at each level.
6693 ;; A completed nested imenu-alist entry looks like this:
6695 ;; ("<definition>" . 7)
6700 ;; In particular, the documentation for `imenu--index-alist' says that
6701 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6702 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6704 (defun js2-treeify (lst)
6705 "Convert (a b c d) to (a ((b ((c d)))))."
6706 (if (null (cddr lst)) ; list length <= 2
6708 (list (car lst) (list (js2-treeify (cdr lst))))))
6710 (defun js2-build-alist-trie (chains trie)
6711 "Merge declaration name chains into a trie-like alist structure for imenu.
6712 CHAINS is the qname chain list produced during parsing. TRIE is a
6713 list of elements built up so far."
6714 (let (head tail pos branch kids)
6715 (dolist (chain chains)
6716 (setq head (car chain)
6718 pos (if (numberp (car tail)) (car tail))
6719 branch (js2-find-if (lambda (n)
6720 (string= (car n) head))
6722 kids (second branch))
6724 ;; case 1: this key isn't in the trie yet
6727 (setcdr (last trie) (list (js2-treeify chain)))
6728 (setq trie (list (js2-treeify chain)))))
6729 ;; case 2: key is present with a single number entry: replace w/ list
6730 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6731 ;; ("<definition>" 20)))
6733 (setcar (cdr branch)
6734 (list (list "<definition-1>" kids)
6736 (list "<definition-2>" pos)
6737 (js2-treeify tail)))))
6738 ;; case 3: key is there (with kids), and we're a number entry
6742 (list (format "<definition-%d>"
6743 (1+ (loop for kid in kids
6744 count (eq ?< (aref (car kid) 0)))))
6746 ;; case 4: key is there with kids, need to merge in our chain
6748 (js2-build-alist-trie (list tail) kids))))
6751 (defun js2-flatten-trie (trie)
6752 "Convert TRIE to imenu-format.
6753 Recurses through nodes, and for each one whose second element is a list,
6754 appends the list's flattened elements to the current element. Also
6755 changes the tails into conses. For instance, this pre-flattened trie
6767 Note that the root of the trie has no key, just a list of chains.
6768 This is also true for the value of any key with multiple children,
6769 e.g. key 'c' in the example above."
6772 (mapcar #'js2-flatten-trie trie))
6774 (if (numberp (second trie))
6775 (cons (car trie) (second trie))
6776 ;; else pop list and append its kids
6777 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6779 (defun js2-build-imenu-index ()
6780 "Turn `js2-imenu-recorder' into an imenu data structure."
6781 (unless (eq js2-imenu-recorder 'empty)
6782 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6783 (result (js2-build-alist-trie chains nil)))
6784 (js2-flatten-trie result))))
6786 (defun js2-test-print-chains (chains)
6787 "Print a list of qname chains.
6788 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6789 i.e. one or more nodes, and an integer position as the list tail."
6790 (mapconcat (lambda (chain)
6792 (mapconcat (lambda (elem)
6793 (if (js2-node-p elem)
6794 (or (js2-node-qname-component elem)
6796 (number-to-string elem)))
6805 (defconst js2-version "1.8.5"
6806 "Version of JavaScript supported.")
6808 (defmacro js2-record-face (face)
6809 "Record a style run of FACE for the current token."
6810 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6812 (defsubst js2-node-end (n)
6813 "Computes the absolute end of node N.
6814 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6815 is only true until the node is added to its parent; i.e., while parsing."
6819 (defun js2-record-comment ()
6820 "Record a comment in `js2-scanned-comments'."
6821 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6822 :format js2-ts-comment-type)
6823 js2-scanned-comments)
6824 (when js2-parse-ide-mode
6825 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6827 'font-lock-comment-face))
6828 (when (memq js2-ts-comment-type '(html preprocessor))
6829 ;; Tell cc-engine the bounds of the comment.
6830 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6832 ;; This function is called depressingly often, so it should be fast.
6833 ;; Most of the time it's looking at the same token it peeked before.
6834 (defun js2-peek-token ()
6835 "Return the next token without consuming it.
6836 If previous token was consumed, calls scanner to get new token.
6837 If previous token was -not- consumed, returns it (idempotent).
6839 This function will not return a newline (js2-EOL) - instead, it
6840 gobbles newlines until it finds a non-newline token, and flags
6841 that token as appearing just after a newline.
6843 This function will also not return a js2-COMMENT. Instead, it
6844 records comments found in `js2-scanned-comments'. If the token
6845 returned by this function immediately follows a jsdoc comment,
6846 the token is flagged as such.
6848 Note that this function always returned the un-flagged token!
6849 The flags, if any, are saved in `js2-current-flagged-token'."
6850 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6851 js2-current-token ; most common case - return already-peeked token
6852 (let ((tt (js2-get-token)) ; call scanner
6855 ;; process comments and whitespace
6856 (while (or (= tt js2-EOL)
6861 (if js2-record-comments
6862 (js2-record-comment)))
6863 (setq tt (js2-get-token))) ; call scanner
6864 (setq js2-current-token tt
6865 js2-current-flagged-token (if saw-eol
6866 (logior tt js2-ti-after-eol)
6868 ;; perform lexical fontification as soon as token is scanned
6869 (when js2-parse-ide-mode
6872 (js2-record-face 'js2-error))
6873 ((setq face (aref js2-kwd-tokens tt))
6874 (js2-record-face face))
6875 ((and (= tt js2-NAME)
6876 (equal js2-ts-string "undefined"))
6877 (js2-record-face 'font-lock-constant-face))))
6878 tt))) ; return unflagged token
6880 (defun js2-peek-flagged-token ()
6881 "Return the current token along with any flags set for it."
6883 js2-current-flagged-token)
6885 (defsubst js2-consume-token ()
6886 (setq js2-current-flagged-token js2-EOF))
6888 (defun js2-next-token ()
6891 (js2-consume-token)))
6893 (defun js2-next-flagged-token ()
6895 (prog1 js2-current-flagged-token
6896 (js2-consume-token)))
6898 (defun js2-match-token (match)
6899 "Consume and return t if next token matches MATCH, a bytecode.
6900 Returns nil and consumes nothing if MATCH is not the next token."
6901 (if (/= (js2-peek-token) match)
6906 (defun js2-match-contextual-kwd (name)
6907 "Consume and return t if next token is `js2-NAME', and its
6908 string is NAME. Returns nil and does nothing otherwise."
6909 (if (or (/= (js2-peek-token) js2-NAME)
6910 (not (string= js2-ts-string name)))
6913 (js2-record-face 'font-lock-keyword-face)
6916 (defun js2-valid-prop-name-token (tt)
6918 (when (and js2-allow-keywords-as-property-names
6920 (aref js2-kwd-tokens tt))
6921 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
6924 (defun js2-match-prop-name ()
6925 "Consume token and return t if next token is a valid property name.
6926 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
6927 is non-nil and it's a keyword token."
6928 (if (js2-valid-prop-name-token (js2-peek-token))
6934 (defun js2-must-match-prop-name (msg-id &optional pos len)
6935 (if (js2-match-prop-name)
6937 (js2-report-error msg-id nil pos len)
6940 (defun js2-peek-token-or-eol ()
6941 "Return js2-EOL if the current token immediately follows a newline.
6942 Else returns the current token. Used in situations where we don't
6943 consider certain token types valid if they are preceded by a newline.
6944 One example is the postfix ++ or -- operator, which has to be on the
6945 same line as its operand."
6946 (let ((tt (js2-peek-token)))
6947 ;; Check for last peeked token flags
6948 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
6952 (defun js2-set-check-for-label ()
6953 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
6954 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
6956 (defun js2-must-match (token msg-id &optional pos len)
6957 "Match next token to token code TOKEN, or record a syntax error.
6958 MSG-ID is the error message to report if the match fails.
6959 Returns t on match, nil if no match."
6960 (if (js2-match-token token)
6962 (js2-report-error msg-id nil pos len)
6965 (defsubst js2-inside-function ()
6966 (plusp js2-nesting-of-function))
6968 (defun js2-set-requires-activation ()
6969 (if (js2-function-node-p js2-current-script-or-fn)
6970 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
6972 (defun js2-check-activation-name (name token)
6973 (when (js2-inside-function)
6974 ;; skip language-version 1.2 check from Rhino
6975 (if (or (string= "arguments" name)
6976 (and js2-compiler-activation-names ; only used in codegen
6977 (gethash name js2-compiler-activation-names)))
6978 (js2-set-requires-activation))))
6980 (defun js2-set-is-generator ()
6981 (if (js2-function-node-p js2-current-script-or-fn)
6982 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
6984 (defun js2-must-have-xml ()
6985 (unless js2-compiler-xml-available
6986 (js2-report-error "msg.XML.not.available")))
6988 (defun js2-push-scope (scope)
6989 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
6990 (assert (js2-scope-p scope))
6991 (assert (null (js2-scope-parent-scope scope)))
6992 (assert (not (eq js2-current-scope scope)))
6993 (setf (js2-scope-parent-scope scope) js2-current-scope
6994 js2-current-scope scope))
6996 (defsubst js2-pop-scope ()
6997 (setq js2-current-scope
6998 (js2-scope-parent-scope js2-current-scope)))
7000 (defun js2-enter-loop (loop-node)
7001 (push loop-node js2-loop-set)
7002 (push loop-node js2-loop-and-switch-set)
7003 (js2-push-scope loop-node)
7004 ;; Tell the current labeled statement (if any) its statement,
7005 ;; and set the jump target of the first label to the loop.
7006 ;; These are used in `js2-parse-continue' to verify that the
7007 ;; continue target is an actual labeled loop. (And for codegen.)
7008 (when js2-labeled-stmt
7009 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7010 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7011 js2-labeled-stmt))) loop-node)))
7013 (defun js2-exit-loop ()
7015 (pop js2-loop-and-switch-set)
7018 (defsubst js2-enter-switch (switch-node)
7019 (push switch-node js2-loop-and-switch-set))
7021 (defsubst js2-exit-switch ()
7022 (pop js2-loop-and-switch-set))
7024 (defun js2-parse (&optional buf cb)
7025 "Tell the js2 parser to parse a region of JavaScript.
7027 BUF is a buffer or buffer name containing the code to parse.
7028 Call `narrow-to-region' first to parse only part of the buffer.
7030 The returned AST root node is given some additional properties:
7031 `node-count' - total number of nodes in the AST
7032 `buffer' - BUF. The buffer it refers to may change or be killed,
7033 so the value is not necessarily reliable.
7035 An optional callback CB can be specified to report parsing
7036 progress. If `(functionp CB)' returns t, it will be called with
7037 the current line number once before parsing begins, then again
7038 each time the lexer reaches a new line number.
7040 CB can also be a list of the form `(symbol cb ...)' to specify
7041 multiple callbacks with different criteria. Each symbol is a
7042 criterion keyword, and the following element is the callback to
7045 :line - called whenever the line number changes
7046 :token - called for each new token consumed
7048 The list of criteria could be extended to include entering or
7049 leaving a statement, an expression, or a function definition."
7050 (if (and cb (not (functionp cb)))
7051 (error "criteria callbacks not yet implemented"))
7052 (let ((inhibit-point-motion-hooks t)
7053 (js2-compiler-xml-available (>= js2-language-version 160))
7054 ;; This is a recursive-descent parser, so give it a big stack.
7055 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7056 (max-specpdl-size (max max-specpdl-size 3000))
7057 (case-fold-search nil)
7059 (message nil) ; clear any error message from previous parse
7060 (with-current-buffer (or buf (current-buffer))
7061 (setq js2-scanned-comments nil
7062 js2-parsed-errors nil
7063 js2-parsed-warnings nil
7064 js2-imenu-recorder nil
7065 js2-imenu-function-map nil
7068 (setq ast (with-silent-modifications
7070 (unless js2-ts-hit-eof
7071 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7072 (setf (js2-ast-root-errors ast) js2-parsed-errors
7073 (js2-ast-root-warnings ast) js2-parsed-warnings)
7074 ;; if we didn't find any declarations, put a dummy in this list so we
7075 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7076 (unless js2-imenu-recorder
7077 (setq js2-imenu-recorder 'empty))
7078 (run-hooks 'js2-parse-finished-hook)
7081 ;; Corresponds to Rhino's Parser.parse() method.
7082 (defun js2-do-parse ()
7083 "Parse current buffer starting from current point.
7084 Scanner should be initialized."
7085 (let ((pos js2-ts-cursor)
7086 (end js2-ts-cursor) ; in case file is empty
7088 ;; initialize buffer-local parsing vars
7089 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7090 js2-current-script-or-fn root
7091 js2-current-scope root
7092 js2-current-flagged-token js2-EOF
7093 js2-nesting-of-function 0
7094 js2-labeled-stmt nil
7095 js2-recorded-identifiers nil) ; for js2-highlight
7096 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7097 (if (= tt js2-FUNCTION)
7100 (setq n (js2-parse-function (if js2-called-by-compile-function
7101 'FUNCTION_EXPRESSION
7102 'FUNCTION_STATEMENT))))
7103 ;; not a function - parse a statement
7104 (setq n (js2-parse-statement)))
7105 ;; add function or statement to script
7106 (setq end (js2-node-end n))
7107 (js2-block-node-push root n))
7108 ;; add comments to root in lexical order
7109 (when js2-scanned-comments
7110 ;; if we find a comment beyond end of normal kids, use its end
7111 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7112 (dolist (comment js2-scanned-comments)
7113 (push comment (js2-ast-root-comments root))
7114 (js2-node-add-children root comment)))
7115 (setf (js2-node-len root) (- end pos))
7116 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7117 ;; Give extensions a chance to muck with things before highlighting starts.
7118 (let ((js2-additional-externs js2-additional-externs))
7120 (dolist (callback js2-post-parse-callbacks)
7121 (funcall callback)))
7122 (js2-highlight-undeclared-vars))
7125 (defun js2-function-parser ()
7127 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7129 (defun js2-parse-function-closure-body (fn-node)
7130 "Parse a JavaScript 1.8 function closure body."
7131 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7133 (js2-report-error "msg.no.brace.body" nil
7134 (js2-node-pos fn-node)
7135 (- js2-ts-cursor (js2-node-pos fn-node)))
7136 (js2-node-add-children fn-node
7137 (setf (js2-function-node-body fn-node)
7138 (js2-parse-expr t))))))
7140 (defun js2-parse-function-body (fn-node)
7141 (js2-must-match js2-LC "msg.no.brace.body"
7142 (js2-node-pos fn-node)
7143 (- js2-ts-cursor (js2-node-pos fn-node)))
7144 (let ((pos js2-token-beg) ; LC position
7145 (pn (make-js2-block-node)) ; starts at LC position
7148 (incf js2-nesting-of-function)
7150 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7153 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7154 (js2-parse-statement)
7156 (js2-parse-function 'FUNCTION_STATEMENT))))
7157 (decf js2-nesting-of-function))
7158 (setq end js2-token-end) ; assume no curly and leave at current token
7159 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7160 (setq end js2-token-end))
7161 (setf (js2-node-pos pn) pos
7162 (js2-node-len pn) (- end pos))
7163 (setf (js2-function-node-body fn-node) pn)
7164 (js2-node-add-children fn-node pn)
7167 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7168 "Declare and fontify destructuring parameters inside NODE.
7169 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7171 ((js2-name-node-p node)
7173 (js2-define-symbol decl-type (js2-name-node-name node)
7174 node ignore-not-in-block)
7176 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7177 (+ leftpos (js2-node-len node))
7179 ((js2-object-node-p node)
7180 (dolist (elem (js2-object-node-elems node))
7181 (js2-define-destruct-symbols
7182 (if (js2-object-prop-node-p elem)
7183 (js2-object-prop-node-right elem)
7184 ;; abbreviated destructuring {a, b}
7186 decl-type face ignore-not-in-block)))
7187 ((js2-array-node-p node)
7188 (dolist (elem (js2-array-node-elems node))
7190 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7191 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7192 (js2-node-len node)))))
7194 (defun js2-parse-function-params (fn-node pos)
7195 (if (js2-match-token js2-RP)
7196 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7197 (let (params len param default-found rest-param-at)
7198 (loop for tt = (js2-peek-token)
7201 ;; destructuring param
7202 ((or (= tt js2-LB) (= tt js2-LC))
7204 (js2-report-error "msg.no.default.after.default.param"))
7205 (setq param (js2-parse-destruct-primary-expr))
7206 (js2-define-destruct-symbols param
7208 'js2-function-param)
7209 (push param params))
7212 (when (and (>= js2-language-version 200)
7213 (js2-match-token js2-TRIPLEDOT)
7214 (not rest-param-at))
7215 ;; to report errors if there are more parameters
7216 (setq rest-param-at (length params)))
7217 (js2-must-match js2-NAME "msg.no.parm")
7218 (js2-record-face 'js2-function-param)
7219 (setq param (js2-create-name-node))
7220 (js2-define-symbol js2-LP js2-ts-string param)
7221 ;; default parameter value
7222 (when (or (and default-found
7224 (js2-must-match js2-ASSIGN
7225 "msg.no.default.after.default.param"
7226 (js2-node-pos param)
7227 (js2-node-len param)))
7228 (and (>= js2-language-version 200)
7229 (js2-match-token js2-ASSIGN)))
7230 (let* ((pos (js2-node-pos param))
7231 (tt js2-current-token)
7232 (op-pos (- js2-token-beg pos))
7234 (right (js2-parse-assign-expr))
7235 (len (- (js2-node-end right) pos)))
7236 (setq param (make-js2-assign-node
7237 :type tt :pos pos :len len :op-pos op-pos
7238 :left left :right right)
7240 (js2-node-add-children param left right)))
7241 (push param params)))
7242 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7243 (js2-report-error "msg.param.after.rest" nil
7244 (js2-node-pos param) (js2-node-len param)))
7246 (js2-match-token js2-COMMA))
7247 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7248 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7250 (setf (js2-function-node-rest-p fn-node) t))
7252 (js2-node-add-children fn-node p)
7253 (push p (js2-function-node-params fn-node))))))
7255 (defun js2-check-inconsistent-return-warning (fn-node name)
7256 "Possibly show inconsistent-return warning.
7257 Last token scanned is the close-curly for the function body."
7258 (when (and js2-mode-show-strict-warnings
7259 js2-strict-inconsistent-return-warning
7260 (not (js2-has-consistent-return-usage
7261 (js2-function-node-body fn-node))))
7262 ;; Have it extend from close-curly to bol or beginning of block.
7263 (let ((pos (save-excursion
7264 (goto-char js2-token-end)
7265 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7267 (end js2-token-end))
7268 (if (plusp (js2-name-node-length name))
7269 (js2-add-strict-warning "msg.no.return.value"
7270 (js2-name-node-name name) pos end)
7271 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7273 (defun js2-parse-function (function-type)
7274 "Function parser. FUNCTION-TYPE is a symbol."
7275 (let ((pos js2-token-beg) ; start of 'function' keyword
7276 name name-beg name-end fn-node lp
7277 (synthetic-type function-type)
7279 ;; parse function name, expression, or non-name (anonymous)
7281 ;; function foo(...)
7282 ((js2-match-token js2-NAME)
7283 (setq name (js2-create-name-node t)
7284 name-beg js2-token-beg
7285 name-end js2-token-end)
7286 (unless (js2-match-token js2-LP)
7287 (when js2-allow-member-expr-as-function-name
7288 ;; function foo.bar(...)
7289 (setq member-expr-node name
7291 member-expr-node (js2-parse-member-expr-tail
7292 nil member-expr-node)))
7293 (js2-must-match js2-LP "msg.no.paren.parms")))
7294 ((js2-match-token js2-LP)
7295 nil) ; anonymous function: leave name as null
7297 ;; function random-member-expr(...)
7298 (when js2-allow-member-expr-as-function-name
7299 ;; Note that memberExpr can not start with '(' like
7300 ;; in function (1+2).toString(), because 'function (' already
7301 ;; processed as anonymous function
7302 (setq member-expr-node (js2-parse-member-expr)))
7303 (js2-must-match js2-LP "msg.no.paren.parms")))
7304 (if (= js2-current-token js2-LP) ; eventually matched LP?
7305 (setq lp js2-token-beg))
7306 (if member-expr-node
7308 (setq synthetic-type 'FUNCTION_EXPRESSION)
7309 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7311 (js2-set-face name-beg name-end
7312 'font-lock-function-name-face 'record)))
7313 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7314 (plusp (js2-name-node-length name)))
7315 ;; Function statements define a symbol in the enclosing scope
7316 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7317 (setf fn-node (make-js2-function-node :pos pos
7320 :lp (if lp (- lp pos))))
7321 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7322 ;; 1. Nested functions are not affected by the dynamic scope flag
7323 ;; as dynamic scope is already a parent of their scope.
7324 ;; 2. Functions defined under the with statement also immune to
7325 ;; this setup, in which case dynamic scope is ignored in favor
7326 ;; of the with object.
7327 (setf (js2-function-node-ignore-dynamic fn-node) t))
7328 ;; dynamically bind all the per-function variables
7329 (let ((js2-current-script-or-fn fn-node)
7330 (js2-current-scope fn-node)
7331 (js2-nesting-of-with 0)
7335 js2-loop-and-switch-set)
7336 (js2-parse-function-params fn-node pos)
7337 (if (and (>= js2-language-version 180)
7338 (/= (js2-peek-token) js2-LC))
7339 (js2-parse-function-closure-body fn-node)
7340 (js2-parse-function-body fn-node))
7342 (js2-node-add-children fn-node name))
7343 (js2-check-inconsistent-return-warning fn-node name)
7344 ;; Function expressions define a name only in the body of the
7345 ;; function, and only if not hidden by a parameter name
7347 (eq synthetic-type 'FUNCTION_EXPRESSION)
7348 (null (js2-scope-get-symbol js2-current-scope
7349 (js2-name-node-name name))))
7350 (js2-define-symbol js2-FUNCTION
7351 (js2-name-node-name name)
7354 (not (eq function-type 'FUNCTION_EXPRESSION)))
7355 (js2-record-imenu-functions fn-node)))
7356 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7357 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7358 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7359 ;; We wait until after parsing the function to set its parent scope,
7360 ;; since `js2-define-symbol' needs the defining-scope check to stop
7361 ;; at the function boundary when checking for redeclarations.
7362 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7365 (defun js2-parse-statements (&optional parent)
7366 "Parse a statement list. Last token consumed must be js2-LC.
7368 PARENT can be a `js2-block-node', in which case the statements are
7369 appended to PARENT. Otherwise a new `js2-block-node' is created
7372 This function does not match the closing js2-RC: the caller
7373 matches the RC so it can provide a suitable error message if not
7374 matched. This means it's up to the caller to set the length of
7375 the node to include the closing RC. The node start pos is set to
7376 the absolute buffer start position, and the caller should fix it
7377 up to be relative to the parent node. All children of this block
7378 node are given relative start positions and correct lengths."
7379 (let ((pn (or parent (make-js2-block-node)))
7381 (setf (js2-node-pos pn) js2-token-beg)
7382 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7384 (js2-block-node-push pn (js2-parse-statement)))
7387 (defun js2-parse-statement ()
7388 (let (tt pn beg end)
7389 ;; coarse-grained user-interrupt check - needs work
7390 (and js2-parse-interruptable-p
7391 (zerop (% (incf js2-parse-stmt-count)
7392 js2-statements-per-pause))
7394 (throw 'interrupted t))
7395 (setq pn (js2-statement-helper))
7396 ;; no-side-effects warning check
7397 (unless (js2-node-has-side-effects pn)
7398 (setq end (js2-node-end pn))
7401 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7402 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7405 ;; These correspond to the switch cases in Parser.statementHelper
7406 (defconst js2-parsers
7407 (let ((parsers (make-vector js2-num-tokens
7408 #'js2-parse-expr-stmt)))
7409 (aset parsers js2-BREAK #'js2-parse-break)
7410 (aset parsers js2-CONST #'js2-parse-const-var)
7411 (aset parsers js2-CONTINUE #'js2-parse-continue)
7412 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7413 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7414 (aset parsers js2-DO #'js2-parse-do)
7415 (aset parsers js2-FOR #'js2-parse-for)
7416 (aset parsers js2-FUNCTION #'js2-function-parser)
7417 (aset parsers js2-IF #'js2-parse-if)
7418 (aset parsers js2-LC #'js2-parse-block)
7419 (aset parsers js2-LET #'js2-parse-let-stmt)
7420 (aset parsers js2-NAME #'js2-parse-name-or-label)
7421 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7422 (aset parsers js2-SEMI #'js2-parse-semi)
7423 (aset parsers js2-SWITCH #'js2-parse-switch)
7424 (aset parsers js2-THROW #'js2-parse-throw)
7425 (aset parsers js2-TRY #'js2-parse-try)
7426 (aset parsers js2-VAR #'js2-parse-const-var)
7427 (aset parsers js2-WHILE #'js2-parse-while)
7428 (aset parsers js2-WITH #'js2-parse-with)
7429 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7431 "A vector mapping token types to parser functions.")
7433 (defun js2-parse-warn-missing-semi (beg end)
7434 (and js2-mode-show-strict-warnings
7435 js2-strict-missing-semi-warning
7436 (js2-add-strict-warning
7437 "msg.missing.semi" nil
7438 ;; back up to beginning of statement or line
7439 (max beg (save-excursion
7444 (defconst js2-no-semi-insertion
7456 "List of tokens that don't do automatic semicolon insertion.")
7458 (defconst js2-autoinsert-semi-and-warn
7459 (list js2-ERROR js2-EOF js2-RC))
7461 (defun js2-statement-helper ()
7462 (let* ((tt (js2-peek-token))
7465 (parser (if (= tt js2-ERROR)
7467 (aref js2-parsers tt)))
7470 ;; If the statement is set, then it's been told its label by now.
7471 (and js2-labeled-stmt
7472 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7473 (setq js2-labeled-stmt nil))
7474 (setq pn (funcall parser))
7475 ;; Don't do auto semi insertion for certain statement types.
7476 (unless (or (memq first-tt js2-no-semi-insertion)
7477 (js2-labeled-stmt-node-p pn))
7478 (js2-auto-insert-semicolon pn))
7481 (defun js2-auto-insert-semicolon (pn)
7482 (let* ((tt-flagged (js2-peek-flagged-token))
7483 (tt (logand tt-flagged js2-clear-ti-mask))
7484 (pos (js2-node-pos pn)))
7487 ;; Consume ';' as a part of expression
7489 ;; extend the node bounds to include the semicolon.
7490 (setf (js2-node-len pn) (- js2-token-end pos)))
7491 ((memq tt js2-autoinsert-semi-and-warn)
7493 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7495 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7496 ;; Report error if no EOL or autoinsert ';' otherwise
7497 (js2-report-error "msg.no.semi.stmt")
7498 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7500 (defun js2-parse-condition ()
7501 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7502 The parens are discarded and the expression node is returned.
7503 The `pos' field of the return value is set to an absolute position
7504 that must be fixed up by the caller.
7505 Return value is a list (EXPR LP RP), with absolute paren positions."
7507 (if (js2-must-match js2-LP "msg.no.paren.cond")
7508 (setq lp js2-token-beg))
7509 (setq pn (js2-parse-expr))
7510 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7511 (setq rp js2-token-beg))
7512 ;; Report strict warning on code like "if (a = 7) ..."
7513 (if (and js2-strict-cond-assign-warning
7514 (js2-assign-node-p pn))
7515 (js2-add-strict-warning "msg.equal.as.assign" nil
7517 (+ (js2-node-pos pn)
7518 (js2-node-len pn))))
7521 (defun js2-parse-if ()
7522 "Parser for if-statement. Last matched token must be js2-IF."
7523 (let ((pos js2-token-beg)
7524 cond if-true if-false else-pos end pn)
7526 (setq cond (js2-parse-condition)
7527 if-true (js2-parse-statement)
7528 if-false (if (js2-match-token js2-ELSE)
7530 (setq else-pos (- js2-token-beg pos))
7531 (js2-parse-statement)))
7532 end (js2-node-end (or if-false if-true))
7533 pn (make-js2-if-node :pos pos
7535 :condition (car cond)
7539 :lp (js2-relpos (second cond) pos)
7540 :rp (js2-relpos (third cond) pos)))
7541 (js2-node-add-children pn (car cond) if-true if-false)
7544 (defun js2-parse-switch ()
7545 "Parser for if-statement. Last matched token must be js2-SWITCH."
7546 (let ((pos js2-token-beg)
7547 tt pn discriminant has-default case-expr case-node
7548 case-pos cases stmt lp rp)
7550 (if (js2-must-match js2-LP "msg.no.paren.switch")
7551 (setq lp js2-token-beg))
7552 (setq discriminant (js2-parse-expr)
7553 pn (make-js2-switch-node :discriminant discriminant
7555 :lp (js2-relpos lp pos)))
7556 (js2-node-add-children pn discriminant)
7557 (js2-enter-switch pn)
7560 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7561 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7562 (js2-must-match js2-LC "msg.no.brace.switch")
7565 (setq tt (js2-next-token)
7566 case-pos js2-token-beg)
7569 (setf (js2-node-len pn) (- js2-token-end pos))
7570 (throw 'break nil)) ; done
7572 (setq case-expr (js2-parse-expr))
7573 (js2-must-match js2-COLON "msg.no.colon.case"))
7576 (js2-report-error "msg.double.switch.default"))
7579 (js2-must-match js2-COLON "msg.no.colon.case"))
7581 (js2-report-error "msg.bad.switch")
7582 (throw 'break nil)))
7583 (setq case-node (make-js2-case-node :pos case-pos
7584 :len (- js2-token-end case-pos)
7586 (js2-node-add-children case-node case-expr)
7587 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7591 (setf stmt (js2-parse-statement)
7592 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7593 (js2-block-node-push case-node stmt))
7594 (push case-node cases)))
7595 ;; add cases last, as pushing reverses the order to be correct
7597 (js2-node-add-children pn kid)
7598 (push kid (js2-switch-node-cases pn)))
7600 (js2-exit-switch))))
7602 (defun js2-parse-while ()
7603 "Parser for while-statement. Last matched token must be js2-WHILE."
7604 (let ((pos js2-token-beg)
7605 (pn (make-js2-while-node))
7611 (setf cond (js2-parse-condition)
7612 (js2-while-node-condition pn) (car cond)
7613 body (js2-parse-statement)
7614 (js2-while-node-body pn) body
7615 (js2-node-len pn) (- (js2-node-end body) pos)
7616 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7617 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7618 (js2-node-add-children pn body (car cond)))
7622 (defun js2-parse-do ()
7623 "Parser for do-statement. Last matched token must be js2-DO."
7624 (let ((pos js2-token-beg)
7625 (pn (make-js2-do-node))
7631 (setq body (js2-parse-statement))
7632 (js2-must-match js2-WHILE "msg.no.while.do")
7633 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7634 cond (js2-parse-condition)
7635 (js2-do-node-condition pn) (car cond)
7636 (js2-do-node-body pn) body
7638 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7639 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7640 (js2-node-add-children pn (car cond) body))
7642 ;; Always auto-insert semicolon to follow SpiderMonkey:
7643 ;; It is required by ECMAScript but is ignored by the rest of
7644 ;; world; see bug 238945
7645 (if (js2-match-token js2-SEMI)
7646 (setq end js2-ts-cursor))
7647 (setf (js2-node-len pn) (- end pos))
7650 (defun js2-parse-for ()
7651 "Parser for for-statement. Last matched token must be js2-FOR.
7652 Parses for, for-in, and for each-in statements."
7653 (let ((for-pos js2-token-beg)
7654 pn is-for-each is-for-in-or-of is-for-of
7655 in-pos each-pos tmp-pos
7656 init ; Node init is also foo in 'foo in object'
7657 cond ; Node cond is also object in 'foo in object'
7658 incr ; 3rd section of for-loop initializer
7661 ;; See if this is a for each () instead of just a for ()
7662 (when (js2-match-token js2-NAME)
7663 (if (string= "each" js2-ts-string)
7666 each-pos (- js2-token-beg for-pos)) ; relative
7667 (js2-record-face 'font-lock-keyword-face))
7668 (js2-report-error "msg.no.paren.for")))
7669 (if (js2-must-match js2-LP "msg.no.paren.for")
7670 (setq lp (- js2-token-beg for-pos)))
7671 (setq tt (js2-peek-token))
7672 ;; 'for' makes local scope
7673 (js2-push-scope (make-js2-scope))
7675 ;; parse init clause
7676 (let ((js2-in-for-init t)) ; set as dynamic variable
7679 (setq init (make-js2-empty-expr-node)))
7680 ((or (= tt js2-VAR) (= tt js2-LET))
7682 (setq init (js2-parse-variables tt js2-token-beg)))
7684 (setq init (js2-parse-expr)))))
7685 (if (or (js2-match-token js2-IN)
7686 (and (>= js2-language-version 200)
7687 (js2-match-contextual-kwd "of")
7688 (setq is-for-of t)))
7689 (setq is-for-in-or-of t
7690 in-pos (- js2-token-beg for-pos)
7691 ;; scope of iteration target object is not the scope we've created above.
7692 ;; stash current scope temporary.
7693 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7694 (js2-parse-expr))) ; object over which we're iterating
7695 ;; else ordinary for loop - parse cond and incr
7696 (js2-must-match js2-SEMI "msg.no.semi.for")
7697 (setq cond (if (= (js2-peek-token) js2-SEMI)
7698 (make-js2-empty-expr-node) ; no loop condition
7700 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7701 (setq tmp-pos js2-token-end
7702 incr (if (= (js2-peek-token) js2-RP)
7703 (make-js2-empty-expr-node :pos tmp-pos)
7705 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7706 (setq rp (- js2-token-beg for-pos)))
7707 (if (not is-for-in-or-of)
7708 (setq pn (make-js2-for-node :init init
7713 ;; cond could be null if 'in obj' got eaten by the init node.
7714 (if (js2-infix-node-p init)
7715 ;; it was (foo in bar) instead of (var foo in bar)
7716 (setq cond (js2-infix-node-right init)
7717 init (js2-infix-node-left init))
7718 (if (and (js2-var-decl-node-p init)
7719 (> (length (js2-var-decl-node-kids init)) 1))
7720 (js2-report-error "msg.mult.index")))
7721 (setq pn (make-js2-for-in-node :iterator init
7724 :foreach-p is-for-each
7732 ;; We have to parse the body -after- creating the loop node,
7733 ;; so that the loop node appears in the js2-loop-set, allowing
7734 ;; break/continue statements to find the enclosing loop.
7735 (setf body (js2-parse-statement)
7736 (js2-loop-node-body pn) body
7737 (js2-node-pos pn) for-pos
7738 (js2-node-len pn) (- (js2-node-end body) for-pos))
7739 (js2-node-add-children pn init cond incr body))
7745 (defun js2-parse-try ()
7746 "Parser for try-statement. Last matched token must be js2-TRY."
7747 (let ((try-pos js2-token-beg)
7765 (if (/= (js2-peek-token) js2-LC)
7766 (js2-report-error "msg.no.brace.try"))
7767 (setq try-block (js2-parse-statement)
7768 try-end (js2-node-end try-block)
7769 peek (js2-peek-token))
7772 (while (js2-match-token js2-CATCH)
7773 (setq catch-pos js2-token-beg
7778 (if saw-default-catch
7779 (js2-report-error "msg.catch.unreachable"))
7780 (if (js2-must-match js2-LP "msg.no.paren.catch")
7781 (setq lp (- js2-token-beg catch-pos)))
7782 (js2-push-scope (make-js2-scope))
7783 (let ((tt (js2-peek-token)))
7785 ;; destructuring pattern
7786 ;; catch ({ message, file }) { ... }
7787 ((or (= tt js2-LB) (= tt js2-LC))
7788 (setq param (js2-parse-destruct-primary-expr))
7789 (js2-define-destruct-symbols param js2-LET nil))
7792 (js2-must-match js2-NAME "msg.bad.catchcond")
7793 (setq param (js2-create-name-node))
7794 (js2-define-symbol js2-LET js2-ts-string param))))
7796 (if (js2-match-token js2-IF)
7797 (setq guard-kwd (- js2-token-beg catch-pos)
7798 catch-cond (js2-parse-expr))
7799 (setq saw-default-catch t))
7800 (if (js2-must-match js2-RP "msg.bad.catchcond")
7801 (setq rp (- js2-token-beg catch-pos)))
7802 (js2-must-match js2-LC "msg.no.brace.catchblock")
7803 (setq block (js2-parse-statements)
7804 try-end (js2-node-end block)
7805 catch-node (make-js2-catch-node :pos catch-pos
7807 :guard-expr catch-cond
7808 :guard-kwd guard-kwd
7813 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7814 (setq try-end js2-token-beg))
7815 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7816 (js2-node-len catch-node) (- try-end catch-pos))
7817 (js2-node-add-children catch-node param catch-cond block)
7818 (push catch-node catch-blocks)))
7819 ((/= peek js2-FINALLY)
7820 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7821 (js2-node-pos try-block)
7822 (- (setq try-end (js2-node-end try-block))
7823 (js2-node-pos try-block)))))
7824 (when (js2-match-token js2-FINALLY)
7825 (setq finally-pos js2-token-beg
7826 block (js2-parse-statement)
7827 try-end (js2-node-end block)
7828 finally-block (make-js2-finally-node :pos finally-pos
7829 :len (- try-end finally-pos)
7831 (js2-node-add-children finally-block block))
7832 (setq pn (make-js2-try-node :pos try-pos
7833 :len (- try-end try-pos)
7834 :try-block try-block
7835 :finally-block finally-block))
7836 (js2-node-add-children pn try-block finally-block)
7837 ;; push them onto the try-node, which reverses and corrects their order
7838 (dolist (cb catch-blocks)
7839 (js2-node-add-children pn cb)
7840 (push cb (js2-try-node-catch-clauses pn)))
7843 (defun js2-parse-throw ()
7844 "Parser for throw-statement. Last matched token must be js2-THROW."
7845 (let ((pos js2-token-beg)
7848 (if (= (js2-peek-token-or-eol) js2-EOL)
7849 ;; ECMAScript does not allow new lines before throw expression,
7851 (js2-report-error "msg.bad.throw.eol"))
7852 (setq expr (js2-parse-expr)
7853 pn (make-js2-throw-node :pos pos
7854 :len (- (js2-node-end expr) pos)
7856 (js2-node-add-children pn expr)
7859 (defun js2-match-jump-label-name (label-name)
7860 "If break/continue specified a label, return that label's labeled stmt.
7861 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7862 does not match an existing label, reports an error and returns nil."
7863 (let ((bundle (cdr (assoc label-name js2-label-set))))
7865 (js2-report-error "msg.undef.label"))
7868 (defun js2-parse-break ()
7869 "Parser for break-statement. Last matched token must be js2-BREAK."
7870 (let ((pos js2-token-beg)
7872 break-target ; statement to break from
7873 break-label ; in "break foo", name-node representing the foo
7874 labels ; matching labeled statement to break to
7876 (js2-consume-token) ; `break'
7877 (when (eq (js2-peek-token-or-eol) js2-NAME)
7879 (setq break-label (js2-create-name-node)
7880 end (js2-node-end break-label)
7881 ;; matchJumpLabelName only matches if there is one
7882 labels (js2-match-jump-label-name js2-ts-string)
7883 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7884 (unless (or break-target break-label)
7885 ;; no break target specified - try for innermost enclosing loop/switch
7886 (if (null js2-loop-and-switch-set)
7888 (js2-report-error "msg.bad.break" nil pos (length "break")))
7889 (setq break-target (car js2-loop-and-switch-set))))
7890 (setq pn (make-js2-break-node :pos pos
7893 :target break-target))
7894 (js2-node-add-children pn break-label) ; but not break-target
7897 (defun js2-parse-continue ()
7898 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7899 (let ((pos js2-token-beg)
7901 label ; optional user-specified label, a `js2-name-node'
7902 labels ; current matching labeled stmt, if any
7903 target ; the `js2-loop-node' target of this continue stmt
7905 (js2-consume-token) ; `continue'
7906 (when (= (js2-peek-token-or-eol) js2-NAME)
7908 (setq label (js2-create-name-node)
7909 end (js2-node-end label)
7910 ;; matchJumpLabelName only matches if there is one
7911 labels (js2-match-jump-label-name js2-ts-string)))
7913 ((null labels) ; no current label to go to
7914 (if (null js2-loop-set) ; no loop to continue to
7915 (js2-report-error "msg.continue.outside" nil pos
7916 (length "continue"))
7917 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7919 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7920 (setq target (js2-labeled-stmt-node-stmt labels))
7921 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7922 (setq pn (make-js2-continue-node :pos pos
7926 (js2-node-add-children pn label) ; but not target - it's not our child
7929 (defun js2-parse-with ()
7930 "Parser for with-statement. Last matched token must be js2-WITH."
7932 (let ((pos js2-token-beg)
7934 (if (js2-must-match js2-LP "msg.no.paren.with")
7935 (setq lp js2-token-beg))
7936 (setq obj (js2-parse-expr))
7937 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7938 (setq rp js2-token-beg))
7939 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7940 (setq body (js2-parse-statement)))
7941 (setq pn (make-js2-with-node :pos pos
7942 :len (- (js2-node-end body) pos)
7945 :lp (js2-relpos lp pos)
7946 :rp (js2-relpos rp pos)))
7947 (js2-node-add-children pn obj body)
7950 (defun js2-parse-const-var ()
7951 "Parser for var- or const-statement.
7952 Last matched token must be js2-CONST or js2-VAR."
7953 (let ((tt (js2-peek-token))
7957 (setq expr (js2-parse-variables tt js2-token-beg)
7958 pn (make-js2-expr-stmt-node :pos pos
7959 :len (- (js2-node-end expr) pos)
7961 (js2-node-add-children pn expr)
7964 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
7965 (let ((pn (make-js2-expr-stmt-node :pos pos
7966 :len (js2-node-len expr)
7967 :type (if (js2-inside-function)
7972 (js2-node-add-children pn expr))
7975 (defun js2-parse-let-stmt ()
7976 "Parser for let-statement. Last matched token must be js2-LET."
7978 (let ((pos js2-token-beg)
7980 (if (= (js2-peek-token) js2-LP)
7981 ;; let expression in statement context
7982 (setq expr (js2-parse-let pos 'statement)
7983 pn (js2-wrap-with-expr-stmt pos expr t))
7984 ;; else we're looking at a statement like let x=6, y=7;
7985 (setf expr (js2-parse-variables js2-LET pos)
7986 pn (js2-wrap-with-expr-stmt pos expr t)
7987 (js2-node-type pn) js2-EXPR_RESULT))
7990 (defun js2-parse-ret-yield ()
7991 (js2-parse-return-or-yield (js2-peek-token) nil))
7993 (defconst js2-parse-return-stmt-enders
7994 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
7996 (defsubst js2-now-all-set (before after mask)
7997 "Return whether or not the bits in the mask have changed to all set.
7998 BEFORE is bits before change, AFTER is bits after change, and MASK is
7999 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8001 (and (/= (logand before mask) mask)
8002 (= (logand after mask) mask)))
8004 (defun js2-parse-return-or-yield (tt expr-context)
8005 (let ((pos js2-token-beg)
8007 (before js2-end-flags)
8008 (inside-function (js2-inside-function))
8010 (unless inside-function
8011 (js2-report-error (if (eq tt js2-RETURN)
8015 ;; This is ugly, but we don't want to require a semicolon.
8016 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8017 (setq e (js2-parse-expr)
8018 end (js2-node-end e)))
8021 (js2-set-flag js2-end-flags (if (null e)
8023 js2-end-returns-value))
8024 (setq ret (make-js2-return-node :pos pos
8027 (js2-node-add-children ret e)
8028 ;; See if we need a strict mode warning.
8029 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8030 ;; more thorough and accurate than this before/after flag check.
8031 ;; E.g. if there's a finally-block that always returns, we shouldn't
8032 ;; show a warning generated by inconsistent returns in the catch blocks.
8033 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8034 ;; so we know which returns/yields to highlight, and we should get rid of
8035 ;; all the checking in `js2-parse-return-or-yield'.
8036 (if (and js2-strict-inconsistent-return-warning
8037 (js2-now-all-set before js2-end-flags
8038 (logior js2-end-returns js2-end-returns-value)))
8039 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8041 (unless (js2-inside-function)
8042 (js2-report-error "msg.bad.yield"))
8043 (js2-set-flag js2-end-flags js2-end-yields)
8044 (setq ret (make-js2-yield-node :pos pos
8047 (js2-node-add-children ret e)
8048 (unless expr-context
8050 ret (js2-wrap-with-expr-stmt pos e t))
8051 (js2-set-requires-activation)
8052 (js2-set-is-generator))))
8053 ;; see if we are mixing yields and value returns.
8054 (when (and inside-function
8055 (js2-now-all-set before js2-end-flags
8056 (logior js2-end-yields js2-end-returns-value)))
8057 (setq name (js2-function-name js2-current-script-or-fn))
8058 (if (zerop (length name))
8059 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8060 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8063 (defun js2-parse-debugger ()
8065 (make-js2-keyword-node :type js2-DEBUGGER))
8067 (defun js2-parse-block ()
8068 "Parser for a curly-delimited statement block.
8069 Last token matched must be `js2-LC'."
8070 (let ((pos js2-token-beg)
8071 (pn (make-js2-scope)))
8076 (js2-parse-statements pn)
8077 (js2-must-match js2-RC "msg.no.brace.block")
8078 (setf (js2-node-len pn) (- js2-token-end pos)))
8082 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8083 (defun js2-parse-semi ()
8084 "Parse a statement or handle an error.
8085 Last matched token is `js2-SEMI' or `js2-ERROR'."
8086 (let ((tt (js2-peek-token)) pos len)
8088 (if (eq tt js2-SEMI)
8089 (make-js2-empty-expr-node :len 1)
8090 (setq pos js2-token-beg
8091 len (- js2-token-beg pos))
8092 (js2-report-error "msg.syntax" nil pos len)
8093 (make-js2-error-node :pos pos :len len))))
8095 (defun js2-parse-default-xml-namespace ()
8096 "Parse a `default xml namespace = <expr>' e4x statement."
8097 (let ((pos js2-token-beg)
8098 end len expr unary es)
8101 (js2-set-requires-activation)
8102 (setq len (- js2-ts-cursor pos))
8103 (unless (and (js2-match-token js2-NAME)
8104 (string= js2-ts-string "xml"))
8105 (js2-report-error "msg.bad.namespace" nil pos len))
8106 (unless (and (js2-match-token js2-NAME)
8107 (string= js2-ts-string "namespace"))
8108 (js2-report-error "msg.bad.namespace" nil pos len))
8109 (unless (js2-match-token js2-ASSIGN)
8110 (js2-report-error "msg.bad.namespace" nil pos len))
8111 (setq expr (js2-parse-expr)
8112 end (js2-node-end expr)
8113 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8117 (js2-node-add-children unary expr)
8118 (make-js2-expr-stmt-node :pos pos
8122 (defun js2-record-label (label bundle)
8123 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8125 (let ((name (js2-label-node-name label))
8128 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8129 ;; flag both labels if possible when used in editing mode
8130 (if (and js2-parse-ide-mode
8131 (setq dup (js2-get-label-by-name labeled-stmt name)))
8132 (js2-report-error "msg.dup.label" nil
8133 (js2-node-abs-pos dup) (js2-node-len dup)))
8134 (js2-report-error "msg.dup.label" nil
8135 (js2-node-pos label) (js2-node-len label)))
8136 (js2-labeled-stmt-node-add-label bundle label)
8137 (js2-node-add-children bundle label)
8138 ;; Add one reference to the bundle per label in `js2-label-set'
8139 (push (cons name bundle) js2-label-set)))
8141 (defun js2-parse-name-or-label ()
8142 "Parser for identifier or label. Last token matched must be js2-NAME.
8143 Called when we found a name in a statement context. If it's a label, we gather
8144 up any following labels and the next non-label statement into a
8145 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8146 expression and return it wrapped in a `js2-expr-stmt-node'."
8147 (let ((pos js2-token-beg)
8151 ;; set check for label and call down to `js2-parse-primary-expr'
8152 (js2-set-check-for-label)
8153 (setq expr (js2-parse-expr))
8154 (if (/= (js2-node-type expr) js2-LABEL)
8155 ;; Parsed non-label expression - wrap with expression stmt.
8156 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8157 ;; else parsed a label
8158 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8159 (js2-record-label expr bundle)
8160 ;; look for more labels
8161 (while (and continue (= (js2-peek-token) js2-NAME))
8162 (js2-set-check-for-label)
8163 (setq expr (js2-parse-expr))
8164 (if (/= (js2-node-type expr) js2-LABEL)
8166 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8168 (js2-auto-insert-semicolon stmt))
8169 (js2-record-label expr bundle)))
8170 ;; no more labels; now parse the labeled statement
8173 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8174 (setq stmt (js2-statement-helper))))
8175 ;; remove the labels for this statement from the global set
8176 (dolist (label (js2-labeled-stmt-node-labels bundle))
8177 (setq js2-label-set (remove label js2-label-set))))
8178 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8179 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8180 (js2-node-add-children bundle stmt)
8183 (defun js2-parse-expr-stmt ()
8184 "Default parser in statement context, if no recognized statement found."
8185 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8187 (defun js2-parse-variables (decl-type pos)
8188 "Parse a comma-separated list of variable declarations.
8189 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8191 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8192 For 'var' or 'const', the keyword should be the token last scanned.
8194 POS is the position where the node should start. It's sometimes the
8195 var/const/let keyword, and other times the beginning of the first token
8196 in the first variable declaration.
8198 Returns the parsed `js2-var-decl-node' expression node."
8199 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8201 destructuring kid-pos tt init name end nbeg nend vi
8204 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8205 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8206 ;; var {a, b} = baz;
8208 (setq destructuring nil
8211 kid-pos js2-token-beg
8214 (if (or (= tt js2-LB) (= tt js2-LC))
8215 ;; Destructuring assignment, e.g., var [a, b] = ...
8216 (setq destructuring (js2-parse-destruct-primary-expr)
8217 end (js2-node-end destructuring))
8218 ;; Simple variable name
8219 (when (js2-must-match js2-NAME "msg.bad.var")
8220 (setq name (js2-create-name-node)
8224 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8225 (when (js2-match-token js2-ASSIGN)
8226 (setq init (js2-parse-assign-expr)
8227 end (js2-node-end init))
8228 (js2-record-imenu-functions init name))
8230 (js2-set-face nbeg nend (if (js2-function-node-p init)
8231 'font-lock-function-name-face
8232 'font-lock-variable-name-face)
8234 (setq vi (make-js2-var-init-node :pos kid-pos
8235 :len (- end kid-pos)
8239 (if (and (null init) (not js2-in-for-init))
8240 (js2-report-error "msg.destruct.assign.no.init"))
8241 (js2-define-destruct-symbols destructuring
8243 'font-lock-variable-name-face)
8244 (setf (js2-var-init-node-target vi) destructuring))
8245 (setf (js2-var-init-node-target vi) name))
8246 (setf (js2-var-init-node-initializer vi) init)
8247 (js2-node-add-children vi name destructuring init)
8248 (js2-block-node-push result vi)
8249 (unless (js2-match-token js2-COMMA)
8250 (setq continue nil)))
8251 (setf (js2-node-len result) (- end pos))
8254 (defun js2-parse-let (pos &optional stmt-p)
8255 "Parse a let expression or statement.
8256 A let-expression is of the form `let (vars) expr'.
8257 A let-statment is of the form `let (vars) {statements}'.
8258 The third form of let is a variable declaration list, handled
8259 by `js2-parse-variables'."
8260 (let ((pn (make-js2-let-node :pos pos))
8262 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8263 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8267 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8268 (if (js2-must-match js2-RP "msg.no.paren.let")
8269 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8270 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8274 (setf beg js2-token-beg ; position stmt at LC
8275 body (js2-parse-statements))
8276 (js2-must-match js2-RC "msg.no.curly.let")
8277 (setf (js2-node-len body) (- js2-token-end beg)
8278 (js2-node-len pn) (- js2-token-end pos)
8279 (js2-let-node-body pn) body
8280 (js2-node-type pn) js2-LET))
8282 (setf body (js2-parse-expr)
8283 (js2-node-len pn) (- (js2-node-end body) pos)
8284 (js2-let-node-body pn) body))
8285 (js2-node-add-children pn vars body))
8289 (defun js2-define-new-symbol (decl-type name node &optional scope)
8290 (js2-scope-put-symbol (or scope js2-current-scope)
8292 (make-js2-symbol decl-type name node)))
8294 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8295 "Define a symbol in the current scope.
8296 If NODE is non-nil, it is the AST node associated with the symbol."
8297 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8298 (symbol (if defining-scope
8299 (js2-scope-get-symbol defining-scope name)))
8300 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8302 ((and symbol ; already defined
8303 (or (= sdt js2-CONST) ; old version is const
8304 (= decl-type js2-CONST) ; new version is const
8305 ;; two let-bound vars in this block have same name
8306 (and (= sdt js2-LET)
8307 (eq defining-scope js2-current-scope))))
8310 ((= sdt js2-CONST) "msg.const.redecl")
8311 ((= sdt js2-LET) "msg.let.redecl")
8312 ((= sdt js2-VAR) "msg.var.redecl")
8313 ((= sdt js2-FUNCTION) "msg.function.redecl")
8314 (t "msg.parm.redecl"))
8316 ((= decl-type js2-LET)
8317 (if (and (not ignore-not-in-block)
8318 (or (= (js2-node-type js2-current-scope) js2-IF)
8319 (js2-loop-node-p js2-current-scope)))
8320 (js2-report-error "msg.let.decl.not.in.block")
8321 (js2-define-new-symbol decl-type name node)))
8322 ((or (= decl-type js2-VAR)
8323 (= decl-type js2-CONST)
8324 (= decl-type js2-FUNCTION))
8326 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8327 (js2-add-strict-warning "msg.var.redecl" name)
8328 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8329 (js2-add-strict-warning "msg.var.hides.arg" name)))
8330 (js2-define-new-symbol decl-type name node
8331 js2-current-script-or-fn)))
8332 ((= decl-type js2-LP)
8334 ;; must be duplicate parameter. Second parameter hides the
8335 ;; first, so go ahead and add the second pararameter
8336 (js2-report-warning "msg.dup.parms" name))
8337 (js2-define-new-symbol decl-type name node))
8338 (t (js2-code-bug)))))
8340 (defun js2-parse-expr (&optional oneshot)
8341 (let* ((pn (js2-parse-assign-expr))
8342 (pos (js2-node-pos pn))
8346 (while (and (not oneshot)
8347 (js2-match-token js2-COMMA))
8348 (setq op-pos (- js2-token-beg pos)) ; relative
8349 (if (= (js2-peek-token) js2-YIELD)
8350 (js2-report-error "msg.yield.parenthesized"))
8351 (setq right (js2-parse-assign-expr)
8353 pn (make-js2-infix-node :type js2-COMMA
8355 :len (- js2-ts-cursor pos)
8359 (js2-node-add-children pn left right))
8362 (defun js2-parse-assign-expr ()
8363 (let ((tt (js2-peek-token))
8365 pn left right op-pos)
8366 (if (= tt js2-YIELD)
8367 (js2-parse-return-or-yield tt t)
8368 ;; not yield - parse assignment expression
8369 (setq pn (js2-parse-cond-expr)
8370 tt (js2-peek-token))
8371 (when (and (<= js2-first-assign tt)
8372 (<= tt js2-last-assign))
8373 ;; tt express assignment (=, |=, ^=, ..., %=)
8375 (setq op-pos (- js2-token-beg pos) ; relative
8377 right (js2-parse-assign-expr)
8378 pn (make-js2-assign-node :type tt
8380 :len (- (js2-node-end right) pos)
8384 (when js2-parse-ide-mode
8385 (js2-highlight-assign-targets pn left right)
8386 (js2-record-imenu-functions right left))
8387 ;; do this last so ide checks above can use absolute positions
8388 (js2-node-add-children pn left right))
8391 (defun js2-parse-cond-expr ()
8392 (let ((pos js2-token-beg)
8393 (pn (js2-parse-or-expr))
8399 (when (js2-match-token js2-HOOK)
8400 (setq q-pos (- js2-token-beg pos)
8401 if-true (js2-parse-assign-expr))
8402 (js2-must-match js2-COLON "msg.no.colon.cond")
8403 (setq c-pos (- js2-token-beg pos)
8404 if-false (js2-parse-assign-expr)
8406 pn (make-js2-cond-node :pos pos
8407 :len (- (js2-node-end if-false) pos)
8408 :test-expr test-expr
8410 :false-expr if-false
8413 (js2-node-add-children pn test-expr if-true if-false))
8416 (defun js2-make-binary (type left parser)
8417 "Helper for constructing a binary-operator AST node.
8418 LEFT is the left-side-expression, already parsed, and the
8419 binary operator should have just been matched.
8420 PARSER is a function to call to parse the right operand,
8421 or a `js2-node' struct if it has already been parsed."
8422 (let* ((pos (js2-node-pos left))
8423 (op-pos (- js2-token-beg pos))
8424 (right (if (js2-node-p parser)
8427 (pn (make-js2-infix-node :type type
8429 :len (- (js2-node-end right) pos)
8433 (js2-node-add-children pn left right)
8436 (defun js2-parse-or-expr ()
8437 (let ((pn (js2-parse-and-expr)))
8438 (when (js2-match-token js2-OR)
8439 (setq pn (js2-make-binary js2-OR
8441 'js2-parse-or-expr)))
8444 (defun js2-parse-and-expr ()
8445 (let ((pn (js2-parse-bit-or-expr)))
8446 (when (js2-match-token js2-AND)
8447 (setq pn (js2-make-binary js2-AND
8449 'js2-parse-and-expr)))
8452 (defun js2-parse-bit-or-expr ()
8453 (let ((pn (js2-parse-bit-xor-expr)))
8454 (while (js2-match-token js2-BITOR)
8455 (setq pn (js2-make-binary js2-BITOR
8457 'js2-parse-bit-xor-expr)))
8460 (defun js2-parse-bit-xor-expr ()
8461 (let ((pn (js2-parse-bit-and-expr)))
8462 (while (js2-match-token js2-BITXOR)
8463 (setq pn (js2-make-binary js2-BITXOR
8465 'js2-parse-bit-and-expr)))
8468 (defun js2-parse-bit-and-expr ()
8469 (let ((pn (js2-parse-eq-expr)))
8470 (while (js2-match-token js2-BITAND)
8471 (setq pn (js2-make-binary js2-BITAND
8473 'js2-parse-eq-expr)))
8476 (defconst js2-parse-eq-ops
8477 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8479 (defun js2-parse-eq-expr ()
8480 (let ((pn (js2-parse-rel-expr))
8482 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8484 (setq pn (js2-make-binary tt
8486 'js2-parse-rel-expr)))
8489 (defconst js2-parse-rel-ops
8490 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8492 (defun js2-parse-rel-expr ()
8493 (let ((pn (js2-parse-shift-expr))
8497 (setq tt (js2-peek-token))
8499 ((and js2-in-for-init (= tt js2-IN))
8500 (setq continue nil))
8501 ((memq tt js2-parse-rel-ops)
8503 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8505 (setq continue nil))))
8508 (defconst js2-parse-shift-ops
8509 (list js2-LSH js2-URSH js2-RSH))
8511 (defun js2-parse-shift-expr ()
8512 (let ((pn (js2-parse-add-expr))
8516 (setq tt (js2-peek-token))
8517 (if (memq tt js2-parse-shift-ops)
8520 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8521 (setq continue nil)))
8524 (defun js2-parse-add-expr ()
8525 (let ((pn (js2-parse-mul-expr))
8529 (setq tt (js2-peek-token))
8530 (if (or (= tt js2-ADD) (= tt js2-SUB))
8533 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8534 (setq continue nil)))
8537 (defconst js2-parse-mul-ops
8538 (list js2-MUL js2-DIV js2-MOD))
8540 (defun js2-parse-mul-expr ()
8541 (let ((pn (js2-parse-unary-expr))
8545 (setq tt (js2-peek-token))
8546 (if (memq tt js2-parse-mul-ops)
8549 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8550 (setq continue nil)))
8553 (defun js2-make-unary (type parser &rest args)
8554 "Make a unary node of type TYPE.
8555 PARSER is either a node (for postfix operators) or a function to call
8556 to parse the operand (for prefix operators)."
8557 (let* ((pos js2-token-beg)
8558 (postfix (js2-node-p parser))
8561 (apply parser args)))
8564 (if postfix ; e.g. i++
8565 (setq pos (js2-node-pos expr)
8567 (setq end (js2-node-end expr)))
8568 (setq pn (make-js2-unary-node :type type
8572 (js2-node-add-children pn expr)
8575 (defconst js2-incrementable-node-types
8576 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8577 "Node types that can be the operand of a ++ or -- operator.")
8579 (defun js2-check-bad-inc-dec (tt beg end unary)
8580 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8581 js2-incrementable-node-types)
8582 (js2-report-error (if (= tt js2-INC)
8585 nil beg (- end beg))))
8587 (defun js2-parse-unary-expr ()
8588 (let ((tt (js2-peek-token))
8591 ((or (= tt js2-VOID)
8596 (js2-make-unary tt 'js2-parse-unary-expr))
8599 ;; Convert to special POS token in decompiler and parse tree
8600 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8603 ;; Convert to special NEG token in decompiler and parse tree
8604 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8609 (setq beg js2-token-beg
8611 expr (js2-make-unary tt 'js2-parse-member-expr t))
8612 (js2-check-bad-inc-dec tt beg end expr)))
8615 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8618 (make-js2-error-node)) ; try to continue
8620 js2-compiler-xml-available)
8621 ;; XML stream encountered in expression.
8623 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8625 (setq pn (js2-parse-member-expr t)
8626 ;; Don't look across a newline boundary for a postfix incop.
8627 tt (js2-peek-token-or-eol))
8628 (when (or (= tt js2-INC) (= tt js2-DEC))
8631 pn (js2-make-unary tt expr))
8632 (js2-node-set-prop pn 'postfix t)
8633 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8636 (defun js2-parse-xml-initializer ()
8637 "Parse an E4X XML initializer.
8638 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8639 Then I'll postprocess the result, depending on whether we're in IDE
8640 mode or codegen mode, and generate the appropriate rewritten AST.
8641 IDE mode uses a rich AST that models the XML structure. Codegen mode
8642 just concatenates everything and makes a new XML or XMLList out of it."
8643 (let ((tt (js2-get-first-xml-token))
8644 pn-xml pn expr kids expr-pos
8647 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8648 (js2-report-error "msg.syntax"))
8649 (setq pn-xml (make-js2-xml-node))
8652 (setq first-token nil)
8653 (setq tt (js2-get-next-xml-token)))
8655 ;; js2-XML means we found a {expr} in the XML stream.
8656 ;; The js2-ts-string is the XML up to the left-curly.
8658 (push (make-js2-string-node :pos js2-token-beg
8659 :len (- js2-ts-cursor js2-token-beg))
8661 (js2-must-match js2-LC "msg.syntax")
8662 (setq expr-pos js2-ts-cursor
8663 expr (if (eq (js2-peek-token) js2-RC)
8664 (make-js2-empty-expr-node :pos expr-pos)
8666 (js2-must-match js2-RC "msg.syntax")
8667 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8668 :len (js2-node-len expr)
8670 (js2-node-add-children pn expr)
8672 ;; a js2-XMLEND token means we hit the final close-tag.
8674 (push (make-js2-string-node :pos js2-token-beg
8675 :len (- js2-ts-cursor js2-token-beg))
8677 (dolist (kid (nreverse kids))
8678 (js2-block-node-push pn-xml kid))
8679 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8680 (js2-node-pos pn-xml))
8683 (js2-report-error "msg.syntax")
8684 (setq continue nil))))
8688 (defun js2-parse-argument-list ()
8689 "Parse an argument list and return it as a Lisp list of nodes.
8690 Returns the list in reverse order. Consumes the right-paren token."
8692 (unless (js2-match-token js2-RP)
8694 (if (= (js2-peek-token) js2-YIELD)
8695 (js2-report-error "msg.yield.parenthesized"))
8696 (push (js2-parse-assign-expr) result)
8698 (js2-match-token js2-COMMA))
8699 (js2-must-match js2-RP "msg.no.paren.arg")
8702 (defun js2-parse-member-expr (&optional allow-call-syntax)
8703 (let ((tt (js2-peek-token))
8704 pn pos target args beg end init tail)
8706 (setq pn (js2-parse-primary-expr))
8707 ;; parse a 'new' expression
8709 (setq pos js2-token-beg
8711 target (js2-parse-member-expr)
8712 end (js2-node-end target)
8713 pn (make-js2-new-node :pos pos
8716 (js2-node-add-children pn target)
8717 (when (js2-match-token js2-LP)
8718 ;; Add the arguments to pn, if any are supplied.
8719 (setf beg pos ; start of "new" keyword
8721 args (nreverse (js2-parse-argument-list))
8722 (js2-new-node-args pn) args
8724 (js2-new-node-lp pn) (- pos beg)
8725 (js2-new-node-rp pn) (- end 1 beg))
8726 (apply #'js2-node-add-children pn args))
8727 (when (and js2-allow-rhino-new-expr-initializer
8728 (js2-match-token js2-LC))
8729 (setf init (js2-parse-object-literal)
8730 end (js2-node-end init)
8731 (js2-new-node-initializer pn) init)
8732 (js2-node-add-children pn init))
8733 (setf (js2-node-len pn) (- end beg))) ; end outer if
8734 (js2-parse-member-expr-tail allow-call-syntax pn)))
8736 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8737 "Parse a chain of property/array accesses or function calls.
8738 Includes parsing for E4X operators like `..' and `.@'.
8739 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8740 Returns an expression tree that includes PN, the parent node."
8741 (let ((beg (js2-node-pos pn))
8745 (setq tt (js2-peek-token))
8747 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8748 (setq pn (js2-parse-property-access tt pn)))
8749 ((= tt js2-DOTQUERY)
8750 (setq pn (js2-parse-dot-query pn)))
8752 (setq pn (js2-parse-element-get pn)))
8754 (if allow-call-syntax
8755 (setq pn (js2-parse-function-call pn))
8756 (setq continue nil)))
8758 (setq continue nil))))
8759 (if (>= js2-highlight-level 2)
8760 (js2-parse-highlight-member-expr-node pn))
8763 (defun js2-parse-dot-query (pn)
8764 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8765 Last token parsed must be `js2-DOTQUERY'."
8766 (let ((pos (js2-node-pos pn))
8770 (js2-set-requires-activation)
8771 (setq op-pos js2-token-beg
8772 expr (js2-parse-expr)
8773 end (js2-node-end expr)
8774 pn (make-js2-xml-dot-query-node :left pn
8778 (js2-node-add-children pn
8779 (js2-xml-dot-query-node-left pn)
8780 (js2-xml-dot-query-node-right pn))
8781 (if (js2-must-match js2-RP "msg.no.paren")
8782 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8784 (setf (js2-node-len pn) (- end pos))
8787 (defun js2-parse-element-get (pn)
8788 "Parse an element-get expression, e.g. foo[bar].
8789 Last token parsed must be `js2-RB'."
8790 (let ((lb js2-token-beg)
8791 (pos (js2-node-pos pn))
8794 (setq expr (js2-parse-expr))
8795 (if (js2-must-match js2-RB "msg.no.bracket.index")
8796 (setq rb js2-token-beg))
8797 (setq pn (make-js2-elem-get-node :target pn
8800 :lb (js2-relpos lb pos)
8801 :rb (js2-relpos rb pos)
8802 :len (- js2-token-end pos)))
8803 (js2-node-add-children pn
8804 (js2-elem-get-node-target pn)
8805 (js2-elem-get-node-element pn))
8808 (defun js2-parse-function-call (pn)
8810 (pos (js2-node-pos pn)))
8812 (setq pn (make-js2-call-node :pos pos
8814 :lp (- js2-token-beg pos)))
8815 (js2-node-add-children pn (js2-call-node-target pn))
8816 ;; Add the arguments to pn, if any are supplied.
8817 (setf args (nreverse (js2-parse-argument-list))
8818 (js2-call-node-rp pn) (- js2-token-beg pos)
8819 (js2-call-node-args pn) args)
8820 (apply #'js2-node-add-children pn args)
8821 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8824 (defun js2-parse-property-access (tt pn)
8825 "Parse a property access, XML descendants access, or XML attr access."
8826 (let ((member-type-flags 0)
8827 (dot-pos js2-token-beg)
8828 (dot-len (if (= tt js2-DOTDOT) 2 1))
8830 ref ; right side of . or .. operator
8833 (when (= tt js2-DOTDOT)
8835 (setq member-type-flags js2-descendants-flag))
8836 (if (not js2-compiler-xml-available)
8838 (js2-must-match-prop-name "msg.no.name.after.dot")
8839 (setq name (js2-create-name-node t js2-GETPROP)
8840 result (make-js2-prop-get-node :left pn
8843 :len (- js2-token-end
8845 (js2-node-add-children result pn name)
8847 ;; otherwise look for XML operators
8848 (setf result (if (= tt js2-DOT)
8849 (make-js2-prop-get-node)
8850 (make-js2-infix-node :type js2-DOTDOT))
8851 (js2-node-pos result) (js2-node-pos pn)
8852 (js2-infix-node-op-pos result) dot-pos
8853 (js2-infix-node-left result) pn ; do this after setting position
8854 tt (js2-next-token))
8856 ;; needed for generator.throw()
8858 (js2-save-name-token-data js2-token-beg "throw")
8859 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8860 ;; handles: name, ns::name, ns::*, ns::[expr]
8861 ((js2-valid-prop-name-token tt)
8862 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8863 ;; handles: *, *::name, *::*, *::[expr]
8865 (js2-save-name-token-data js2-token-beg "*")
8866 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8867 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8869 (setq result (js2-parse-attribute-access)))
8871 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8873 (setf (js2-node-len result) (- (js2-node-end ref)
8874 (js2-node-pos result))
8875 (js2-infix-node-right result) ref))
8876 (if (js2-infix-node-p result)
8877 (js2-node-add-children result
8878 (js2-infix-node-left result)
8879 (js2-infix-node-right result)))
8882 (defun js2-parse-attribute-access ()
8883 "Parse an E4X XML attribute expression.
8884 This includes expressions of the forms:
8886 @attr @ns::attr @ns::*
8888 @[expr] @*::[expr] @ns::[expr]
8890 Called if we peeked an '@' token."
8891 (let ((tt (js2-next-token))
8892 (at-pos js2-token-beg))
8894 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8895 ((js2-valid-prop-name-token tt)
8896 (js2-parse-property-name at-pos js2-ts-string 0))
8897 ;; handles: @*, @*::name, @*::*, @*::[expr]
8899 (js2-save-name-token-data js2-token-beg "*")
8900 (js2-parse-property-name js2-token-beg "*" 0))
8903 (js2-parse-xml-elem-ref at-pos))
8905 (js2-report-error "msg.no.name.after.xmlAttr")
8906 ;; Avoid cascaded errors that happen if we make an error node here.
8907 (js2-save-name-token-data js2-token-beg "")
8908 (js2-parse-property-name js2-token-beg "" 0)))))
8910 (defun js2-parse-property-name (at-pos s member-type-flags)
8911 "Check if :: follows name in which case it becomes qualified name.
8913 AT-POS is a natural number if we just read an '@' token, else nil.
8914 S is the name or string that was matched: an identifier, 'throw' or '*'.
8915 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8917 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8918 operator, or the name is followed by ::. For a plain name, returns a
8919 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8920 (let ((pos (or at-pos js2-token-beg))
8922 (name (js2-create-name-node t js2-current-token))
8925 (when (js2-match-token js2-COLONCOLON)
8927 colon-pos js2-token-beg
8928 tt (js2-next-token))
8930 ;; handles name::name
8931 ((js2-valid-prop-name-token tt)
8932 (setq name (js2-create-name-node)))
8935 (js2-save-name-token-data js2-token-beg "*")
8936 (setq name (js2-create-name-node)))
8937 ;; handles name::[expr]
8939 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8941 (js2-report-error "msg.no.name.after.coloncolon"))))
8942 (if (and (null ns) (zerop member-type-flags))
8946 (make-js2-xml-prop-ref-node :pos pos
8947 :len (- (js2-node-end name) pos)
8949 :colon-pos colon-pos
8951 (js2-node-add-children pn name))))))
8953 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
8954 "Parse the [expr] portion of an xml element reference.
8955 For instance, @[expr], @*::[expr], or ns::[expr]."
8956 (let* ((lb js2-token-beg)
8957 (pos (or at-pos lb))
8959 (expr (js2-parse-expr))
8960 (end (js2-node-end expr))
8962 (if (js2-must-match js2-RB "msg.no.bracket.index")
8963 (setq rb js2-token-beg
8967 (make-js2-xml-elem-ref-node :pos pos
8969 :namespace namespace
8970 :colon-pos colon-pos
8973 :lb (js2-relpos lb pos)
8974 :rb (js2-relpos rb pos)))
8975 (js2-node-add-children pn namespace expr))))
8977 (defun js2-parse-destruct-primary-expr ()
8978 (let ((js2-is-in-destructuring t))
8979 (js2-parse-primary-expr)))
8981 (defun js2-parse-primary-expr ()
8982 "Parse a literal (leaf) expression of some sort.
8983 Includes complex literals such as functions, object-literals,
8984 array-literals, array comprehensions and regular expressions."
8985 (let ((tt-flagged (js2-next-flagged-token))
8986 pn ; parent node (usually return value)
8988 px-pos ; paren-expr pos
8990 flags ; regexp flags
8992 (setq tt js2-current-token)
8994 ((= tt js2-FUNCTION)
8995 (js2-parse-function 'FUNCTION_EXPRESSION))
8997 (js2-parse-array-literal))
8999 (js2-parse-object-literal))
9001 (js2-parse-let js2-token-beg))
9003 (setq px-pos js2-token-beg
9004 expr (js2-parse-expr))
9005 (js2-must-match js2-RP "msg.no.paren")
9006 (setq pn (make-js2-paren-node :pos px-pos
9008 :len (- js2-token-end px-pos)))
9009 (js2-node-add-children pn (js2-paren-node-expr pn))
9013 (js2-parse-attribute-access))
9015 (js2-parse-name tt-flagged tt))
9017 (make-js2-number-node))
9020 (make-js2-string-node)
9021 (js2-record-face 'font-lock-string-face)))
9022 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9023 ;; Got / or /= which in this context means a regexp literal
9024 (setq px-pos js2-token-beg)
9025 (js2-read-regexp tt)
9026 (setq flags js2-ts-regexp-flags
9027 js2-ts-regexp-flags nil)
9029 (make-js2-regexp-node :pos px-pos
9030 :len (- js2-ts-cursor px-pos)
9031 :value js2-ts-string
9033 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9034 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9035 ((or (= tt js2-NULL)
9039 (make-js2-keyword-node :type tt))
9040 ((= tt js2-RESERVED)
9041 (js2-report-error "msg.reserved.id")
9042 (make-js2-name-node))
9044 ;; the scanner or one of its subroutines reported the error.
9045 (make-js2-error-node))
9047 (setq px-pos (point-at-bol)
9048 len (- js2-ts-cursor px-pos))
9049 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9050 (make-js2-error-node :pos px-pos :len len))
9052 (js2-report-error "msg.syntax")
9053 (make-js2-error-node)))))
9055 (defun js2-parse-name (tt-flagged tt)
9056 (let ((name js2-ts-string)
9057 (name-pos js2-token-beg)
9059 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9060 (= (js2-peek-token) js2-COLON))
9062 ;; Do not consume colon, it is used as unwind indicator
9063 ;; to return to statementHelper.
9064 (make-js2-label-node :pos name-pos
9065 :len (- js2-token-end name-pos)
9067 (js2-set-face name-pos
9069 'font-lock-variable-name-face 'record))
9070 ;; Otherwise not a label, just a name. Unfortunately peeking
9071 ;; the next token to check for a colon has biffed js2-token-beg
9072 ;; and js2-token-end. We store the name's bounds in buffer vars
9073 ;; and `js2-create-name-node' uses them.
9074 (js2-save-name-token-data name-pos name)
9075 (setq node (if js2-compiler-xml-available
9076 (js2-parse-property-name nil name 0)
9077 (js2-create-name-node 'check-activation)))
9078 (if js2-highlight-external-variables
9079 (js2-record-name-node node))
9082 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9083 (js2-add-strict-warning
9085 ;; back up from comma to beginning of line or array/objlit
9087 (js2-node-pos (car elems))
9090 (goto-char comma-pos)
9091 (back-to-indentation)
9095 (defun js2-parse-array-literal ()
9096 (let ((pos js2-token-beg)
9098 (after-lb-or-comma t)
9099 after-comma tt elems pn
9101 (unless js2-is-in-destructuring
9102 (js2-push-scope (make-js2-scope))) ; for array comp
9104 (setq tt (js2-peek-token))
9109 (setq after-comma js2-token-end)
9110 (if (not after-lb-or-comma)
9111 (setq after-lb-or-comma t)
9115 (= tt js2-EOF)) ; prevent infinite loop
9117 (js2-report-error "msg.no.bracket.arg" nil pos)
9118 (js2-consume-token))
9121 pn (make-js2-array-node :pos pos
9122 :len (- js2-ts-cursor pos)
9123 :elems (nreverse elems)))
9124 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9125 (when (and after-comma (not js2-is-in-destructuring))
9126 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9127 pos elems after-comma)))
9128 ;; destructuring binding
9129 (js2-is-in-destructuring
9130 (push (if (or (= tt js2-LC)
9133 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9134 (js2-parse-destruct-primary-expr)
9137 (js2-report-error "msg.bad.var")
9138 (make-js2-error-node))
9140 (setq after-lb-or-comma nil
9143 ((and (>= js2-language-version 170)
9144 (= tt js2-FOR) ; check for array comprehension
9145 (not after-lb-or-comma) ; "for" can't follow a comma
9146 elems ; must have at least 1 element
9147 (not (cdr elems))) ; but no 2nd element
9149 pn (js2-parse-array-comprehension (car elems) pos)))
9153 (unless after-lb-or-comma
9154 (js2-report-error "msg.no.bracket.arg"))
9155 (push (js2-parse-assign-expr) elems)
9156 (setq after-lb-or-comma nil
9158 (unless js2-is-in-destructuring
9162 (defun js2-parse-array-comprehension (expr pos)
9163 "Parse a JavaScript 1.7 Array Comprehension.
9164 EXPR is the first expression after the opening left-bracket.
9165 POS is the beginning of the LB token preceding EXPR.
9166 We should have just parsed the 'for' keyword before calling this function."
9167 (let (loops loop first prev filter if-pos result)
9168 (while (= (js2-peek-token) js2-FOR)
9169 (let ((prev (car loops))) ; rearrange scope chain
9170 (push (setq loop (js2-parse-array-comp-loop)) loops)
9171 (if prev ; each loop is parent scope to the next one
9172 (setf (js2-scope-parent-scope loop) prev)
9173 ; first loop takes expr scope's parent
9174 (setf (js2-scope-parent-scope (setq first loop))
9175 (js2-scope-parent-scope js2-current-scope)))))
9176 ;; set expr scope's parent to the last loop
9177 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9178 (when (= (js2-peek-token) js2-IF)
9180 (setq if-pos (- js2-token-beg pos) ; relative
9181 filter (js2-parse-condition)))
9182 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9183 (setq result (make-js2-array-comp-node :pos pos
9184 :len (- js2-ts-cursor pos)
9186 :loops (nreverse loops)
9187 :filter (car filter)
9188 :lp (js2-relpos (second filter) pos)
9189 :rp (js2-relpos (third filter) pos)
9191 (apply #'js2-node-add-children result expr (car filter)
9192 (js2-array-comp-node-loops result))
9193 (setq js2-current-scope first) ; pop to the first loop
9196 (defun js2-parse-array-comp-loop ()
9197 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9198 Last token peeked should be the initial FOR."
9199 (let ((pos js2-token-beg)
9200 (pn (make-js2-array-comp-loop-node))
9201 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9202 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9206 (when (js2-match-token js2-NAME)
9207 (if (string= js2-ts-string "each")
9210 each-pos (- js2-token-beg pos)) ; relative
9211 (js2-record-face 'font-lock-keyword-face))
9212 (js2-report-error "msg.no.paren.for")))
9213 (if (js2-must-match js2-LP "msg.no.paren.for")
9214 (setq lp (- js2-token-beg pos)))
9215 (setq tt (js2-peek-token))
9219 (setq iter (js2-parse-destruct-primary-expr))
9220 (js2-define-destruct-symbols iter js2-LET
9221 'font-lock-variable-name-face t))
9222 ((js2-match-token js2-NAME)
9223 (setq iter (js2-create-name-node)))
9225 (js2-report-error "msg.bad.var")))
9226 ;; Define as a let since we want the scope of the variable to
9227 ;; be restricted to the array comprehension
9228 (if (js2-name-node-p iter)
9229 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9230 (if (or (js2-match-token js2-IN)
9231 (and (>= js2-language-version 200)
9232 (js2-match-contextual-kwd "of")
9234 (setq in-pos (- js2-token-beg pos))
9235 (js2-report-error "msg.in.after.for.name"))
9236 (setq obj (js2-parse-expr))
9237 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9238 (setq rp (- js2-token-beg pos)))
9239 (setf (js2-node-pos pn) pos
9240 (js2-node-len pn) (- js2-ts-cursor pos)
9241 (js2-array-comp-loop-node-iterator pn) iter
9242 (js2-array-comp-loop-node-object pn) obj
9243 (js2-array-comp-loop-node-in-pos pn) in-pos
9244 (js2-array-comp-loop-node-each-pos pn) each-pos
9245 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9246 (js2-array-comp-loop-node-forof-p pn) forof-p
9247 (js2-array-comp-loop-node-lp pn) lp
9248 (js2-array-comp-loop-node-rp pn) rp)
9249 (js2-node-add-children pn iter obj))
9253 (defun js2-parse-object-literal ()
9254 (let ((pos js2-token-beg)
9255 tt elems result after-comma
9258 (setq tt (js2-peek-token))
9260 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9261 ;; {get foo() {...}}, or {set foo(x) {...}}
9262 ((or (js2-valid-prop-name-token tt)
9264 (setq after-comma nil
9265 result (js2-parse-named-prop tt))
9266 (if (and (null result)
9267 (not js2-recover-from-parse-errors))
9269 (push result elems)))
9270 ;; {12: x} or {10.7: x}
9273 (setq after-comma nil)
9274 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9279 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9280 pos elems after-comma)))
9282 (js2-report-error "msg.bad.prop")
9283 (unless js2-recover-from-parse-errors
9284 (setq continue nil)))) ; end switch
9285 (if (js2-match-token js2-COMMA)
9286 (setq after-comma js2-token-end)
9287 (setq continue nil))) ; end loop
9288 (js2-must-match js2-RC "msg.no.brace.prop")
9289 (setq result (make-js2-object-node :pos pos
9290 :len (- js2-ts-cursor pos)
9291 :elems (nreverse elems)))
9292 (apply #'js2-node-add-children result (js2-object-node-elems result))
9295 (defun js2-parse-named-prop (tt)
9296 "Parse a name, string, or getter/setter object property.
9297 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9299 (let ((string-prop (and (= tt js2-STRING)
9300 (make-js2-string-node)))
9302 (ppos js2-token-beg)
9303 (pend js2-token-end)
9304 (name (js2-create-name-node))
9305 (prop js2-ts-string))
9307 ;; getter/setter prop
9308 ((and (= tt js2-NAME)
9309 (= (js2-peek-token) js2-NAME)
9310 (or (string= prop "get")
9311 (string= prop "set")))
9313 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9314 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9315 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9316 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9317 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9318 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9319 ;; when patterns are used in variable declarations, function parameters,
9320 ;; catch-clause, and iterators.
9321 ;; We have to set `js2-is-in-destructuring' to t when the current
9322 ;; expressions are on the left side of any assignment, but it's difficult
9323 ;; because it requires looking ahead of expression.
9324 ((and js2-is-in-destructuring
9326 (let ((ctk (js2-peek-token)))
9327 (or (= ctk js2-COMMA)
9329 (js2-valid-prop-name-token ctk))))
9334 (setq expr (js2-parse-plain-property (or string-prop name)))
9335 (js2-set-face ppos pend
9336 (if (js2-function-node-p
9337 (js2-object-prop-node-right expr))
9338 'font-lock-function-name-face
9339 'font-lock-variable-name-face)
9342 (defun js2-parse-plain-property (prop)
9343 "Parse a non-getter/setter property in an object literal.
9344 PROP is the node representing the property: a number, name or string."
9345 (js2-must-match js2-COLON "msg.no.colon.prop")
9346 (let* ((pos (js2-node-pos prop))
9347 (colon (- js2-token-beg pos))
9348 (expr (js2-parse-assign-expr))
9349 (result (make-js2-object-prop-node
9351 ;; don't include last consumed token in length
9352 :len (- (+ (js2-node-pos expr)
9353 (js2-node-len expr))
9358 (js2-node-add-children result prop expr)
9361 (defun js2-parse-getter-setter-prop (pos prop get-p)
9362 "Parse getter or setter property in an object literal.
9363 JavaScript syntax is:
9365 { get foo() {...}, set foo(x) {...} }
9367 and expression closure style is also supported
9369 { get foo() x, set foo(x) _x = x }
9371 POS is the start position of the `get' or `set' keyword.
9372 PROP is the `js2-name-node' representing the property name.
9373 GET-P is non-nil if the keyword was `get'."
9374 (let ((type (if get-p js2-GET js2-SET))
9376 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9377 ;; it has to be an anonymous function, as we already parsed the name
9378 (if (/= (js2-node-type fn) js2-FUNCTION)
9379 (js2-report-error "msg.bad.prop")
9380 (if (plusp (length (js2-function-name fn)))
9381 (js2-report-error "msg.bad.prop")))
9382 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9383 (setq end (js2-node-end fn)
9384 result (make-js2-getter-setter-node :type type
9389 (js2-node-add-children result prop fn)
9392 (defun js2-create-name-node (&optional check-activation-p token)
9393 "Create a name node using the token info from last scanned name.
9394 In some cases we need to either synthesize a name node, or we lost
9395 the name token information by peeking. If the TOKEN parameter is
9396 not `js2-NAME', then we use the token info saved in instance vars."
9397 (let ((beg js2-token-beg)
9400 (when (/= js2-current-token js2-NAME)
9401 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9402 s js2-prev-name-token-string
9403 js2-prev-name-token-start nil
9404 js2-prev-name-token-string nil))
9405 (setq name (make-js2-name-node :pos beg
9408 (if check-activation-p
9409 (js2-check-activation-name s (or token js2-NAME)))
9412 ;;; Indentation support
9414 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9415 ;; Karl cleverly deduces that the desired indentation level is often a
9416 ;; function of paren/bracket/brace nesting depth, which can be determined
9417 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9418 ;; then does some equally clever checks to see if we're in the context of a
9419 ;; substatement of a possibly braceless statement keyword such as if, while,
9420 ;; or finally. This approach yields pretty good results.
9422 ;; The indenter is often "wrong", however, and needs to be overridden.
9423 ;; The right long-term solution is probably to emulate (or integrate
9424 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9425 ;; parse tree from `js2-parse' is present, which is not true at the
9426 ;; moment the user is typing, computing indentation is still thousands
9427 ;; of lines of code to handle every possible syntactic edge case.
9429 ;; In the meantime, the compromise solution is that we offer a "bounce
9430 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9431 ;; current line indent among various likely guess points. This approach
9432 ;; is far from perfect, but should at least make it slightly easier to
9433 ;; move the line towards its desired indentation when manually
9434 ;; overriding Karl's heuristic nesting guesser.
9436 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9437 ;; extensions such as `let' and Array comprehensions. Major kudos to
9438 ;; Karl for coming up with the initial approach, which packs a lot of
9439 ;; punch for so little code.
9441 (defconst js2-possibly-braceless-keywords-re
9442 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9443 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9444 "try" "while" "with" "let")))
9445 "Regular expression matching keywords that are optionally
9446 followed by an opening brace.")
9448 (defconst js2-indent-operator-re
9449 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9450 (regexp-opt '("in" "instanceof") 'words))
9451 "Regular expression matching operators that affect indentation
9452 of continued expressions.")
9454 (defconst js2-declaration-keyword-re
9455 (regexp-opt '("var" "let" "const") 'words)
9456 "Regular expression matching variable declaration keywords.")
9458 (defun js2-re-search-forward-inner (regexp &optional bound count)
9459 "Auxiliary function for `js2-re-search-forward'."
9460 (let (parse saved-point)
9462 (re-search-forward regexp bound)
9463 (setq parse (if saved-point
9464 (parse-partial-sexp saved-point (point))
9465 (syntax-ppss (point))))
9466 (cond ((nth 3 parse)
9468 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9469 (save-excursion (end-of-line) (point)) t))
9473 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9474 (re-search-forward "\\*/"))
9476 (setq count (1- count))))
9477 (setq saved-point (point))))
9480 (defun js2-re-search-forward (regexp &optional bound noerror count)
9481 "Search forward but ignore strings and comments.
9482 Invokes `re-search-forward' but treats the buffer as if strings
9483 and comments have been removed."
9484 (let ((saved-point (point))
9487 '(js2-re-search-forward-inner regexp bound 1))
9489 '(js2-re-search-backward-inner regexp bound (- count)))
9491 '(js2-re-search-forward-inner regexp bound count)))))
9495 (goto-char saved-point)
9497 (error (error-message-string err)))))))
9499 (defun js2-re-search-backward-inner (regexp &optional bound count)
9500 "Auxiliary function for `js2-re-search-backward'."
9503 (re-search-backward regexp bound)
9504 (setq parse (syntax-ppss (point)))
9505 (cond ((nth 3 parse)
9507 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9508 (line-beginning-position) t))
9510 (goto-char (nth 8 parse)))
9512 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9513 (re-search-backward "/\\*"))
9515 (setq count (1- count))))))
9518 (defun js2-re-search-backward (regexp &optional bound noerror count)
9519 "Search backward but ignore strings and comments.
9520 Invokes `re-search-backward' but treats the buffer as if strings
9521 and comments have been removed."
9522 (let ((saved-point (point))
9525 '(js2-re-search-backward-inner regexp bound 1))
9527 '(js2-re-search-forward-inner regexp bound (- count)))
9529 '(js2-re-search-backward-inner regexp bound count)))))
9533 (goto-char saved-point)
9535 (error (error-message-string err)))))))
9537 (defun js2-looking-at-operator-p ()
9538 "Return non-nil if text after point is a non-comma operator."
9539 (and (looking-at js2-indent-operator-re)
9540 (or (not (looking-at ":"))
9542 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9543 (looking-at "?"))))))
9545 (defun js2-continued-expression-p ()
9546 "Return non-nil if the current line continues an expression."
9548 (back-to-indentation)
9549 (or (js2-looking-at-operator-p)
9551 (while (and (re-search-backward "\n" nil t)
9552 (let ((state (syntax-ppss)))
9554 (goto-char (nth 8 state))) ;; skip comments
9555 (skip-chars-backward " \t")
9558 (throw 'found t))))))
9560 (when (js2-looking-at-operator-p)
9562 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9564 (defun js2-end-of-do-while-loop-p ()
9565 "Return non-nil if word after point is `while' of a do-while
9566 statement, else returns nil. A braceless do-while statement
9567 spanning several lines requires that the start of the loop is
9568 indented to the same column as the current line."
9571 (when (looking-at "\\s-*\\<while\\>")
9573 (skip-chars-backward "[ \t\n]*}")
9574 (looking-at "[ \t\n]*}"))
9576 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9577 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9578 (or (looking-at "\\<do\\>")
9579 (let ((saved-indent (current-indentation)))
9580 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9581 (/= (current-indentation) saved-indent)))
9582 (and (looking-at "[ \t]*\\<do\\>")
9583 (not (js2-re-search-forward
9584 "\\<while\\>" (point-at-eol) t))
9585 (= (current-indentation) saved-indent))))))))
9587 (defun js2-multiline-decl-indentation ()
9588 "Return the declaration indentation column if the current line belongs
9589 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9590 (let (forward-sexp-function ; use Lisp version
9593 (back-to-indentation)
9594 (when (not (looking-at js2-declaration-keyword-re))
9595 (when (looking-at js2-indent-operator-re)
9596 (goto-char (match-end 0))) ; continued expressions are ok
9597 (while (and (not at-opening-bracket)
9599 (let ((pos (point)))
9602 (or (eq (char-before) ?,)
9603 (and (not (eq (char-before) ?\;))
9604 (prog2 (skip-syntax-backward ".")
9605 (looking-at js2-indent-operator-re)
9607 (not (eq (char-before) ?\;)))
9608 (js2-same-line pos)))))
9611 (scan-error (setq at-opening-bracket t))))
9612 (when (looking-at js2-declaration-keyword-re)
9613 (goto-char (match-end 0))
9614 (1+ (current-column)))))))
9616 (defun js2-ctrl-statement-indentation ()
9617 "Return the proper indentation of current line if it is a control statement.
9618 Returns an indentation if this line starts the body of a control
9619 statement without braces, else returns nil."
9620 (let (forward-sexp-function)
9622 (back-to-indentation)
9623 (when (and (not (js2-same-line (point-min)))
9624 (not (looking-at "{"))
9625 (js2-re-search-backward "[[:graph:]]" nil t)
9626 (not (looking-at "[{([]"))
9629 (when (= (char-before) ?\))
9630 ;; scan-sexps sometimes throws an error
9631 (ignore-errors (backward-sexp))
9632 (skip-chars-backward " \t" (point-at-bol)))
9634 (back-to-indentation)
9635 (when (looking-at "}[ \t]*")
9636 (goto-char (match-end 0)))
9637 (and (looking-at js2-possibly-braceless-keywords-re)
9638 (= (match-end 0) pt)
9639 (not (js2-end-of-do-while-loop-p))))))
9640 (+ (current-indentation) js2-basic-offset)))))
9642 (defun js2-indent-in-array-comp (parse-status)
9643 "Return non-nil if we think we're in an array comprehension.
9644 In particular, return the buffer position of the first `for' kwd."
9645 (let ((bracket (nth 1 parse-status))
9650 (when (looking-at "\\[")
9653 (if (looking-at "[[{]")
9654 (let (forward-sexp-function) ; use Lisp version
9655 (forward-sexp) ; skip destructuring form
9657 (if (and (/= (char-after) ?,) ; regular array
9659 (match-beginning 0)))
9660 ;; to skip arbitrary expressions we need the parser,
9661 ;; so we'll just guess at it.
9662 (if (and (> end (point)) ; not empty literal
9663 (re-search-forward "[^,]]* \\(for\\) " end t)
9664 ;; not inside comment or string literal
9665 (let ((state (parse-partial-sexp bracket (point))))
9666 (not (or (nth 3 state) (nth 4 state)))))
9667 (match-beginning 1))))))))
9669 (defun js2-array-comp-indentation (parse-status for-kwd)
9670 (if (js2-same-line for-kwd)
9671 ;; first continuation line
9673 (goto-char (nth 1 parse-status))
9675 (skip-chars-forward " \t")
9681 (defun js2-proper-indentation (parse-status)
9682 "Return the proper indentation for the current line."
9684 (back-to-indentation)
9685 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9686 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9687 (continued-expr-p (js2-continued-expression-p))
9688 (declaration-indent (and js2-pretty-multiline-declarations
9689 (js2-multiline-decl-indentation)))
9690 (bracket (nth 1 parse-status))
9693 ;; indent array comprehension continuation lines specially
9695 (>= js2-language-version 170)
9696 (not (js2-same-line bracket))
9697 (setq beg (js2-indent-in-array-comp parse-status))
9698 (>= (point) (save-excursion
9700 (point-at-bol)))) ; at or after first loop?
9701 (js2-array-comp-indentation parse-status beg))
9705 ((and declaration-indent continued-expr-p)
9706 (+ declaration-indent js2-basic-offset))
9708 (declaration-indent)
9713 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9714 (when (save-excursion (skip-chars-backward " \t)")
9717 (back-to-indentation)
9718 (and (eq js2-pretty-multiline-declarations 'all)
9719 (looking-at js2-declaration-keyword-re)
9720 (goto-char (1+ (match-end 0))))
9721 (cond (same-indent-p
9724 (+ (current-column) (* 2 js2-basic-offset)))
9726 (+ (current-column) js2-basic-offset))))
9728 (unless same-indent-p
9730 (skip-chars-forward " \t"))
9733 (continued-expr-p js2-basic-offset)
9737 (defun js2-lineup-comment (parse-status)
9738 "Indent a multi-line block comment continuation line."
9739 (let* ((beg (nth 8 parse-status))
9740 (first-line (js2-same-line beg))
9741 (offset (save-excursion
9743 (if (looking-at "/\\*")
9744 (+ 1 (current-column))
9747 (indent-line-to offset))))
9749 (defun js2-backward-sws ()
9750 "Move backward through whitespace and comments."
9752 (while (forward-comment -1)))
9754 (defun js2-forward-sws ()
9755 "Move forward through whitespace and comments."
9757 (while (forward-comment 1)))
9759 (defun js2-current-indent (&optional pos)
9760 "Return column of indentation on current line.
9761 If POS is non-nil, go to that point and return indentation for that line."
9765 (back-to-indentation)
9768 (defun js2-arglist-close ()
9769 "Return non-nil if we're on a line beginning with a close-paren/brace."
9771 (goto-char (point-at-bol))
9773 (looking-at "[])}]")))
9775 (defun js2-indent-looks-like-label-p ()
9776 (goto-char (point-at-bol))
9778 (looking-at (concat js2-mode-identifier-re ":")))
9780 (defun js2-indent-in-objlit-p (parse-status)
9781 "Return non-nil if this looks like an object-literal entry."
9782 (let ((start (nth 1 parse-status)))
9786 (and (zerop (forward-line -1))
9787 (not (< (point) start)) ; crossed a {} boundary
9788 (js2-indent-looks-like-label-p)))
9790 (js2-indent-looks-like-label-p)))))
9792 ;; If prev line looks like foobar({ then we're passing an object
9793 ;; literal to a function call, and people pretty much always want to
9794 ;; de-dent back to the previous line, so move the 'basic-offset'
9795 ;; position to the front.
9796 (defun js2-indent-objlit-arg-p (parse-status)
9798 (back-to-indentation)
9800 (and (eq (1- (point)) (nth 1 parse-status))
9801 (eq (char-before) ?{)
9804 (skip-chars-backward " \t")
9805 (eq (char-before) ?\()))))
9807 (defun js2-indent-case-block-p ()
9809 (back-to-indentation)
9811 (goto-char (point-at-bol))
9812 (skip-chars-forward " \t")
9813 (looking-at "case\\s-.+:")))
9815 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9816 "Cycle among alternate computed indentation positions.
9817 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9818 of the buffer to the current point. NORMAL-COL is the indentation
9819 column computed by the heuristic guesser based on current paren,
9820 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9822 (let ((cur-indent (js2-current-indent))
9823 (old-buffer-undo-list buffer-undo-list)
9824 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9825 (current-line (save-excursion
9826 (forward-line 0) ; move to bol
9827 (1+ (count-lines (point-min) (point)))))
9828 positions pos main-pos anchor arglist-cont same-indent
9829 prev-line-col basic-offset computed-pos)
9830 ;; temporarily don't record undo info, if user requested this
9831 (when js2-mode-indent-inhibit-undo
9832 (setq buffer-undo-list t))
9835 ;; First likely point: indent from beginning of previous code line
9836 (push (setq basic-offset
9838 (back-to-indentation)
9840 (back-to-indentation)
9841 (setq prev-line-col (current-column)))
9845 ;; (First + epsilon) likely point: indent 2x from beginning of
9846 ;; previous code line. Google does it this way.
9847 (push (setq basic-offset
9849 (back-to-indentation)
9851 (back-to-indentation)
9852 (setq prev-line-col (current-column)))
9853 (* 2 js2-basic-offset)))
9856 ;; Second likely point: indent from assign-expr RHS. This
9857 ;; is just a crude guess based on finding " = " on the previous
9858 ;; line containing actual code.
9859 (setq pos (save-excursion
9861 (goto-char (point-at-bol))
9862 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9864 (goto-char (match-end 1))
9865 (skip-chars-forward " \t\r\n")
9868 (incf pos js2-basic-offset)
9869 (push pos positions))
9871 ;; Third likely point: same indent as previous line of code.
9872 ;; Make it the first likely point if we're not on an
9873 ;; arglist-close line and previous line ends in a comma, or
9874 ;; both this line and prev line look like object-literal
9876 (setq pos (save-excursion
9877 (goto-char (point-at-bol))
9879 (back-to-indentation)
9882 ;; while we're here, look for trailing comma
9884 (goto-char (point-at-eol))
9886 (eq (char-before) ?,))
9887 (setq arglist-cont (1- (point)))))))
9889 (if (and (or arglist-cont
9890 (js2-indent-in-objlit-p parse-status))
9891 (not (js2-arglist-close)))
9892 (setq same-indent pos))
9893 (push pos positions))
9895 ;; Fourth likely point: first preceding code with less indentation.
9896 ;; than the immediately preceding code line.
9897 (setq pos (save-excursion
9898 (back-to-indentation)
9900 (back-to-indentation)
9901 (setq anchor (current-column))
9902 (while (and (zerop (forward-line -1))
9904 (back-to-indentation)
9907 (setq pos (current-column))))
9908 (push pos positions)
9910 ;; nesting-heuristic position, main by default
9911 (push (setq main-pos normal-col) positions)
9913 ;; delete duplicates and sort positions list
9914 (setq positions (sort (delete-dups positions) '<))
9916 ;; comma-list continuation lines: prev line indent takes precedence
9918 (setq main-pos same-indent))
9920 ;; common special cases where we want to indent in from previous line
9921 (if (or (js2-indent-case-block-p)
9922 (js2-indent-objlit-arg-p parse-status))
9923 (setq main-pos basic-offset))
9925 ;; if bouncing backwards, reverse positions list
9927 (setq positions (reverse positions)))
9929 ;; record whether we're already sitting on one of the alternatives
9930 (setq pos (member cur-indent positions))
9933 ;; case 0: we're one one of the alternatives and this is the
9934 ;; first time they've pressed TAB on this line (best-guess).
9935 ((and js2-mode-indent-ignore-first-tab
9937 ;; first time pressing TAB on this line?
9938 (not (eq js2-mode-last-indented-line current-line)))
9940 (setq computed-pos nil))
9941 ;; case 1: only one computed position => use it
9942 ((null (cdr positions))
9943 (setq computed-pos 0))
9944 ;; case 2: not on any of the computed spots => use main spot
9946 (setq computed-pos (js2-position main-pos positions)))
9947 ;; case 3: on last position: cycle to first position
9949 (setq computed-pos 0))
9950 ;; case 4: on intermediate position: cycle to next position
9952 (setq computed-pos (js2-position (second pos) positions))))
9954 ;; see if any hooks want to indent; otherwise we do it
9955 (loop with result = nil
9956 for hook in js2-indent-hook
9959 (setq result (funcall hook positions computed-pos))
9961 (unless (or result (null computed-pos))
9962 (indent-line-to (nth computed-pos positions)))))
9965 (if js2-mode-indent-inhibit-undo
9966 (setq buffer-undo-list old-buffer-undo-list))
9967 ;; see commentary for `js2-mode-last-indented-line'
9968 (setq js2-mode-last-indented-line current-line))))
9970 (defun js2-indent-bounce-backwards ()
9971 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
9972 cycles between the computed indentation positions in reverse order."
9974 (js2-indent-line t))
9976 (defun js2-1-line-comment-continuation-p ()
9977 "Return t if we're in a 1-line comment continuation.
9978 If so, we don't ever want to use bounce-indent."
9982 (looking-at "\\s-*//"))
9986 (when (looking-at "\\s-*$")
9989 (looking-at "\\s-*//")))))
9991 (defun js2-indent-line (&optional bounce-backwards)
9992 "Indent the current line as JavaScript source text."
9994 (let (parse-status current-indent offset indent-col moved
9995 ;; Don't whine about errors/warnings when we're indenting.
9996 ;; This has to be set before calling parse-partial-sexp below.
9997 (inhibit-point-motion-hooks t))
9998 (setq parse-status (save-excursion
9999 (syntax-ppss (point-at-bol)))
10000 offset (- (point) (save-excursion
10001 (back-to-indentation)
10003 (js2-with-underscore-as-word-syntax
10004 (if (nth 4 parse-status)
10005 (js2-lineup-comment parse-status)
10006 (setq indent-col (js2-proper-indentation parse-status))
10007 ;; See comments below about `js2-mode-last-indented-line'.
10009 ;; bounce-indenting is disabled during electric-key indent.
10010 ;; It doesn't work well on first line of buffer.
10011 ((and js2-bounce-indent-p
10012 (not (js2-same-line (point-min)))
10013 (not (js2-1-line-comment-continuation-p)))
10014 (js2-bounce-indent indent-col parse-status bounce-backwards))
10015 ;; just indent to the guesser's likely spot
10016 (t (indent-line-to indent-col))))
10017 (when (plusp offset)
10018 (forward-char offset)))))
10020 (defun js2-indent-region (start end)
10021 "Indent the region, but don't use bounce indenting."
10022 (let ((js2-bounce-indent-p nil)
10023 (indent-region-function nil)
10024 (after-change-functions (remq 'js2-mode-edit
10025 after-change-functions)))
10026 (indent-region start end nil) ; nil for byte-compiler
10027 (js2-mode-edit start end (- end start))))
10029 (defvar js2-minor-mode-map
10030 (let ((map (make-sparse-keymap)))
10031 (define-key map (kbd "C-c C-`") #'js2-next-error)
10032 (define-key map [mouse-1] #'js2-mode-show-node)
10034 "Keymap used when `js2-minor-mode' is active.")
10037 (define-minor-mode js2-minor-mode
10038 "Minor mode for running js2 as a background linter.
10039 This allows you to use a different major mode for JavaScript editing,
10040 such as `espresso-mode', while retaining the asynchronous error/warning
10041 highlighting features of `js2-mode'."
10043 :lighter " js-lint"
10045 (js2-minor-mode-enter)
10046 (js2-minor-mode-exit)))
10048 (defun js2-minor-mode-enter ()
10049 "Initialization for `js2-minor-mode'."
10050 (set (make-local-variable 'max-lisp-eval-depth)
10051 (max max-lisp-eval-depth 3000))
10052 (setq next-error-function #'js2-next-error)
10053 (setq js2-default-externs
10054 (append js2-ecma-262-externs
10055 (if js2-include-browser-externs js2-browser-externs)
10056 (if js2-include-rhino-externs js2-rhino-externs)
10057 (if js2-include-node-externs js2-node-externs)))
10058 ;; Experiment: make reparse-delay longer for longer files.
10059 (if (plusp js2-dynamic-idle-timer-adjust)
10060 (setq js2-idle-timer-delay
10061 (* js2-idle-timer-delay
10062 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10063 (setq js2-mode-buffer-dirty-p t
10064 js2-mode-parsing nil)
10065 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10066 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10067 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10070 (defun js2-minor-mode-exit ()
10071 "Turn off `js2-minor-mode'."
10072 (setq next-error-function nil)
10073 (remove-hook 'after-change-functions #'js2-mode-edit t)
10074 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10075 (when js2-mode-node-overlay
10076 (delete-overlay js2-mode-node-overlay)
10077 (setq js2-mode-node-overlay nil))
10078 (js2-remove-overlays)
10079 (setq js2-mode-ast nil))
10081 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10082 (make-variable-buffer-local 'js2-source-buffer)
10084 (defun* js2-display-error-list ()
10085 "Display a navigable buffer listing parse errors/warnings."
10087 (unless (js2-have-errors-p)
10088 (message "No errors")
10089 (return-from js2-display-error-list))
10090 (labels ((annotate-list
10092 "Add diagnostic TYPE and line number to errs list"
10093 (mapcar (lambda (err)
10094 (list err type (line-number-at-pos (nth 1 err))))
10096 (let* ((srcbuf (current-buffer))
10097 (errbuf (get-buffer-create "*js-lint*"))
10098 (errors (annotate-list
10099 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10100 'js2-error)) ; must be a valid face name
10101 (warnings (annotate-list
10102 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10103 'js2-warning)) ; must be a valid face name
10104 (all-errs (sort (append errors warnings)
10105 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10106 (with-current-buffer errbuf
10107 (let ((inhibit-read-only t))
10109 (dolist (err all-errs)
10110 (destructuring-bind ((msg-key beg end &rest) type line) err
10111 (insert-text-button
10112 (format "line %d: %s" line (js2-get-msg msg-key))
10114 'follow-link "\C-m"
10115 'action 'js2-error-buffer-jump
10116 'js2-msg (js2-get-msg msg-key)
10119 (js2-error-buffer-mode)
10120 (setq js2-source-buffer srcbuf)
10121 (pop-to-buffer errbuf)
10122 (goto-char (point-min))
10124 (js2-error-buffer-view))))))
10126 (defvar js2-error-buffer-mode-map
10127 (let ((map (make-sparse-keymap)))
10128 (define-key map "n" #'js2-error-buffer-next)
10129 (define-key map "p" #'js2-error-buffer-prev)
10130 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10131 (define-key map "o" #'js2-error-buffer-view)
10132 (define-key map "q" #'js2-error-buffer-quit)
10134 "Keymap used for js2 diagnostics buffers.")
10136 (defun js2-error-buffer-mode ()
10137 "Major mode for js2 diagnostics buffers.
10138 Selecting an error will jump it to the corresponding source-buffer error.
10139 \\{js2-error-buffer-mode-map}"
10141 (setq major-mode 'js2-error-buffer-mode
10142 mode-name "JS Lint Diagnostics")
10143 (use-local-map js2-error-buffer-mode-map)
10144 (setq truncate-lines t)
10145 (set-buffer-modified-p nil)
10146 (setq buffer-read-only t)
10147 (run-hooks 'js2-error-buffer-mode-hook))
10149 (defun js2-error-buffer-next ()
10150 "Move to next error and view it."
10152 (when (zerop (forward-line 1))
10153 (js2-error-buffer-view)))
10155 (defun js2-error-buffer-prev ()
10156 "Move to previous error and view it."
10158 (when (zerop (forward-line -1))
10159 (js2-error-buffer-view)))
10161 (defun js2-error-buffer-quit ()
10162 "Kill the current buffer."
10166 (defun js2-error-buffer-jump (&rest ignored)
10167 "Jump cursor to current error in source buffer."
10169 (when (js2-error-buffer-view)
10170 (pop-to-buffer js2-source-buffer)))
10172 (defun js2-error-buffer-view ()
10173 "Scroll source buffer to show error at current line."
10176 ((not (eq major-mode 'js2-error-buffer-mode))
10177 (message "Not in a js2 errors buffer"))
10178 ((not (buffer-live-p js2-source-buffer))
10179 (message "Source buffer has been killed"))
10180 ((not (wholenump (get-text-property (point) 'js2-pos)))
10181 (message "There does not seem to be an error here"))
10183 (let ((pos (get-text-property (point) 'js2-pos))
10184 (msg (get-text-property (point) 'js2-msg)))
10185 (save-selected-window
10186 (pop-to-buffer js2-source-buffer)
10191 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10192 ;; FIXME: Should derive from js-mode.
10193 "Major mode for editing JavaScript code."
10194 (setq comment-start "//" ; used by comment-region; don't change it
10196 (set (make-local-variable 'max-lisp-eval-depth)
10197 (max max-lisp-eval-depth 3000))
10198 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10199 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10200 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10201 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10202 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10203 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10204 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10205 ;; for characters inside regexp literals.
10206 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10207 ;; this is necessary to make `show-paren-function' work properly
10208 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10209 ;; needed for M-x rgrep, among other things
10210 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10212 (set (make-local-variable 'electric-indent-chars)
10213 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10214 electric-indent-chars))
10215 (set (make-local-variable 'electric-layout-rules)
10216 '((?\; . after) (?\{ . after) (?\} . before)))
10218 ;; some variables needed by cc-engine for paragraph-fill, etc.
10219 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10220 c-comment-start-regexp "/[*/]\\|\\s|"
10221 c-line-comment-starter "//"
10222 c-paragraph-start js2-paragraph-start
10223 c-paragraph-separate "$"
10224 comment-start-skip js2-comment-start-skip
10225 c-syntactic-ws-start js2-syntactic-ws-start
10226 c-syntactic-ws-end js2-syntactic-ws-end
10227 c-syntactic-eol js2-syntactic-eol)
10229 (let ((c-buffer-is-cc-mode t))
10230 ;; Copied from `js-mode'. Also see Bug#6071.
10231 (make-local-variable 'paragraph-start)
10232 (make-local-variable 'paragraph-separate)
10233 (make-local-variable 'paragraph-ignore-fill-prefix)
10234 (make-local-variable 'adaptive-fill-mode)
10235 (make-local-variable 'adaptive-fill-regexp)
10236 (c-setup-paragraph-variables))
10238 (setq js2-default-externs
10239 (append js2-ecma-262-externs
10240 (if js2-include-browser-externs js2-browser-externs)
10241 (if js2-include-rhino-externs js2-rhino-externs)
10242 (if js2-include-node-externs js2-node-externs)))
10244 (setq font-lock-defaults '(nil t))
10246 ;; Experiment: make reparse-delay longer for longer files.
10247 (when (plusp js2-dynamic-idle-timer-adjust)
10248 (setq js2-idle-timer-delay
10249 (* js2-idle-timer-delay
10250 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10252 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10253 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10254 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10255 (setq next-error-function #'js2-next-error)
10256 (imenu-add-to-menubar (concat "IM-" mode-name))
10257 (add-to-invisibility-spec '(js2-outline . t))
10258 (set (make-local-variable 'line-move-ignore-invisible) t)
10259 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10261 (setq js2-mode-functions-hidden nil
10262 js2-mode-comments-hidden nil
10263 js2-mode-buffer-dirty-p t
10264 js2-mode-parsing nil)
10267 (defun js2-mode-exit ()
10268 "Exit `js2-mode' and clean up."
10270 (when js2-mode-node-overlay
10271 (delete-overlay js2-mode-node-overlay)
10272 (setq js2-mode-node-overlay nil))
10273 (js2-remove-overlays)
10274 (setq js2-mode-ast nil)
10275 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10276 (remove-from-invisibility-spec '(js2-outline . t))
10277 (js2-mode-show-all)
10278 (with-silent-modifications
10279 (js2-clear-face (point-min) (point-max))))
10281 (defun js2-mode-reset-timer ()
10282 "Cancel any existing parse timer and schedule a new one."
10283 (if js2-mode-parse-timer
10284 (cancel-timer js2-mode-parse-timer))
10285 (setq js2-mode-parsing nil)
10286 (let ((timer (timer-create)))
10287 (setq js2-mode-parse-timer timer)
10288 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10289 (timer-set-idle-time timer js2-idle-timer-delay)
10290 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10291 (timer-activate-when-idle timer nil)))
10293 (defun js2-mode-idle-reparse (buffer)
10294 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10295 it to be reparsed when the buffer is selected."
10296 (if (eq buffer (current-buffer))
10298 ;; reparse when the buffer is selected again
10299 (with-current-buffer buffer
10300 (add-hook 'window-configuration-change-hook
10301 #'js2-mode-idle-reparse-inner
10304 (defun js2-mode-idle-reparse-inner ()
10305 (remove-hook 'window-configuration-change-hook
10306 #'js2-mode-idle-reparse-inner
10310 (defun js2-mode-edit (beg end len)
10311 "Schedule a new parse after buffer is edited.
10312 Buffer edit spans from BEG to END and is of length LEN."
10313 (setq js2-mode-buffer-dirty-p t)
10314 (js2-mode-hide-overlay)
10315 (js2-mode-reset-timer))
10317 (defun js2-minor-mode-edit (beg end len)
10318 "Callback for buffer edits in `js2-mode'.
10319 Schedules a new parse after buffer is edited.
10320 Buffer edit spans from BEG to END and is of length LEN."
10321 (setq js2-mode-buffer-dirty-p t)
10322 (js2-mode-hide-overlay)
10323 (js2-mode-reset-timer))
10325 (defun js2-reparse (&optional force)
10326 "Re-parse current buffer after user finishes some data entry.
10327 If we get any user input while parsing, including cursor motion,
10328 we discard the parse and reschedule it. If FORCE is nil, then the
10329 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10332 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10333 (unless js2-mode-parsing
10334 (setq js2-mode-parsing t)
10336 (when (or js2-mode-buffer-dirty-p force)
10337 (js2-remove-overlays)
10338 (with-silent-modifications
10339 (setq js2-mode-buffer-dirty-p nil
10340 js2-mode-fontifications nil
10341 js2-mode-deferred-properties nil)
10342 (if js2-mode-verbose-parse-p
10343 (message "parsing..."))
10346 (setq interrupted-p
10347 (catch 'interrupted
10349 ;; if parsing is interrupted, comments and regex
10350 ;; literals stay ignored by `parse-partial-sexp'
10351 (remove-text-properties (point-min) (point-max)
10353 (js2-mode-apply-deferred-properties)
10354 (js2-mode-remove-suppressed-warnings)
10355 (js2-mode-show-warnings)
10356 (js2-mode-show-errors)
10357 (if (>= js2-highlight-level 1)
10358 (js2-highlight-jsdoc js2-mode-ast))
10362 ;; unfinished parse => try again
10363 (setq js2-mode-buffer-dirty-p t)
10364 (js2-mode-reset-timer))
10365 (if js2-mode-verbose-parse-p
10366 (message "Parse time: %s" time)))))
10367 (setq js2-mode-parsing nil)
10368 (unless interrupted-p
10369 (setq js2-mode-parse-timer nil))))))
10371 (defun js2-mode-show-node (event)
10372 "Debugging aid: highlight selected AST node on mouse click."
10374 (mouse-set-point event)
10375 (setq deactivate-mark t)
10376 (when js2-mode-show-overlay
10377 (let ((node (js2-node-at-point))
10380 (message "No node found at location %s" (point))
10381 (setq beg (js2-node-abs-pos node)
10382 end (+ beg (js2-node-len node)))
10383 (if js2-mode-node-overlay
10384 (move-overlay js2-mode-node-overlay beg end)
10385 (setq js2-mode-node-overlay (make-overlay beg end))
10386 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10387 (with-silent-modifications
10388 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10389 (message "%s, parent: %s"
10390 (js2-node-short-name node)
10391 (if (js2-node-parent node)
10392 (js2-node-short-name (js2-node-parent node))
10395 (defun js2-mode-hide-overlay (&optional p1 p2)
10396 "Remove the debugging overlay when the point moves.
10397 P1 and P2 are the old and new values of point, respectively."
10398 (when js2-mode-node-overlay
10399 (let ((beg (overlay-start js2-mode-node-overlay))
10400 (end (overlay-end js2-mode-node-overlay)))
10401 ;; Sometimes we're called spuriously.
10405 (with-silent-modifications
10406 (remove-text-properties beg end '(point-left nil)))
10407 (delete-overlay js2-mode-node-overlay)
10408 (setq js2-mode-node-overlay nil)))))
10410 (defun js2-mode-reset ()
10411 "Debugging helper: reset everything."
10416 (defun js2-mode-show-warn-or-err (e face)
10417 "Highlight a warning or error E with FACE.
10418 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10419 The last element is optional. When present, use instead of FACE."
10420 (let* ((key (first e))
10422 (end (+ beg (third e)))
10423 ;; Don't inadvertently go out of bounds.
10424 (beg (max (point-min) (min beg (point-max))))
10425 (end (max (point-min) (min end (point-max))))
10426 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10427 (ovl (make-overlay beg end)))
10428 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10429 (overlay-put ovl 'js2-error t)
10430 (put-text-property beg end 'help-echo (js2-get-msg key))
10431 (put-text-property beg end 'point-entered #'js2-echo-error)))
10433 (defun js2-remove-overlays ()
10434 "Remove overlays from buffer that have a `js2-error' property."
10435 (let ((beg (point-min))
10438 (dolist (o (overlays-in beg end))
10439 (when (overlay-get o 'js2-error)
10440 (delete-overlay o))))))
10442 (defun js2-error-at-point (&optional pos)
10443 "Return non-nil if there's an error overlay at POS.
10444 Defaults to point."
10445 (loop with pos = (or pos (point))
10446 for o in (overlays-at pos)
10447 thereis (overlay-get o 'js2-error)))
10449 (defun js2-mode-apply-deferred-properties ()
10450 "Apply fontifications and other text properties recorded during parsing."
10451 (when (plusp js2-highlight-level)
10452 ;; We defer clearing faces as long as possible to eliminate flashing.
10453 (js2-clear-face (point-min) (point-max))
10454 ;; Have to reverse the recorded fontifications list so that errors
10455 ;; and warnings overwrite the normal fontifications.
10456 (dolist (f (nreverse js2-mode-fontifications))
10457 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10458 (setq js2-mode-fontifications nil))
10459 (dolist (p js2-mode-deferred-properties)
10460 (apply #'put-text-property p))
10461 (setq js2-mode-deferred-properties nil))
10463 (defun js2-mode-show-errors ()
10464 "Highlight syntax errors."
10465 (when js2-mode-show-parse-errors
10466 (dolist (e (js2-ast-root-errors js2-mode-ast))
10467 (js2-mode-show-warn-or-err e 'js2-error))))
10469 (defun js2-mode-remove-suppressed-warnings ()
10470 "Take suppressed warnings out of the AST warnings list.
10471 This ensures that the counts and `next-error' are correct."
10472 (setf (js2-ast-root-warnings js2-mode-ast)
10475 (let ((key (caar e)))
10477 (and (not js2-strict-trailing-comma-warning)
10478 (string-match "trailing\\.comma" key))
10479 (and (not js2-strict-cond-assign-warning)
10480 (string= key "msg.equal.as.assign"))
10481 (and js2-missing-semi-one-line-override
10482 (string= key "msg.missing.semi")
10483 (let* ((beg (second e))
10484 (node (js2-node-at-point beg))
10485 (fn (js2-mode-find-parent-fn node))
10486 (body (and fn (js2-function-node-body fn)))
10487 (lc (and body (js2-node-abs-pos body)))
10488 (rc (and lc (+ lc (js2-node-len body)))))
10493 (and (js2-same-line lc)
10494 (js2-same-line rc))))))))))
10495 (js2-ast-root-warnings js2-mode-ast))))
10497 (defun js2-mode-show-warnings ()
10498 "Highlight strict-mode warnings."
10499 (when js2-mode-show-strict-warnings
10500 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10501 (js2-mode-show-warn-or-err e 'js2-warning))))
10503 (defun js2-echo-error (old-point new-point)
10504 "Called by point-motion hooks."
10505 (let ((msg (get-text-property new-point 'help-echo)))
10506 (when (and (stringp msg) (or (not (current-message))
10507 (string= (current-message) "Quit")))
10510 (defalias #'js2-echo-help #'js2-echo-error)
10512 (defun js2-line-break (&optional soft)
10513 "Break line at point and indent, continuing comment if within one.
10514 If inside a string, and `js2-concat-multiline-strings' is not
10515 nil, turn it into concatenation."
10517 (let ((parse-status (syntax-ppss)))
10519 ;; Check if we're inside a string.
10520 ((nth 3 parse-status)
10521 (if js2-concat-multiline-strings
10522 (js2-mode-split-string parse-status)
10524 ;; Check if inside a block comment.
10525 ((nth 4 parse-status)
10526 (js2-mode-extend-comment (nth 8 parse-status)))
10528 (newline-and-indent)))))
10530 (defun js2-mode-split-string (parse-status)
10531 "Turn a newline in mid-string into a string concatenation.
10532 PARSE-STATUS is as documented in `parse-partial-sexp'."
10533 (let* ((col (current-column))
10534 (quote-char (nth 3 parse-status))
10535 (string-beg (nth 8 parse-status))
10536 (at-eol (eq js2-concat-multiline-strings 'eol)))
10537 (insert quote-char)
10544 (insert quote-char)
10546 (insert quote-char)
10547 (backward-char 1))))
10549 (defun js2-mode-extend-comment (start-pos)
10550 "Indent the line and, when inside a comment block, add comment prefix."
10551 (let (star single col first-line needs-close)
10553 (back-to-indentation)
10554 (when (< (point) start-pos)
10555 (goto-char start-pos))
10557 ((looking-at "\\*[^/]")
10559 col (current-column)))
10560 ((looking-at "/\\*")
10563 col (1+ (current-column))))
10566 col (current-column)))))
10567 ;; Heuristic for whether we need to close the comment:
10568 ;; if we've got a parse error here, assume it's an unterminated
10572 (eq (get-text-property (1- (point)) 'point-entered)
10574 ;; The heuristic above doesn't work well when we're
10575 ;; creating a comment and there's another one downstream,
10576 ;; as our parser thinks this one ends at the end of the
10577 ;; next one. (You can have a /* inside a js block comment.)
10578 ;; So just close it if the next non-ws char isn't a *.
10582 (skip-chars-forward " \t\r\n")
10583 (not (eq (char-after) ?*))))))
10584 (delete-horizontal-space)
10590 (if (and first-line needs-close)
10597 (and (zerop (forward-line 1))
10598 (looking-at "\\s-*//"))))
10601 ;; Don't need to extend the comment after all.
10602 (js2-indent-line)))
10604 (defun js2-beginning-of-line ()
10605 "Toggle point between bol and first non-whitespace char in line.
10606 Also moves past comment delimiters when inside comments."
10611 (back-to-indentation))
10613 (skip-chars-forward "/ \t"))
10614 ((and (eq (char-after) ?*)
10615 (setq node (js2-comment-at-point))
10616 (memq (js2-comment-node-format node) '(jsdoc block))
10618 (skip-chars-backward " \t")
10620 (skip-chars-forward "\* \t"))
10622 (goto-char (point-at-bol))))))
10624 (defun js2-end-of-line ()
10625 "Toggle point between eol and last non-whitespace char in line."
10628 (skip-chars-backward " \t")
10629 (goto-char (point-at-eol))))
10631 (defun js2-mode-wait-for-parse (callback)
10632 "Invoke CALLBACK when parsing is finished.
10633 If parsing is already finished, calls CALLBACK immediately."
10634 (if (not js2-mode-buffer-dirty-p)
10636 (push callback js2-mode-pending-parse-callbacks)
10637 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10639 (defun js2-mode-parse-finished ()
10640 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10641 ;; We can't let errors propagate up, since it prevents the
10642 ;; `js2-parse' method from completing normally and returning
10643 ;; the ast, which makes things mysteriously not work right.
10645 (dolist (cb js2-mode-pending-parse-callbacks)
10646 (condition-case err
10648 (error (message "%s" err))))
10649 (setq js2-mode-pending-parse-callbacks nil)))
10651 (defun js2-mode-flag-region (from to flag)
10652 "Hide or show text from FROM to TO, according to FLAG.
10653 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10654 Returns the created overlay if FLAG is non-nil."
10655 (remove-overlays from to 'invisible 'js2-outline)
10657 (let ((o (make-overlay from to)))
10658 (overlay-put o 'invisible 'js2-outline)
10659 (overlay-put o 'isearch-open-invisible
10660 'js2-isearch-open-invisible)
10663 ;; Function to be set as an outline-isearch-open-invisible' property
10664 ;; to the overlay that makes the outline invisible (see
10665 ;; `js2-mode-flag-region').
10666 (defun js2-isearch-open-invisible (overlay)
10667 ;; We rely on the fact that isearch places point on the matched text.
10668 (js2-mode-show-element))
10670 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10671 "Return cons cell of bounds of folding overlay at POS.
10672 Returns nil if not found."
10673 (let ((overlays (overlays-at (or pos (point))))
10675 (while (and overlays
10677 (if (overlay-get (car overlays) 'invisible)
10678 (setq o (car overlays))
10679 (setq overlays (cdr overlays))))
10681 (cons (overlay-start o) (overlay-end o)))))
10683 (defun js2-mode-function-at-point (&optional pos)
10684 "Return the innermost function node enclosing current point.
10685 Returns nil if point is not in a function."
10686 (let ((node (js2-node-at-point pos)))
10687 (while (and node (not (js2-function-node-p node)))
10688 (setq node (js2-node-parent node)))
10689 (if (js2-function-node-p node)
10692 (defun js2-mode-toggle-element ()
10693 "Hide or show the foldable element at the point."
10695 (let (comment fn pos)
10698 ;; /* ... */ comment?
10699 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10700 (if (js2-mode-invisible-overlay-bounds
10701 (setq pos (+ 3 (js2-node-abs-pos comment))))
10704 (js2-mode-show-element))
10705 (js2-mode-hide-element)))
10708 (back-to-indentation)
10709 (looking-at js2-mode-//-comment-re))
10710 (js2-mode-toggle-//-comment))
10712 ((setq fn (js2-mode-function-at-point))
10713 (setq pos (and (js2-function-node-body fn)
10714 (js2-node-abs-pos (js2-function-node-body fn))))
10715 (goto-char (1+ pos))
10716 (if (js2-mode-invisible-overlay-bounds)
10717 (js2-mode-show-element)
10718 (js2-mode-hide-element)))
10720 (message "Nothing at point to hide or show"))))))
10722 (defun js2-mode-hide-element ()
10723 "Fold/hide contents of a block, showing ellipses.
10724 Show the hidden text with \\[js2-mode-show-element]."
10726 (if js2-mode-buffer-dirty-p
10727 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10728 (let (node body beg end)
10730 ((js2-mode-invisible-overlay-bounds)
10731 (message "already hidden"))
10733 (setq node (js2-node-at-point))
10735 ((js2-block-comment-p node)
10736 (js2-mode-hide-comment node))
10738 (while (and node (not (js2-function-node-p node)))
10739 (setq node (js2-node-parent node)))
10741 (setq body (js2-function-node-body node)))
10743 (setq beg (js2-node-abs-pos body)
10744 end (+ beg (js2-node-len body)))
10745 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10746 (message "No collapsable element found at point"))))))))
10748 (defun js2-mode-show-element ()
10749 "Show the hidden element at current point."
10751 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10753 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10754 (message "Nothing to un-hide"))))
10756 (defun js2-mode-show-all ()
10757 "Show all of the text in the buffer."
10759 (js2-mode-flag-region (point-min) (point-max) nil))
10761 (defun js2-mode-toggle-hide-functions ()
10763 (if js2-mode-functions-hidden
10764 (js2-mode-show-functions)
10765 (js2-mode-hide-functions)))
10767 (defun js2-mode-hide-functions ()
10768 "Hides all non-nested function bodies in the buffer.
10769 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10770 to open an individual entry."
10772 (if js2-mode-buffer-dirty-p
10773 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10774 (if (null js2-mode-ast)
10775 (message "Oops - parsing failed")
10776 (setq js2-mode-functions-hidden t)
10777 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10779 (defun js2-mode-function-hider (n endp)
10781 (let ((tt (js2-node-type n))
10784 ((and (= tt js2-FUNCTION)
10785 (setq body (js2-function-node-body n)))
10786 (setq beg (js2-node-abs-pos body)
10787 end (+ beg (js2-node-len body)))
10788 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10789 nil) ; don't process children of function
10791 t))))) ; keep processing other AST nodes
10793 (defun js2-mode-show-functions ()
10794 "Un-hide any folded function bodies in the buffer."
10796 (setq js2-mode-functions-hidden nil)
10798 (goto-char (point-min))
10799 (while (/= (goto-char (next-overlay-change (point)))
10801 (dolist (o (overlays-at (point)))
10802 (when (and (overlay-get o 'invisible)
10803 (not (overlay-get o 'comment)))
10804 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10806 (defun js2-mode-hide-comment (n)
10807 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10810 (beg (+ (js2-node-abs-pos n) head))
10811 (end (- (+ beg (js2-node-len n)) head 2))
10812 (o (js2-mode-flag-region beg end 'hide)))
10813 (overlay-put o 'comment t)))
10815 (defun js2-mode-toggle-hide-comments ()
10816 "Folds all block comments in the buffer.
10817 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10818 to open an individual entry."
10820 (if js2-mode-comments-hidden
10821 (js2-mode-show-comments)
10822 (js2-mode-hide-comments)))
10824 (defun js2-mode-hide-comments ()
10826 (if js2-mode-buffer-dirty-p
10827 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10828 (if (null js2-mode-ast)
10829 (message "Oops - parsing failed")
10830 (setq js2-mode-comments-hidden t)
10831 (dolist (n (js2-ast-root-comments js2-mode-ast))
10832 (let ((format (js2-comment-node-format n)))
10833 (when (js2-block-comment-p n)
10834 (js2-mode-hide-comment n))))
10835 (js2-mode-hide-//-comments)))
10837 (defun js2-mode-extend-//-comment (direction)
10838 "Find start or end of a block of similar //-comment lines.
10839 DIRECTION is -1 to look back, 1 to look forward.
10840 INDENT is the indentation level to match.
10841 Returns the end-of-line position of the furthest adjacent
10842 //-comment line with the same indentation as the current line.
10843 If there is no such matching line, returns current end of line."
10844 (let ((pos (point-at-eol))
10845 (indent (current-indentation)))
10847 (while (and (zerop (forward-line direction))
10848 (looking-at js2-mode-//-comment-re)
10849 (eq indent (length (match-string 1))))
10850 (setq pos (point-at-eol))
10853 (defun js2-mode-hide-//-comments ()
10854 "Fold adjacent 1-line comments, showing only snippet of first one."
10857 (goto-char (point-min))
10858 (while (re-search-forward js2-mode-//-comment-re nil t)
10860 end (js2-mode-extend-//-comment 1))
10861 (unless (eq beg end)
10862 (overlay-put (js2-mode-flag-region beg end 'hide)
10865 (forward-char 1)))))
10867 (defun js2-mode-toggle-//-comment ()
10868 "Fold or un-fold any multi-line //-comment at point.
10869 Caller should have determined that this line starts with a //-comment."
10870 (let* ((beg (point-at-eol))
10874 (if (js2-mode-invisible-overlay-bounds)
10875 (js2-mode-show-element)
10876 ;; else hide the comment
10877 (setq beg (js2-mode-extend-//-comment -1)
10878 end (js2-mode-extend-//-comment 1))
10879 (unless (eq beg end)
10880 (overlay-put (js2-mode-flag-region beg end 'hide)
10883 (defun js2-mode-show-comments ()
10884 "Un-hide any hidden comments, leaving other hidden elements alone."
10886 (setq js2-mode-comments-hidden nil)
10888 (goto-char (point-min))
10889 (while (/= (goto-char (next-overlay-change (point)))
10891 (dolist (o (overlays-at (point)))
10892 (when (overlay-get o 'comment)
10893 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10895 (defun js2-mode-display-warnings-and-errors ()
10896 "Turn on display of warnings and errors."
10898 (setq js2-mode-show-parse-errors t
10899 js2-mode-show-strict-warnings t)
10900 (js2-reparse 'force))
10902 (defun js2-mode-hide-warnings-and-errors ()
10903 "Turn off display of warnings and errors."
10905 (setq js2-mode-show-parse-errors nil
10906 js2-mode-show-strict-warnings nil)
10907 (js2-reparse 'force))
10909 (defun js2-mode-toggle-warnings-and-errors ()
10910 "Toggle the display of warnings and errors.
10911 Some users don't like having warnings/errors reported while they type."
10913 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10914 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10915 (if (called-interactively-p 'any)
10916 (message "warnings and errors %s"
10917 (if js2-mode-show-parse-errors
10920 (js2-reparse 'force))
10922 (defun js2-mode-customize ()
10924 (customize-group 'js2-mode))
10926 (defun js2-mode-forward-sexp (&optional arg)
10927 "Move forward across one statement or balanced expression.
10928 With ARG, do it that many times. Negative arg -N means
10929 move backward across N balanced expressions."
10931 (setq arg (or arg 1))
10933 (widen) ;; `blink-matching-open' calls `narrow-to-region'
10935 (let (forward-sexp-function
10936 node (start (point)) pos lp rp child)
10939 ;; could probably make this better for some cases:
10940 ;; - if in statement block (e.g. function body), go to parent
10941 ;; - infix exprs like (foo in bar) - maybe go to beginning
10942 ;; of infix expr if in the right-side expression?
10943 ((and arg (minusp arg))
10944 (dotimes (i (- arg))
10946 (forward-char -1) ; Enter the node we backed up to.
10947 (when (setq node (js2-node-at-point (point) t))
10948 (setq pos (js2-node-abs-pos node))
10949 (let ((parens (js2-mode-forward-sexp-parens node pos)))
10950 (setq lp (car parens)
10952 (when (and lp (> start lp))
10953 (if (and rp (<= start rp))
10954 ;; Between parens, check if there's a child node we can jump.
10955 (when (setq child (js2-node-closest-child node (point) lp t))
10956 (setq pos (js2-node-abs-pos child)))
10957 ;; Before both parens.
10959 (let ((state (parse-partial-sexp start pos)))
10960 (goto-char (if (not (zerop (car state)))
10961 ;; Stumble at the unbalanced paren if < 0, or
10962 ;; jump a bit further if > 0.
10963 (scan-sexps start -1)
10965 (unless pos (goto-char (point-min)))))
10970 (when (setq node (js2-node-at-point (point) t))
10971 (setq pos (js2-node-abs-pos node))
10972 (let ((parens (js2-mode-forward-sexp-parens node pos)))
10973 (setq lp (car parens)
10976 (when (and rp (<= start rp))
10978 (when (setq child (js2-node-closest-child node (point) rp))
10979 (setq pos (js2-node-abs-end child)))
10980 (setq pos (1+ rp))))
10981 ;; No parens or child nodes, looks for the end of the curren node.
10982 (incf pos (js2-node-len
10983 (if (js2-expr-stmt-node-p (js2-node-parent node))
10984 ;; Stop after the semicolon.
10985 (js2-node-parent node)
10987 (let ((state (save-excursion (parse-partial-sexp start pos))))
10988 (goto-char (if (not (zerop (car state)))
10989 (scan-sexps start 1)
10991 (unless pos (goto-char (point-max))))))))
10993 (defun js2-mode-forward-sexp-parens (node abs-pos)
10994 "Return a cons cell with positions of main parens in NODE."
10996 ((or (js2-array-node-p node)
10997 (js2-object-node-p node)
10998 (js2-array-comp-node-p node)
10999 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11000 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11001 ((js2-paren-expr-node-p node)
11002 (let ((lp (js2-node-lp node))
11003 (rp (js2-node-rp node)))
11004 (cons (when lp (+ abs-pos lp))
11005 (when rp (+ abs-pos rp)))))))
11007 (defun js2-node-closest-child (parent point limit &optional before)
11008 (let* ((parent-pos (js2-node-abs-pos parent))
11009 (rpoint (- point parent-pos))
11010 (rlimit (- limit parent-pos))
11011 (min (min rpoint rlimit))
11012 (max (max rpoint rlimit))
11017 (lambda (node end-p)
11018 (if (eq node parent)
11020 (let ((pos (js2-node-pos node)) ;; Both relative values.
11021 (end (+ (js2-node-pos node) (js2-node-len node))))
11022 (when (and (>= pos min) (<= end max)
11023 (if before (< pos rpoint) (> end rpoint)))
11025 (when (> end rpoint)
11026 (throw 'done nil)))
11030 (defun js2-errors ()
11031 "Return a list of errors found."
11033 (js2-ast-root-errors js2-mode-ast)))
11035 (defun js2-warnings ()
11036 "Return a list of warnings found."
11038 (js2-ast-root-warnings js2-mode-ast)))
11040 (defun js2-have-errors-p ()
11041 "Return non-nil if any parse errors or warnings were found."
11042 (or (js2-errors) (js2-warnings)))
11044 (defun js2-errors-and-warnings ()
11045 "Return a copy of the concatenated errors and warnings lists.
11046 They are appended: first the errors, then the warnings.
11047 Entries are of the form (MSG BEG END)."
11049 (append (js2-ast-root-errors js2-mode-ast)
11050 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11052 (defun js2-next-error (&optional arg reset)
11053 "Move to next parse error.
11054 Typically invoked via \\[next-error].
11055 ARG is the number of errors, forward or backward, to move.
11056 RESET means start over from the beginning."
11058 (if (not (or (js2-errors) (js2-warnings)))
11059 (message "No errors")
11061 (goto-char (point-min)))
11062 (let* ((errs (js2-errors-and-warnings))
11066 (backward (minusp count))
11067 (sorter (if backward '> '<))
11068 (stopper (if backward '< '>))
11069 (count (abs count))
11071 ;; Sort by start position.
11072 (setq errs (sort errs (lambda (e1 e2)
11073 (funcall sorter (second e1) (second e2))))
11075 ;; Find nth error with pos > start.
11076 (while (and errs continue)
11077 (when (funcall stopper (cadar errs) start)
11078 (setq err (car errs))
11079 (if (zerop (decf count))
11080 (setq continue nil)))
11081 (setq errs (cdr errs)))
11083 (goto-char (second err))
11084 ;; Wrap around to first error.
11085 (goto-char (second (car all-errs)))
11086 ;; If we were already on it, echo msg again.
11087 (if (= (point) start)
11088 (js2-echo-error (point) (point)))))))
11090 (defun js2-down-mouse-3 ()
11091 "Make right-click move the point to the click location.
11092 This makes right-click context menu operations a bit more intuitive.
11093 The point will not move if the region is active, however, to avoid
11094 destroying the region selection."
11096 (when (and js2-move-point-on-right-click
11098 (let ((e last-input-event))
11100 (goto-char (cadadr e))))))
11102 (defun js2-mode-create-imenu-index ()
11103 "Return an alist for `imenu--index-alist'."
11104 ;; This is built up in `js2-parse-record-imenu' during parsing.
11106 ;; if we have an ast but no recorder, they're requesting a rescan
11107 (unless js2-imenu-recorder
11108 (js2-reparse 'force))
11110 (js2-build-imenu-index)
11111 (setq js2-imenu-recorder nil
11112 js2-imenu-function-map nil))))
11114 (defun js2-mode-find-tag ()
11115 "Replacement for `find-tag-default'.
11116 `find-tag-default' returns a ridiculous answer inside comments."
11118 (js2-with-underscore-as-word-syntax
11120 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11121 (looking-back "[A-Za-z0-9_$]"))
11122 (setq beg (progn (forward-word -1) (point))
11123 end (progn (forward-word 1) (point)))
11124 (setq beg (progn (forward-word 1) (point))
11125 end (progn (forward-word -1) (point))))
11126 (replace-regexp-in-string
11128 (buffer-substring-no-properties beg end))))))
11130 (defun js2-mode-forward-sibling ()
11131 "Move to the end of the sibling following point in parent.
11132 Returns non-nil if successful, or nil if there was no following sibling."
11133 (let* ((node (js2-node-at-point))
11134 (parent (js2-mode-find-enclosing-fn node))
11136 (when (setq sib (js2-node-find-child-after (point) parent))
11137 (goto-char (+ (js2-node-abs-pos sib)
11138 (js2-node-len sib))))))
11140 (defun js2-mode-backward-sibling ()
11141 "Move to the beginning of the sibling node preceding point in parent.
11142 Parent is defined as the enclosing script or function."
11143 (let* ((node (js2-node-at-point))
11144 (parent (js2-mode-find-enclosing-fn node))
11146 (when (setq sib (js2-node-find-child-before (point) parent))
11147 (goto-char (js2-node-abs-pos sib)))))
11149 (defun js2-beginning-of-defun (&optional arg)
11150 "Go to line on which current function starts, and return t on success.
11151 If we're not in a function or already at the beginning of one, go
11152 to beginning of previous script-level element.
11153 With ARG N, do that N times. If N is negative, move forward."
11154 (setq arg (or arg 1))
11156 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11158 ((js2-function-node-p parent)
11159 (goto-char (js2-node-abs-pos parent)))
11161 (js2-mode-backward-sibling)))
11163 (js2-beginning-of-defun (1- arg))
11165 (when (js2-end-of-defun)
11167 (js2-beginning-of-defun 1)
11168 (js2-beginning-of-defun (1+ arg))))))
11170 (defun js2-end-of-defun ()
11171 "Go to the char after the last position of the current function
11172 or script-level element."
11173 (let* ((node (js2-node-at-point))
11174 (parent (or (and (js2-function-node-p node) node)
11175 (js2-node-parent-script-or-fn node)))
11177 (unless (js2-function-node-p parent)
11178 ;; Use current script-level node, or, if none, the next one.
11179 (setq script (or parent node)
11180 parent (js2-node-find-child-before (point) script))
11181 (when (or (null parent)
11182 (>= (point) (+ (js2-node-abs-pos parent)
11183 (js2-node-len parent))))
11184 (setq parent (js2-node-find-child-after (point) script))))
11186 (goto-char (+ (js2-node-abs-pos parent)
11187 (js2-node-len parent))))))
11189 (defun js2-mark-defun (&optional allow-extend)
11190 "Put mark at end of this function, point at beginning.
11191 The function marked is the one that contains point.
11193 Interactively, if this command is repeated,
11194 or (in Transient Mark mode) if the mark is active,
11195 it marks the next defun after the ones already marked."
11198 (when (and allow-extend
11199 (or (and (eq last-command this-command) (mark t))
11200 (and transient-mark-mode mark-active)))
11201 (let ((sib (save-excursion
11203 (if (js2-mode-forward-sibling)
11210 ;; no more siblings - try extending to enclosing node
11211 (goto-char (mark t)))))
11212 (when (not extended)
11213 (let ((node (js2-node-at-point (point) t)) ; skip comments
11214 ast fn stmt parent beg end)
11215 (when (js2-ast-root-p node)
11217 node (or (js2-node-find-child-after (point) node)
11218 (js2-node-find-child-before (point) node))))
11219 ;; only mark whole buffer if we can't find any children
11222 (if (js2-function-node-p node)
11224 (setq fn (js2-mode-find-enclosing-fn node)
11225 stmt (if (or (null fn)
11226 (js2-ast-root-p fn))
11227 (js2-mode-find-first-stmt node))
11228 parent (or stmt fn)))
11229 (setq beg (js2-node-abs-pos parent)
11230 end (+ beg (js2-node-len parent)))
11233 (exchange-point-and-mark)))))
11235 (defun js2-narrow-to-defun ()
11236 "Narrow to the function enclosing point."
11238 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11239 (fn (if (js2-script-node-p node)
11241 (js2-mode-find-enclosing-fn node)))
11242 (beg (js2-node-abs-pos fn)))
11243 (unless (js2-ast-root-p fn)
11244 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11246 (provide 'js2-mode)
11248 ;;; js2-mode.el ends here