]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Merge branch 'emacs24'
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- Improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2011, 2012 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: 1.1
9 ;; Keywords: languages, javascript
10 ;; Package-Requires: ((emacs "24.1"))
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; This JavaScript editing mode supports:
30
31 ;; - strict recognition of the Ecma-262 language standard
32 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
33 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
34 ;; - accurate syntax highlighting using a recursive-descent parser
35 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
36 ;; - undeclared-variable warnings using a configurable externs framework
37 ;; - "bouncing" line indentation to choose among alternate indentation points
38 ;; - smart line-wrapping within comments and strings
39 ;; - code folding:
40 ;; - show some or all function bodies as {...}
41 ;; - show some or all block comments as /*...*/
42 ;; - context-sensitive menu bar and popup menus
43 ;; - code browsing using the `imenu' package
44 ;; - many customization options
45
46 ;; Installation:
47 ;;
48 ;; To install it as your major mode for JavaScript editing:
49
50 ;; (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
51
52 ;; Alternately, to install it as a minor mode just for JavaScript linting,
53 ;; you must add it to the appropriate major-mode hook. Normally this would be:
54
55 ;; (add-hook 'js-mode-hook 'js2-minor-mode)
56
57 ;; To customize how it works:
58 ;; M-x customize-group RET js2-mode RET
59
60 ;; Notes:
61
62 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
63 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
64 ;; `js2-mode' current as the EcmaScript language standard evolves.
65
66 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
67 ;; customizable. It is a surprising amount of work to support customizable
68 ;; indentation. The current compromise is that the tab key lets you cycle among
69 ;; various likely indentation points, similar to the behavior of python-mode.
70
71 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
72 ;; and `mumamo', although it could be made to do so with some effort.
73 ;; This means that `js2-mode' is currently only useful for editing JavaScript
74 ;; files, and not for editing JavaScript within <script> tags or templates.
75
76 ;;; Code:
77
78 (eval-when-compile
79 (require 'cl))
80
81 (require 'imenu)
82 (require 'cc-cmds) ; for `c-fill-paragraph'
83
84 (eval-and-compile
85 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
86 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
87
88 (defvar electric-layout-rules)
89
90 ;;; Externs (variables presumed to be defined by the host system)
91
92 (defvar js2-ecma-262-externs
93 (mapcar 'symbol-name
94 '(Array Boolean Date Error EvalError Function Infinity JSON
95 Math NaN Number Object RangeError ReferenceError RegExp
96 String SyntaxError TypeError URIError arguments
97 decodeURI decodeURIComponent encodeURI
98 encodeURIComponent escape eval isFinite isNaN
99 parseFloat parseInt undefined unescape))
100 "Ecma-262 externs. Included in `js2-externs' by default.")
101
102 (defvar js2-browser-externs
103 (mapcar 'symbol-name
104 '(;; DOM level 1
105 Attr CDATASection CharacterData Comment DOMException
106 DOMImplementation Document DocumentFragment
107 DocumentType Element Entity EntityReference
108 ExceptionCode NamedNodeMap Node NodeList Notation
109 ProcessingInstruction Text
110
111 ;; DOM level 2
112 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
113 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
114 HTMLBodyElement HTMLButtonElement HTMLCollection
115 HTMLDListElement HTMLDirectoryElement HTMLDivElement
116 HTMLDocument HTMLElement HTMLFieldSetElement
117 HTMLFontElement HTMLFormElement HTMLFrameElement
118 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
119 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
120 HTMLImageElement HTMLInputElement HTMLIsIndexElement
121 HTMLLIElement HTMLLabelElement HTMLLegendElement
122 HTMLLinkElement HTMLMapElement HTMLMenuElement
123 HTMLMetaElement HTMLModElement HTMLOListElement
124 HTMLObjectElement HTMLOptGroupElement
125 HTMLOptionElement HTMLOptionsCollection
126 HTMLParagraphElement HTMLParamElement HTMLPreElement
127 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
128 HTMLStyleElement HTMLTableCaptionElement
129 HTMLTableCellElement HTMLTableColElement
130 HTMLTableElement HTMLTableRowElement
131 HTMLTableSectionElement HTMLTextAreaElement
132 HTMLTitleElement HTMLUListElement
133
134 ;; DOM level 3
135 DOMConfiguration DOMError DOMException
136 DOMImplementationList DOMImplementationSource
137 DOMLocator DOMStringList NameList TypeInfo
138 UserDataHandler
139
140 ;; Window
141 window alert confirm document java navigator prompt screen
142 self top
143
144 ;; W3C CSS
145 CSSCharsetRule CSSFontFace CSSFontFaceRule
146 CSSImportRule CSSMediaRule CSSPageRule
147 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
148 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
149 CSSValue CSSValueList Counter DOMImplementationCSS
150 DocumentCSS DocumentStyle ElementCSSInlineStyle
151 LinkStyle MediaList RGBColor Rect StyleSheet
152 StyleSheetList ViewCSS
153
154 ;; W3C Event
155 EventListener EventTarget Event DocumentEvent UIEvent
156 MouseEvent MutationEvent KeyboardEvent
157
158 ;; W3C Range
159 DocumentRange Range RangeException
160
161 ;; W3C XML
162 XPathResult XMLHttpRequest))
163 "Browser externs.
164 You can cause these to be included or excluded with the custom
165 variable `js2-include-browser-externs'.")
166
167 (defvar js2-rhino-externs
168 (mapcar 'symbol-name
169 '(Packages importClass importPackage com org java
170 ;; Global object (shell) externs.
171 defineClass deserialize doctest gc help load
172 loadClass print quit readFile readUrl runCommand seal
173 serialize spawn sync toint32 version))
174 "Mozilla Rhino externs.
175 Set `js2-include-rhino-externs' to t to include them.")
176
177 (defvar js2-gears-externs
178 (mapcar 'symbol-name
179 '(
180 ;; TODO(stevey): add these
181 ))
182 "Google Gears externs.
183 Set `js2-include-gears-externs' to t to include them.")
184
185 ;;; Variables
186
187 (defun js2-mark-safe-local (name pred)
188 "Make the variable NAME buffer-local and mark it as safe file-local
189 variable with predicate PRED."
190 (make-variable-buffer-local name)
191 (put name 'safe-local-variable pred))
192
193 (defcustom js2-highlight-level 2
194 "Amount of syntax highlighting to perform.
195 0 or a negative value means none.
196 1 adds basic syntax highlighting.
197 2 adds highlighting of some Ecma built-in properties.
198 3 adds highlighting of many Ecma built-in functions."
199 :group 'js2-mode
200 :type '(choice (const :tag "None" 0)
201 (const :tag "Basic" 1)
202 (const :tag "Include Properties" 2)
203 (const :tag "Include Functions" 3)))
204
205 (defvar js2-mode-dev-mode-p nil
206 "Non-nil if running in development mode. Normally nil.")
207
208 (defgroup js2-mode nil
209 "An improved JavaScript mode."
210 :group 'languages)
211
212 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
213 (numberp c-basic-offset))
214 c-basic-offset
215 4)
216 "Number of spaces to indent nested statements.
217 Similar to `c-basic-offset'."
218 :group 'js2-mode
219 :type 'integer)
220 (js2-mark-safe-local 'js2-basic-offset 'integerp)
221
222 (make-obsolete-variable 'js2-auto-indent-p 'electric-indent-mode "1.0")
223
224 (defcustom js2-bounce-indent-p nil
225 "Non-nil to have indent-line function choose among alternatives.
226 If nil, the indent-line function will indent to a predetermined column
227 based on heuristic guessing. If non-nil, then if the current line is
228 already indented to that predetermined column, indenting will choose
229 another likely column and indent to that spot. Repeated invocation of
230 the indent-line function will cycle among the computed alternatives.
231 See the function `js2-bounce-indent' for details. When it is non-nil,
232 js2-mode also binds `js2-bounce-indent-backwards' to Shift-Tab."
233 :type 'boolean
234 :group 'js2-mode)
235
236 (defcustom js2-pretty-multiline-declarations t
237 "Non-nil to line up multiline declarations vertically:
238
239 var a = 10,
240 b = 20,
241 c = 30;
242
243 If the value is not `all', and the first assigned value in
244 declaration is a function/array/object literal spanning several
245 lines, it won't be indented additionally:
246
247 var o = { var bar = 2,
248 foo: 3 vs. o = {
249 }, foo: 3
250 bar = 2; };"
251 :group 'js2-mode
252 :type 'symbol)
253 (js2-mark-safe-local 'js2-pretty-multiline-declarations 'symbolp)
254
255 (defcustom js2-idle-timer-delay 0.2
256 "Delay in secs before re-parsing after user makes changes.
257 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
258 :type 'number
259 :group 'js2-mode)
260 (make-variable-buffer-local 'js2-idle-timer-delay)
261
262 (defcustom js2-dynamic-idle-timer-adjust 0
263 "Positive to adjust `js2-idle-timer-delay' based on file size.
264 The idea is that for short files, parsing is faster so we can be
265 more responsive to user edits without interfering with editing.
266 The buffer length in characters (typically bytes) is divided by
267 this value and used to multiply `js2-idle-timer-delay' for the
268 buffer. For example, a 21k file and 10k adjust yields 21k/10k
269 == 2, so js2-idle-timer-delay is multiplied by 2.
270 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
271 `js2-idle-timer-delay' is not dependent on the file size."
272 :type 'number
273 :group 'js2-mode)
274
275 (defcustom js2-concat-multiline-strings t
276 "Non-nil to automatically turn a newline in mid-string into a
277 string concatenation. When `eol', the '+' will be inserted at the
278 end of the line, otherwise, at the beginning of the next line."
279 :type '(choice (const t) (const eol) (const nil))
280 :group 'js2-mode)
281
282 (defcustom js2-mode-show-parse-errors t
283 "True to highlight parse errors."
284 :type 'boolean
285 :group 'js2-mode)
286
287 (defcustom js2-mode-show-strict-warnings t
288 "Non-nil to emit Ecma strict-mode warnings.
289 Some of the warnings can be individually disabled by other flags,
290 even if this flag is non-nil."
291 :type 'boolean
292 :group 'js2-mode)
293
294 (defcustom js2-strict-trailing-comma-warning t
295 "Non-nil to warn about trailing commas in array literals.
296 Ecma-262-5.1 allows them, but older versions of IE raise an error."
297 :type 'boolean
298 :group 'js2-mode)
299
300 (defcustom js2-strict-missing-semi-warning t
301 "Non-nil to warn about semicolon auto-insertion after statement.
302 Technically this is legal per Ecma-262, but some style guides disallow
303 depending on it."
304 :type 'boolean
305 :group 'js2-mode)
306
307 (defcustom js2-missing-semi-one-line-override nil
308 "Non-nil to permit missing semicolons in one-line functions.
309 In one-liner functions such as `function identity(x) {return x}'
310 people often omit the semicolon for a cleaner look. If you are
311 such a person, you can suppress the missing-semicolon warning
312 by setting this variable to t."
313 :type 'boolean
314 :group 'js2-mode)
315
316 (defcustom js2-strict-inconsistent-return-warning t
317 "Non-nil to warn about mixing returns with value-returns.
318 It's perfectly legal to have a `return' and a `return foo' in the
319 same function, but it's often an indicator of a bug, and it also
320 interferes with type inference (in systems that support it.)"
321 :type 'boolean
322 :group 'js2-mode)
323
324 (defcustom js2-strict-cond-assign-warning t
325 "Non-nil to warn about expressions like if (a = b).
326 This often should have been '==' instead of '='. If the warning
327 is enabled, you can suppress it on a per-expression basis by
328 parenthesizing the expression, e.g. if ((a = b)) ..."
329 :type 'boolean
330 :group 'js2-mode)
331
332 (defcustom js2-strict-var-redeclaration-warning t
333 "Non-nil to warn about redeclaring variables in a script or function."
334 :type 'boolean
335 :group 'js2-mode)
336
337 (defcustom js2-strict-var-hides-function-arg-warning t
338 "Non-nil to warn about a var decl hiding a function argument."
339 :type 'boolean
340 :group 'js2-mode)
341
342 (defcustom js2-skip-preprocessor-directives nil
343 "Non-nil to treat lines beginning with # as comments.
344 Useful for viewing Mozilla JavaScript source code."
345 :type 'boolean
346 :group 'js2-mode)
347
348 (defcustom js2-language-version 200
349 "Configures what JavaScript language version to recognize.
350 Currently versions 150, 160, 170, 180 and 200 are supported,
351 corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
352 respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
353 yield, and Array comprehensions, and 1.8 adds function closures."
354 :type 'integer
355 :group 'js2-mode)
356
357 (defcustom js2-allow-keywords-as-property-names t
358 "If non-nil, you can use JavaScript keywords as object property names.
359 Examples:
360
361 var foo = {int: 5, while: 6, continue: 7};
362 foo.return = 8;
363
364 Ecma-262 5.1 allows this syntax, but some engines still don't."
365 :type 'boolean
366 :group 'js2-mode)
367
368 (defcustom js2-instanceof-has-side-effects nil
369 "If non-nil, treats the instanceof operator as having side effects.
370 This is useful for xulrunner apps."
371 :type 'boolean
372 :group 'js2-mode)
373
374 (defcustom js2-move-point-on-right-click t
375 "Non-nil to move insertion point when you right-click.
376 This makes right-click context menu behavior a bit more intuitive,
377 since menu operations generally apply to the point. The exception
378 is if there is a region selection, in which case the point does -not-
379 move, so cut/copy/paste can work properly.
380
381 Note that IntelliJ moves the point, and Eclipse leaves it alone,
382 so this behavior is customizable."
383 :group 'js2-mode
384 :type 'boolean)
385
386 (defcustom js2-allow-rhino-new-expr-initializer t
387 "Non-nil to support a Rhino's experimental syntactic construct.
388
389 Rhino supports the ability to follow a `new' expression with an object
390 literal, which is used to set additional properties on the new object
391 after calling its constructor. Syntax:
392
393 new <expr> [ ( arglist ) ] [initializer]
394
395 Hence, this expression:
396
397 new Object {a: 1, b: 2}
398
399 results in an Object with properties a=1 and b=2. This syntax is
400 apparently not configurable in Rhino - it's currently always enabled,
401 as of Rhino version 1.7R2."
402 :type 'boolean
403 :group 'js2-mode)
404
405 (defcustom js2-allow-member-expr-as-function-name nil
406 "Non-nil to support experimental Rhino syntax for function names.
407
408 Rhino supports an experimental syntax configured via the Rhino Context
409 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
410
411 function <member-expr> ( [ arg-list ] ) { <body> }
412
413 Where member-expr is a non-parenthesized 'member expression', which
414 is anything at the grammar level of a new-expression or lower, meaning
415 any expression that does not involve infix or unary operators.
416
417 When <member-expr> is not a simple identifier, then it is syntactic
418 sugar for assigning the anonymous function to the <member-expr>. Hence,
419 this code:
420
421 function a.b().c[2] (x, y) { ... }
422
423 is rewritten as:
424
425 a.b().c[2] = function(x, y) {...}
426
427 which doesn't seem particularly useful, but Rhino permits it."
428 :type 'boolean
429 :group 'js2-mode)
430
431 ;; scanner variables
432
433 (defmacro js2-deflocal (name value &optional comment)
434 "Define a buffer-local variable NAME with VALUE and COMMENT."
435 `(progn
436 (defvar ,name ,value ,comment)
437 (make-variable-buffer-local ',name)))
438
439 ;; We record the start and end position of each token.
440 (js2-deflocal js2-token-beg 1)
441 (js2-deflocal js2-token-end -1)
442
443 (defvar js2-EOF_CHAR -1
444 "Represents end of stream. Distinct from js2-EOF token type.")
445
446 ;; I originally used symbols to represent tokens, but Rhino uses
447 ;; ints and then sets various flag bits in them, so ints it is.
448 ;; The upshot is that we need a `js2-' prefix in front of each name.
449 (defvar js2-ERROR -1)
450 (defvar js2-EOF 0)
451 (defvar js2-EOL 1)
452 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
453 (defvar js2-LEAVEWITH 3)
454 (defvar js2-RETURN 4)
455 (defvar js2-GOTO 5)
456 (defvar js2-IFEQ 6)
457 (defvar js2-IFNE 7)
458 (defvar js2-SETNAME 8)
459 (defvar js2-BITOR 9)
460 (defvar js2-BITXOR 10)
461 (defvar js2-BITAND 11)
462 (defvar js2-EQ 12)
463 (defvar js2-NE 13)
464 (defvar js2-LT 14)
465 (defvar js2-LE 15)
466 (defvar js2-GT 16)
467 (defvar js2-GE 17)
468 (defvar js2-LSH 18)
469 (defvar js2-RSH 19)
470 (defvar js2-URSH 20)
471 (defvar js2-ADD 21) ; infix plus
472 (defvar js2-SUB 22) ; infix minus
473 (defvar js2-MUL 23)
474 (defvar js2-DIV 24)
475 (defvar js2-MOD 25)
476 (defvar js2-NOT 26)
477 (defvar js2-BITNOT 27)
478 (defvar js2-POS 28) ; unary plus
479 (defvar js2-NEG 29) ; unary minus
480 (defvar js2-NEW 30)
481 (defvar js2-DELPROP 31)
482 (defvar js2-TYPEOF 32)
483 (defvar js2-GETPROP 33)
484 (defvar js2-GETPROPNOWARN 34)
485 (defvar js2-SETPROP 35)
486 (defvar js2-GETELEM 36)
487 (defvar js2-SETELEM 37)
488 (defvar js2-CALL 38)
489 (defvar js2-NAME 39) ; an identifier
490 (defvar js2-NUMBER 40)
491 (defvar js2-STRING 41)
492 (defvar js2-NULL 42)
493 (defvar js2-THIS 43)
494 (defvar js2-FALSE 44)
495 (defvar js2-TRUE 45)
496 (defvar js2-SHEQ 46) ; shallow equality (===)
497 (defvar js2-SHNE 47) ; shallow inequality (!==)
498 (defvar js2-REGEXP 48)
499 (defvar js2-BINDNAME 49)
500 (defvar js2-THROW 50)
501 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
502 (defvar js2-IN 52)
503 (defvar js2-INSTANCEOF 53)
504 (defvar js2-LOCAL_LOAD 54)
505 (defvar js2-GETVAR 55)
506 (defvar js2-SETVAR 56)
507 (defvar js2-CATCH_SCOPE 57)
508 (defvar js2-ENUM_INIT_KEYS 58)
509 (defvar js2-ENUM_INIT_VALUES 59)
510 (defvar js2-ENUM_INIT_ARRAY 60)
511 (defvar js2-ENUM_NEXT 61)
512 (defvar js2-ENUM_ID 62)
513 (defvar js2-THISFN 63)
514 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
515 (defvar js2-ARRAYLIT 65) ; array literal
516 (defvar js2-OBJECTLIT 66) ; object literal
517 (defvar js2-GET_REF 67) ; *reference
518 (defvar js2-SET_REF 68) ; *reference = something
519 (defvar js2-DEL_REF 69) ; delete reference
520 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
521 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
522 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
523
524 ;; XML support
525 (defvar js2-DEFAULTNAMESPACE 73)
526 (defvar js2-ESCXMLATTR 74)
527 (defvar js2-ESCXMLTEXT 75)
528 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
529 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
530 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
531 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
532
533 (defvar js2-first-bytecode js2-ENTERWITH)
534 (defvar js2-last-bytecode js2-REF_NS_NAME)
535
536 (defvar js2-TRY 80)
537 (defvar js2-SEMI 81) ; semicolon
538 (defvar js2-LB 82) ; left and right brackets
539 (defvar js2-RB 83)
540 (defvar js2-LC 84) ; left and right curly-braces
541 (defvar js2-RC 85)
542 (defvar js2-LP 86) ; left and right parens
543 (defvar js2-RP 87)
544 (defvar js2-COMMA 88) ; comma operator
545
546 (defvar js2-ASSIGN 89) ; simple assignment (=)
547 (defvar js2-ASSIGN_BITOR 90) ; |=
548 (defvar js2-ASSIGN_BITXOR 91) ; ^=
549 (defvar js2-ASSIGN_BITAND 92) ; &=
550 (defvar js2-ASSIGN_LSH 93) ; <<=
551 (defvar js2-ASSIGN_RSH 94) ; >>=
552 (defvar js2-ASSIGN_URSH 95) ; >>>=
553 (defvar js2-ASSIGN_ADD 96) ; +=
554 (defvar js2-ASSIGN_SUB 97) ; -=
555 (defvar js2-ASSIGN_MUL 98) ; *=
556 (defvar js2-ASSIGN_DIV 99) ; /=
557 (defvar js2-ASSIGN_MOD 100) ; %=
558
559 (defvar js2-first-assign js2-ASSIGN)
560 (defvar js2-last-assign js2-ASSIGN_MOD)
561
562 (defvar js2-HOOK 101) ; conditional (?:)
563 (defvar js2-COLON 102)
564 (defvar js2-OR 103) ; logical or (||)
565 (defvar js2-AND 104) ; logical and (&&)
566 (defvar js2-INC 105) ; increment/decrement (++ --)
567 (defvar js2-DEC 106)
568 (defvar js2-DOT 107) ; member operator (.)
569 (defvar js2-FUNCTION 108) ; function keyword
570 (defvar js2-EXPORT 109) ; export keyword
571 (defvar js2-IMPORT 110) ; import keyword
572 (defvar js2-IF 111) ; if keyword
573 (defvar js2-ELSE 112) ; else keyword
574 (defvar js2-SWITCH 113) ; switch keyword
575 (defvar js2-CASE 114) ; case keyword
576 (defvar js2-DEFAULT 115) ; default keyword
577 (defvar js2-WHILE 116) ; while keyword
578 (defvar js2-DO 117) ; do keyword
579 (defvar js2-FOR 118) ; for keyword
580 (defvar js2-BREAK 119) ; break keyword
581 (defvar js2-CONTINUE 120) ; continue keyword
582 (defvar js2-VAR 121) ; var keyword
583 (defvar js2-WITH 122) ; with keyword
584 (defvar js2-CATCH 123) ; catch keyword
585 (defvar js2-FINALLY 124) ; finally keyword
586 (defvar js2-VOID 125) ; void keyword
587 (defvar js2-RESERVED 126) ; reserved keywords
588
589 (defvar js2-EMPTY 127)
590
591 ;; Types used for the parse tree - never returned by scanner.
592
593 (defvar js2-BLOCK 128) ; statement block
594 (defvar js2-LABEL 129) ; label
595 (defvar js2-TARGET 130)
596 (defvar js2-LOOP 131)
597 (defvar js2-EXPR_VOID 132) ; expression statement in functions
598 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
599 (defvar js2-JSR 134)
600 (defvar js2-SCRIPT 135) ; top-level node for entire script
601 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
602 (defvar js2-USE_STACK 137)
603 (defvar js2-SETPROP_OP 138) ; x.y op= something
604 (defvar js2-SETELEM_OP 139) ; x[y] op= something
605 (defvar js2-LOCAL_BLOCK 140)
606 (defvar js2-SET_REF_OP 141) ; *reference op= something
607
608 ;; For XML support:
609 (defvar js2-DOTDOT 142) ; member operator (..)
610 (defvar js2-COLONCOLON 143) ; namespace::name
611 (defvar js2-XML 144) ; XML type
612 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
613 (defvar js2-XMLATTR 146) ; @
614 (defvar js2-XMLEND 147)
615
616 ;; Optimizer-only tokens
617 (defvar js2-TO_OBJECT 148)
618 (defvar js2-TO_DOUBLE 149)
619
620 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
621 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
622 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
623 (defvar js2-CONST 153)
624 (defvar js2-SETCONST 154)
625 (defvar js2-SETCONSTVAR 155)
626 (defvar js2-ARRAYCOMP 156)
627 (defvar js2-LETEXPR 157)
628 (defvar js2-WITHEXPR 158)
629 (defvar js2-DEBUGGER 159)
630
631 (defvar js2-COMMENT 160)
632 (defvar js2-ENUM 161) ; for "enum" reserved word
633 (defvar js2-TRIPLEDOT 162) ; for rest parameter
634
635 (defconst js2-num-tokens (1+ js2-TRIPLEDOT))
636
637 (defconst js2-debug-print-trees nil)
638
639 ;; Rhino accepts any string or stream as input. Emacs character
640 ;; processing works best in buffers, so we'll assume the input is a
641 ;; buffer. JavaScript strings can be copied into temp buffers before
642 ;; scanning them.
643
644 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
645 ;; They're the Emacs equivalent of instance variables, more or less.
646
647 (js2-deflocal js2-ts-dirty-line nil
648 "Token stream buffer-local variable.
649 Indicates stuff other than whitespace since start of line.")
650
651 (js2-deflocal js2-ts-regexp-flags nil
652 "Token stream buffer-local variable.")
653
654 (js2-deflocal js2-ts-string ""
655 "Token stream buffer-local variable.
656 Last string scanned.")
657
658 (js2-deflocal js2-ts-number nil
659 "Token stream buffer-local variable.
660 Last literal number scanned.")
661
662 (js2-deflocal js2-ts-hit-eof nil
663 "Token stream buffer-local variable.")
664
665 (js2-deflocal js2-ts-line-start 0
666 "Token stream buffer-local variable.")
667
668 (js2-deflocal js2-ts-lineno 1
669 "Token stream buffer-local variable.")
670
671 (js2-deflocal js2-ts-line-end-char -1
672 "Token stream buffer-local variable.")
673
674 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
675 "Token stream buffer-local variable.
676 Current scan position.")
677
678 (js2-deflocal js2-ts-is-xml-attribute nil
679 "Token stream buffer-local variable.")
680
681 (js2-deflocal js2-ts-xml-is-tag-content nil
682 "Token stream buffer-local variable.")
683
684 (js2-deflocal js2-ts-xml-open-tags-count 0
685 "Token stream buffer-local variable.")
686
687 (js2-deflocal js2-ts-string-buffer nil
688 "Token stream buffer-local variable.
689 List of chars built up while scanning various tokens.")
690
691 (js2-deflocal js2-ts-comment-type nil
692 "Token stream buffer-local variable.")
693
694 ;;; Parser variables
695
696 (js2-deflocal js2-parsed-errors nil
697 "List of errors produced during scanning/parsing.")
698
699 (js2-deflocal js2-parsed-warnings nil
700 "List of warnings produced during scanning/parsing.")
701
702 (js2-deflocal js2-recover-from-parse-errors t
703 "Non-nil to continue parsing after a syntax error.
704
705 In recovery mode, the AST will be built in full, and any error
706 nodes will be flagged with appropriate error information. If
707 this flag is nil, a syntax error will result in an error being
708 signaled.
709
710 The variable is automatically buffer-local, because different
711 modes that use the parser will need different settings.")
712
713 (js2-deflocal js2-parse-hook nil
714 "List of callbacks for receiving parsing progress.")
715
716 (defvar js2-parse-finished-hook nil
717 "List of callbacks to notify when parsing finishes.
718 Not called if parsing was interrupted.")
719
720 (js2-deflocal js2-is-eval-code nil
721 "True if we're evaluating code in a string.
722 If non-nil, the tokenizer will record the token text, and the AST nodes
723 will record their source text. Off by default for IDE modes, since the
724 text is available in the buffer.")
725
726 (defvar js2-parse-ide-mode t
727 "Non-nil if the parser is being used for `js2-mode'.
728 If non-nil, the parser will set text properties for fontification
729 and the syntax table. The value should be nil when using the
730 parser as a frontend to an interpreter or byte compiler.")
731
732 ;;; Parser instance variables (buffer-local vars for js2-parse)
733
734 (defconst js2-clear-ti-mask #xFFFF
735 "Mask to clear token information bits.")
736
737 (defconst js2-ti-after-eol (lsh 1 16)
738 "Flag: first token of the source line.")
739
740 (defconst js2-ti-check-label (lsh 1 17)
741 "Flag: indicates to check for label.")
742
743 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
744
745 (js2-deflocal js2-compiler-generate-debug-info t)
746 (js2-deflocal js2-compiler-use-dynamic-scope nil)
747 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
748 (js2-deflocal js2-compiler-xml-available t)
749 (js2-deflocal js2-compiler-optimization-level 0)
750 (js2-deflocal js2-compiler-generating-source t)
751 (js2-deflocal js2-compiler-strict-mode nil)
752 (js2-deflocal js2-compiler-report-warning-as-error nil)
753 (js2-deflocal js2-compiler-generate-observer-count nil)
754 (js2-deflocal js2-compiler-activation-names nil)
755
756 ;; SKIP: sourceURI
757
758 ;; There's a compileFunction method in Context.java - may need it.
759 (js2-deflocal js2-called-by-compile-function nil
760 "True if `js2-parse' was called by `js2-compile-function'.
761 Will only be used when we finish implementing the interpreter.")
762
763 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
764
765 (js2-deflocal js2-current-flagged-token js2-EOF)
766 (js2-deflocal js2-current-token js2-EOF)
767
768 ;; SKIP: node factory - we're going to just call functions directly,
769 ;; and eventually go to a unified AST format.
770
771 (js2-deflocal js2-nesting-of-function 0)
772
773 (js2-deflocal js2-recorded-identifiers nil
774 "Tracks identifiers found during parsing.")
775
776 (js2-deflocal js2-is-in-destructuring nil
777 "True while parsing destructuring expression.")
778
779 (defcustom js2-global-externs nil
780 "A list of any extern names you'd like to consider always declared.
781 This list is global and is used by all `js2-mode' files.
782 You can create buffer-local externs list using `js2-additional-externs'.
783
784 There is also a buffer-local variable `js2-default-externs',
785 which is initialized by default to include the Ecma-262 externs
786 and the standard browser externs. The three lists are all
787 checked during highlighting."
788 :type 'list
789 :group 'js2-mode)
790
791 (js2-deflocal js2-default-externs nil
792 "Default external declarations.
793
794 These are currently only used for highlighting undeclared variables,
795 which only worries about top-level (unqualified) references.
796 As js2-mode's processing improves, we will flesh out this list.
797
798 The initial value is set to `js2-ecma-262-externs', unless you
799 have set `js2-include-browser-externs', in which case the browser
800 externs are also included.
801
802 See `js2-additional-externs' for more information.")
803
804 (defcustom js2-include-browser-externs t
805 "Non-nil to include browser externs in the master externs list.
806 If you work on JavaScript files that are not intended for browsers,
807 such as Mozilla Rhino server-side JavaScript, set this to nil.
808 You can always include them on a per-file basis by calling
809 `js2-add-browser-externs' from a function on `js2-mode-hook'.
810
811 See `js2-additional-externs' for more information about externs."
812 :type 'boolean
813 :group 'js2-mode)
814
815 (defcustom js2-include-rhino-externs t
816 "Non-nil to include Mozilla Rhino externs in the master externs list.
817 See `js2-additional-externs' for more information about externs."
818 :type 'boolean
819 :group 'js2-mode)
820
821 (defcustom js2-include-gears-externs t
822 "Non-nil to include Google Gears externs in the master externs list.
823 See `js2-additional-externs' for more information about externs."
824 :type 'boolean
825 :group 'js2-mode)
826
827 (js2-deflocal js2-additional-externs nil
828 "A buffer-local list of additional external declarations.
829 It is used to decide whether variables are considered undeclared
830 for purposes of highlighting.
831
832 Each entry is a Lisp string. The string should be the fully qualified
833 name of an external entity. All externs should be added to this list,
834 so that as js2-mode's processing improves it can take advantage of them.
835
836 You may want to declare your externs in three ways.
837 First, you can add externs that are valid for all your JavaScript files.
838 You should probably do this by adding them to `js2-global-externs', which
839 is a global list used for all js2-mode files.
840
841 Next, you can add a function to `js2-mode-hook' that adds additional
842 externs appropriate for the specific file, perhaps based on its path.
843 These should go in `js2-additional-externs', which is buffer-local.
844
845 Finally, you can add a function to `js2-post-parse-callbacks',
846 which is called after parsing completes, and `js2-mode-ast' is bound to
847 the root of the parse tree. At this stage you can set up an AST
848 node visitor using `js2-visit-ast' and examine the parse tree
849 for specific import patterns that may imply the existence of
850 other externs, possibly tied to your build system. These should also
851 be added to `js2-additional-externs'.
852
853 Your post-parse callback may of course also use the simpler and
854 faster (but perhaps less robust) approach of simply scanning the
855 buffer text for your imports, using regular expressions.")
856
857 ;; SKIP: decompiler
858 ;; SKIP: encoded-source
859
860 ;;; The following variables are per-function and should be saved/restored
861 ;;; during function parsing...
862
863 (js2-deflocal js2-current-script-or-fn nil)
864 (js2-deflocal js2-current-scope nil)
865 (js2-deflocal js2-nesting-of-with 0)
866 (js2-deflocal js2-label-set nil
867 "An alist mapping label names to nodes.")
868
869 (js2-deflocal js2-loop-set nil)
870 (js2-deflocal js2-loop-and-switch-set nil)
871 (js2-deflocal js2-has-return-value nil)
872 (js2-deflocal js2-end-flags 0)
873
874 ;;; ...end of per function variables
875
876 ;; Without 2-token lookahead, labels are a problem.
877 ;; These vars store the token info of the last matched name,
878 ;; iff it wasn't the last matched token. Only valid in some contexts.
879 (defvar js2-prev-name-token-start nil)
880 (defvar js2-prev-name-token-string nil)
881
882 (defsubst js2-save-name-token-data (pos name)
883 (setq js2-prev-name-token-start pos
884 js2-prev-name-token-string name))
885
886 ;; These flags enumerate the possible ways a statement/function can
887 ;; terminate. These flags are used by endCheck() and by the Parser to
888 ;; detect inconsistent return usage.
889 ;;
890 ;; END_UNREACHED is reserved for code paths that are assumed to always be
891 ;; able to execute (example: throw, continue)
892 ;;
893 ;; END_DROPS_OFF indicates if the statement can transfer control to the
894 ;; next one. Statement such as return dont. A compound statement may have
895 ;; some branch that drops off control to the next statement.
896 ;;
897 ;; END_RETURNS indicates that the statement can return (without arguments)
898 ;; END_RETURNS_VALUE indicates that the statement can return a value.
899 ;;
900 ;; A compound statement such as
901 ;; if (condition) {
902 ;; return value;
903 ;; }
904 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
905
906 (defconst js2-end-unreached #x0)
907 (defconst js2-end-drops-off #x1)
908 (defconst js2-end-returns #x2)
909 (defconst js2-end-returns-value #x4)
910 (defconst js2-end-yields #x8)
911
912 ;; Rhino awkwardly passes a statementLabel parameter to the
913 ;; statementHelper() function, the main statement parser, which
914 ;; is then used by quite a few of the sub-parsers. We just make
915 ;; it a buffer-local variable and make sure it's cleaned up properly.
916 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
917
918 ;; Similarly, Rhino passes an inForInit boolean through about half
919 ;; the expression parsers. We use a dynamically-scoped variable,
920 ;; which makes it easier to funcall the parsers individually without
921 ;; worrying about whether they take the parameter or not.
922 (js2-deflocal js2-in-for-init nil)
923 (js2-deflocal js2-temp-name-counter 0)
924 (js2-deflocal js2-parse-stmt-count 0)
925
926 (defsubst js2-get-next-temp-name ()
927 (format "$%d" (incf js2-temp-name-counter)))
928
929 (defvar js2-parse-interruptable-p t
930 "Set this to nil to force parse to continue until finished.
931 This will mostly be useful for interpreters.")
932
933 (defvar js2-statements-per-pause 50
934 "Pause after this many statements to check for user input.
935 If user input is pending, stop the parse and discard the tree.
936 This makes for a smoother user experience for large files.
937 You may have to wait a second or two before the highlighting
938 and error-reporting appear, but you can always type ahead if
939 you wish. This appears to be more or less how Eclipse, IntelliJ
940 and other editors work.")
941
942 (js2-deflocal js2-record-comments t
943 "Instructs the scanner to record comments in `js2-scanned-comments'.")
944
945 (js2-deflocal js2-scanned-comments nil
946 "List of all comments from the current parse.")
947
948 (defcustom js2-mode-indent-inhibit-undo nil
949 "Non-nil to disable collection of Undo information when indenting lines.
950 Some users have requested this behavior. It's nil by default because
951 other Emacs modes don't work this way."
952 :type 'boolean
953 :group 'js2-mode)
954
955 (defcustom js2-mode-indent-ignore-first-tab nil
956 "If non-nil, ignore first TAB keypress if we look indented properly.
957 It's fairly common for users to navigate to an already-indented line
958 and press TAB for reassurance that it's been indented. For this class
959 of users, we want the first TAB press on a line to be ignored if the
960 line is already indented to one of the precomputed alternatives.
961
962 This behavior is only partly implemented. If you TAB-indent a line,
963 navigate to another line, and then navigate back, it fails to clear
964 the last-indented variable, so it thinks you've already hit TAB once,
965 and performs the indent. A full solution would involve getting on the
966 point-motion hooks for the entire buffer. If we come across another
967 use cases that requires watching point motion, I'll consider doing it.
968
969 If you set this variable to nil, then the TAB key will always change
970 the indentation of the current line, if more than one alternative
971 indentation spot exists."
972 :type 'boolean
973 :group 'js2-mode)
974
975 (defvar js2-indent-hook nil
976 "A hook for user-defined indentation rules.
977
978 Functions on this hook should expect two arguments: (LIST INDEX)
979 The LIST argument is the list of computed indentation points for
980 the current line. INDEX is the list index of the indentation point
981 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
982 indent function is not going to change the current line indentation.
983
984 If a hook function on this list returns a non-nil value, then
985 `js2-bounce-indent' assumes the hook function has performed its own
986 indentation, and will do nothing. If all hook functions on the list
987 return nil, then `js2-bounce-indent' will use its computed indentation
988 and reindent the line.
989
990 When hook functions on this hook list are called, the variable
991 `js2-mode-ast' may or may not be set, depending on whether the
992 parse tree is available. If the variable is nil, you can pass a
993 callback to `js2-mode-wait-for-parse', and your callback will be
994 called after the new parse tree is built. This can take some time
995 in large files.")
996
997 (defface js2-warning
998 `((((class color) (background light))
999 (:underline "orange"))
1000 (((class color) (background dark))
1001 (:underline "orange"))
1002 (t (:underline t)))
1003 "Face for JavaScript warnings."
1004 :group 'js2-mode)
1005
1006 (defface js2-error
1007 `((((class color) (background light))
1008 (:foreground "red"))
1009 (((class color) (background dark))
1010 (:foreground "red"))
1011 (t (:foreground "red")))
1012 "Face for JavaScript errors."
1013 :group 'js2-mode)
1014
1015 (defface js2-jsdoc-tag
1016 '((t :foreground "SlateGray"))
1017 "Face used to highlight @whatever tags in jsdoc comments."
1018 :group 'js2-mode)
1019
1020 (defface js2-jsdoc-type
1021 '((t :foreground "SteelBlue"))
1022 "Face used to highlight {FooBar} types in jsdoc comments."
1023 :group 'js2-mode)
1024
1025 (defface js2-jsdoc-value
1026 '((t :foreground "PeachPuff3"))
1027 "Face used to highlight tag values in jsdoc comments."
1028 :group 'js2-mode)
1029
1030 (defface js2-function-param
1031 '((t :foreground "SeaGreen"))
1032 "Face used to highlight function parameters in javascript."
1033 :group 'js2-mode)
1034
1035 (defface js2-instance-member
1036 '((t :foreground "DarkOrchid"))
1037 "Face used to highlight instance variables in javascript.
1038 Not currently used."
1039 :group 'js2-mode)
1040
1041 (defface js2-private-member
1042 '((t :foreground "PeachPuff3"))
1043 "Face used to highlight calls to private methods in javascript.
1044 Not currently used."
1045 :group 'js2-mode)
1046
1047 (defface js2-private-function-call
1048 '((t :foreground "goldenrod"))
1049 "Face used to highlight calls to private functions in javascript.
1050 Not currently used."
1051 :group 'js2-mode)
1052
1053 (defface js2-jsdoc-html-tag-name
1054 '((((class color) (min-colors 88) (background light))
1055 (:foreground "rosybrown"))
1056 (((class color) (min-colors 8) (background dark))
1057 (:foreground "yellow"))
1058 (((class color) (min-colors 8) (background light))
1059 (:foreground "magenta")))
1060 "Face used to highlight jsdoc html tag names"
1061 :group 'js2-mode)
1062
1063 (defface js2-jsdoc-html-tag-delimiter
1064 '((((class color) (min-colors 88) (background light))
1065 (:foreground "dark khaki"))
1066 (((class color) (min-colors 8) (background dark))
1067 (:foreground "green"))
1068 (((class color) (min-colors 8) (background light))
1069 (:foreground "green")))
1070 "Face used to highlight brackets in jsdoc html tags."
1071 :group 'js2-mode)
1072
1073 (defface js2-external-variable
1074 '((t :foreground "orange"))
1075 "Face used to highlight undeclared variable identifiers.")
1076
1077 (defcustom js2-post-parse-callbacks nil
1078 "A list of callback functions invoked after parsing finishes.
1079 Currently, the main use for this function is to add synthetic
1080 declarations to `js2-recorded-identifiers', which see."
1081 :type 'list
1082 :group 'js2-mode)
1083
1084 (defcustom js2-highlight-external-variables t
1085 "Non-nil to highlight undeclared variable identifiers.
1086 An undeclared variable is any variable not declared with var or let
1087 in the current scope or any lexically enclosing scope. If you use
1088 such a variable, then you are either expecting it to originate from
1089 another file, or you've got a potential bug."
1090 :type 'boolean
1091 :group 'js2-mode)
1092
1093 (defcustom js2-auto-insert-catch-block t
1094 "Non-nil to insert matching catch block on open-curly after `try'."
1095 :type 'boolean
1096 :group 'js2-mode)
1097
1098 (defvar js2-mode-map
1099 (let ((map (make-sparse-keymap))
1100 keys)
1101 (define-key map [mouse-1] #'js2-mode-show-node)
1102 (define-key map (kbd "M-j") #'js2-line-break)
1103 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1104 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1105 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1106 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1107 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1108 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1109 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1110 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1111 (when js2-bounce-indent-p
1112 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1113
1114 (define-key map [menu-bar javascript]
1115 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1116
1117 (define-key map [menu-bar javascript customize-js2-mode]
1118 '(menu-item "Customize js2-mode" js2-mode-customize
1119 :help "Customize the behavior of this mode"))
1120
1121 (define-key map [menu-bar javascript js2-force-refresh]
1122 '(menu-item "Force buffer refresh" js2-mode-reset
1123 :help "Re-parse the buffer from scratch"))
1124
1125 (define-key map [menu-bar javascript separator-2]
1126 '("--"))
1127
1128 (define-key map [menu-bar javascript next-error]
1129 '(menu-item "Next warning or error" next-error
1130 :enabled (and js2-mode-ast
1131 (or (js2-ast-root-errors js2-mode-ast)
1132 (js2-ast-root-warnings js2-mode-ast)))
1133 :help "Move to next warning or error"))
1134
1135 (define-key map [menu-bar javascript display-errors]
1136 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1137 :visible (not js2-mode-show-parse-errors)
1138 :help "Turn on display of warnings and errors"))
1139
1140 (define-key map [menu-bar javascript hide-errors]
1141 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1142 :visible js2-mode-show-parse-errors
1143 :help "Turn off display of warnings and errors"))
1144
1145 (define-key map [menu-bar javascript separator-1]
1146 '("--"))
1147
1148 (define-key map [menu-bar javascript js2-toggle-function]
1149 '(menu-item "Show/collapse element" js2-mode-toggle-element
1150 :help "Hide or show function body or comment"))
1151
1152 (define-key map [menu-bar javascript show-comments]
1153 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1154 :visible js2-mode-comments-hidden
1155 :help "Expand all hidden block comments"))
1156
1157 (define-key map [menu-bar javascript hide-comments]
1158 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1159 :visible (not js2-mode-comments-hidden)
1160 :help "Show block comments as /*...*/"))
1161
1162 (define-key map [menu-bar javascript show-all-functions]
1163 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1164 :visible js2-mode-functions-hidden
1165 :help "Expand all hidden function bodies"))
1166
1167 (define-key map [menu-bar javascript hide-all-functions]
1168 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1169 :visible (not js2-mode-functions-hidden)
1170 :help "Show {...} for all top-level function bodies"))
1171
1172 map)
1173 "Keymap used in `js2-mode' buffers.")
1174
1175 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1176
1177 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1178 "Matches a //-comment line. Must be first non-whitespace on line.
1179 First match-group is the leading whitespace.")
1180
1181 (defvar js2-mode-hook nil)
1182
1183 (js2-deflocal js2-mode-ast nil "Private variable.")
1184 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1185 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1186 (js2-deflocal js2-mode-parsing nil "Private variable.")
1187 (js2-deflocal js2-mode-node-overlay nil)
1188
1189 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1190 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1191
1192 (js2-deflocal js2-mode-fontifications nil "Private variable")
1193 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1194 (js2-deflocal js2-imenu-recorder nil "Private variable")
1195 (js2-deflocal js2-imenu-function-map nil "Private variable")
1196
1197 (defvar js2-paragraph-start
1198 "\\(@[a-zA-Z]+\\>\\|$\\)")
1199
1200 ;; Note that we also set a 'c-in-sws text property in html comments,
1201 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1202 (defvar js2-syntactic-ws-start
1203 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1204
1205 (defvar js2-syntactic-ws-end
1206 "\\s \\|[\n\r/]\\|\\s!")
1207
1208 (defvar js2-syntactic-eol
1209 (concat "\\s *\\(/\\*[^*\n\r]*"
1210 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1211 "\\*+/\\s *\\)*"
1212 "\\(//\\|/\\*[^*\n\r]*"
1213 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1214 "\\|\\\\$\\|$\\)")
1215 "Copied from `java-mode'. Needed for some cc-engine functions.")
1216
1217 (defvar js2-comment-prefix-regexp
1218 "//+\\|\\**")
1219
1220 (defvar js2-comment-start-skip
1221 "\\(//+\\|/\\*+\\)\\s *")
1222
1223 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1224 "Non-nil to emit status messages during parsing.")
1225
1226 (defvar js2-mode-functions-hidden nil "Private variable.")
1227 (defvar js2-mode-comments-hidden nil "Private variable.")
1228
1229 (defvar js2-mode-syntax-table
1230 (let ((table (make-syntax-table)))
1231 (c-populate-syntax-table table)
1232 table)
1233 "Syntax table used in `js2-mode' buffers.")
1234
1235 (defvar js2-mode-abbrev-table nil
1236 "Abbrev table in use in `js2-mode' buffers.")
1237 (define-abbrev-table 'js2-mode-abbrev-table ())
1238
1239 (defvar js2-mode-pending-parse-callbacks nil
1240 "List of functions waiting to be notified that parse is finished.")
1241
1242 (defvar js2-mode-last-indented-line -1)
1243
1244 ;;; Localizable error and warning messages
1245
1246 ;; Messages are copied from Rhino's Messages.properties.
1247 ;; Many of the Java-specific messages have been elided.
1248 ;; Add any js2-specific ones at the end, so we can keep
1249 ;; this file synced with changes to Rhino's.
1250
1251 (defvar js2-message-table
1252 (make-hash-table :test 'equal :size 250)
1253 "Contains localized messages for `js2-mode'.")
1254
1255 ;; TODO(stevey): construct this table at compile-time.
1256 (defmacro js2-msg (key &rest strings)
1257 `(puthash ,key (concat ,@strings)
1258 js2-message-table))
1259
1260 (defun js2-get-msg (msg-key)
1261 "Look up a localized message.
1262 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1263 the correct number of ARGS must be provided."
1264 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1265 (args (if (listp msg-key) (cdr msg-key)))
1266 (msg (gethash key js2-message-table)))
1267 (if msg
1268 (apply #'format msg args)
1269 key))) ; default to showing the key
1270
1271 (js2-msg "msg.dup.parms"
1272 "Duplicate parameter name '%s'.")
1273
1274 (js2-msg "msg.too.big.jump"
1275 "Program too complex: jump offset too big.")
1276
1277 (js2-msg "msg.too.big.index"
1278 "Program too complex: internal index exceeds 64K limit.")
1279
1280 (js2-msg "msg.while.compiling.fn"
1281 "Encountered code generation error while compiling function '%s': %s")
1282
1283 (js2-msg "msg.while.compiling.script"
1284 "Encountered code generation error while compiling script: %s")
1285
1286 ;; Context
1287 (js2-msg "msg.ctor.not.found"
1288 "Constructor for '%s' not found.")
1289
1290 (js2-msg "msg.not.ctor"
1291 "'%s' is not a constructor.")
1292
1293 ;; FunctionObject
1294 (js2-msg "msg.varargs.ctor"
1295 "Method or constructor '%s' must be static "
1296 "with the signature (Context cx, Object[] args, "
1297 "Function ctorObj, boolean inNewExpr) "
1298 "to define a variable arguments constructor.")
1299
1300 (js2-msg "msg.varargs.fun"
1301 "Method '%s' must be static with the signature "
1302 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1303 "to define a variable arguments function.")
1304
1305 (js2-msg "msg.incompat.call"
1306 "Method '%s' called on incompatible object.")
1307
1308 (js2-msg "msg.bad.parms"
1309 "Unsupported parameter type '%s' in method '%s'.")
1310
1311 (js2-msg "msg.bad.method.return"
1312 "Unsupported return type '%s' in method '%s'.")
1313
1314 (js2-msg "msg.bad.ctor.return"
1315 "Construction of objects of type '%s' is not supported.")
1316
1317 (js2-msg "msg.no.overload"
1318 "Method '%s' occurs multiple times in class '%s'.")
1319
1320 (js2-msg "msg.method.not.found"
1321 "Method '%s' not found in '%s'.")
1322
1323 ;; IRFactory
1324
1325 (js2-msg "msg.bad.for.in.lhs"
1326 "Invalid left-hand side of for..in loop.")
1327
1328 (js2-msg "msg.mult.index"
1329 "Only one variable allowed in for..in loop.")
1330
1331 (js2-msg "msg.bad.for.in.destruct"
1332 "Left hand side of for..in loop must be an array of "
1333 "length 2 to accept key/value pair.")
1334
1335 (js2-msg "msg.cant.convert"
1336 "Can't convert to type '%s'.")
1337
1338 (js2-msg "msg.bad.assign.left"
1339 "Invalid assignment left-hand side.")
1340
1341 (js2-msg "msg.bad.decr"
1342 "Invalid decerement operand.")
1343
1344 (js2-msg "msg.bad.incr"
1345 "Invalid increment operand.")
1346
1347 (js2-msg "msg.bad.yield"
1348 "yield must be in a function.")
1349
1350 (js2-msg "msg.yield.parenthesized"
1351 "yield expression must be parenthesized.")
1352
1353 ;; NativeGlobal
1354 (js2-msg "msg.cant.call.indirect"
1355 "Function '%s' must be called directly, and not by way of a "
1356 "function of another name.")
1357
1358 (js2-msg "msg.eval.nonstring"
1359 "Calling eval() with anything other than a primitive "
1360 "string value will simply return the value. "
1361 "Is this what you intended?")
1362
1363 (js2-msg "msg.eval.nonstring.strict"
1364 "Calling eval() with anything other than a primitive "
1365 "string value is not allowed in strict mode.")
1366
1367 (js2-msg "msg.bad.destruct.op"
1368 "Invalid destructuring assignment operator")
1369
1370 ;; NativeCall
1371 (js2-msg "msg.only.from.new"
1372 "'%s' may only be invoked from a `new' expression.")
1373
1374 (js2-msg "msg.deprec.ctor"
1375 "The '%s' constructor is deprecated.")
1376
1377 ;; NativeFunction
1378 (js2-msg "msg.no.function.ref.found"
1379 "no source found to decompile function reference %s")
1380
1381 (js2-msg "msg.arg.isnt.array"
1382 "second argument to Function.prototype.apply must be an array")
1383
1384 ;; NativeGlobal
1385 (js2-msg "msg.bad.esc.mask"
1386 "invalid string escape mask")
1387
1388 ;; NativeRegExp
1389 (js2-msg "msg.bad.quant"
1390 "Invalid quantifier %s")
1391
1392 (js2-msg "msg.overlarge.backref"
1393 "Overly large back reference %s")
1394
1395 (js2-msg "msg.overlarge.min"
1396 "Overly large minimum %s")
1397
1398 (js2-msg "msg.overlarge.max"
1399 "Overly large maximum %s")
1400
1401 (js2-msg "msg.zero.quant"
1402 "Zero quantifier %s")
1403
1404 (js2-msg "msg.max.lt.min"
1405 "Maximum %s less than minimum")
1406
1407 (js2-msg "msg.unterm.quant"
1408 "Unterminated quantifier %s")
1409
1410 (js2-msg "msg.unterm.paren"
1411 "Unterminated parenthetical %s")
1412
1413 (js2-msg "msg.unterm.class"
1414 "Unterminated character class %s")
1415
1416 (js2-msg "msg.bad.range"
1417 "Invalid range in character class.")
1418
1419 (js2-msg "msg.trail.backslash"
1420 "Trailing \\ in regular expression.")
1421
1422 (js2-msg "msg.re.unmatched.right.paren"
1423 "unmatched ) in regular expression.")
1424
1425 (js2-msg "msg.no.regexp"
1426 "Regular expressions are not available.")
1427
1428 (js2-msg "msg.bad.backref"
1429 "back-reference exceeds number of capturing parentheses.")
1430
1431 (js2-msg "msg.bad.regexp.compile"
1432 "Only one argument may be specified if the first "
1433 "argument to RegExp.prototype.compile is a RegExp object.")
1434
1435 ;; Parser
1436 (js2-msg "msg.got.syntax.errors"
1437 "Compilation produced %s syntax errors.")
1438
1439 (js2-msg "msg.var.redecl"
1440 "TypeError: redeclaration of var %s.")
1441
1442 (js2-msg "msg.const.redecl"
1443 "TypeError: redeclaration of const %s.")
1444
1445 (js2-msg "msg.let.redecl"
1446 "TypeError: redeclaration of variable %s.")
1447
1448 (js2-msg "msg.parm.redecl"
1449 "TypeError: redeclaration of formal parameter %s.")
1450
1451 (js2-msg "msg.fn.redecl"
1452 "TypeError: redeclaration of function %s.")
1453
1454 (js2-msg "msg.let.decl.not.in.block"
1455 "SyntaxError: let declaration not directly within block")
1456
1457 ;; NodeTransformer
1458 (js2-msg "msg.dup.label"
1459 "duplicated label")
1460
1461 (js2-msg "msg.undef.label"
1462 "undefined label")
1463
1464 (js2-msg "msg.bad.break"
1465 "unlabelled break must be inside loop or switch")
1466
1467 (js2-msg "msg.continue.outside"
1468 "continue must be inside loop")
1469
1470 (js2-msg "msg.continue.nonloop"
1471 "continue can only use labels of iteration statements")
1472
1473 (js2-msg "msg.bad.throw.eol"
1474 "Line terminator is not allowed between the throw "
1475 "keyword and throw expression.")
1476
1477 (js2-msg "msg.no.paren.parms"
1478 "missing ( before function parameters.")
1479
1480 (js2-msg "msg.no.parm"
1481 "missing formal parameter")
1482
1483 (js2-msg "msg.no.paren.after.parms"
1484 "missing ) after formal parameters")
1485
1486 (js2-msg "msg.no.default.after.default.param" ; added by js2-mode
1487 "parameter without default follows parameter with default")
1488
1489 (js2-msg "msg.param.after.rest" ; added by js2-mode
1490 "parameter after rest parameter")
1491
1492 (js2-msg "msg.no.brace.body"
1493 "missing '{' before function body")
1494
1495 (js2-msg "msg.no.brace.after.body"
1496 "missing } after function body")
1497
1498 (js2-msg "msg.no.paren.cond"
1499 "missing ( before condition")
1500
1501 (js2-msg "msg.no.paren.after.cond"
1502 "missing ) after condition")
1503
1504 (js2-msg "msg.no.semi.stmt"
1505 "missing ; before statement")
1506
1507 (js2-msg "msg.missing.semi"
1508 "missing ; after statement")
1509
1510 (js2-msg "msg.no.name.after.dot"
1511 "missing name after . operator")
1512
1513 (js2-msg "msg.no.name.after.coloncolon"
1514 "missing name after :: operator")
1515
1516 (js2-msg "msg.no.name.after.dotdot"
1517 "missing name after .. operator")
1518
1519 (js2-msg "msg.no.name.after.xmlAttr"
1520 "missing name after .@")
1521
1522 (js2-msg "msg.no.bracket.index"
1523 "missing ] in index expression")
1524
1525 (js2-msg "msg.no.paren.switch"
1526 "missing ( before switch expression")
1527
1528 (js2-msg "msg.no.paren.after.switch"
1529 "missing ) after switch expression")
1530
1531 (js2-msg "msg.no.brace.switch"
1532 "missing '{' before switch body")
1533
1534 (js2-msg "msg.bad.switch"
1535 "invalid switch statement")
1536
1537 (js2-msg "msg.no.colon.case"
1538 "missing : after case expression")
1539
1540 (js2-msg "msg.double.switch.default"
1541 "double default label in the switch statement")
1542
1543 (js2-msg "msg.no.while.do"
1544 "missing while after do-loop body")
1545
1546 (js2-msg "msg.no.paren.for"
1547 "missing ( after for")
1548
1549 (js2-msg "msg.no.semi.for"
1550 "missing ; after for-loop initializer")
1551
1552 (js2-msg "msg.no.semi.for.cond"
1553 "missing ; after for-loop condition")
1554
1555 (js2-msg "msg.in.after.for.name"
1556 "missing in or of after for")
1557
1558 (js2-msg "msg.no.paren.for.ctrl"
1559 "missing ) after for-loop control")
1560
1561 (js2-msg "msg.no.paren.with"
1562 "missing ( before with-statement object")
1563
1564 (js2-msg "msg.no.paren.after.with"
1565 "missing ) after with-statement object")
1566
1567 (js2-msg "msg.no.paren.after.let"
1568 "missing ( after let")
1569
1570 (js2-msg "msg.no.paren.let"
1571 "missing ) after variable list")
1572
1573 (js2-msg "msg.no.curly.let"
1574 "missing } after let statement")
1575
1576 (js2-msg "msg.bad.return"
1577 "invalid return")
1578
1579 (js2-msg "msg.no.brace.block"
1580 "missing } in compound statement")
1581
1582 (js2-msg "msg.bad.label"
1583 "invalid label")
1584
1585 (js2-msg "msg.bad.var"
1586 "missing variable name")
1587
1588 (js2-msg "msg.bad.var.init"
1589 "invalid variable initialization")
1590
1591 (js2-msg "msg.no.colon.cond"
1592 "missing : in conditional expression")
1593
1594 (js2-msg "msg.no.paren.arg"
1595 "missing ) after argument list")
1596
1597 (js2-msg "msg.no.bracket.arg"
1598 "missing ] after element list")
1599
1600 (js2-msg "msg.bad.prop"
1601 "invalid property id")
1602
1603 (js2-msg "msg.no.colon.prop"
1604 "missing : after property id")
1605
1606 (js2-msg "msg.no.brace.prop"
1607 "missing } after property list")
1608
1609 (js2-msg "msg.no.paren"
1610 "missing ) in parenthetical")
1611
1612 (js2-msg "msg.reserved.id"
1613 "identifier is a reserved word")
1614
1615 (js2-msg "msg.no.paren.catch"
1616 "missing ( before catch-block condition")
1617
1618 (js2-msg "msg.bad.catchcond"
1619 "invalid catch block condition")
1620
1621 (js2-msg "msg.catch.unreachable"
1622 "any catch clauses following an unqualified catch are unreachable")
1623
1624 (js2-msg "msg.no.brace.try"
1625 "missing '{' before try block")
1626
1627 (js2-msg "msg.no.brace.catchblock"
1628 "missing '{' before catch-block body")
1629
1630 (js2-msg "msg.try.no.catchfinally"
1631 "'try' without 'catch' or 'finally'")
1632
1633 (js2-msg "msg.no.return.value"
1634 "function %s does not always return a value")
1635
1636 (js2-msg "msg.anon.no.return.value"
1637 "anonymous function does not always return a value")
1638
1639 (js2-msg "msg.return.inconsistent"
1640 "return statement is inconsistent with previous usage")
1641
1642 (js2-msg "msg.generator.returns"
1643 "TypeError: generator function '%s' returns a value")
1644
1645 (js2-msg "msg.anon.generator.returns"
1646 "TypeError: anonymous generator function returns a value")
1647
1648 (js2-msg "msg.syntax"
1649 "syntax error")
1650
1651 (js2-msg "msg.unexpected.eof"
1652 "Unexpected end of file")
1653
1654 (js2-msg "msg.XML.bad.form"
1655 "illegally formed XML syntax")
1656
1657 (js2-msg "msg.XML.not.available"
1658 "XML runtime not available")
1659
1660 (js2-msg "msg.too.deep.parser.recursion"
1661 "Too deep recursion while parsing")
1662
1663 (js2-msg "msg.no.side.effects"
1664 "Code has no side effects")
1665
1666 (js2-msg "msg.extra.trailing.comma"
1667 "Trailing comma is not supported in some browsers")
1668
1669 (js2-msg "msg.array.trailing.comma"
1670 "Trailing comma yields different behavior across browsers")
1671
1672 (js2-msg "msg.equal.as.assign"
1673 (concat "Test for equality (==) mistyped as assignment (=)?"
1674 " (parenthesize to suppress warning)"))
1675
1676 (js2-msg "msg.var.hides.arg"
1677 "Variable %s hides argument")
1678
1679 (js2-msg "msg.destruct.assign.no.init"
1680 "Missing = in destructuring declaration")
1681
1682 ;; ScriptRuntime
1683 (js2-msg "msg.no.properties"
1684 "%s has no properties.")
1685
1686 (js2-msg "msg.invalid.iterator"
1687 "Invalid iterator value")
1688
1689 (js2-msg "msg.iterator.primitive"
1690 "__iterator__ returned a primitive value")
1691
1692 (js2-msg "msg.assn.create.strict"
1693 "Assignment to undeclared variable %s")
1694
1695 (js2-msg "msg.undeclared.variable" ; added by js2-mode
1696 "Undeclared variable or function '%s'")
1697
1698 (js2-msg "msg.ref.undefined.prop"
1699 "Reference to undefined property '%s'")
1700
1701 (js2-msg "msg.prop.not.found"
1702 "Property %s not found.")
1703
1704 (js2-msg "msg.invalid.type"
1705 "Invalid JavaScript value of type %s")
1706
1707 (js2-msg "msg.primitive.expected"
1708 "Primitive type expected (had %s instead)")
1709
1710 (js2-msg "msg.namespace.expected"
1711 "Namespace object expected to left of :: (found %s instead)")
1712
1713 (js2-msg "msg.null.to.object"
1714 "Cannot convert null to an object.")
1715
1716 (js2-msg "msg.undef.to.object"
1717 "Cannot convert undefined to an object.")
1718
1719 (js2-msg "msg.cyclic.value"
1720 "Cyclic %s value not allowed.")
1721
1722 (js2-msg "msg.is.not.defined"
1723 "'%s' is not defined.")
1724
1725 (js2-msg "msg.undef.prop.read"
1726 "Cannot read property '%s' from %s")
1727
1728 (js2-msg "msg.undef.prop.write"
1729 "Cannot set property '%s' of %s to '%s'")
1730
1731 (js2-msg "msg.undef.prop.delete"
1732 "Cannot delete property '%s' of %s")
1733
1734 (js2-msg "msg.undef.method.call"
1735 "Cannot call method '%s' of %s")
1736
1737 (js2-msg "msg.undef.with"
1738 "Cannot apply 'with' to %s")
1739
1740 (js2-msg "msg.isnt.function"
1741 "%s is not a function, it is %s.")
1742
1743 (js2-msg "msg.isnt.function.in"
1744 "Cannot call property %s in object %s. "
1745 "It is not a function, it is '%s'.")
1746
1747 (js2-msg "msg.function.not.found"
1748 "Cannot find function %s.")
1749
1750 (js2-msg "msg.function.not.found.in"
1751 "Cannot find function %s in object %s.")
1752
1753 (js2-msg "msg.isnt.xml.object"
1754 "%s is not an xml object.")
1755
1756 (js2-msg "msg.no.ref.to.get"
1757 "%s is not a reference to read reference value.")
1758
1759 (js2-msg "msg.no.ref.to.set"
1760 "%s is not a reference to set reference value to %s.")
1761
1762 (js2-msg "msg.no.ref.from.function"
1763 "Function %s can not be used as the left-hand "
1764 "side of assignment or as an operand of ++ or -- operator.")
1765
1766 (js2-msg "msg.bad.default.value"
1767 "Object's getDefaultValue() method returned an object.")
1768
1769 (js2-msg "msg.instanceof.not.object"
1770 "Can't use instanceof on a non-object.")
1771
1772 (js2-msg "msg.instanceof.bad.prototype"
1773 "'prototype' property of %s is not an object.")
1774
1775 (js2-msg "msg.bad.radix"
1776 "illegal radix %s.")
1777
1778 ;; ScriptableObject
1779 (js2-msg "msg.default.value"
1780 "Cannot find default value for object.")
1781
1782 (js2-msg "msg.zero.arg.ctor"
1783 "Cannot load class '%s' which has no zero-parameter constructor.")
1784
1785 (js2-msg "msg.ctor.multiple.parms"
1786 "Can't define constructor or class %s since more than "
1787 "one constructor has multiple parameters.")
1788
1789 (js2-msg "msg.extend.scriptable"
1790 "%s must extend ScriptableObject in order to define property %s.")
1791
1792 (js2-msg "msg.bad.getter.parms"
1793 "In order to define a property, getter %s must have zero "
1794 "parameters or a single ScriptableObject parameter.")
1795
1796 (js2-msg "msg.obj.getter.parms"
1797 "Expected static or delegated getter %s to take "
1798 "a ScriptableObject parameter.")
1799
1800 (js2-msg "msg.getter.static"
1801 "Getter and setter must both be static or neither be static.")
1802
1803 (js2-msg "msg.setter.return"
1804 "Setter must have void return type: %s")
1805
1806 (js2-msg "msg.setter2.parms"
1807 "Two-parameter setter must take a ScriptableObject as "
1808 "its first parameter.")
1809
1810 (js2-msg "msg.setter1.parms"
1811 "Expected single parameter setter for %s")
1812
1813 (js2-msg "msg.setter2.expected"
1814 "Expected static or delegated setter %s to take two parameters.")
1815
1816 (js2-msg "msg.setter.parms"
1817 "Expected either one or two parameters for setter.")
1818
1819 (js2-msg "msg.setter.bad.type"
1820 "Unsupported parameter type '%s' in setter '%s'.")
1821
1822 (js2-msg "msg.add.sealed"
1823 "Cannot add a property to a sealed object: %s.")
1824
1825 (js2-msg "msg.remove.sealed"
1826 "Cannot remove a property from a sealed object: %s.")
1827
1828 (js2-msg "msg.modify.sealed"
1829 "Cannot modify a property of a sealed object: %s.")
1830
1831 (js2-msg "msg.modify.readonly"
1832 "Cannot modify readonly property: %s.")
1833
1834 ;; TokenStream
1835 (js2-msg "msg.missing.exponent"
1836 "missing exponent")
1837
1838 (js2-msg "msg.caught.nfe"
1839 "number format error")
1840
1841 (js2-msg "msg.unterminated.string.lit"
1842 "unterminated string literal")
1843
1844 (js2-msg "msg.unterminated.comment"
1845 "unterminated comment")
1846
1847 (js2-msg "msg.unterminated.re.lit"
1848 "unterminated regular expression literal")
1849
1850 (js2-msg "msg.invalid.re.flag"
1851 "invalid flag after regular expression")
1852
1853 (js2-msg "msg.no.re.input.for"
1854 "no input for %s")
1855
1856 (js2-msg "msg.illegal.character"
1857 "illegal character")
1858
1859 (js2-msg "msg.invalid.escape"
1860 "invalid Unicode escape sequence")
1861
1862 (js2-msg "msg.bad.namespace"
1863 "not a valid default namespace statement. "
1864 "Syntax is: default xml namespace = EXPRESSION;")
1865
1866 ;; TokensStream warnings
1867 (js2-msg "msg.bad.octal.literal"
1868 "illegal octal literal digit %s; "
1869 "interpreting it as a decimal digit")
1870
1871 (js2-msg "msg.reserved.keyword"
1872 "illegal usage of future reserved keyword %s; "
1873 "interpreting it as ordinary identifier")
1874
1875 (js2-msg "msg.script.is.not.constructor"
1876 "Script objects are not constructors.")
1877
1878 ;; Arrays
1879 (js2-msg "msg.arraylength.bad"
1880 "Inappropriate array length.")
1881
1882 ;; Arrays
1883 (js2-msg "msg.arraylength.too.big"
1884 "Array length %s exceeds supported capacity limit.")
1885
1886 ;; URI
1887 (js2-msg "msg.bad.uri"
1888 "Malformed URI sequence.")
1889
1890 ;; Number
1891 (js2-msg "msg.bad.precision"
1892 "Precision %s out of range.")
1893
1894 ;; NativeGenerator
1895 (js2-msg "msg.send.newborn"
1896 "Attempt to send value to newborn generator")
1897
1898 (js2-msg "msg.already.exec.gen"
1899 "Already executing generator")
1900
1901 (js2-msg "msg.StopIteration.invalid"
1902 "StopIteration may not be changed to an arbitrary object.")
1903
1904 ;; Interpreter
1905 (js2-msg "msg.yield.closing"
1906 "Yield from closing generator")
1907
1908 ;;; Utilities
1909
1910 (defun js2-delete-if (predicate list)
1911 "Remove all items satisfying PREDICATE in LIST."
1912 (loop for item in list
1913 if (not (funcall predicate item))
1914 collect item))
1915
1916 (defun js2-position (element list)
1917 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1918 Returns nil if element is not found in the list."
1919 (let ((count 0)
1920 found)
1921 (while (and list (not found))
1922 (if (eq element (car list))
1923 (setq found t)
1924 (setq count (1+ count)
1925 list (cdr list))))
1926 (if found count)))
1927
1928 (defun js2-find-if (predicate list)
1929 "Find first item satisfying PREDICATE in LIST."
1930 (let (result)
1931 (while (and list (not result))
1932 (if (funcall predicate (car list))
1933 (setq result (car list)))
1934 (setq list (cdr list)))
1935 result))
1936
1937 (defmacro js2-time (form)
1938 "Evaluate FORM, discard result, and return elapsed time in sec."
1939 (declare (debug t))
1940 (let ((beg (make-symbol "--js2-time-beg--"))
1941 (delta (make-symbol "--js2-time-end--")))
1942 `(let ((,beg (current-time))
1943 ,delta)
1944 ,form
1945 (/ (truncate (* (- (float-time (current-time))
1946 (float-time ,beg))
1947 10000))
1948 10000.0))))
1949
1950 (defsubst js2-same-line (pos)
1951 "Return t if POS is on the same line as current point."
1952 (and (>= pos (point-at-bol))
1953 (<= pos (point-at-eol))))
1954
1955 (defun js2-same-line-2 (p1 p2)
1956 "Return t if P1 is on the same line as P2."
1957 (save-excursion
1958 (goto-char p1)
1959 (js2-same-line p2)))
1960
1961 (defun js2-code-bug ()
1962 "Signal an error when we encounter an unexpected code path."
1963 (error "failed assertion"))
1964
1965 (defsubst js2-record-text-property (beg end prop value)
1966 "Record a text property to set when parsing finishes."
1967 (push (list beg end prop value) js2-mode-deferred-properties))
1968
1969 ;; I'd like to associate errors with nodes, but for now the
1970 ;; easiest thing to do is get the context info from the last token.
1971 (defun js2-record-parse-error (msg &optional arg pos len)
1972 (push (list (list msg arg)
1973 (or pos js2-token-beg)
1974 (or len (- js2-token-end js2-token-beg)))
1975 js2-parsed-errors))
1976
1977 (defun js2-report-error (msg &optional msg-arg pos len)
1978 "Signal a syntax error or record a parse error."
1979 (if js2-recover-from-parse-errors
1980 (js2-record-parse-error msg msg-arg pos len)
1981 (signal 'js2-syntax-error
1982 (list msg
1983 js2-ts-lineno
1984 (save-excursion
1985 (goto-char js2-ts-cursor)
1986 (current-column))
1987 js2-ts-hit-eof))))
1988
1989 (defun js2-report-warning (msg &optional msg-arg pos len face)
1990 (if js2-compiler-report-warning-as-error
1991 (js2-report-error msg msg-arg pos len)
1992 (push (list (list msg msg-arg)
1993 (or pos js2-token-beg)
1994 (or len (- js2-token-end js2-token-beg))
1995 face)
1996 js2-parsed-warnings)))
1997
1998 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
1999 (if js2-compiler-strict-mode
2000 (js2-report-warning msg-id msg-arg beg
2001 (and beg end (- end beg)))))
2002
2003 (put 'js2-syntax-error 'error-conditions
2004 '(error syntax-error js2-syntax-error))
2005 (put 'js2-syntax-error 'error-message "Syntax error")
2006
2007 (put 'js2-parse-error 'error-conditions
2008 '(error parse-error js2-parse-error))
2009 (put 'js2-parse-error 'error-message "Parse error")
2010
2011 (defmacro js2-clear-flag (flags flag)
2012 `(setq ,flags (logand ,flags (lognot ,flag))))
2013
2014 (defmacro js2-set-flag (flags flag)
2015 "Logical-or FLAG into FLAGS."
2016 `(setq ,flags (logior ,flags ,flag)))
2017
2018 (defsubst js2-flag-set-p (flags flag)
2019 (/= 0 (logand flags flag)))
2020
2021 (defsubst js2-flag-not-set-p (flags flag)
2022 (zerop (logand flags flag)))
2023
2024 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2025 "Evaluate BODY with the _ character set to be word-syntax."
2026 (declare (indent 0) (debug t))
2027 (let ((old-syntax (make-symbol "old-syntax")))
2028 `(let ((,old-syntax (string (char-syntax ?_))))
2029 (unwind-protect
2030 (progn
2031 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2032 ,@body)
2033 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2034
2035 (defsubst js2-char-uppercase-p (c)
2036 "Return t if C is an uppercase character.
2037 Handles unicode and latin chars properly."
2038 (/= c (downcase c)))
2039
2040 (defsubst js2-char-lowercase-p (c)
2041 "Return t if C is an uppercase character.
2042 Handles unicode and latin chars properly."
2043 (/= c (upcase c)))
2044
2045 ;;; AST struct and function definitions
2046
2047 ;; flags for ast node property 'member-type (used for e4x operators)
2048 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2049 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2050 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2051
2052 (defsubst js2-relpos (pos anchor)
2053 "Convert POS to be relative to ANCHOR.
2054 If POS is nil, returns nil."
2055 (and pos (- pos anchor)))
2056
2057 (defun js2-make-pad (indent)
2058 (if (zerop indent)
2059 ""
2060 (make-string (* indent js2-basic-offset) ? )))
2061
2062 (defun js2-visit-ast (node callback)
2063 "Visit every node in ast NODE with visitor CALLBACK.
2064
2065 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2066 called twice: once to visit the node, and again after all the node's
2067 children have been processed. The END-P argument is nil on the first
2068 call and non-nil on the second call. The return value of the callback
2069 affects the traversal: if non-nil, the children of NODE are processed.
2070 If the callback returns nil, or if the node has no children, then the
2071 callback is called immediately with a non-nil END-P argument.
2072
2073 The node traversal is approximately lexical-order, although there
2074 are currently no guarantees around this."
2075 (when node
2076 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2077 ;; visit the node
2078 (when (funcall callback node nil)
2079 ;; visit the kids
2080 (cond
2081 ((eq vfunc 'js2-visit-none)
2082 nil) ; don't even bother calling it
2083 ;; Each AST node type has to define a `js2-visitor' function
2084 ;; that takes a node and a callback, and calls `js2-visit-ast'
2085 ;; on each child of the node.
2086 (vfunc
2087 (funcall vfunc node callback))
2088 (t
2089 (error "%s does not define a visitor-traversal function"
2090 (aref node 0)))))
2091 ;; call the end-visit
2092 (funcall callback node t))))
2093
2094 (defstruct (js2-node
2095 (:constructor nil)) ; abstract
2096 "Base AST node type."
2097 (type -1) ; token type
2098 (pos -1) ; start position of this AST node in parsed input
2099 (len 1) ; num characters spanned by the node
2100 props ; optional node property list (an alist)
2101 parent) ; link to parent node; null for root
2102
2103 (defsubst js2-node-get-prop (node prop &optional default)
2104 (or (cadr (assoc prop (js2-node-props node))) default))
2105
2106 (defsubst js2-node-set-prop (node prop value)
2107 (setf (js2-node-props node)
2108 (cons (list prop value) (js2-node-props node))))
2109
2110 (defun js2-fixup-starts (n nodes)
2111 "Adjust the start positions of NODES to be relative to N.
2112 Any node in the list may be nil, for convenience."
2113 (dolist (node nodes)
2114 (when node
2115 (setf (js2-node-pos node) (- (js2-node-pos node)
2116 (js2-node-pos n))))))
2117
2118 (defun js2-node-add-children (parent &rest nodes)
2119 "Set parent node of NODES to PARENT, and return PARENT.
2120 Does nothing if we're not recording parent links.
2121 If any given node in NODES is nil, doesn't record that link."
2122 (js2-fixup-starts parent nodes)
2123 (dolist (node nodes)
2124 (and node
2125 (setf (js2-node-parent node) parent))))
2126
2127 ;; Non-recursive since it's called a frightening number of times.
2128 (defun js2-node-abs-pos (n)
2129 (let ((pos (js2-node-pos n)))
2130 (while (setq n (js2-node-parent n))
2131 (setq pos (+ pos (js2-node-pos n))))
2132 pos))
2133
2134 (defsubst js2-node-abs-end (n)
2135 "Return absolute buffer position of end of N."
2136 (+ (js2-node-abs-pos n) (js2-node-len n)))
2137
2138 ;; It's important to make sure block nodes have a Lisp list for the
2139 ;; child nodes, to limit printing recursion depth in an AST that
2140 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2141 ;; a sufficiently large vector tree.
2142
2143 (defstruct (js2-block-node
2144 (:include js2-node)
2145 (:constructor nil)
2146 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2147 (pos js2-token-beg)
2148 len
2149 props
2150 kids)))
2151 "A block of statements."
2152 kids) ; a Lisp list of the child statement nodes
2153
2154 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2155 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2156
2157 (defun js2-visit-block (ast callback)
2158 "Visit the `js2-block-node' children of AST."
2159 (dolist (kid (js2-block-node-kids ast))
2160 (js2-visit-ast kid callback)))
2161
2162 (defun js2-print-block (n i)
2163 (let ((pad (js2-make-pad i)))
2164 (insert pad "{\n")
2165 (dolist (kid (js2-block-node-kids n))
2166 (js2-print-ast kid (1+ i)))
2167 (insert pad "}")))
2168
2169 (defstruct (js2-scope
2170 (:include js2-block-node)
2171 (:constructor nil)
2172 (:constructor make-js2-scope (&key (type js2-BLOCK)
2173 (pos js2-token-beg)
2174 len
2175 kids)))
2176 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2177 ;; I don't have one of those handy, so I'll use an alist for now.
2178 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2179 ;; and is much lighter-weight to construct (both CPU and mem).
2180 ;; The keys are interned strings (symbols) for faster lookup.
2181 ;; Should switch to hybrid alist/hashtable eventually.
2182 symbol-table ; an alist of (symbol . js2-symbol)
2183 parent-scope ; a `js2-scope'
2184 top) ; top-level `js2-scope' (script/function)
2185
2186 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2187 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2188
2189 (defun js2-scope-set-parent-scope (scope parent)
2190 (setf (js2-scope-parent-scope scope) parent
2191 (js2-scope-top scope) (if (null parent)
2192 scope
2193 (js2-scope-top parent))))
2194
2195 (defun js2-node-get-enclosing-scope (node)
2196 "Return the innermost `js2-scope' node surrounding NODE.
2197 Returns nil if there is no enclosing scope node."
2198 (let ((parent (js2-node-parent node)))
2199 (while (not (js2-scope-p parent))
2200 (setq parent (js2-node-parent parent)))
2201 parent))
2202
2203 (defun js2-get-defining-scope (scope name)
2204 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2205 Returns `js2-scope' in which NAME is defined, or nil if not found."
2206 (let ((sym (if (symbolp name)
2207 name
2208 (intern name)))
2209 table
2210 result
2211 (continue t))
2212 (while (and scope continue)
2213 (if (and (setq table (js2-scope-symbol-table scope))
2214 (assq sym table))
2215 (setq continue nil
2216 result scope)
2217 (setq scope (js2-scope-parent-scope scope))))
2218 result))
2219
2220 (defun js2-scope-get-symbol (scope name)
2221 "Return symbol table entry for NAME in SCOPE.
2222 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2223 (and (js2-scope-symbol-table scope)
2224 (cdr (assq (if (symbolp name)
2225 name
2226 (intern name))
2227 (js2-scope-symbol-table scope)))))
2228
2229 (defun js2-scope-put-symbol (scope name symbol)
2230 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2231 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2232 (let* ((table (js2-scope-symbol-table scope))
2233 (sym (if (symbolp name) name (intern name)))
2234 (entry (assq sym table)))
2235 (if entry
2236 (setcdr entry symbol)
2237 (push (cons sym symbol)
2238 (js2-scope-symbol-table scope)))))
2239
2240 (defstruct (js2-symbol
2241 (:constructor nil)
2242 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2243 "A symbol table entry."
2244 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2245 ;; js2-LET, or js2-CONST
2246 decl-type
2247 name ; string
2248 ast-node) ; a `js2-node'
2249
2250 (defstruct (js2-error-node
2251 (:include js2-node)
2252 (:constructor nil) ; silence emacs21 byte-compiler
2253 (:constructor make-js2-error-node (&key (type js2-ERROR)
2254 (pos js2-token-beg)
2255 len)))
2256 "AST node representing a parse error.")
2257
2258 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2259 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2260
2261 (defstruct (js2-script-node
2262 (:include js2-scope)
2263 (:constructor nil)
2264 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2265 (pos js2-token-beg)
2266 len
2267 var-decls
2268 fun-decls)))
2269 functions ; Lisp list of nested functions
2270 regexps ; Lisp list of (string . flags)
2271 symbols ; alist (every symbol gets unique index)
2272 (param-count 0)
2273 var-names ; vector of string names
2274 consts ; bool-vector matching var-decls
2275 (temp-number 0)) ; for generating temp variables
2276
2277 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2278 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2279
2280 (defun js2-print-script (node indent)
2281 (dolist (kid (js2-block-node-kids node))
2282 (js2-print-ast kid indent)))
2283
2284 (defstruct (js2-ast-root
2285 (:include js2-script-node)
2286 (:constructor nil)
2287 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2288 (pos js2-token-beg)
2289 len
2290 buffer)))
2291 "The root node of a js2 AST."
2292 buffer ; the source buffer from which the code was parsed
2293 comments ; a Lisp list of comments, ordered by start position
2294 errors ; a Lisp list of errors found during parsing
2295 warnings ; a Lisp list of warnings found during parsing
2296 node-count) ; number of nodes in the tree, including the root
2297
2298 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2299 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2300
2301 (defun js2-visit-ast-root (ast callback)
2302 (dolist (kid (js2-ast-root-kids ast))
2303 (js2-visit-ast kid callback))
2304 (dolist (comment (js2-ast-root-comments ast))
2305 (js2-visit-ast comment callback)))
2306
2307 (defstruct (js2-comment-node
2308 (:include js2-node)
2309 (:constructor nil)
2310 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2311 (pos js2-token-beg)
2312 len
2313 (format js2-ts-comment-type))))
2314 format) ; 'line, 'block, 'jsdoc or 'html
2315
2316 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2317 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2318
2319 (defun js2-print-comment (n i)
2320 ;; We really ought to link end-of-line comments to their nodes.
2321 ;; Or maybe we could add a new comment type, 'endline.
2322 (insert (js2-make-pad i)
2323 (js2-node-string n)))
2324
2325 (defstruct (js2-expr-stmt-node
2326 (:include js2-node)
2327 (:constructor nil)
2328 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2329 (pos js2-ts-cursor)
2330 len
2331 expr)))
2332 "An expression statement."
2333 expr)
2334
2335 (defsubst js2-expr-stmt-node-set-has-result (node)
2336 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2337 (setf (js2-node-type node) js2-EXPR_RESULT))
2338
2339 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2340 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2341
2342 (defun js2-visit-expr-stmt-node (n v)
2343 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2344
2345 (defun js2-print-expr-stmt-node (n indent)
2346 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2347 (insert ";\n"))
2348
2349 (defstruct (js2-loop-node
2350 (:include js2-scope)
2351 (:constructor nil))
2352 "Abstract supertype of loop nodes."
2353 body ; a `js2-block-node'
2354 lp ; position of left-paren, nil if omitted
2355 rp) ; position of right-paren, nil if omitted
2356
2357 (defstruct (js2-do-node
2358 (:include js2-loop-node)
2359 (:constructor nil)
2360 (:constructor make-js2-do-node (&key (type js2-DO)
2361 (pos js2-token-beg)
2362 len
2363 body
2364 condition
2365 while-pos
2366 lp
2367 rp)))
2368 "AST node for do-loop."
2369 condition ; while (expression)
2370 while-pos) ; buffer position of 'while' keyword
2371
2372 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2373 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2374
2375 (defun js2-visit-do-node (n v)
2376 (js2-visit-ast (js2-do-node-body n) v)
2377 (js2-visit-ast (js2-do-node-condition n) v))
2378
2379 (defun js2-print-do-node (n i)
2380 (let ((pad (js2-make-pad i)))
2381 (insert pad "do {\n")
2382 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2383 (js2-print-ast kid (1+ i)))
2384 (insert pad "} while (")
2385 (js2-print-ast (js2-do-node-condition n) 0)
2386 (insert ");\n")))
2387
2388 (defstruct (js2-while-node
2389 (:include js2-loop-node)
2390 (:constructor nil)
2391 (:constructor make-js2-while-node (&key (type js2-WHILE)
2392 (pos js2-token-beg)
2393 len body
2394 condition lp
2395 rp)))
2396 "AST node for while-loop."
2397 condition) ; while-condition
2398
2399 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2400 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2401
2402 (defun js2-visit-while-node (n v)
2403 (js2-visit-ast (js2-while-node-condition n) v)
2404 (js2-visit-ast (js2-while-node-body n) v))
2405
2406 (defun js2-print-while-node (n i)
2407 (let ((pad (js2-make-pad i)))
2408 (insert pad "while (")
2409 (js2-print-ast (js2-while-node-condition n) 0)
2410 (insert ") {\n")
2411 (js2-print-body (js2-while-node-body n) (1+ i))
2412 (insert pad "}\n")))
2413
2414 (defstruct (js2-for-node
2415 (:include js2-loop-node)
2416 (:constructor nil)
2417 (:constructor make-js2-for-node (&key (type js2-FOR)
2418 (pos js2-ts-cursor)
2419 len body init
2420 condition
2421 update lp rp)))
2422 "AST node for a C-style for-loop."
2423 init ; initialization expression
2424 condition ; loop condition
2425 update) ; update clause
2426
2427 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2428 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2429
2430 (defun js2-visit-for-node (n v)
2431 (js2-visit-ast (js2-for-node-init n) v)
2432 (js2-visit-ast (js2-for-node-condition n) v)
2433 (js2-visit-ast (js2-for-node-update n) v)
2434 (js2-visit-ast (js2-for-node-body n) v))
2435
2436 (defun js2-print-for-node (n i)
2437 (let ((pad (js2-make-pad i)))
2438 (insert pad "for (")
2439 (js2-print-ast (js2-for-node-init n) 0)
2440 (insert "; ")
2441 (js2-print-ast (js2-for-node-condition n) 0)
2442 (insert "; ")
2443 (js2-print-ast (js2-for-node-update n) 0)
2444 (insert ") {\n")
2445 (js2-print-body (js2-for-node-body n) (1+ i))
2446 (insert pad "}\n")))
2447
2448 (defstruct (js2-for-in-node
2449 (:include js2-loop-node)
2450 (:constructor nil)
2451 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2452 (pos js2-ts-cursor)
2453 len body
2454 iterator
2455 object
2456 in-pos
2457 each-pos
2458 foreach-p forof-p
2459 lp rp)))
2460 "AST node for a for..in loop."
2461 iterator ; [var] foo in ...
2462 object ; object over which we're iterating
2463 in-pos ; buffer position of 'in' keyword
2464 each-pos ; buffer position of 'each' keyword, if foreach-p
2465 foreach-p ; t if it's a for-each loop
2466 forof-p) ; t if it's a for-of loop
2467
2468 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2469 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2470
2471 (defun js2-visit-for-in-node (n v)
2472 (js2-visit-ast (js2-for-in-node-iterator n) v)
2473 (js2-visit-ast (js2-for-in-node-object n) v)
2474 (js2-visit-ast (js2-for-in-node-body n) v))
2475
2476 (defun js2-print-for-in-node (n i)
2477 (let ((pad (js2-make-pad i))
2478 (foreach (js2-for-in-node-foreach-p n))
2479 (forof (js2-for-in-node-forof-p n)))
2480 (insert pad "for ")
2481 (if foreach
2482 (insert "each "))
2483 (insert "(")
2484 (js2-print-ast (js2-for-in-node-iterator n) 0)
2485 (if forof
2486 (insert " of ")
2487 (insert " in "))
2488 (js2-print-ast (js2-for-in-node-object n) 0)
2489 (insert ") {\n")
2490 (js2-print-body (js2-for-in-node-body n) (1+ i))
2491 (insert pad "}\n")))
2492
2493 (defstruct (js2-return-node
2494 (:include js2-node)
2495 (:constructor nil)
2496 (:constructor make-js2-return-node (&key (type js2-RETURN)
2497 (pos js2-ts-cursor)
2498 len
2499 retval)))
2500 "AST node for a return statement."
2501 retval) ; expression to return, or 'undefined
2502
2503 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2504 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2505
2506 (defun js2-visit-return-node (n v)
2507 (js2-visit-ast (js2-return-node-retval n) v))
2508
2509 (defun js2-print-return-node (n i)
2510 (insert (js2-make-pad i) "return")
2511 (when (js2-return-node-retval n)
2512 (insert " ")
2513 (js2-print-ast (js2-return-node-retval n) 0))
2514 (insert ";\n"))
2515
2516 (defstruct (js2-if-node
2517 (:include js2-node)
2518 (:constructor nil)
2519 (:constructor make-js2-if-node (&key (type js2-IF)
2520 (pos js2-ts-cursor)
2521 len condition
2522 then-part
2523 else-pos
2524 else-part lp
2525 rp)))
2526 "AST node for an if-statement."
2527 condition ; expression
2528 then-part ; statement or block
2529 else-pos ; optional buffer position of 'else' keyword
2530 else-part ; optional statement or block
2531 lp ; position of left-paren, nil if omitted
2532 rp) ; position of right-paren, nil if omitted
2533
2534 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2535 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2536
2537 (defun js2-visit-if-node (n v)
2538 (js2-visit-ast (js2-if-node-condition n) v)
2539 (js2-visit-ast (js2-if-node-then-part n) v)
2540 (js2-visit-ast (js2-if-node-else-part n) v))
2541
2542 (defun js2-print-if-node (n i)
2543 (let ((pad (js2-make-pad i))
2544 (then-part (js2-if-node-then-part n))
2545 (else-part (js2-if-node-else-part n)))
2546 (insert pad "if (")
2547 (js2-print-ast (js2-if-node-condition n) 0)
2548 (insert ") {\n")
2549 (js2-print-body then-part (1+ i))
2550 (insert pad "}")
2551 (cond
2552 ((not else-part)
2553 (insert "\n"))
2554 ((js2-if-node-p else-part)
2555 (insert " else ")
2556 (js2-print-body else-part i))
2557 (t
2558 (insert " else {\n")
2559 (js2-print-body else-part (1+ i))
2560 (insert pad "}\n")))))
2561
2562 (defstruct (js2-try-node
2563 (:include js2-node)
2564 (:constructor nil)
2565 (:constructor make-js2-try-node (&key (type js2-TRY)
2566 (pos js2-ts-cursor)
2567 len
2568 try-block
2569 catch-clauses
2570 finally-block)))
2571 "AST node for a try-statement."
2572 try-block
2573 catch-clauses ; a Lisp list of `js2-catch-node'
2574 finally-block) ; a `js2-finally-node'
2575
2576 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2577 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2578
2579 (defun js2-visit-try-node (n v)
2580 (js2-visit-ast (js2-try-node-try-block n) v)
2581 (dolist (clause (js2-try-node-catch-clauses n))
2582 (js2-visit-ast clause v))
2583 (js2-visit-ast (js2-try-node-finally-block n) v))
2584
2585 (defun js2-print-try-node (n i)
2586 (let ((pad (js2-make-pad i))
2587 (catches (js2-try-node-catch-clauses n))
2588 (finally (js2-try-node-finally-block n)))
2589 (insert pad "try {\n")
2590 (js2-print-body (js2-try-node-try-block n) (1+ i))
2591 (insert pad "}")
2592 (when catches
2593 (dolist (catch catches)
2594 (js2-print-ast catch i)))
2595 (if finally
2596 (js2-print-ast finally i)
2597 (insert "\n"))))
2598
2599 (defstruct (js2-catch-node
2600 (:include js2-node)
2601 (:constructor nil)
2602 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2603 (pos js2-ts-cursor)
2604 len
2605 param
2606 guard-kwd
2607 guard-expr
2608 block lp
2609 rp)))
2610 "AST node for a catch clause."
2611 param ; destructuring form or simple name node
2612 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2613 guard-expr ; catch condition, a `js2-node'
2614 block ; statements, a `js2-block-node'
2615 lp ; buffer position of left-paren, nil if omitted
2616 rp) ; buffer position of right-paren, nil if omitted
2617
2618 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2619 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2620
2621 (defun js2-visit-catch-node (n v)
2622 (js2-visit-ast (js2-catch-node-param n) v)
2623 (when (js2-catch-node-guard-kwd n)
2624 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2625 (js2-visit-ast (js2-catch-node-block n) v))
2626
2627 (defun js2-print-catch-node (n i)
2628 (let ((pad (js2-make-pad i))
2629 (guard-kwd (js2-catch-node-guard-kwd n))
2630 (guard-expr (js2-catch-node-guard-expr n)))
2631 (insert " catch (")
2632 (js2-print-ast (js2-catch-node-param n) 0)
2633 (when guard-kwd
2634 (insert " if ")
2635 (js2-print-ast guard-expr 0))
2636 (insert ") {\n")
2637 (js2-print-body (js2-catch-node-block n) (1+ i))
2638 (insert pad "}")))
2639
2640 (defstruct (js2-finally-node
2641 (:include js2-node)
2642 (:constructor nil)
2643 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2644 (pos js2-ts-cursor)
2645 len body)))
2646 "AST node for a finally clause."
2647 body) ; a `js2-node', often but not always a block node
2648
2649 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2650 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2651
2652 (defun js2-visit-finally-node (n v)
2653 (js2-visit-ast (js2-finally-node-body n) v))
2654
2655 (defun js2-print-finally-node (n i)
2656 (let ((pad (js2-make-pad i)))
2657 (insert " finally {\n")
2658 (js2-print-body (js2-finally-node-body n) (1+ i))
2659 (insert pad "}\n")))
2660
2661 (defstruct (js2-switch-node
2662 (:include js2-node)
2663 (:constructor nil)
2664 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2665 (pos js2-ts-cursor)
2666 len
2667 discriminant
2668 cases lp
2669 rp)))
2670 "AST node for a switch statement."
2671 discriminant ; a `js2-node' (switch expression)
2672 cases ; a Lisp list of `js2-case-node'
2673 lp ; position of open-paren for discriminant, nil if omitted
2674 rp) ; position of close-paren for discriminant, nil if omitted
2675
2676 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2677 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2678
2679 (defun js2-visit-switch-node (n v)
2680 (js2-visit-ast (js2-switch-node-discriminant n) v)
2681 (dolist (c (js2-switch-node-cases n))
2682 (js2-visit-ast c v)))
2683
2684 (defun js2-print-switch-node (n i)
2685 (let ((pad (js2-make-pad i))
2686 (cases (js2-switch-node-cases n)))
2687 (insert pad "switch (")
2688 (js2-print-ast (js2-switch-node-discriminant n) 0)
2689 (insert ") {\n")
2690 (dolist (case cases)
2691 (js2-print-ast case i))
2692 (insert pad "}\n")))
2693
2694 (defstruct (js2-case-node
2695 (:include js2-block-node)
2696 (:constructor nil)
2697 (:constructor make-js2-case-node (&key (type js2-CASE)
2698 (pos js2-ts-cursor)
2699 len kids expr)))
2700 "AST node for a case clause of a switch statement."
2701 expr) ; the case expression (nil for default)
2702
2703 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2704 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2705
2706 (defun js2-visit-case-node (n v)
2707 (js2-visit-ast (js2-case-node-expr n) v)
2708 (js2-visit-block n v))
2709
2710 (defun js2-print-case-node (n i)
2711 (let ((pad (js2-make-pad i))
2712 (expr (js2-case-node-expr n)))
2713 (insert pad)
2714 (if (null expr)
2715 (insert "default:\n")
2716 (insert "case ")
2717 (js2-print-ast expr 0)
2718 (insert ":\n"))
2719 (dolist (kid (js2-case-node-kids n))
2720 (js2-print-ast kid (1+ i)))))
2721
2722 (defstruct (js2-throw-node
2723 (:include js2-node)
2724 (:constructor nil)
2725 (:constructor make-js2-throw-node (&key (type js2-THROW)
2726 (pos js2-ts-cursor)
2727 len expr)))
2728 "AST node for a throw statement."
2729 expr) ; the expression to throw
2730
2731 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2732 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2733
2734 (defun js2-visit-throw-node (n v)
2735 (js2-visit-ast (js2-throw-node-expr n) v))
2736
2737 (defun js2-print-throw-node (n i)
2738 (insert (js2-make-pad i) "throw ")
2739 (js2-print-ast (js2-throw-node-expr n) 0)
2740 (insert ";\n"))
2741
2742 (defstruct (js2-with-node
2743 (:include js2-node)
2744 (:constructor nil)
2745 (:constructor make-js2-with-node (&key (type js2-WITH)
2746 (pos js2-ts-cursor)
2747 len object
2748 body lp rp)))
2749 "AST node for a with-statement."
2750 object
2751 body
2752 lp ; buffer position of left-paren around object, nil if omitted
2753 rp) ; buffer position of right-paren around object, nil if omitted
2754
2755 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2756 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2757
2758 (defun js2-visit-with-node (n v)
2759 (js2-visit-ast (js2-with-node-object n) v)
2760 (js2-visit-ast (js2-with-node-body n) v))
2761
2762 (defun js2-print-with-node (n i)
2763 (let ((pad (js2-make-pad i)))
2764 (insert pad "with (")
2765 (js2-print-ast (js2-with-node-object n) 0)
2766 (insert ") {\n")
2767 (js2-print-body (js2-with-node-body n) (1+ i))
2768 (insert pad "}\n")))
2769
2770 (defstruct (js2-label-node
2771 (:include js2-node)
2772 (:constructor nil)
2773 (:constructor make-js2-label-node (&key (type js2-LABEL)
2774 (pos js2-ts-cursor)
2775 len name)))
2776 "AST node for a statement label or case label."
2777 name ; a string
2778 loop) ; for validating and code-generating continue-to-label
2779
2780 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2781 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2782
2783 (defun js2-print-label (n i)
2784 (insert (js2-make-pad i)
2785 (js2-label-node-name n)
2786 ":\n"))
2787
2788 (defstruct (js2-labeled-stmt-node
2789 (:include js2-node)
2790 (:constructor nil)
2791 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2792 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2793 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2794 (pos js2-ts-cursor)
2795 len labels stmt)))
2796 "AST node for a statement with one or more labels.
2797 Multiple labels for a statement are collapsed into the labels field."
2798 labels ; Lisp list of `js2-label-node'
2799 stmt) ; the statement these labels are for
2800
2801 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2802 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2803
2804 (defun js2-get-label-by-name (lbl-stmt name)
2805 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2806 Returns nil if no such label is in the list."
2807 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2808 result)
2809 (while (and label-list (not result))
2810 (if (string= (js2-label-node-name (car label-list)) name)
2811 (setq result (car label-list))
2812 (setq label-list (cdr label-list))))
2813 result))
2814
2815 (defun js2-visit-labeled-stmt (n v)
2816 (dolist (label (js2-labeled-stmt-node-labels n))
2817 (js2-visit-ast label v))
2818 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2819
2820 (defun js2-print-labeled-stmt (n i)
2821 (dolist (label (js2-labeled-stmt-node-labels n))
2822 (js2-print-ast label i))
2823 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2824
2825 (defun js2-labeled-stmt-node-contains (node label)
2826 "Return t if NODE contains LABEL in its label set.
2827 NODE is a `js2-labels-node'. LABEL is an identifier."
2828 (loop for nl in (js2-labeled-stmt-node-labels node)
2829 if (string= label (js2-label-node-name nl))
2830 return t
2831 finally return nil))
2832
2833 (defsubst js2-labeled-stmt-node-add-label (node label)
2834 "Add a `js2-label-node' to the label set for this statement."
2835 (setf (js2-labeled-stmt-node-labels node)
2836 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2837
2838 (defstruct (js2-jump-node
2839 (:include js2-node)
2840 (:constructor nil))
2841 "Abstract supertype of break and continue nodes."
2842 label ; `js2-name-node' for location of label identifier, if present
2843 target) ; target js2-labels-node or loop/switch statement
2844
2845 (defun js2-visit-jump-node (n v)
2846 ;; We don't visit the target, since it's a back-link.
2847 (js2-visit-ast (js2-jump-node-label n) v))
2848
2849 (defstruct (js2-break-node
2850 (:include js2-jump-node)
2851 (:constructor nil)
2852 (:constructor make-js2-break-node (&key (type js2-BREAK)
2853 (pos js2-ts-cursor)
2854 len label target)))
2855 "AST node for a break statement.
2856 The label field is a `js2-name-node', possibly nil, for the named label
2857 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2858 is the target of the break - a label node or enclosing loop/switch statement.")
2859
2860 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2861 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2862
2863 (defun js2-print-break-node (n i)
2864 (insert (js2-make-pad i) "break")
2865 (when (js2-break-node-label n)
2866 (insert " ")
2867 (js2-print-ast (js2-break-node-label n) 0))
2868 (insert ";\n"))
2869
2870 (defstruct (js2-continue-node
2871 (:include js2-jump-node)
2872 (:constructor nil)
2873 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2874 (pos js2-ts-cursor)
2875 len label target)))
2876 "AST node for a continue statement.
2877 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2878 It is nil if continue specifies no label. The target field is the jump target:
2879 a `js2-label-node' or the innermost enclosing loop.")
2880
2881 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2882 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2883
2884 (defun js2-print-continue-node (n i)
2885 (insert (js2-make-pad i) "continue")
2886 (when (js2-continue-node-label n)
2887 (insert " ")
2888 (js2-print-ast (js2-continue-node-label n) 0))
2889 (insert ";\n"))
2890
2891 (defstruct (js2-function-node
2892 (:include js2-script-node)
2893 (:constructor nil)
2894 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2895 (pos js2-ts-cursor)
2896 len
2897 (ftype 'FUNCTION)
2898 (form 'FUNCTION_STATEMENT)
2899 (name "")
2900 params rest-p
2901 body
2902 lp rp)))
2903 "AST node for a function declaration.
2904 The `params' field is a Lisp list of nodes. Each node is either a simple
2905 `js2-name-node', or if it's a destructuring-assignment parameter, a
2906 `js2-array-node' or `js2-object-node'."
2907 ftype ; FUNCTION, GETTER or SETTER
2908 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2909 name ; function name (a `js2-name-node', or nil if anonymous)
2910 params ; a Lisp list of destructuring forms or simple name nodes
2911 rest-p ; if t, the last parameter is rest parameter
2912 body ; a `js2-block-node' or expression node (1.8 only)
2913 lp ; position of arg-list open-paren, or nil if omitted
2914 rp ; position of arg-list close-paren, or nil if omitted
2915 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2916 needs-activation ; t if we need an activation object for this frame
2917 is-generator ; t if this function contains a yield
2918 member-expr) ; nonstandard Ecma extension from Rhino
2919
2920 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2921 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2922
2923 (defun js2-visit-function-node (n v)
2924 (js2-visit-ast (js2-function-node-name n) v)
2925 (dolist (p (js2-function-node-params n))
2926 (js2-visit-ast p v))
2927 (js2-visit-ast (js2-function-node-body n) v))
2928
2929 (defun js2-print-function-node (n i)
2930 (let ((pad (js2-make-pad i))
2931 (getter (js2-node-get-prop n 'GETTER_SETTER))
2932 (name (js2-function-node-name n))
2933 (params (js2-function-node-params n))
2934 (rest-p (js2-function-node-rest-p n))
2935 (body (js2-function-node-body n))
2936 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2937 (unless getter
2938 (insert pad "function"))
2939 (when name
2940 (insert " ")
2941 (js2-print-ast name 0))
2942 (insert "(")
2943 (loop with len = (length params)
2944 for param in params
2945 for count from 1
2946 do
2947 (when (and rest-p (= count len))
2948 (insert "..."))
2949 (js2-print-ast param 0)
2950 (when (< count len)
2951 (insert ", ")))
2952 (insert ") {")
2953 (unless expr
2954 (insert "\n"))
2955 ;; TODO: fix this to be smarter about indenting, etc.
2956 (js2-print-body body (1+ i))
2957 (insert pad "}")
2958 (unless expr
2959 (insert "\n"))))
2960
2961 (defun js2-function-name (node)
2962 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2963 (and (js2-function-node-name node)
2964 (js2-name-node-name (js2-function-node-name node))))
2965
2966 ;; Having this be an expression node makes it more flexible.
2967 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2968 ;; that work better if you assume it's an expression. Whenever we have
2969 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2970 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2971 (defstruct (js2-var-decl-node
2972 (:include js2-node)
2973 (:constructor nil)
2974 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2975 (pos js2-token-beg)
2976 len kids
2977 decl-type)))
2978 "AST node for a variable declaration list (VAR, CONST or LET).
2979 The node bounds differ depending on the declaration type. For VAR or
2980 CONST declarations, the bounds include the var/const keyword. For LET
2981 declarations, the node begins at the position of the first child."
2982 kids ; a Lisp list of `js2-var-init-node' structs.
2983 decl-type) ; js2-VAR, js2-CONST or js2-LET
2984
2985 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
2986 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
2987
2988 (defun js2-visit-var-decl (n v)
2989 (dolist (kid (js2-var-decl-node-kids n))
2990 (js2-visit-ast kid v)))
2991
2992 (defun js2-print-var-decl (n i)
2993 (let ((pad (js2-make-pad i))
2994 (tt (js2-var-decl-node-decl-type n)))
2995 (insert pad)
2996 (insert (cond
2997 ((= tt js2-VAR) "var ")
2998 ((= tt js2-LET) "let ")
2999 ((= tt js2-CONST) "const ")
3000 (t
3001 (error "malformed var-decl node"))))
3002 (loop with kids = (js2-var-decl-node-kids n)
3003 with len = (length kids)
3004 for kid in kids
3005 for count from 1
3006 do
3007 (js2-print-ast kid 0)
3008 (if (< count len)
3009 (insert ", ")))))
3010
3011 (defstruct (js2-var-init-node
3012 (:include js2-node)
3013 (:constructor nil)
3014 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3015 (pos js2-ts-cursor)
3016 len target
3017 initializer)))
3018 "AST node for a variable declaration.
3019 The type field will be js2-CONST for a const decl."
3020 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3021 initializer) ; initializer expression, a `js2-node'
3022
3023 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3024 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3025
3026 (defun js2-visit-var-init-node (n v)
3027 (js2-visit-ast (js2-var-init-node-target n) v)
3028 (js2-visit-ast (js2-var-init-node-initializer n) v))
3029
3030 (defun js2-print-var-init-node (n i)
3031 (let ((pad (js2-make-pad i))
3032 (name (js2-var-init-node-target n))
3033 (init (js2-var-init-node-initializer n)))
3034 (insert pad)
3035 (js2-print-ast name 0)
3036 (when init
3037 (insert " = ")
3038 (js2-print-ast init 0))))
3039
3040 (defstruct (js2-cond-node
3041 (:include js2-node)
3042 (:constructor nil)
3043 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3044 (pos js2-ts-cursor)
3045 len
3046 test-expr
3047 true-expr
3048 false-expr
3049 q-pos c-pos)))
3050 "AST node for the ternary operator"
3051 test-expr
3052 true-expr
3053 false-expr
3054 q-pos ; buffer position of ?
3055 c-pos) ; buffer position of :
3056
3057 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3058 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3059
3060 (defun js2-visit-cond-node (n v)
3061 (js2-visit-ast (js2-cond-node-test-expr n) v)
3062 (js2-visit-ast (js2-cond-node-true-expr n) v)
3063 (js2-visit-ast (js2-cond-node-false-expr n) v))
3064
3065 (defun js2-print-cond-node (n i)
3066 (let ((pad (js2-make-pad i)))
3067 (insert pad)
3068 (js2-print-ast (js2-cond-node-test-expr n) 0)
3069 (insert " ? ")
3070 (js2-print-ast (js2-cond-node-true-expr n) 0)
3071 (insert " : ")
3072 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3073
3074 (defstruct (js2-infix-node
3075 (:include js2-node)
3076 (:constructor nil)
3077 (:constructor make-js2-infix-node (&key type
3078 (pos js2-ts-cursor)
3079 len op-pos
3080 left right)))
3081 "Represents infix expressions.
3082 Includes assignment ops like `|=', and the comma operator.
3083 The type field inherited from `js2-node' holds the operator."
3084 op-pos ; buffer position where operator begins
3085 left ; any `js2-node'
3086 right) ; any `js2-node'
3087
3088 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3089 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3090
3091 (defun js2-visit-infix-node (n v)
3092 (js2-visit-ast (js2-infix-node-left n) v)
3093 (js2-visit-ast (js2-infix-node-right n) v))
3094
3095 (defconst js2-operator-tokens
3096 (let ((table (make-hash-table :test 'eq))
3097 (tokens
3098 (list (cons js2-IN "in")
3099 (cons js2-TYPEOF "typeof")
3100 (cons js2-INSTANCEOF "instanceof")
3101 (cons js2-DELPROP "delete")
3102 (cons js2-COMMA ",")
3103 (cons js2-COLON ":")
3104 (cons js2-OR "||")
3105 (cons js2-AND "&&")
3106 (cons js2-INC "++")
3107 (cons js2-DEC "--")
3108 (cons js2-BITOR "|")
3109 (cons js2-BITXOR "^")
3110 (cons js2-BITAND "&")
3111 (cons js2-EQ "==")
3112 (cons js2-NE "!=")
3113 (cons js2-LT "<")
3114 (cons js2-LE "<=")
3115 (cons js2-GT ">")
3116 (cons js2-GE ">=")
3117 (cons js2-LSH "<<")
3118 (cons js2-RSH ">>")
3119 (cons js2-URSH ">>>")
3120 (cons js2-ADD "+") ; infix plus
3121 (cons js2-SUB "-") ; infix minus
3122 (cons js2-MUL "*")
3123 (cons js2-DIV "/")
3124 (cons js2-MOD "%")
3125 (cons js2-NOT "!")
3126 (cons js2-BITNOT "~")
3127 (cons js2-POS "+") ; unary plus
3128 (cons js2-NEG "-") ; unary minus
3129 (cons js2-SHEQ "===") ; shallow equality
3130 (cons js2-SHNE "!==") ; shallow inequality
3131 (cons js2-ASSIGN "=")
3132 (cons js2-ASSIGN_BITOR "|=")
3133 (cons js2-ASSIGN_BITXOR "^=")
3134 (cons js2-ASSIGN_BITAND "&=")
3135 (cons js2-ASSIGN_LSH "<<=")
3136 (cons js2-ASSIGN_RSH ">>=")
3137 (cons js2-ASSIGN_URSH ">>>=")
3138 (cons js2-ASSIGN_ADD "+=")
3139 (cons js2-ASSIGN_SUB "-=")
3140 (cons js2-ASSIGN_MUL "*=")
3141 (cons js2-ASSIGN_DIV "/=")
3142 (cons js2-ASSIGN_MOD "%="))))
3143 (loop for (k . v) in tokens do
3144 (puthash k v table))
3145 table))
3146
3147 (defun js2-print-infix-node (n i)
3148 (let* ((tt (js2-node-type n))
3149 (op (gethash tt js2-operator-tokens)))
3150 (unless op
3151 (error "unrecognized infix operator %s" (js2-node-type n)))
3152 (insert (js2-make-pad i))
3153 (js2-print-ast (js2-infix-node-left n) 0)
3154 (unless (= tt js2-COMMA)
3155 (insert " "))
3156 (insert op)
3157 (insert " ")
3158 (js2-print-ast (js2-infix-node-right n) 0)))
3159
3160 (defstruct (js2-assign-node
3161 (:include js2-infix-node)
3162 (:constructor nil)
3163 (:constructor make-js2-assign-node (&key type
3164 (pos js2-ts-cursor)
3165 len op-pos
3166 left right)))
3167 "Represents any assignment.
3168 The type field holds the actual assignment operator.")
3169
3170 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3171 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3172
3173 (defstruct (js2-unary-node
3174 (:include js2-node)
3175 (:constructor nil)
3176 (:constructor make-js2-unary-node (&key type ; required
3177 (pos js2-ts-cursor)
3178 len operand)))
3179 "AST node type for unary operator nodes.
3180 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3181 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3182 property is added if the operator follows the operand."
3183 operand) ; a `js2-node' expression
3184
3185 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3186 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3187
3188 (defun js2-visit-unary-node (n v)
3189 (js2-visit-ast (js2-unary-node-operand n) v))
3190
3191 (defun js2-print-unary-node (n i)
3192 (let* ((tt (js2-node-type n))
3193 (op (gethash tt js2-operator-tokens))
3194 (postfix (js2-node-get-prop n 'postfix)))
3195 (unless op
3196 (error "unrecognized unary operator %s" tt))
3197 (insert (js2-make-pad i))
3198 (unless postfix
3199 (insert op))
3200 (if (or (= tt js2-TYPEOF)
3201 (= tt js2-DELPROP))
3202 (insert " "))
3203 (js2-print-ast (js2-unary-node-operand n) 0)
3204 (when postfix
3205 (insert op))))
3206
3207 (defstruct (js2-let-node
3208 (:include js2-scope)
3209 (:constructor nil)
3210 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3211 (pos js2-token-beg)
3212 len vars body
3213 lp rp)))
3214 "AST node for a let expression or a let statement.
3215 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3216 vars ; a `js2-var-decl-node'
3217 body ; a `js2-node' representing the expression or body block
3218 lp
3219 rp)
3220
3221 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3222 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3223
3224 (defun js2-visit-let-node (n v)
3225 (js2-visit-ast (js2-let-node-vars n) v)
3226 (js2-visit-ast (js2-let-node-body n) v))
3227
3228 (defun js2-print-let-node (n i)
3229 (insert (js2-make-pad i) "let (")
3230 (js2-print-ast (js2-let-node-vars n) 0)
3231 (insert ") ")
3232 (js2-print-ast (js2-let-node-body n) i))
3233
3234 (defstruct (js2-keyword-node
3235 (:include js2-node)
3236 (:constructor nil)
3237 (:constructor make-js2-keyword-node (&key type
3238 (pos js2-token-beg)
3239 (len (- js2-ts-cursor pos)))))
3240 "AST node representing a literal keyword such as `null'.
3241 Used for `null', `this', `true', `false' and `debugger'.
3242 The node type is set to js2-NULL, js2-THIS, etc.")
3243
3244 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3245 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3246
3247 (defun js2-print-keyword-node (n i)
3248 (insert (js2-make-pad i)
3249 (let ((tt (js2-node-type n)))
3250 (cond
3251 ((= tt js2-THIS) "this")
3252 ((= tt js2-NULL) "null")
3253 ((= tt js2-TRUE) "true")
3254 ((= tt js2-FALSE) "false")
3255 ((= tt js2-DEBUGGER) "debugger")
3256 (t (error "Invalid keyword literal type: %d" tt))))))
3257
3258 (defsubst js2-this-node-p (node)
3259 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3260 (eq (js2-node-type node) js2-THIS))
3261
3262 (defstruct (js2-new-node
3263 (:include js2-node)
3264 (:constructor nil)
3265 (:constructor make-js2-new-node (&key (type js2-NEW)
3266 (pos js2-token-beg)
3267 len target
3268 args initializer
3269 lp rp)))
3270 "AST node for new-expression such as new Foo()."
3271 target ; an identifier or reference
3272 args ; a Lisp list of argument nodes
3273 lp ; position of left-paren, nil if omitted
3274 rp ; position of right-paren, nil if omitted
3275 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3276
3277 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3278 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3279
3280 (defun js2-visit-new-node (n v)
3281 (js2-visit-ast (js2-new-node-target n) v)
3282 (dolist (arg (js2-new-node-args n))
3283 (js2-visit-ast arg v))
3284 (js2-visit-ast (js2-new-node-initializer n) v))
3285
3286 (defun js2-print-new-node (n i)
3287 (insert (js2-make-pad i) "new ")
3288 (js2-print-ast (js2-new-node-target n))
3289 (insert "(")
3290 (js2-print-list (js2-new-node-args n))
3291 (insert ")")
3292 (when (js2-new-node-initializer n)
3293 (insert " ")
3294 (js2-print-ast (js2-new-node-initializer n))))
3295
3296 (defstruct (js2-name-node
3297 (:include js2-node)
3298 (:constructor nil)
3299 (:constructor make-js2-name-node (&key (type js2-NAME)
3300 (pos js2-token-beg)
3301 (len (- js2-ts-cursor
3302 js2-token-beg))
3303 (name js2-ts-string))))
3304 "AST node for a JavaScript identifier"
3305 name ; a string
3306 scope) ; a `js2-scope' (optional, used for codegen)
3307
3308 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3309 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3310
3311 (defun js2-print-name-node (n i)
3312 (insert (js2-make-pad i)
3313 (js2-name-node-name n)))
3314
3315 (defsubst js2-name-node-length (node)
3316 "Return identifier length of NODE, a `js2-name-node'.
3317 Returns 0 if NODE is nil or its identifier field is nil."
3318 (if node
3319 (length (js2-name-node-name node))
3320 0))
3321
3322 (defstruct (js2-number-node
3323 (:include js2-node)
3324 (:constructor nil)
3325 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3326 (pos js2-token-beg)
3327 (len (- js2-ts-cursor
3328 js2-token-beg))
3329 (value js2-ts-string)
3330 (num-value js2-ts-number))))
3331 "AST node for a number literal."
3332 value ; the original string, e.g. "6.02e23"
3333 num-value) ; the parsed number value
3334
3335 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3336 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3337
3338 (defun js2-print-number-node (n i)
3339 (insert (js2-make-pad i)
3340 (number-to-string (js2-number-node-num-value n))))
3341
3342 (defstruct (js2-regexp-node
3343 (:include js2-node)
3344 (:constructor nil)
3345 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3346 (pos js2-token-beg)
3347 (len (- js2-ts-cursor
3348 js2-token-beg))
3349 value flags)))
3350 "AST node for a regular expression literal."
3351 value ; the regexp string, without // delimiters
3352 flags) ; a string of flags, e.g. `mi'.
3353
3354 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3355 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3356
3357 (defun js2-print-regexp (n i)
3358 (insert (js2-make-pad i)
3359 "/"
3360 (js2-regexp-node-value n)
3361 "/")
3362 (if (js2-regexp-node-flags n)
3363 (insert (js2-regexp-node-flags n))))
3364
3365 (defstruct (js2-string-node
3366 (:include js2-node)
3367 (:constructor nil)
3368 (:constructor make-js2-string-node (&key (type js2-STRING)
3369 (pos js2-token-beg)
3370 (len (- js2-ts-cursor
3371 js2-token-beg))
3372 (value js2-ts-string))))
3373 "String literal.
3374 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3375 You can tell the quote type by looking at the first character."
3376 value) ; the characters of the string, including the quotes
3377
3378 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3379 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3380
3381 (defun js2-print-string-node (n i)
3382 (insert (js2-make-pad i)
3383 (js2-node-string n)))
3384
3385 (defstruct (js2-array-node
3386 (:include js2-node)
3387 (:constructor nil)
3388 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3389 (pos js2-ts-cursor)
3390 len elems)))
3391 "AST node for an array literal."
3392 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3393
3394 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3395 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3396
3397 (defun js2-visit-array-node (n v)
3398 (dolist (e (js2-array-node-elems n))
3399 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3400
3401 (defun js2-print-array-node (n i)
3402 (insert (js2-make-pad i) "[")
3403 (js2-print-list (js2-array-node-elems n))
3404 (insert "]"))
3405
3406 (defstruct (js2-object-node
3407 (:include js2-node)
3408 (:constructor nil)
3409 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3410 (pos js2-ts-cursor)
3411 len
3412 elems)))
3413 "AST node for an object literal expression.
3414 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3415 The latter represents abbreviation in destructuring expressions."
3416 elems)
3417
3418 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3419 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3420
3421 (defun js2-visit-object-node (n v)
3422 (dolist (e (js2-object-node-elems n))
3423 (js2-visit-ast e v)))
3424
3425 (defun js2-print-object-node (n i)
3426 (insert (js2-make-pad i) "{")
3427 (js2-print-list (js2-object-node-elems n))
3428 (insert "}"))
3429
3430 (defstruct (js2-object-prop-node
3431 (:include js2-infix-node)
3432 (:constructor nil)
3433 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3434 (pos js2-ts-cursor)
3435 len left
3436 right op-pos)))
3437 "AST node for an object literal prop:value entry.
3438 The `left' field is the property: a name node, string node or number node.
3439 The `right' field is a `js2-node' representing the initializer value.")
3440
3441 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3442 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3443
3444 (defun js2-print-object-prop-node (n i)
3445 (insert (js2-make-pad i))
3446 (js2-print-ast (js2-object-prop-node-left n) 0)
3447 (insert ": ")
3448 (js2-print-ast (js2-object-prop-node-right n) 0))
3449
3450 (defstruct (js2-getter-setter-node
3451 (:include js2-infix-node)
3452 (:constructor nil)
3453 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3454 (pos js2-ts-cursor)
3455 len left right)))
3456 "AST node for a getter/setter property in an object literal.
3457 The `left' field is the `js2-name-node' naming the getter/setter prop.
3458 The `right' field is always an anonymous `js2-function-node' with a node
3459 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3460
3461 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3462 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3463
3464 (defun js2-print-getter-setter (n i)
3465 (let ((pad (js2-make-pad i))
3466 (left (js2-getter-setter-node-left n))
3467 (right (js2-getter-setter-node-right n)))
3468 (insert pad)
3469 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3470 (js2-print-ast left 0)
3471 (js2-print-ast right 0)))
3472
3473 (defstruct (js2-prop-get-node
3474 (:include js2-infix-node)
3475 (:constructor nil)
3476 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3477 (pos js2-ts-cursor)
3478 len left right)))
3479 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3480
3481 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3482 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3483
3484 (defun js2-visit-prop-get-node (n v)
3485 (js2-visit-ast (js2-prop-get-node-left n) v)
3486 (js2-visit-ast (js2-prop-get-node-right n) v))
3487
3488 (defun js2-print-prop-get-node (n i)
3489 (insert (js2-make-pad i))
3490 (js2-print-ast (js2-prop-get-node-left n) 0)
3491 (insert ".")
3492 (js2-print-ast (js2-prop-get-node-right n) 0))
3493
3494 (defstruct (js2-elem-get-node
3495 (:include js2-node)
3496 (:constructor nil)
3497 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3498 (pos js2-ts-cursor)
3499 len target element
3500 lb rb)))
3501 "AST node for an array index expression such as foo[bar]."
3502 target ; a `js2-node' - the expression preceding the "."
3503 element ; a `js2-node' - the expression in brackets
3504 lb ; position of left-bracket, nil if omitted
3505 rb) ; position of right-bracket, nil if omitted
3506
3507 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3508 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3509
3510 (defun js2-visit-elem-get-node (n v)
3511 (js2-visit-ast (js2-elem-get-node-target n) v)
3512 (js2-visit-ast (js2-elem-get-node-element n) v))
3513
3514 (defun js2-print-elem-get-node (n i)
3515 (insert (js2-make-pad i))
3516 (js2-print-ast (js2-elem-get-node-target n) 0)
3517 (insert "[")
3518 (js2-print-ast (js2-elem-get-node-element n) 0)
3519 (insert "]"))
3520
3521 (defstruct (js2-call-node
3522 (:include js2-node)
3523 (:constructor nil)
3524 (:constructor make-js2-call-node (&key (type js2-CALL)
3525 (pos js2-ts-cursor)
3526 len target args
3527 lp rp)))
3528 "AST node for a JavaScript function call."
3529 target ; a `js2-node' evaluating to the function to call
3530 args ; a Lisp list of `js2-node' arguments
3531 lp ; position of open-paren, or nil if missing
3532 rp) ; position of close-paren, or nil if missing
3533
3534 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3535 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3536
3537 (defun js2-visit-call-node (n v)
3538 (js2-visit-ast (js2-call-node-target n) v)
3539 (dolist (arg (js2-call-node-args n))
3540 (js2-visit-ast arg v)))
3541
3542 (defun js2-print-call-node (n i)
3543 (insert (js2-make-pad i))
3544 (js2-print-ast (js2-call-node-target n) 0)
3545 (insert "(")
3546 (js2-print-list (js2-call-node-args n))
3547 (insert ")"))
3548
3549 (defstruct (js2-yield-node
3550 (:include js2-node)
3551 (:constructor nil)
3552 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3553 (pos js2-ts-cursor)
3554 len value)))
3555 "AST node for yield statement or expression."
3556 value) ; optional: value to be yielded
3557
3558 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3559 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3560
3561 (defun js2-visit-yield-node (n v)
3562 (js2-visit-ast (js2-yield-node-value n) v))
3563
3564 (defun js2-print-yield-node (n i)
3565 (insert (js2-make-pad i))
3566 (insert "yield")
3567 (when (js2-yield-node-value n)
3568 (insert " ")
3569 (js2-print-ast (js2-yield-node-value n) 0)))
3570
3571 (defstruct (js2-paren-node
3572 (:include js2-node)
3573 (:constructor nil)
3574 (:constructor make-js2-paren-node (&key (type js2-LP)
3575 (pos js2-ts-cursor)
3576 len expr)))
3577 "AST node for a parenthesized expression.
3578 In particular, used when the parens are syntactically optional,
3579 as opposed to required parens such as those enclosing an if-conditional."
3580 expr) ; `js2-node'
3581
3582 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3583 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3584
3585 (defun js2-visit-paren-node (n v)
3586 (js2-visit-ast (js2-paren-node-expr n) v))
3587
3588 (defun js2-print-paren-node (n i)
3589 (insert (js2-make-pad i))
3590 (insert "(")
3591 (js2-print-ast (js2-paren-node-expr n) 0)
3592 (insert ")"))
3593
3594 (defstruct (js2-array-comp-node
3595 (:include js2-scope)
3596 (:constructor nil)
3597 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3598 (pos js2-ts-cursor)
3599 len result
3600 loops filter
3601 if-pos lp rp)))
3602 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3603 result ; result expression (just after left-bracket)
3604 loops ; a Lisp list of `js2-array-comp-loop-node'
3605 filter ; guard/filter expression
3606 if-pos ; buffer pos of 'if' keyword, if present, else nil
3607 lp ; buffer position of if-guard left-paren, or nil if not present
3608 rp) ; buffer position of if-guard right-paren, or nil if not present
3609
3610 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3611 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3612
3613 (defun js2-visit-array-comp-node (n v)
3614 (js2-visit-ast (js2-array-comp-node-result n) v)
3615 (dolist (l (js2-array-comp-node-loops n))
3616 (js2-visit-ast l v))
3617 (js2-visit-ast (js2-array-comp-node-filter n) v))
3618
3619 (defun js2-print-array-comp-node (n i)
3620 (let ((pad (js2-make-pad i))
3621 (result (js2-array-comp-node-result n))
3622 (loops (js2-array-comp-node-loops n))
3623 (filter (js2-array-comp-node-filter n)))
3624 (insert pad "[")
3625 (js2-print-ast result 0)
3626 (dolist (l loops)
3627 (insert " ")
3628 (js2-print-ast l 0))
3629 (when filter
3630 (insert " if (")
3631 (js2-print-ast filter 0)
3632 (insert ")"))
3633 (insert "]")))
3634
3635 (defstruct (js2-array-comp-loop-node
3636 (:include js2-for-in-node)
3637 (:constructor nil)
3638 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3639 (pos js2-ts-cursor)
3640 len iterator
3641 object in-pos
3642 foreach-p
3643 each-pos
3644 forof-p
3645 lp rp)))
3646 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3647
3648 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3649 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3650
3651 (defun js2-visit-array-comp-loop (n v)
3652 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3653 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3654
3655 (defun js2-print-array-comp-loop (n i)
3656 (insert "for ")
3657 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3658 (insert "(")
3659 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3660 (if (js2-array-comp-loop-node-forof-p n)
3661 (insert " of ")
3662 (insert " in "))
3663 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3664 (insert ")"))
3665
3666 (defstruct (js2-empty-expr-node
3667 (:include js2-node)
3668 (:constructor nil)
3669 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3670 (pos js2-token-beg)
3671 len)))
3672 "AST node for an empty expression.")
3673
3674 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3675 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3676
3677 (defstruct (js2-xml-node
3678 (:include js2-block-node)
3679 (:constructor nil)
3680 (:constructor make-js2-xml-node (&key (type js2-XML)
3681 (pos js2-token-beg)
3682 len kids)))
3683 "AST node for initial parse of E4X literals.
3684 The kids field is a list of XML fragments, each a `js2-string-node' or
3685 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3686
3687 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3688 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3689
3690 (defun js2-print-xml-node (n i)
3691 (dolist (kid (js2-xml-node-kids n))
3692 (js2-print-ast kid i)))
3693
3694 (defstruct (js2-xml-js-expr-node
3695 (:include js2-xml-node)
3696 (:constructor nil)
3697 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3698 (pos js2-ts-cursor)
3699 len expr)))
3700 "AST node for an embedded JavaScript {expression} in an E4X literal.
3701 The start and end fields correspond to the curly-braces."
3702 expr) ; a `js2-expr-node' of some sort
3703
3704 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3705 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3706
3707 (defun js2-visit-xml-js-expr (n v)
3708 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3709
3710 (defun js2-print-xml-js-expr (n i)
3711 (insert (js2-make-pad i))
3712 (insert "{")
3713 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3714 (insert "}"))
3715
3716 (defstruct (js2-xml-dot-query-node
3717 (:include js2-infix-node)
3718 (:constructor nil)
3719 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3720 (pos js2-ts-cursor)
3721 op-pos len left
3722 right rp)))
3723 "AST node for an E4X foo.(bar) filter expression.
3724 Note that the left-paren is automatically the character immediately
3725 following the dot (.) in the operator. No whitespace is permitted
3726 between the dot and the lp by the scanner."
3727 rp)
3728
3729 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3730 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3731
3732 (defun js2-print-xml-dot-query (n i)
3733 (insert (js2-make-pad i))
3734 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3735 (insert ".(")
3736 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3737 (insert ")"))
3738
3739 (defstruct (js2-xml-ref-node
3740 (:include js2-node)
3741 (:constructor nil)) ; abstract
3742 "Base type for E4X XML attribute-access or property-get expressions.
3743 Such expressions can take a variety of forms. The general syntax has
3744 three parts:
3745
3746 - (optional) an @ (specifying an attribute access)
3747 - (optional) a namespace (a `js2-name-node') and double-colon
3748 - (required) either a `js2-name-node' or a bracketed [expression]
3749
3750 The property-name expressions (examples: ns::name, @name) are
3751 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3752 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3753
3754 This node type (or more specifically, its subclasses) will sometimes
3755 be the right-hand child of a `js2-prop-get-node' or a
3756 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3757 The `js2-xml-ref-node' may also be a standalone primary expression with
3758 no explicit target, which is valid in certain expression contexts such as
3759
3760 company..employee.(@id < 100)
3761
3762 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3763 expression whose parent is a `js2-xml-dot-query-node'."
3764 namespace
3765 at-pos
3766 colon-pos)
3767
3768 (defsubst js2-xml-ref-node-attr-access-p (node)
3769 "Return non-nil if this expression began with an @-token."
3770 (and (numberp (js2-xml-ref-node-at-pos node))
3771 (plusp (js2-xml-ref-node-at-pos node))))
3772
3773 (defstruct (js2-xml-prop-ref-node
3774 (:include js2-xml-ref-node)
3775 (:constructor nil)
3776 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3777 (pos js2-token-beg)
3778 len propname
3779 namespace at-pos
3780 colon-pos)))
3781 "AST node for an E4X XML [expr] property-ref expression.
3782 The JavaScript syntax is an optional @, an optional ns::, and a name.
3783
3784 [ '@' ] [ name '::' ] name
3785
3786 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3787 @ns::*, @*::attr, @*::*, and @*.
3788
3789 The node starts at the @ token, if present. Otherwise it starts at the
3790 namespace name. The node bounds extend through the closing right-bracket,
3791 or if it is missing due to a syntax error, through the end of the index
3792 expression."
3793 propname)
3794
3795 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3796 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3797
3798 (defun js2-visit-xml-prop-ref-node (n v)
3799 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3800 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3801
3802 (defun js2-print-xml-prop-ref-node (n i)
3803 (insert (js2-make-pad i))
3804 (if (js2-xml-ref-node-attr-access-p n)
3805 (insert "@"))
3806 (when (js2-xml-prop-ref-node-namespace n)
3807 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3808 (insert "::"))
3809 (if (js2-xml-prop-ref-node-propname n)
3810 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3811
3812 (defstruct (js2-xml-elem-ref-node
3813 (:include js2-xml-ref-node)
3814 (:constructor nil)
3815 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3816 (pos js2-token-beg)
3817 len expr lb rb
3818 namespace at-pos
3819 colon-pos)))
3820 "AST node for an E4X XML [expr] member-ref expression.
3821 Syntax:
3822
3823 [ '@' ] [ name '::' ] '[' expr ']'
3824
3825 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3826
3827 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3828 is not a legal E4X XML element-ref expression, since it's already used
3829 for standard JavaScript element-get array indexing. Hence, a
3830 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3831 non-nil namespace node, or both.
3832
3833 The node starts at the @ token, if present. Otherwise it starts
3834 at the namespace name. The node bounds extend through the closing
3835 right-bracket, or if it is missing due to a syntax error, through the
3836 end of the index expression."
3837 expr ; the bracketed index expression
3838 lb
3839 rb)
3840
3841 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3842 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3843
3844 (defun js2-visit-xml-elem-ref-node (n v)
3845 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3846 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3847
3848 (defun js2-print-xml-elem-ref-node (n i)
3849 (insert (js2-make-pad i))
3850 (if (js2-xml-ref-node-attr-access-p n)
3851 (insert "@"))
3852 (when (js2-xml-elem-ref-node-namespace n)
3853 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3854 (insert "::"))
3855 (insert "[")
3856 (if (js2-xml-elem-ref-node-expr n)
3857 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3858 (insert "]"))
3859
3860 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3861
3862 (defstruct (js2-xml-start-tag-node
3863 (:include js2-xml-node)
3864 (:constructor nil)
3865 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3866 (pos js2-ts-cursor)
3867 len name attrs kids
3868 empty-p)))
3869 "AST node for an XML start-tag. Not currently used.
3870 The `kids' field is a Lisp list of child content nodes."
3871 name ; a `js2-xml-name-node'
3872 attrs ; a Lisp list of `js2-xml-attr-node'
3873 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3874
3875 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3876 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3877
3878 (defun js2-visit-xml-start-tag (n v)
3879 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3880 (dolist (attr (js2-xml-start-tag-node-attrs n))
3881 (js2-visit-ast attr v))
3882 (js2-visit-block n v))
3883
3884 (defun js2-print-xml-start-tag (n i)
3885 (insert (js2-make-pad i) "<")
3886 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3887 (when (js2-xml-start-tag-node-attrs n)
3888 (insert " ")
3889 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3890 (insert ">"))
3891
3892 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3893 ;; and add the end-tag to the kids list of the parent as well.
3894 (defstruct (js2-xml-end-tag-node
3895 (:include js2-xml-node)
3896 (:constructor nil)
3897 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3898 (pos js2-ts-cursor)
3899 len name)))
3900 "AST node for an XML end-tag. Not currently used."
3901 name) ; a `js2-xml-name-node'
3902
3903 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3904 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3905
3906 (defun js2-visit-xml-end-tag (n v)
3907 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3908
3909 (defun js2-print-xml-end-tag (n i)
3910 (insert (js2-make-pad i))
3911 (insert "</")
3912 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3913 (insert ">"))
3914
3915 (defstruct (js2-xml-name-node
3916 (:include js2-xml-node)
3917 (:constructor nil)
3918 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3919 (pos js2-ts-cursor)
3920 len namespace kids)))
3921 "AST node for an E4X XML name. Not currently used.
3922 Any XML name can be qualified with a namespace, hence the namespace field.
3923 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3924 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3925 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3926 namespace) ; a `js2-string-node'
3927
3928 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3929 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3930
3931 (defun js2-visit-xml-name-node (n v)
3932 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3933
3934 (defun js2-print-xml-name-node (n i)
3935 (insert (js2-make-pad i))
3936 (when (js2-xml-name-node-namespace n)
3937 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3938 (insert "::"))
3939 (dolist (kid (js2-xml-name-node-kids n))
3940 (js2-print-ast kid 0)))
3941
3942 (defstruct (js2-xml-pi-node
3943 (:include js2-xml-node)
3944 (:constructor nil)
3945 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3946 (pos js2-ts-cursor)
3947 len name attrs)))
3948 "AST node for an E4X XML processing instruction. Not currently used."
3949 name ; a `js2-xml-name-node'
3950 attrs) ; a list of `js2-xml-attr-node'
3951
3952 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3953 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3954
3955 (defun js2-visit-xml-pi-node (n v)
3956 (js2-visit-ast (js2-xml-pi-node-name n) v)
3957 (dolist (attr (js2-xml-pi-node-attrs n))
3958 (js2-visit-ast attr v)))
3959
3960 (defun js2-print-xml-pi-node (n i)
3961 (insert (js2-make-pad i) "<?")
3962 (js2-print-ast (js2-xml-pi-node-name n))
3963 (when (js2-xml-pi-node-attrs n)
3964 (insert " ")
3965 (js2-print-list (js2-xml-pi-node-attrs n)))
3966 (insert "?>"))
3967
3968 (defstruct (js2-xml-cdata-node
3969 (:include js2-xml-node)
3970 (:constructor nil)
3971 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3972 (pos js2-ts-cursor)
3973 len content)))
3974 "AST node for a CDATA escape section. Not currently used."
3975 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3976
3977 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3978 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3979
3980 (defun js2-visit-xml-cdata-node (n v)
3981 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3982
3983 (defun js2-print-xml-cdata-node (n i)
3984 (insert (js2-make-pad i))
3985 (js2-print-ast (js2-xml-cdata-node-content n)))
3986
3987 (defstruct (js2-xml-attr-node
3988 (:include js2-xml-node)
3989 (:constructor nil)
3990 (:constructor make-js2-attr-node (&key (type js2-XML)
3991 (pos js2-ts-cursor)
3992 len name value
3993 eq-pos quote-type)))
3994 "AST node representing a foo='bar' XML attribute value. Not yet used."
3995 name ; a `js2-xml-name-node'
3996 value ; a `js2-xml-name-node'
3997 eq-pos ; buffer position of "=" sign
3998 quote-type) ; 'single or 'double
3999
4000 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4001 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4002
4003 (defun js2-visit-xml-attr-node (n v)
4004 (js2-visit-ast (js2-xml-attr-node-name n) v)
4005 (js2-visit-ast (js2-xml-attr-node-value n) v))
4006
4007 (defun js2-print-xml-attr-node (n i)
4008 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4009 "'"
4010 "\"")))
4011 (insert (js2-make-pad i))
4012 (js2-print-ast (js2-xml-attr-node-name n) 0)
4013 (insert "=" quote)
4014 (js2-print-ast (js2-xml-attr-node-value n) 0)
4015 (insert quote)))
4016
4017 (defstruct (js2-xml-text-node
4018 (:include js2-xml-node)
4019 (:constructor nil)
4020 (:constructor make-js2-text-node (&key (type js2-XML)
4021 (pos js2-ts-cursor)
4022 len content)))
4023 "AST node for an E4X XML text node. Not currently used."
4024 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4025
4026 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4027 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4028
4029 (defun js2-visit-xml-text-node (n v)
4030 (js2-visit-ast (js2-xml-text-node-content n) v))
4031
4032 (defun js2-print-xml-text-node (n i)
4033 (insert (js2-make-pad i))
4034 (dolist (kid (js2-xml-text-node-content n))
4035 (js2-print-ast kid)))
4036
4037 (defstruct (js2-xml-comment-node
4038 (:include js2-xml-node)
4039 (:constructor nil)
4040 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4041 (pos js2-ts-cursor)
4042 len)))
4043 "AST node for E4X XML comment. Not currently used.")
4044
4045 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4046 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4047
4048 (defun js2-print-xml-comment (n i)
4049 (insert (js2-make-pad i)
4050 (js2-node-string n)))
4051
4052 ;;; Node utilities
4053
4054 (defsubst js2-node-line (n)
4055 "Fetch the source line number at the start of node N.
4056 This is O(n) in the length of the source buffer; use prudently."
4057 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4058
4059 (defsubst js2-block-node-kid (n i)
4060 "Return child I of node N, or nil if there aren't that many."
4061 (nth i (js2-block-node-kids n)))
4062
4063 (defsubst js2-block-node-first (n)
4064 "Return first child of block node N, or nil if there is none."
4065 (first (js2-block-node-kids n)))
4066
4067 (defun js2-node-root (n)
4068 "Return the root of the AST containing N.
4069 If N has no parent pointer, returns N."
4070 (let ((parent (js2-node-parent n)))
4071 (if parent
4072 (js2-node-root parent)
4073 n)))
4074
4075 (defun js2-node-position-in-parent (node &optional parent)
4076 "Return the position of NODE in parent's block-kids list.
4077 PARENT can be supplied if known. Positioned returned is zero-indexed.
4078 Returns 0 if NODE is not a child of a block statement, or if NODE
4079 is not a statement node."
4080 (let ((p (or parent (js2-node-parent node)))
4081 (i 0))
4082 (if (not (js2-block-node-p p))
4083 i
4084 (or (js2-position node (js2-block-node-kids p))
4085 0))))
4086
4087 (defsubst js2-node-short-name (n)
4088 "Return the short name of node N as a string, e.g. `js2-if-node'."
4089 (substring (symbol-name (aref n 0))
4090 (length "cl-struct-")))
4091
4092 (defun js2-node-child-list (node)
4093 "Return the child list for NODE, a Lisp list of nodes.
4094 Works for block nodes, array nodes, obj literals, funarg lists,
4095 var decls and try nodes (for catch clauses). Note that you should call
4096 `js2-block-node-kids' on the function body for the body statements.
4097 Returns nil for zero-length child lists or unsupported nodes."
4098 (cond
4099 ((js2-function-node-p node)
4100 (js2-function-node-params node))
4101 ((js2-block-node-p node)
4102 (js2-block-node-kids node))
4103 ((js2-try-node-p node)
4104 (js2-try-node-catch-clauses node))
4105 ((js2-array-node-p node)
4106 (js2-array-node-elems node))
4107 ((js2-object-node-p node)
4108 (js2-object-node-elems node))
4109 ((js2-call-node-p node)
4110 (js2-call-node-args node))
4111 ((js2-new-node-p node)
4112 (js2-new-node-args node))
4113 ((js2-var-decl-node-p node)
4114 (js2-var-decl-node-kids node))
4115 (t
4116 nil)))
4117
4118 (defun js2-node-set-child-list (node kids)
4119 "Set the child list for NODE to KIDS."
4120 (cond
4121 ((js2-function-node-p node)
4122 (setf (js2-function-node-params node) kids))
4123 ((js2-block-node-p node)
4124 (setf (js2-block-node-kids node) kids))
4125 ((js2-try-node-p node)
4126 (setf (js2-try-node-catch-clauses node) kids))
4127 ((js2-array-node-p node)
4128 (setf (js2-array-node-elems node) kids))
4129 ((js2-object-node-p node)
4130 (setf (js2-object-node-elems node) kids))
4131 ((js2-call-node-p node)
4132 (setf (js2-call-node-args node) kids))
4133 ((js2-new-node-p node)
4134 (setf (js2-new-node-args node) kids))
4135 ((js2-var-decl-node-p node)
4136 (setf (js2-var-decl-node-kids node) kids))
4137 (t
4138 (error "Unsupported node type: %s" (js2-node-short-name node))))
4139 kids)
4140
4141 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4142 (defconst js2-paren-expr-nodes
4143 '(cl-struct-js2-array-comp-loop-node
4144 cl-struct-js2-array-comp-node
4145 cl-struct-js2-call-node
4146 cl-struct-js2-catch-node
4147 cl-struct-js2-do-node
4148 cl-struct-js2-elem-get-node
4149 cl-struct-js2-for-in-node
4150 cl-struct-js2-for-node
4151 cl-struct-js2-function-node
4152 cl-struct-js2-if-node
4153 cl-struct-js2-let-node
4154 cl-struct-js2-new-node
4155 cl-struct-js2-paren-node
4156 cl-struct-js2-switch-node
4157 cl-struct-js2-while-node
4158 cl-struct-js2-with-node
4159 cl-struct-js2-xml-dot-query-node)
4160 "Node types that can have a parenthesized child expression.
4161 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4162
4163 (defsubst js2-paren-expr-node-p (node)
4164 "Return t for nodes that typically have a parenthesized child expression.
4165 Useful for computing the indentation anchors for arg-lists and conditions.
4166 Note that it may return a false positive, for instance when NODE is
4167 a `js2-new-node' and there are no arguments or parentheses."
4168 (memq (aref node 0) js2-paren-expr-nodes))
4169
4170 ;; Fake polymorphism... yech.
4171 (defun js2-node-lp (node)
4172 "Return relative left-paren position for NODE, if applicable.
4173 For `js2-elem-get-node' structs, returns left-bracket position.
4174 Note that the position may be nil in the case of a parse error."
4175 (cond
4176 ((js2-elem-get-node-p node)
4177 (js2-elem-get-node-lb node))
4178 ((js2-loop-node-p node)
4179 (js2-loop-node-lp node))
4180 ((js2-function-node-p node)
4181 (js2-function-node-lp node))
4182 ((js2-if-node-p node)
4183 (js2-if-node-lp node))
4184 ((js2-new-node-p node)
4185 (js2-new-node-lp node))
4186 ((js2-call-node-p node)
4187 (js2-call-node-lp node))
4188 ((js2-paren-node-p node)
4189 (js2-node-pos node))
4190 ((js2-switch-node-p node)
4191 (js2-switch-node-lp node))
4192 ((js2-catch-node-p node)
4193 (js2-catch-node-lp node))
4194 ((js2-let-node-p node)
4195 (js2-let-node-lp node))
4196 ((js2-array-comp-node-p node)
4197 (js2-array-comp-node-lp node))
4198 ((js2-with-node-p node)
4199 (js2-with-node-lp node))
4200 ((js2-xml-dot-query-node-p node)
4201 (1+ (js2-infix-node-op-pos node)))
4202 (t
4203 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4204
4205 ;; Fake polymorphism... blech.
4206 (defun js2-node-rp (node)
4207 "Return relative right-paren position for NODE, if applicable.
4208 For `js2-elem-get-node' structs, returns right-bracket position.
4209 Note that the position may be nil in the case of a parse error."
4210 (cond
4211 ((js2-elem-get-node-p node)
4212 (js2-elem-get-node-rb node))
4213 ((js2-loop-node-p node)
4214 (js2-loop-node-rp node))
4215 ((js2-function-node-p node)
4216 (js2-function-node-rp node))
4217 ((js2-if-node-p node)
4218 (js2-if-node-rp node))
4219 ((js2-new-node-p node)
4220 (js2-new-node-rp node))
4221 ((js2-call-node-p node)
4222 (js2-call-node-rp node))
4223 ((js2-paren-node-p node)
4224 (+ (js2-node-pos node) (js2-node-len node)))
4225 ((js2-switch-node-p node)
4226 (js2-switch-node-rp node))
4227 ((js2-catch-node-p node)
4228 (js2-catch-node-rp node))
4229 ((js2-let-node-p node)
4230 (js2-let-node-rp node))
4231 ((js2-array-comp-node-p node)
4232 (js2-array-comp-node-rp node))
4233 ((js2-with-node-p node)
4234 (js2-with-node-rp node))
4235 ((js2-xml-dot-query-node-p node)
4236 (1+ (js2-xml-dot-query-node-rp node)))
4237 (t
4238 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4239
4240 (defsubst js2-node-first-child (node)
4241 "Return the first element of `js2-node-child-list' for NODE."
4242 (car (js2-node-child-list node)))
4243
4244 (defsubst js2-node-last-child (node)
4245 "Return the last element of `js2-node-last-child' for NODE."
4246 (car (last (js2-node-child-list node))))
4247
4248 (defun js2-node-prev-sibling (node)
4249 "Return the previous statement in parent.
4250 Works for parents supported by `js2-node-child-list'.
4251 Returns nil if NODE is not in the parent, or PARENT is
4252 not a supported node, or if NODE is the first child."
4253 (let* ((p (js2-node-parent node))
4254 (kids (js2-node-child-list p))
4255 (sib (car kids)))
4256 (while (and kids
4257 (not (eq node (cadr kids))))
4258 (setq kids (cdr kids)
4259 sib (car kids)))
4260 sib))
4261
4262 (defun js2-node-next-sibling (node)
4263 "Return the next statement in parent block.
4264 Returns nil if NODE is not in the block, or PARENT is not
4265 a block node, or if NODE is the last statement."
4266 (let* ((p (js2-node-parent node))
4267 (kids (js2-node-child-list p)))
4268 (while (and kids
4269 (not (eq node (car kids))))
4270 (setq kids (cdr kids)))
4271 (cadr kids)))
4272
4273 (defun js2-node-find-child-before (pos parent &optional after)
4274 "Find the last child that starts before POS in parent.
4275 If AFTER is non-nil, returns first child starting after POS.
4276 POS is an absolute buffer position. PARENT is any node
4277 supported by `js2-node-child-list'.
4278 Returns nil if no applicable child is found."
4279 (let ((kids (if (js2-function-node-p parent)
4280 (js2-block-node-kids (js2-function-node-body parent))
4281 (js2-node-child-list parent)))
4282 (beg (if (js2-function-node-p parent)
4283 (js2-node-abs-pos (js2-function-node-body parent))
4284 (js2-node-abs-pos parent)))
4285 kid result fn
4286 (continue t))
4287 (setq fn (if after '>= '<))
4288 (while (and kids continue)
4289 (setq kid (car kids))
4290 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4291 (setq result kid
4292 continue (if after nil t))
4293 (setq continue (if after t nil)))
4294 (setq kids (cdr kids)))
4295 result))
4296
4297 (defun js2-node-find-child-after (pos parent)
4298 "Find first child that starts after POS in parent.
4299 POS is an absolute buffer position. PARENT is any node
4300 supported by `js2-node-child-list'.
4301 Returns nil if no applicable child is found."
4302 (js2-node-find-child-before pos parent 'after))
4303
4304 (defun js2-node-replace-child (pos parent new-node)
4305 "Replace node at index POS in PARENT with NEW-NODE.
4306 Only works for parents supported by `js2-node-child-list'."
4307 (let ((kids (js2-node-child-list parent))
4308 (i 0))
4309 (while (< i pos)
4310 (setq kids (cdr kids)
4311 i (1+ i)))
4312 (setcar kids new-node)
4313 (js2-node-add-children parent new-node)))
4314
4315 (defun js2-node-buffer (n)
4316 "Return the buffer associated with AST N.
4317 Returns nil if the buffer is not set as a property on the root
4318 node, or if parent links were not recorded during parsing."
4319 (let ((root (js2-node-root n)))
4320 (and root
4321 (js2-ast-root-p root)
4322 (js2-ast-root-buffer root))))
4323
4324 (defun js2-block-node-push (n kid)
4325 "Push js2-node KID onto the end of js2-block-node N's child list.
4326 KID is always added to the -end- of the kids list.
4327 Function also calls `js2-node-add-children' to add the parent link."
4328 (let ((kids (js2-node-child-list n)))
4329 (if kids
4330 (setcdr kids (nconc (cdr kids) (list kid)))
4331 (js2-node-set-child-list n (list kid)))
4332 (js2-node-add-children n kid)))
4333
4334 (defun js2-node-string (node)
4335 (with-current-buffer (or (js2-node-buffer node)
4336 (error "No buffer available for node %s" node))
4337 (let ((pos (js2-node-abs-pos node)))
4338 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4339
4340 ;; Container for storing the node we're looking for in a traversal.
4341 (js2-deflocal js2-discovered-node nil)
4342
4343 ;; Keep track of absolute node position during traversals.
4344 (js2-deflocal js2-visitor-offset nil)
4345
4346 (js2-deflocal js2-node-search-point nil)
4347
4348 (when js2-mode-dev-mode-p
4349 (defun js2-find-node-at-point ()
4350 (interactive)
4351 (let ((node (js2-node-at-point)))
4352 (message "%s" (or node "No node found at point"))))
4353 (defun js2-node-name-at-point ()
4354 (interactive)
4355 (let ((node (js2-node-at-point)))
4356 (message "%s" (if node
4357 (js2-node-short-name node)
4358 "No node found at point.")))))
4359
4360 (defun js2-node-at-point (&optional pos skip-comments)
4361 "Return AST node at POS, a buffer position, defaulting to current point.
4362 The `js2-mode-ast' variable must be set to the current parse tree.
4363 Signals an error if the AST (`js2-mode-ast') is nil.
4364 Always returns a node - if it can't find one, it returns the root.
4365 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4366 (let ((ast js2-mode-ast)
4367 result)
4368 (unless ast
4369 (error "No JavaScript AST available"))
4370 ;; Look through comments first, since they may be inside nodes that
4371 ;; would otherwise report a match.
4372 (setq pos (or pos (point))
4373 result (if (> pos (js2-node-abs-end ast))
4374 ast
4375 (if (not skip-comments)
4376 (js2-comment-at-point pos))))
4377 (unless result
4378 (setq js2-discovered-node nil
4379 js2-visitor-offset 0
4380 js2-node-search-point pos)
4381 (unwind-protect
4382 (catch 'js2-visit-done
4383 (js2-visit-ast ast #'js2-node-at-point-visitor))
4384 (setq js2-visitor-offset nil
4385 js2-node-search-point nil))
4386 (setq result js2-discovered-node))
4387 ;; may have found a comment beyond end of last child node,
4388 ;; since visiting the ast-root looks at the comment-list last.
4389 (if (and skip-comments
4390 (js2-comment-node-p result))
4391 (setq result nil))
4392 (or result js2-mode-ast)))
4393
4394 (defun js2-node-at-point-visitor (node end-p)
4395 (let ((rel-pos (js2-node-pos node))
4396 abs-pos
4397 abs-end
4398 (point js2-node-search-point))
4399 (cond
4400 (end-p
4401 ;; this evaluates to a non-nil return value, even if it's zero
4402 (decf js2-visitor-offset rel-pos))
4403 ;; we already looked for comments before visiting, and don't want them now
4404 ((js2-comment-node-p node)
4405 nil)
4406 (t
4407 (setq abs-pos (incf js2-visitor-offset rel-pos)
4408 ;; we only want to use the node if the point is before
4409 ;; the last character position in the node, so we decrement
4410 ;; the absolute end by 1.
4411 abs-end (+ abs-pos (js2-node-len node) -1))
4412 (cond
4413 ;; If this node starts after search-point, stop the search.
4414 ((> abs-pos point)
4415 (throw 'js2-visit-done nil))
4416 ;; If this node ends before the search-point, don't check kids.
4417 ((> point abs-end)
4418 nil)
4419 (t
4420 ;; Otherwise point is within this node, possibly in a child.
4421 (setq js2-discovered-node node)
4422 t)))))) ; keep processing kids to look for more specific match
4423
4424 (defsubst js2-block-comment-p (node)
4425 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4426 (and (js2-comment-node-p node)
4427 (memq (js2-comment-node-format node) '(jsdoc block))))
4428
4429 ;; TODO: put the comments in a vector and binary-search them instead
4430 (defun js2-comment-at-point (&optional pos)
4431 "Look through scanned comment nodes for one containing POS.
4432 POS is a buffer position that defaults to current point.
4433 Function returns nil if POS was not in any comment node."
4434 (let ((ast js2-mode-ast)
4435 (x (or pos (point)))
4436 beg end)
4437 (unless ast
4438 (error "No JavaScript AST available"))
4439 (catch 'done
4440 ;; Comments are stored in lexical order.
4441 (dolist (comment (js2-ast-root-comments ast) nil)
4442 (setq beg (js2-node-abs-pos comment)
4443 end (+ beg (js2-node-len comment)))
4444 (if (and (>= x beg)
4445 (<= x end))
4446 (throw 'done comment))))))
4447
4448 (defun js2-mode-find-parent-fn (node)
4449 "Find function enclosing NODE.
4450 Returns nil if NODE is not inside a function."
4451 (setq node (js2-node-parent node))
4452 (while (and node (not (js2-function-node-p node)))
4453 (setq node (js2-node-parent node)))
4454 (and (js2-function-node-p node) node))
4455
4456 (defun js2-mode-find-enclosing-fn (node)
4457 "Find function or root enclosing NODE."
4458 (if (js2-ast-root-p node)
4459 node
4460 (setq node (js2-node-parent node))
4461 (while (not (or (js2-ast-root-p node)
4462 (js2-function-node-p node)))
4463 (setq node (js2-node-parent node)))
4464 node))
4465
4466 (defun js2-mode-find-enclosing-node (beg end)
4467 "Find script or function fully enclosing BEG and END."
4468 (let ((node (js2-node-at-point beg))
4469 pos
4470 (continue t))
4471 (while continue
4472 (if (or (js2-ast-root-p node)
4473 (and (js2-function-node-p node)
4474 (<= (setq pos (js2-node-abs-pos node)) beg)
4475 (>= (+ pos (js2-node-len node)) end)))
4476 (setq continue nil)
4477 (setq node (js2-node-parent node))))
4478 node))
4479
4480 (defun js2-node-parent-script-or-fn (node)
4481 "Find script or function immediately enclosing NODE.
4482 If NODE is the ast-root, returns nil."
4483 (if (js2-ast-root-p node)
4484 nil
4485 (setq node (js2-node-parent node))
4486 (while (and node (not (or (js2-function-node-p node)
4487 (js2-script-node-p node))))
4488 (setq node (js2-node-parent node)))
4489 node))
4490
4491 (defun js2-nested-function-p (node)
4492 "Return t if NODE is a nested function, or is inside a nested function."
4493 (unless (js2-ast-root-p node)
4494 (js2-function-node-p (if (js2-function-node-p node)
4495 (js2-node-parent-script-or-fn node)
4496 (js2-node-parent-script-or-fn
4497 (js2-node-parent-script-or-fn node))))))
4498
4499 (defun js2-mode-shift-kids (kids start offset)
4500 (dolist (kid kids)
4501 (if (> (js2-node-pos kid) start)
4502 (incf (js2-node-pos kid) offset))))
4503
4504 (defun js2-mode-shift-children (parent start offset)
4505 "Update start-positions of all children of PARENT beyond START."
4506 (let ((root (js2-node-root parent)))
4507 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4508 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4509
4510 (defun js2-node-is-descendant (node ancestor)
4511 "Return t if NODE is a descendant of ANCESTOR."
4512 (while (and node
4513 (not (eq node ancestor)))
4514 (setq node (js2-node-parent node)))
4515 node)
4516
4517 ;;; visitor infrastructure
4518
4519 (defun js2-visit-none (node callback)
4520 "Visitor for AST node that have no node children."
4521 nil)
4522
4523 (defun js2-print-none (node indent)
4524 "Visitor for AST node with no printed representation.")
4525
4526 (defun js2-print-body (node indent)
4527 "Print a statement, or a block without braces."
4528 (if (js2-block-node-p node)
4529 (dolist (kid (js2-block-node-kids node))
4530 (js2-print-ast kid indent))
4531 (js2-print-ast node indent)))
4532
4533 (defun js2-print-list (args &optional delimiter)
4534 (loop with len = (length args)
4535 for arg in args
4536 for count from 1
4537 do
4538 (when arg (js2-print-ast arg 0))
4539 (if (< count len)
4540 (insert (or delimiter ", ")))))
4541
4542 (defun js2-print-tree (ast)
4543 "Prints an AST to the current buffer.
4544 Makes `js2-ast-parent-nodes' available to the printer functions."
4545 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4546 (js2-print-ast ast)))
4547
4548 (defun js2-print-ast (node &optional indent)
4549 "Helper function for printing AST nodes.
4550 Requires `js2-ast-parent-nodes' to be non-nil.
4551 You should use `js2-print-tree' instead of this function."
4552 (let ((printer (get (aref node 0) 'js2-printer))
4553 (i (or indent 0))
4554 (pos (js2-node-abs-pos node)))
4555 ;; TODO: wedge comments in here somewhere
4556 (if printer
4557 (funcall printer node i))))
4558
4559 (defconst js2-side-effecting-tokens
4560 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4561 (dolist (tt (list js2-ASSIGN
4562 js2-ASSIGN_ADD
4563 js2-ASSIGN_BITAND
4564 js2-ASSIGN_BITOR
4565 js2-ASSIGN_BITXOR
4566 js2-ASSIGN_DIV
4567 js2-ASSIGN_LSH
4568 js2-ASSIGN_MOD
4569 js2-ASSIGN_MUL
4570 js2-ASSIGN_RSH
4571 js2-ASSIGN_SUB
4572 js2-ASSIGN_URSH
4573 js2-BLOCK
4574 js2-BREAK
4575 js2-CALL
4576 js2-CATCH
4577 js2-CATCH_SCOPE
4578 js2-CONST
4579 js2-CONTINUE
4580 js2-DEBUGGER
4581 js2-DEC
4582 js2-DELPROP
4583 js2-DEL_REF
4584 js2-DO
4585 js2-ELSE
4586 js2-EMPTY
4587 js2-ENTERWITH
4588 js2-EXPORT
4589 js2-EXPR_RESULT
4590 js2-FINALLY
4591 js2-FOR
4592 js2-FUNCTION
4593 js2-GOTO
4594 js2-IF
4595 js2-IFEQ
4596 js2-IFNE
4597 js2-IMPORT
4598 js2-INC
4599 js2-JSR
4600 js2-LABEL
4601 js2-LEAVEWITH
4602 js2-LET
4603 js2-LETEXPR
4604 js2-LOCAL_BLOCK
4605 js2-LOOP
4606 js2-NEW
4607 js2-REF_CALL
4608 js2-RETHROW
4609 js2-RETURN
4610 js2-RETURN_RESULT
4611 js2-SEMI
4612 js2-SETELEM
4613 js2-SETELEM_OP
4614 js2-SETNAME
4615 js2-SETPROP
4616 js2-SETPROP_OP
4617 js2-SETVAR
4618 js2-SET_REF
4619 js2-SET_REF_OP
4620 js2-SWITCH
4621 js2-TARGET
4622 js2-THROW
4623 js2-TRY
4624 js2-VAR
4625 js2-WHILE
4626 js2-WITH
4627 js2-WITHEXPR
4628 js2-YIELD))
4629 (aset tokens tt t))
4630 (if js2-instanceof-has-side-effects
4631 (aset tokens js2-INSTANCEOF t))
4632 tokens))
4633
4634 (defun js2-node-has-side-effects (node)
4635 "Return t if NODE has side effects."
4636 (when node ; makes it easier to handle malformed expressions
4637 (let ((tt (js2-node-type node)))
4638 (cond
4639 ;; This doubtless needs some work, since EXPR_VOID is used
4640 ;; in several ways in Rhino and I may not have caught them all.
4641 ;; I'll wait for people to notice incorrect warnings.
4642 ((and (= tt js2-EXPR_VOID)
4643 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4644 (let ((expr (js2-expr-stmt-node-expr node)))
4645 (or (js2-node-has-side-effects expr)
4646 (when (js2-string-node-p expr)
4647 (string= "use strict" (js2-string-node-value expr))))))
4648 ((= tt js2-COMMA)
4649 (js2-node-has-side-effects (js2-infix-node-right node)))
4650 ((or (= tt js2-AND)
4651 (= tt js2-OR))
4652 (or (js2-node-has-side-effects (js2-infix-node-right node))
4653 (js2-node-has-side-effects (js2-infix-node-left node))))
4654 ((= tt js2-HOOK)
4655 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4656 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4657 ((js2-paren-node-p node)
4658 (js2-node-has-side-effects (js2-paren-node-expr node)))
4659 ((= tt js2-ERROR) ; avoid cascaded error messages
4660 nil)
4661 (t
4662 (aref js2-side-effecting-tokens tt))))))
4663
4664 (defun js2-member-expr-leftmost-name (node)
4665 "For an expr such as foo.bar.baz, return leftmost node foo.
4666 NODE is any `js2-node' object. If it represents a member expression,
4667 which is any sequence of property gets, element-gets, function calls,
4668 or xml descendants/filter operators, then we look at the lexically
4669 leftmost (first) node in the chain. If it is a name-node we return it.
4670 Note that NODE can be a raw name-node and it will be returned as well.
4671 If NODE is not a name-node or member expression, or if it is a member
4672 expression whose leftmost target is not a name node, returns nil."
4673 (let ((continue t)
4674 result)
4675 (while (and continue (not result))
4676 (cond
4677 ((js2-name-node-p node)
4678 (setq result node))
4679 ((js2-prop-get-node-p node)
4680 (setq node (js2-prop-get-node-left node)))
4681 ;; TODO: handle call-nodes, xml-nodes, others?
4682 (t
4683 (setq continue nil))))
4684 result))
4685
4686 (defconst js2-stmt-node-types
4687 (list js2-BLOCK
4688 js2-BREAK
4689 js2-CONTINUE
4690 js2-DEFAULT ; e4x "default xml namespace" statement
4691 js2-DO
4692 js2-EXPR_RESULT
4693 js2-EXPR_VOID
4694 js2-FOR
4695 js2-IF
4696 js2-RETURN
4697 js2-SWITCH
4698 js2-THROW
4699 js2-TRY
4700 js2-WHILE
4701 js2-WITH)
4702 "Node types that only appear in statement contexts.
4703 The list does not include nodes that always appear as the child
4704 of another specific statement type, such as switch-cases,
4705 catch and finally blocks, and else-clauses. The list also excludes
4706 nodes like yield, let and var, which may appear in either expression
4707 or statement context, and in the latter context always have a
4708 `js2-expr-stmt-node' parent. Finally, the list does not include
4709 functions or scripts, which are treated separately from statements
4710 by the JavaScript parser and runtime.")
4711
4712 (defun js2-stmt-node-p (node)
4713 "Heuristic for figuring out if NODE is a statement.
4714 Some node types can appear in either an expression context or a
4715 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4716 For these node types in a statement context, the parent will be a
4717 `js2-expr-stmt-node'.
4718 Functions aren't included in the check."
4719 (memq (js2-node-type node) js2-stmt-node-types))
4720
4721 (defun js2-mode-find-first-stmt (node)
4722 "Search upward starting from NODE looking for a statement.
4723 For purposes of this function, a `js2-function-node' counts."
4724 (while (not (or (js2-stmt-node-p node)
4725 (js2-function-node-p node)))
4726 (setq node (js2-node-parent node)))
4727 node)
4728
4729 (defun js2-node-parent-stmt (node)
4730 "Return the node's first ancestor that is a statement.
4731 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4732 appearing in a statement context will have a parent that is a
4733 `js2-expr-stmt-node' that will be returned by this function."
4734 (let ((parent (js2-node-parent node)))
4735 (if (or (null parent)
4736 (js2-stmt-node-p parent)
4737 (and (js2-function-node-p parent)
4738 (not (eq (js2-function-node-form parent)
4739 'FUNCTION_EXPRESSION))))
4740 parent
4741 (js2-node-parent-stmt parent))))
4742
4743 ;; In the Mozilla Rhino sources, Roshan James writes:
4744 ;; Does consistent-return analysis on the function body when strict mode is
4745 ;; enabled.
4746 ;;
4747 ;; function (x) { return (x+1) }
4748 ;;
4749 ;; is ok, but
4750 ;;
4751 ;; function (x) { if (x < 0) return (x+1); }
4752 ;;
4753 ;; is not because the function can potentially return a value when the
4754 ;; condition is satisfied and if not, the function does not explicitly
4755 ;; return a value.
4756 ;;
4757 ;; This extends to checking mismatches such as "return" and "return <value>"
4758 ;; used in the same function. Warnings are not emitted if inconsistent
4759 ;; returns exist in code that can be statically shown to be unreachable.
4760 ;; Ex.
4761 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4762 ;;
4763 ;; emits no warning. However if the loop had a break statement, then a
4764 ;; warning would be emitted.
4765 ;;
4766 ;; The consistency analysis looks at control structures such as loops, ifs,
4767 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4768 ;; warns the user about an inconsistent set of termination possibilities.
4769 ;;
4770 ;; These flags enumerate the possible ways a statement/function can
4771 ;; terminate. These flags are used by endCheck() and by the Parser to
4772 ;; detect inconsistent return usage.
4773 ;;
4774 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4775 ;; able to execute (example: throw, continue)
4776 ;;
4777 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4778 ;; next one. Statement such as return dont. A compound statement may have
4779 ;; some branch that drops off control to the next statement.
4780 ;;
4781 ;; END_RETURNS indicates that the statement can return with no value.
4782 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4783 ;;
4784 ;; A compound statement such as
4785 ;; if (condition) {
4786 ;; return value;
4787 ;; }
4788 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4789
4790 (defconst js2-END_UNREACHED 0)
4791 (defconst js2-END_DROPS_OFF 1)
4792 (defconst js2-END_RETURNS 2)
4793 (defconst js2-END_RETURNS_VALUE 4)
4794 (defconst js2-END_YIELDS 8)
4795
4796 (defun js2-has-consistent-return-usage (node)
4797 "Check that every return usage in a function body is consistent.
4798 Returns t if the function satisfies strict mode requirement."
4799 (let ((n (js2-end-check node)))
4800 ;; either it doesn't return a value in any branch...
4801 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4802 ;; or it returns a value (or is unreached) at every branch
4803 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4804 js2-END_RETURNS
4805 js2-END_YIELDS)))))
4806
4807 (defun js2-end-check-if (node)
4808 "Ensure that return usage in then/else blocks is consistent.
4809 If there is no else block, then the return statement can fall through.
4810 Returns logical OR of END_* flags"
4811 (let ((th (js2-if-node-then-part node))
4812 (el (js2-if-node-else-part node)))
4813 (if (null th)
4814 js2-END_UNREACHED
4815 (logior (js2-end-check th) (if el
4816 (js2-end-check el)
4817 js2-END_DROPS_OFF)))))
4818
4819 (defun js2-end-check-switch (node)
4820 "Consistency of return statements is checked between the case statements.
4821 If there is no default, then the switch can fall through. If there is a
4822 default, we check to see if all code paths in the default return or if
4823 there is a code path that can fall through.
4824 Returns logical OR of END_* flags."
4825 (let ((rv js2-END_UNREACHED)
4826 default-case)
4827 ;; examine the cases
4828 (catch 'break
4829 (dolist (c (js2-switch-node-cases node))
4830 (if (js2-case-node-expr c)
4831 (js2-set-flag rv (js2-end-check-block c))
4832 (setq default-case c)
4833 (throw 'break nil))))
4834 ;; we don't care how the cases drop into each other
4835 (js2-clear-flag rv js2-END_DROPS_OFF)
4836 ;; examine the default
4837 (js2-set-flag rv (if default-case
4838 (js2-end-check default-case)
4839 js2-END_DROPS_OFF))
4840 rv))
4841
4842 (defun js2-end-check-try (node)
4843 "If the block has a finally, return consistency is checked in the
4844 finally block. If all code paths in the finally return, then the
4845 returns in the try-catch blocks don't matter. If there is a code path
4846 that does not return or if there is no finally block, the returns
4847 of the try and catch blocks are checked for mismatch.
4848 Returns logical OR of END_* flags."
4849 (let ((finally (js2-try-node-finally-block node))
4850 rv)
4851 ;; check the finally if it exists
4852 (setq rv (if finally
4853 (js2-end-check (js2-finally-node-body finally))
4854 js2-END_DROPS_OFF))
4855 ;; If the finally block always returns, then none of the returns
4856 ;; in the try or catch blocks matter.
4857 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4858 (js2-clear-flag rv js2-END_DROPS_OFF)
4859 ;; examine the try block
4860 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4861 ;; check each catch block
4862 (dolist (cb (js2-try-node-catch-clauses node))
4863 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4864 rv))
4865
4866 (defun js2-end-check-loop (node)
4867 "Return statement in the loop body must be consistent.
4868 The default assumption for any kind of a loop is that it will eventually
4869 terminate. The only exception is a loop with a constant true condition.
4870 Code that follows such a loop is examined only if one can determine
4871 statically that there is a break out of the loop.
4872
4873 for(... ; ... ; ...) {}
4874 for(... in ... ) {}
4875 while(...) { }
4876 do { } while(...)
4877
4878 Returns logical OR of END_* flags."
4879 (let ((rv (js2-end-check (js2-loop-node-body node)))
4880 (condition (cond
4881 ((js2-while-node-p node)
4882 (js2-while-node-condition node))
4883 ((js2-do-node-p node)
4884 (js2-do-node-condition node))
4885 ((js2-for-node-p node)
4886 (js2-for-node-condition node)))))
4887
4888 ;; check to see if the loop condition is always true
4889 (if (and condition
4890 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4891 (js2-clear-flag rv js2-END_DROPS_OFF))
4892
4893 ;; look for effect of breaks
4894 (js2-set-flag rv (js2-node-get-prop node
4895 'CONTROL_BLOCK_PROP
4896 js2-END_UNREACHED))
4897 rv))
4898
4899 (defun js2-end-check-block (node)
4900 "A general block of code is examined statement by statement.
4901 If any statement (even a compound one) returns in all branches, then
4902 subsequent statements are not examined.
4903 Returns logical OR of END_* flags."
4904 (let* ((rv js2-END_DROPS_OFF)
4905 (kids (js2-block-node-kids node))
4906 (n (car kids)))
4907 ;; Check each statment. If the statement can continue onto the next
4908 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4909 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4910 (js2-clear-flag rv js2-END_DROPS_OFF)
4911 (js2-set-flag rv (js2-end-check n))
4912 (setq kids (cdr kids)
4913 n (car kids)))
4914 rv))
4915
4916 (defun js2-end-check-label (node)
4917 "A labeled statement implies that there may be a break to the label.
4918 The function processes the labeled statement and then checks the
4919 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4920 particular label.
4921 Returns logical OR of END_* flags."
4922 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4923 (logior rv (js2-node-get-prop node
4924 'CONTROL_BLOCK_PROP
4925 js2-END_UNREACHED))))
4926
4927 (defun js2-end-check-break (node)
4928 "When a break is encountered annotate the statement being broken
4929 out of by setting its CONTROL_BLOCK_PROP property.
4930 Returns logical OR of END_* flags."
4931 (and (js2-break-node-target node)
4932 (js2-node-set-prop (js2-break-node-target node)
4933 'CONTROL_BLOCK_PROP
4934 js2-END_DROPS_OFF))
4935 js2-END_UNREACHED)
4936
4937 (defun js2-end-check (node)
4938 "Examine the body of a function, doing a basic reachability analysis.
4939 Returns a combination of flags END_* flags that indicate
4940 how the function execution can terminate. These constitute only the
4941 pessimistic set of termination conditions. It is possible that at
4942 runtime certain code paths will never be actually taken. Hence this
4943 analysis will flag errors in cases where there may not be errors.
4944 Returns logical OR of END_* flags"
4945 (let (kid)
4946 (cond
4947 ((js2-break-node-p node)
4948 (js2-end-check-break node))
4949 ((js2-expr-stmt-node-p node)
4950 (if (setq kid (js2-expr-stmt-node-expr node))
4951 (js2-end-check kid)
4952 js2-END_DROPS_OFF))
4953 ((or (js2-continue-node-p node)
4954 (js2-throw-node-p node))
4955 js2-END_UNREACHED)
4956 ((js2-return-node-p node)
4957 (if (setq kid (js2-return-node-retval node))
4958 js2-END_RETURNS_VALUE
4959 js2-END_RETURNS))
4960 ((js2-loop-node-p node)
4961 (js2-end-check-loop node))
4962 ((js2-switch-node-p node)
4963 (js2-end-check-switch node))
4964 ((js2-labeled-stmt-node-p node)
4965 (js2-end-check-label node))
4966 ((js2-if-node-p node)
4967 (js2-end-check-if node))
4968 ((js2-try-node-p node)
4969 (js2-end-check-try node))
4970 ((js2-block-node-p node)
4971 (if (null (js2-block-node-kids node))
4972 js2-END_DROPS_OFF
4973 (js2-end-check-block node)))
4974 ((js2-yield-node-p node)
4975 js2-END_YIELDS)
4976 (t
4977 js2-END_DROPS_OFF))))
4978
4979 (defun js2-always-defined-boolean-p (node)
4980 "Check if NODE always evaluates to true or false in boolean context.
4981 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4982 nor always false."
4983 (let ((tt (js2-node-type node))
4984 num)
4985 (cond
4986 ((or (= tt js2-FALSE) (= tt js2-NULL))
4987 'ALWAYS_FALSE)
4988 ((= tt js2-TRUE)
4989 'ALWAYS_TRUE)
4990 ((= tt js2-NUMBER)
4991 (setq num (js2-number-node-num-value node))
4992 (if (and (not (eq num 0.0e+NaN))
4993 (not (zerop num)))
4994 'ALWAYS_TRUE
4995 'ALWAYS_FALSE))
4996 (t
4997 nil))))
4998
4999 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5000 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5001
5002 (defvar js2-tokens nil
5003 "List of all defined token names.") ; initialized in `js2-token-names'
5004
5005 (defconst js2-token-names
5006 (let* ((names (make-vector js2-num-tokens -1))
5007 (case-fold-search nil) ; only match js2-UPPER_CASE
5008 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5009 (loop for sym in syms
5010 for i from 0
5011 do
5012 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5013 (not (boundp sym)))
5014 (aset names (symbol-value sym) ; code, e.g. 152
5015 (downcase
5016 (substring (symbol-name sym) 4))) ; name, e.g. "let"
5017 (push sym js2-tokens)))
5018 names)
5019 "Vector mapping int values to token string names, sans `js2-' prefix.")
5020
5021 (defun js2-token-name (tok)
5022 "Return a string name for TOK, a token symbol or code.
5023 Signals an error if it's not a recognized token."
5024 (let ((code tok))
5025 (if (symbolp tok)
5026 (setq code (symbol-value tok)))
5027 (if (eq code -1)
5028 "ERROR"
5029 (if (and (numberp code)
5030 (not (minusp code))
5031 (< code js2-num-tokens))
5032 (aref js2-token-names code)
5033 (error "Invalid token: %s" code)))))
5034
5035 (defsubst js2-token-sym (tok)
5036 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5037 (intern (js2-token-name tok)))
5038
5039 (defconst js2-token-codes
5040 (let ((table (make-hash-table :test 'eq :size 256)))
5041 (loop for name across js2-token-names
5042 for sym = (intern (concat "js2-" (upcase name)))
5043 do
5044 (puthash sym (symbol-value sym) table))
5045 ;; clean up a few that are "wrong" in Rhino's token codes
5046 (puthash 'js2-DELETE js2-DELPROP table)
5047 table)
5048 "Hashtable mapping token symbols to their bytecodes.")
5049
5050 (defsubst js2-token-code (sym)
5051 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5052 (or (gethash sym js2-token-codes)
5053 (error "Invalid token symbol: %s " sym))) ; signal code bug
5054
5055 (defun js2-report-scan-error (msg &optional no-throw beg len)
5056 (setq js2-token-end js2-ts-cursor)
5057 (js2-report-error msg nil
5058 (or beg js2-token-beg)
5059 (or len (- js2-token-end js2-token-beg)))
5060 (unless no-throw
5061 (throw 'return js2-ERROR)))
5062
5063 (defun js2-get-string-from-buffer ()
5064 "Reverse the char accumulator and return it as a string."
5065 (setq js2-token-end js2-ts-cursor)
5066 (if js2-ts-string-buffer
5067 (apply #'string (nreverse js2-ts-string-buffer))
5068 ""))
5069
5070 ;; TODO: could potentially avoid a lot of consing by allocating a
5071 ;; char buffer the way Rhino does.
5072 (defsubst js2-add-to-string (c)
5073 (push c js2-ts-string-buffer))
5074
5075 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5076 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5077 ;; any other character: when it's not part of the current token, we
5078 ;; unget it, allowing it to be read again by the following call.
5079 (defsubst js2-unget-char ()
5080 (decf js2-ts-cursor))
5081
5082 ;; Rhino distinguishes \r and \n line endings. We don't need to
5083 ;; because we only scan from Emacs buffers, which always use \n.
5084 (defun js2-get-char ()
5085 "Read and return the next character from the input buffer.
5086 Increments `js2-ts-lineno' if the return value is a newline char.
5087 Updates `js2-ts-cursor' to the point after the returned char.
5088 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5089 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5090 (let (c)
5091 ;; check for end of buffer
5092 (if (>= js2-ts-cursor (point-max))
5093 (setq js2-ts-hit-eof t
5094 js2-ts-cursor (1+ js2-ts-cursor)
5095 c js2-EOF_CHAR) ; return value
5096 ;; otherwise read next char
5097 (setq c (char-before (incf js2-ts-cursor)))
5098 ;; if we read a newline, update counters
5099 (if (= c ?\n)
5100 (setq js2-ts-line-start js2-ts-cursor
5101 js2-ts-lineno (1+ js2-ts-lineno)))
5102 ;; TODO: skip over format characters
5103 c)))
5104
5105 (defun js2-read-unicode-escape ()
5106 "Read a \\uNNNN sequence from the input.
5107 Assumes the ?\ and ?u have already been read.
5108 Returns the unicode character, or nil if it wasn't a valid character.
5109 Doesn't change the values of any scanner variables."
5110 ;; I really wish I knew a better way to do this, but I can't
5111 ;; find the Emacs function that takes a 16-bit int and converts
5112 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5113 ;; Have to first check that it's 4 hex characters or it may stop
5114 ;; the read early.
5115 (ignore-errors
5116 (let ((s (buffer-substring-no-properties js2-ts-cursor
5117 (+ 4 js2-ts-cursor))))
5118 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5119 (read (concat "?\\u" s))))))
5120
5121 (defun js2-match-char (test)
5122 "Consume and return next character if it matches TEST, a character.
5123 Returns nil and consumes nothing if TEST is not the next character."
5124 (let ((c (js2-get-char)))
5125 (if (eq c test)
5126 t
5127 (js2-unget-char)
5128 nil)))
5129
5130 (defun js2-peek-char ()
5131 (prog1
5132 (js2-get-char)
5133 (js2-unget-char)))
5134
5135 (defun js2-java-identifier-start-p (c)
5136 (or
5137 (memq c '(?$ ?_))
5138 (js2-char-uppercase-p c)
5139 (js2-char-lowercase-p c)))
5140
5141 (defun js2-java-identifier-part-p (c)
5142 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5143 ;; TODO: make me Unicode-friendly. See comments above.
5144 (or
5145 (memq c '(?$ ?_))
5146 (js2-char-uppercase-p c)
5147 (js2-char-lowercase-p c)
5148 (and (>= c ?0) (<= c ?9))))
5149
5150 (defun js2-alpha-p (c)
5151 (cond ((and (<= ?A c) (<= c ?Z)) t)
5152 ((and (<= ?a c) (<= c ?z)) t)
5153 (t nil)))
5154
5155 (defsubst js2-digit-p (c)
5156 (and (<= ?0 c) (<= c ?9)))
5157
5158 (defun js2-js-space-p (c)
5159 (if (<= c 127)
5160 (memq c '(#x20 #x9 #xB #xC #xD))
5161 (or
5162 (eq c #xA0)
5163 ;; TODO: change this nil to check for Unicode space character
5164 nil)))
5165
5166 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5167
5168 (defun js2-skip-line ()
5169 "Skip to end of line."
5170 (let (c)
5171 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5172 (js2-unget-char)
5173 (setq js2-token-end js2-ts-cursor)))
5174
5175 (defun js2-init-scanner (&optional buf line)
5176 "Create token stream for BUF starting on LINE.
5177 BUF defaults to `current-buffer' and LINE defaults to 1.
5178
5179 A buffer can only have one scanner active at a time, which yields
5180 dramatically simpler code than using a defstruct. If you need to
5181 have simultaneous scanners in a buffer, copy the regions to scan
5182 into temp buffers."
5183 (with-current-buffer (or buf (current-buffer))
5184 (setq js2-ts-dirty-line nil
5185 js2-ts-regexp-flags nil
5186 js2-ts-string ""
5187 js2-ts-number nil
5188 js2-ts-hit-eof nil
5189 js2-ts-line-start 0
5190 js2-ts-lineno (or line 1)
5191 js2-ts-line-end-char -1
5192 js2-ts-cursor (point-min)
5193 js2-ts-is-xml-attribute nil
5194 js2-ts-xml-is-tag-content nil
5195 js2-ts-xml-open-tags-count 0
5196 js2-ts-string-buffer nil)))
5197
5198 ;; This function uses the cached op, string and number fields in
5199 ;; TokenStream; if getToken has been called since the passed token
5200 ;; was scanned, the op or string printed may be incorrect.
5201 (defun js2-token-to-string (token)
5202 ;; Not sure where this function is used in Rhino. Not tested.
5203 (if (not js2-debug-print-trees)
5204 ""
5205 (let ((name (js2-token-name token)))
5206 (cond
5207 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5208 (concat name " `" js2-ts-string "'"))
5209 ((eq token js2-NUMBER)
5210 (format "NUMBER %g" js2-ts-number))
5211 (t
5212 name)))))
5213
5214 (defconst js2-keywords
5215 '(break
5216 case catch const continue
5217 debugger default delete do
5218 else enum
5219 false finally for function
5220 if in instanceof import
5221 let
5222 new null
5223 return
5224 switch
5225 this throw true try typeof
5226 var void
5227 while with
5228 yield))
5229
5230 ;; Token names aren't exactly the same as the keywords, unfortunately.
5231 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5232 (defconst js2-kwd-tokens
5233 (let ((table (make-vector js2-num-tokens nil))
5234 (tokens
5235 (list js2-BREAK
5236 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5237 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5238 js2-ELSE
5239 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5240 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5241 js2-LET
5242 js2-NEW js2-NULL
5243 js2-RETURN
5244 js2-SWITCH
5245 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5246 js2-VAR
5247 js2-WHILE js2-WITH
5248 js2-YIELD)))
5249 (dolist (i tokens)
5250 (aset table i 'font-lock-keyword-face))
5251 (aset table js2-STRING 'font-lock-string-face)
5252 (aset table js2-REGEXP 'font-lock-string-face)
5253 (aset table js2-COMMENT 'font-lock-comment-face)
5254 (aset table js2-THIS 'font-lock-builtin-face)
5255 (aset table js2-VOID 'font-lock-constant-face)
5256 (aset table js2-NULL 'font-lock-constant-face)
5257 (aset table js2-TRUE 'font-lock-constant-face)
5258 (aset table js2-FALSE 'font-lock-constant-face)
5259 table)
5260 "Vector whose values are non-nil for tokens that are keywords.
5261 The values are default faces to use for highlighting the keywords.")
5262
5263 (defconst js2-reserved-words
5264 '(abstract
5265 boolean byte
5266 char class
5267 double
5268 enum export extends
5269 final float
5270 goto
5271 implements import int interface
5272 long
5273 native
5274 package private protected public
5275 short static super synchronized
5276 throws transient
5277 volatile))
5278
5279 (defconst js2-keyword-names
5280 (let ((table (make-hash-table :test 'equal)))
5281 (loop for k in js2-keywords
5282 do (puthash
5283 (symbol-name k) ; instanceof
5284 (intern (concat "js2-"
5285 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5286 table))
5287 table)
5288 "JavaScript keywords by name, mapped to their symbols.")
5289
5290 (defconst js2-reserved-word-names
5291 (let ((table (make-hash-table :test 'equal)))
5292 (loop for k in js2-reserved-words
5293 do
5294 (puthash (symbol-name k) 'js2-RESERVED table))
5295 table)
5296 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5297
5298 (defun js2-collect-string (buf)
5299 "Convert BUF, a list of chars, to a string.
5300 Reverses BUF before converting."
5301 (cond
5302 ((stringp buf)
5303 buf)
5304 ((null buf) ; for emacs21 compat
5305 "")
5306 (t
5307 (if buf
5308 (apply #'string (nreverse buf))
5309 ""))))
5310
5311 (defun js2-string-to-keyword (s)
5312 "Return token for S, a string, if S is a keyword or reserved word.
5313 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5314 (or (gethash s js2-keyword-names)
5315 (gethash s js2-reserved-word-names)))
5316
5317 (defsubst js2-ts-set-char-token-bounds ()
5318 "Used when next token is one character."
5319 (setq js2-token-beg (1- js2-ts-cursor)
5320 js2-token-end js2-ts-cursor))
5321
5322 (defsubst js2-ts-return (token)
5323 "Return an N-character TOKEN from `js2-get-token'.
5324 Updates `js2-token-end' accordingly."
5325 (setq js2-token-end js2-ts-cursor)
5326 (throw 'return token))
5327
5328 (defun js2-x-digit-to-int (c accumulator)
5329 "Build up a hex number.
5330 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5331 corresponding number. Otherwise return -1."
5332 (catch 'return
5333 (catch 'check
5334 ;; Use 0..9 < A..Z < a..z
5335 (cond
5336 ((<= c ?9)
5337 (decf c ?0)
5338 (if (<= 0 c)
5339 (throw 'check nil)))
5340 ((<= c ?F)
5341 (when (<= ?A c)
5342 (decf c (- ?A 10))
5343 (throw 'check nil)))
5344 ((<= c ?f)
5345 (when (<= ?a c)
5346 (decf c (- ?a 10))
5347 (throw 'check nil))))
5348 (throw 'return -1))
5349 (logior c (lsh accumulator 4))))
5350
5351 (defun js2-get-token ()
5352 "Return next JavaScript token, an int such as js2-RETURN."
5353 (let (c c1 identifier-start is-unicode-escape-start
5354 contains-escape escape-val escape-start str result base
5355 is-integer quote-char val look-for-slash continue)
5356 (catch 'return
5357 (while t
5358 ;; Eat whitespace, possibly sensitive to newlines.
5359 (setq continue t)
5360 (while continue
5361 (setq c (js2-get-char))
5362 (cond
5363 ((eq c js2-EOF_CHAR)
5364 (js2-ts-set-char-token-bounds)
5365 (throw 'return js2-EOF))
5366 ((eq c ?\n)
5367 (js2-ts-set-char-token-bounds)
5368 (setq js2-ts-dirty-line nil)
5369 (throw 'return js2-EOL))
5370 ((not (js2-js-space-p c))
5371 (if (/= c ?-) ; in case end of HTML comment
5372 (setq js2-ts-dirty-line t))
5373 (setq continue nil))))
5374 ;; Assume the token will be 1 char - fixed up below.
5375 (js2-ts-set-char-token-bounds)
5376 (when (eq c ?@)
5377 (throw 'return js2-XMLATTR))
5378 ;; identifier/keyword/instanceof?
5379 ;; watch out for starting with a <backslash>
5380 (cond
5381 ((eq c ?\\)
5382 (setq c (js2-get-char))
5383 (if (eq c ?u)
5384 (setq identifier-start t
5385 is-unicode-escape-start t
5386 js2-ts-string-buffer nil)
5387 (setq identifier-start nil)
5388 (js2-unget-char)
5389 (setq c ?\\)))
5390 (t
5391 (when (setq identifier-start (js2-java-identifier-start-p c))
5392 (setq js2-ts-string-buffer nil)
5393 (js2-add-to-string c))))
5394 (when identifier-start
5395 (setq contains-escape is-unicode-escape-start)
5396 (catch 'break
5397 (while t
5398 (if is-unicode-escape-start
5399 ;; strictly speaking we should probably push-back
5400 ;; all the bad characters if the <backslash>uXXXX
5401 ;; sequence is malformed. But since there isn't a
5402 ;; correct context(is there?) for a bad Unicode
5403 ;; escape sequence in an identifier, we can report
5404 ;; an error here.
5405 (progn
5406 (setq escape-val 0)
5407 (dotimes (i 4)
5408 (setq c (js2-get-char)
5409 escape-val (js2-x-digit-to-int c escape-val))
5410 ;; Next check takes care of c < 0 and bad escape
5411 (if (minusp escape-val)
5412 (throw 'break nil)))
5413 (if (minusp escape-val)
5414 (js2-report-scan-error "msg.invalid.escape" t))
5415 (js2-add-to-string escape-val)
5416 (setq is-unicode-escape-start nil))
5417 (setq c (js2-get-char))
5418 (cond
5419 ((eq c ?\\)
5420 (setq c (js2-get-char))
5421 (if (eq c ?u)
5422 (setq is-unicode-escape-start t
5423 contains-escape t)
5424 (js2-report-scan-error "msg.illegal.character" t)))
5425 (t
5426 (if (or (eq c js2-EOF_CHAR)
5427 (not (js2-java-identifier-part-p c)))
5428 (throw 'break nil))
5429 (js2-add-to-string c))))))
5430 (js2-unget-char)
5431 (setq str (js2-get-string-from-buffer))
5432 (unless contains-escape
5433 ;; OPT we shouldn't have to make a string (object!) to
5434 ;; check if it's a keyword.
5435 ;; Return the corresponding token if it's a keyword
5436 (when (setq result (js2-string-to-keyword str))
5437 (if (and (< js2-language-version 170)
5438 (memq result '(js2-LET js2-YIELD)))
5439 ;; LET and YIELD are tokens only in 1.7 and later
5440 (setq result 'js2-NAME))
5441 (if (not (eq result 'js2-RESERVED))
5442 (throw 'return (js2-token-code result)))
5443 (js2-report-warning "msg.reserved.keyword" str)))
5444 ;; If we want to intern these as Rhino does, just use (intern str)
5445 (setq js2-ts-string str)
5446 (throw 'return js2-NAME)) ; end identifier/kwd check
5447 ;; is it a number?
5448 (when (or (js2-digit-p c)
5449 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5450 (setq js2-ts-string-buffer nil
5451 base 10)
5452 (when (eq c ?0)
5453 (setq c (js2-get-char))
5454 (cond
5455 ((or (eq c ?x) (eq c ?X))
5456 (setq base 16)
5457 (setq c (js2-get-char)))
5458 ((js2-digit-p c)
5459 (setq base 8))
5460 (t
5461 (js2-add-to-string ?0))))
5462 (if (eq base 16)
5463 (while (<= 0 (js2-x-digit-to-int c 0))
5464 (js2-add-to-string c)
5465 (setq c (js2-get-char)))
5466 (while (and (<= ?0 c) (<= c ?9))
5467 ;; We permit 08 and 09 as decimal numbers, which
5468 ;; makes our behavior a superset of the ECMA
5469 ;; numeric grammar. We might not always be so
5470 ;; permissive, so we warn about it.
5471 (when (and (eq base 8) (>= c ?8))
5472 (js2-report-warning "msg.bad.octal.literal"
5473 (if (eq c ?8) "8" "9"))
5474 (setq base 10))
5475 (js2-add-to-string c)
5476 (setq c (js2-get-char))))
5477 (setq is-integer t)
5478 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5479 (setq is-integer nil)
5480 (when (eq c ?.)
5481 (loop do
5482 (js2-add-to-string c)
5483 (setq c (js2-get-char))
5484 while (js2-digit-p c)))
5485 (when (memq c '(?e ?E))
5486 (js2-add-to-string c)
5487 (setq c (js2-get-char))
5488 (when (memq c '(?+ ?-))
5489 (js2-add-to-string c)
5490 (setq c (js2-get-char)))
5491 (unless (js2-digit-p c)
5492 (js2-report-scan-error "msg.missing.exponent" t))
5493 (loop do
5494 (js2-add-to-string c)
5495 (setq c (js2-get-char))
5496 while (js2-digit-p c))))
5497 (js2-unget-char)
5498 (setq js2-ts-string (js2-get-string-from-buffer)
5499 js2-ts-number
5500 (if (and (eq base 10) (not is-integer))
5501 (string-to-number js2-ts-string)
5502 ;; TODO: call runtime number-parser. Some of it is in
5503 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5504 (string-to-number js2-ts-string)))
5505 (throw 'return js2-NUMBER))
5506 ;; is it a string?
5507 (when (memq c '(?\" ?\'))
5508 ;; We attempt to accumulate a string the fast way, by
5509 ;; building it directly out of the reader. But if there
5510 ;; are any escaped characters in the string, we revert to
5511 ;; building it out of a string buffer.
5512 (setq quote-char c
5513 js2-ts-string-buffer nil
5514 c (js2-get-char))
5515 (catch 'break
5516 (while (/= c quote-char)
5517 (catch 'continue
5518 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5519 (js2-unget-char)
5520 (setq js2-token-end js2-ts-cursor)
5521 (js2-report-error "msg.unterminated.string.lit")
5522 (throw 'return js2-STRING))
5523 (when (eq c ?\\)
5524 ;; We've hit an escaped character
5525 (setq c (js2-get-char))
5526 (case c
5527 (?b (setq c ?\b))
5528 (?f (setq c ?\f))
5529 (?n (setq c ?\n))
5530 (?r (setq c ?\r))
5531 (?t (setq c ?\t))
5532 (?v (setq c ?\v))
5533 (?u
5534 (setq c1 (js2-read-unicode-escape))
5535 (if js2-parse-ide-mode
5536 (if c1
5537 (progn
5538 ;; just copy the string in IDE-mode
5539 (js2-add-to-string ?\\)
5540 (js2-add-to-string ?u)
5541 (dotimes (i 3)
5542 (js2-add-to-string (js2-get-char)))
5543 (setq c (js2-get-char))) ; added at end of loop
5544 ;; flag it as an invalid escape
5545 (js2-report-warning "msg.invalid.escape"
5546 nil (- js2-ts-cursor 2) 6))
5547 ;; Get 4 hex digits; if the u escape is not
5548 ;; followed by 4 hex digits, use 'u' + the
5549 ;; literal character sequence that follows.
5550 (js2-add-to-string ?u)
5551 (setq escape-val 0)
5552 (dotimes (i 4)
5553 (setq c (js2-get-char)
5554 escape-val (js2-x-digit-to-int c escape-val))
5555 (if (minusp escape-val)
5556 (throw 'continue nil))
5557 (js2-add-to-string c))
5558 ;; prepare for replace of stored 'u' sequence by escape value
5559 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5560 c escape-val)))
5561 (?x
5562 ;; Get 2 hex digits, defaulting to 'x'+literal
5563 ;; sequence, as above.
5564 (setq c (js2-get-char)
5565 escape-val (js2-x-digit-to-int c 0))
5566 (if (minusp escape-val)
5567 (progn
5568 (js2-add-to-string ?x)
5569 (throw 'continue nil))
5570 (setq c1 c
5571 c (js2-get-char)
5572 escape-val (js2-x-digit-to-int c escape-val))
5573 (if (minusp escape-val)
5574 (progn
5575 (js2-add-to-string ?x)
5576 (js2-add-to-string c1)
5577 (throw 'continue nil))
5578 ;; got 2 hex digits
5579 (setq c escape-val))))
5580 (?\n
5581 ;; Remove line terminator after escape to follow
5582 ;; SpiderMonkey and C/C++
5583 (setq c (js2-get-char))
5584 (throw 'continue nil))
5585 (t
5586 (when (and (<= ?0 c) (< c ?8))
5587 (setq val (- c ?0)
5588 c (js2-get-char))
5589 (when (and (<= ?0 c) (< c ?8))
5590 (setq val (- (+ (* 8 val) c) ?0)
5591 c (js2-get-char))
5592 (when (and (<= ?0 c)
5593 (< c ?8)
5594 (< val #o37))
5595 ;; c is 3rd char of octal sequence only
5596 ;; if the resulting val <= 0377
5597 (setq val (- (+ (* 8 val) c) ?0)
5598 c (js2-get-char))))
5599 (js2-unget-char)
5600 (setq c val)))))
5601 (js2-add-to-string c)
5602 (setq c (js2-get-char)))))
5603 (setq js2-ts-string (js2-get-string-from-buffer))
5604 (throw 'return js2-STRING))
5605 (case c
5606 (?\;
5607 (throw 'return js2-SEMI))
5608 (?\[
5609 (throw 'return js2-LB))
5610 (?\]
5611 (throw 'return js2-RB))
5612 (?{
5613 (throw 'return js2-LC))
5614 (?}
5615 (throw 'return js2-RC))
5616 (?\(
5617 (throw 'return js2-LP))
5618 (?\)
5619 (throw 'return js2-RP))
5620 (?,
5621 (throw 'return js2-COMMA))
5622 (??
5623 (throw 'return js2-HOOK))
5624 (?:
5625 (if (js2-match-char ?:)
5626 (js2-ts-return js2-COLONCOLON)
5627 (throw 'return js2-COLON)))
5628 (?.
5629 (if (js2-match-char ?.)
5630 (if (js2-match-char ?.)
5631 (js2-ts-return js2-TRIPLEDOT)
5632 (js2-ts-return js2-DOTDOT))
5633 (if (js2-match-char ?\()
5634 (js2-ts-return js2-DOTQUERY)
5635 (throw 'return js2-DOT))))
5636 (?|
5637 (if (js2-match-char ?|)
5638 (throw 'return js2-OR)
5639 (if (js2-match-char ?=)
5640 (js2-ts-return js2-ASSIGN_BITOR)
5641 (throw 'return js2-BITOR))))
5642 (?^
5643 (if (js2-match-char ?=)
5644 (js2-ts-return js2-ASSIGN_BITOR)
5645 (throw 'return js2-BITXOR)))
5646 (?&
5647 (if (js2-match-char ?&)
5648 (throw 'return js2-AND)
5649 (if (js2-match-char ?=)
5650 (js2-ts-return js2-ASSIGN_BITAND)
5651 (throw 'return js2-BITAND))))
5652 (?=
5653 (if (js2-match-char ?=)
5654 (if (js2-match-char ?=)
5655 (js2-ts-return js2-SHEQ)
5656 (throw 'return js2-EQ))
5657 (throw 'return js2-ASSIGN)))
5658 (?!
5659 (if (js2-match-char ?=)
5660 (if (js2-match-char ?=)
5661 (js2-ts-return js2-SHNE)
5662 (js2-ts-return js2-NE))
5663 (throw 'return js2-NOT)))
5664 (?<
5665 ;; NB:treat HTML begin-comment as comment-till-eol
5666 (when (js2-match-char ?!)
5667 (when (js2-match-char ?-)
5668 (when (js2-match-char ?-)
5669 (js2-skip-line)
5670 (setq js2-ts-comment-type 'html)
5671 (throw 'return js2-COMMENT)))
5672 (js2-unget-char))
5673 (if (js2-match-char ?<)
5674 (if (js2-match-char ?=)
5675 (js2-ts-return js2-ASSIGN_LSH)
5676 (js2-ts-return js2-LSH))
5677 (if (js2-match-char ?=)
5678 (js2-ts-return js2-LE)
5679 (throw 'return js2-LT))))
5680 (?>
5681 (if (js2-match-char ?>)
5682 (if (js2-match-char ?>)
5683 (if (js2-match-char ?=)
5684 (js2-ts-return js2-ASSIGN_URSH)
5685 (js2-ts-return js2-URSH))
5686 (if (js2-match-char ?=)
5687 (js2-ts-return js2-ASSIGN_RSH)
5688 (js2-ts-return js2-RSH)))
5689 (if (js2-match-char ?=)
5690 (js2-ts-return js2-GE)
5691 (throw 'return js2-GT))))
5692 (?*
5693 (if (js2-match-char ?=)
5694 (js2-ts-return js2-ASSIGN_MUL)
5695 (throw 'return js2-MUL)))
5696 (?/
5697 ;; is it a // comment?
5698 (when (js2-match-char ?/)
5699 (setq js2-token-beg (- js2-ts-cursor 2))
5700 (js2-skip-line)
5701 (setq js2-ts-comment-type 'line)
5702 ;; include newline so highlighting goes to end of window
5703 (incf js2-token-end)
5704 (throw 'return js2-COMMENT))
5705 ;; is it a /* comment?
5706 (when (js2-match-char ?*)
5707 (setq look-for-slash nil
5708 js2-token-beg (- js2-ts-cursor 2)
5709 js2-ts-comment-type
5710 (if (js2-match-char ?*)
5711 (progn
5712 (setq look-for-slash t)
5713 'jsdoc)
5714 'block))
5715 (while t
5716 (setq c (js2-get-char))
5717 (cond
5718 ((eq c js2-EOF_CHAR)
5719 (setq js2-token-end (1- js2-ts-cursor))
5720 (js2-report-error "msg.unterminated.comment")
5721 (throw 'return js2-COMMENT))
5722 ((eq c ?*)
5723 (setq look-for-slash t))
5724 ((eq c ?/)
5725 (if look-for-slash
5726 (js2-ts-return js2-COMMENT)))
5727 (t
5728 (setq look-for-slash nil
5729 js2-token-end js2-ts-cursor)))))
5730 (if (js2-match-char ?=)
5731 (js2-ts-return js2-ASSIGN_DIV)
5732 (throw 'return js2-DIV)))
5733 (?#
5734 (when js2-skip-preprocessor-directives
5735 (js2-skip-line)
5736 (setq js2-ts-comment-type 'preprocessor
5737 js2-token-end js2-ts-cursor)
5738 (throw 'return js2-COMMENT))
5739 (throw 'return js2-ERROR))
5740 (?%
5741 (if (js2-match-char ?=)
5742 (js2-ts-return js2-ASSIGN_MOD)
5743 (throw 'return js2-MOD)))
5744 (?~
5745 (throw 'return js2-BITNOT))
5746 (?+
5747 (if (js2-match-char ?=)
5748 (js2-ts-return js2-ASSIGN_ADD)
5749 (if (js2-match-char ?+)
5750 (js2-ts-return js2-INC)
5751 (throw 'return js2-ADD))))
5752 (?-
5753 (cond
5754 ((js2-match-char ?=)
5755 (setq c js2-ASSIGN_SUB))
5756 ((js2-match-char ?-)
5757 (unless js2-ts-dirty-line
5758 ;; treat HTML end-comment after possible whitespace
5759 ;; after line start as comment-until-eol
5760 (when (js2-match-char ?>)
5761 (js2-skip-line)
5762 (setq js2-ts-comment-type 'html)
5763 (throw 'return js2-COMMENT)))
5764 (setq c js2-DEC))
5765 (t
5766 (setq c js2-SUB)))
5767 (setq js2-ts-dirty-line t)
5768 (js2-ts-return c))
5769 (otherwise
5770 (js2-report-scan-error "msg.illegal.character")))))))
5771
5772 (defun js2-read-regexp (start-token)
5773 "Called by parser when it gets / or /= in literal context."
5774 (let (c err
5775 in-class ; inside a '[' .. ']' character-class
5776 flags
5777 (continue t))
5778 (setq js2-token-beg js2-ts-cursor
5779 js2-ts-string-buffer nil
5780 js2-ts-regexp-flags nil)
5781 (if (eq start-token js2-ASSIGN_DIV)
5782 ;; mis-scanned /=
5783 (js2-add-to-string ?=)
5784 (if (not (eq start-token js2-DIV))
5785 (error "failed assertion")))
5786 (while (and (not err)
5787 (or (/= (setq c (js2-get-char)) ?/)
5788 in-class))
5789 (cond
5790 ((or (= c ?\n)
5791 (= c js2-EOF_CHAR))
5792 (setq js2-token-end (1- js2-ts-cursor)
5793 err t
5794 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5795 (js2-report-error "msg.unterminated.re.lit"))
5796 (t (cond
5797 ((= c ?\\)
5798 (js2-add-to-string c)
5799 (setq c (js2-get-char)))
5800 ((= c ?\[)
5801 (setq in-class t))
5802 ((= c ?\])
5803 (setq in-class nil)))
5804 (js2-add-to-string c))))
5805 (unless err
5806 (while continue
5807 (cond
5808 ((js2-match-char ?g)
5809 (push ?g flags))
5810 ((js2-match-char ?i)
5811 (push ?i flags))
5812 ((js2-match-char ?m)
5813 (push ?m flags))
5814 (t
5815 (setq continue nil))))
5816 (if (js2-alpha-p (js2-peek-char))
5817 (js2-report-scan-error "msg.invalid.re.flag" t
5818 js2-ts-cursor 1))
5819 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5820 js2-ts-regexp-flags (js2-collect-string flags)
5821 js2-token-end js2-ts-cursor)
5822 ;; tell `parse-partial-sexp' to ignore this range of chars
5823 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5824
5825 (defun js2-get-first-xml-token ()
5826 (setq js2-ts-xml-open-tags-count 0
5827 js2-ts-is-xml-attribute nil
5828 js2-ts-xml-is-tag-content nil)
5829 (js2-unget-char)
5830 (js2-get-next-xml-token))
5831
5832 (defun js2-xml-discard-string ()
5833 "Throw away the string in progress and flag an XML parse error."
5834 (setq js2-ts-string-buffer nil
5835 js2-ts-string nil)
5836 (js2-report-scan-error "msg.XML.bad.form" t))
5837
5838 (defun js2-get-next-xml-token ()
5839 (setq js2-ts-string-buffer nil ; for recording the XML
5840 js2-token-beg js2-ts-cursor)
5841 (let (c result)
5842 (setq result
5843 (catch 'return
5844 (while t
5845 (setq c (js2-get-char))
5846 (cond
5847 ((= c js2-EOF_CHAR)
5848 (throw 'return js2-ERROR))
5849 (js2-ts-xml-is-tag-content
5850 (case c
5851 (?>
5852 (js2-add-to-string c)
5853 (setq js2-ts-xml-is-tag-content nil
5854 js2-ts-is-xml-attribute nil))
5855 (?/
5856 (js2-add-to-string c)
5857 (when (eq ?> (js2-peek-char))
5858 (setq c (js2-get-char))
5859 (js2-add-to-string c)
5860 (setq js2-ts-xml-is-tag-content nil)
5861 (decf js2-ts-xml-open-tags-count)))
5862 (?{
5863 (js2-unget-char)
5864 (setq js2-ts-string (js2-get-string-from-buffer))
5865 (throw 'return js2-XML))
5866 ((?\' ?\")
5867 (js2-add-to-string c)
5868 (unless (js2-read-quoted-string c)
5869 (throw 'return js2-ERROR)))
5870 (?=
5871 (js2-add-to-string c)
5872 (setq js2-ts-is-xml-attribute t))
5873 ((? ?\t ?\r ?\n)
5874 (js2-add-to-string c))
5875 (t
5876 (js2-add-to-string c)
5877 (setq js2-ts-is-xml-attribute nil)))
5878 (when (and (not js2-ts-xml-is-tag-content)
5879 (zerop js2-ts-xml-open-tags-count))
5880 (setq js2-ts-string (js2-get-string-from-buffer))
5881 (throw 'return js2-XMLEND)))
5882 (t
5883 ;; else not tag content
5884 (case c
5885 (?<
5886 (js2-add-to-string c)
5887 (setq c (js2-peek-char))
5888 (case c
5889 (?!
5890 (setq c (js2-get-char)) ;; skip !
5891 (js2-add-to-string c)
5892 (setq c (js2-peek-char))
5893 (case c
5894 (?-
5895 (setq c (js2-get-char)) ;; skip -
5896 (js2-add-to-string c)
5897 (if (eq c ?-)
5898 (progn
5899 (js2-add-to-string c)
5900 (unless (js2-read-xml-comment)
5901 (throw 'return js2-ERROR)))
5902 (js2-xml-discard-string)
5903 (throw 'return js2-ERROR)))
5904 (?\[
5905 (setq c (js2-get-char)) ;; skip [
5906 (js2-add-to-string c)
5907 (if (and (= (js2-get-char) ?C)
5908 (= (js2-get-char) ?D)
5909 (= (js2-get-char) ?A)
5910 (= (js2-get-char) ?T)
5911 (= (js2-get-char) ?A)
5912 (= (js2-get-char) ?\[))
5913 (progn
5914 (js2-add-to-string ?C)
5915 (js2-add-to-string ?D)
5916 (js2-add-to-string ?A)
5917 (js2-add-to-string ?T)
5918 (js2-add-to-string ?A)
5919 (js2-add-to-string ?\[)
5920 (unless (js2-read-cdata)
5921 (throw 'return js2-ERROR)))
5922 (js2-xml-discard-string)
5923 (throw 'return js2-ERROR)))
5924 (t
5925 (unless (js2-read-entity)
5926 (throw 'return js2-ERROR))))
5927 ;; Allow bare CDATA section, e.g.:
5928 ;; let xml = <![CDATA[ foo bar baz ]]>;
5929 (when (zerop js2-ts-xml-open-tags-count)
5930 (throw 'return js2-XMLEND)))
5931 (??
5932 (setq c (js2-get-char)) ;; skip ?
5933 (js2-add-to-string c)
5934 (unless (js2-read-PI)
5935 (throw 'return js2-ERROR)))
5936 (?/
5937 ;; end tag
5938 (setq c (js2-get-char)) ;; skip /
5939 (js2-add-to-string c)
5940 (when (zerop js2-ts-xml-open-tags-count)
5941 (js2-xml-discard-string)
5942 (throw 'return js2-ERROR))
5943 (setq js2-ts-xml-is-tag-content t)
5944 (decf js2-ts-xml-open-tags-count))
5945 (t
5946 ;; start tag
5947 (setq js2-ts-xml-is-tag-content t)
5948 (incf js2-ts-xml-open-tags-count))))
5949 (?{
5950 (js2-unget-char)
5951 (setq js2-ts-string (js2-get-string-from-buffer))
5952 (throw 'return js2-XML))
5953 (t
5954 (js2-add-to-string c))))))))
5955 (setq js2-token-end js2-ts-cursor)
5956 result))
5957
5958 (defun js2-read-quoted-string (quote)
5959 (let (c)
5960 (catch 'return
5961 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5962 (js2-add-to-string c)
5963 (if (eq c quote)
5964 (throw 'return t)))
5965 (js2-xml-discard-string) ;; throw away string in progress
5966 nil)))
5967
5968 (defun js2-read-xml-comment ()
5969 (let ((c (js2-get-char)))
5970 (catch 'return
5971 (while (/= c js2-EOF_CHAR)
5972 (catch 'continue
5973 (js2-add-to-string c)
5974 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5975 (setq c (js2-get-char))
5976 (js2-add-to-string c)
5977 (if (eq (js2-peek-char) ?>)
5978 (progn
5979 (setq c (js2-get-char)) ;; skip >
5980 (js2-add-to-string c)
5981 (throw 'return t))
5982 (throw 'continue nil)))
5983 (setq c (js2-get-char))))
5984 (js2-xml-discard-string)
5985 nil)))
5986
5987 (defun js2-read-cdata ()
5988 (let ((c (js2-get-char)))
5989 (catch 'return
5990 (while (/= c js2-EOF_CHAR)
5991 (catch 'continue
5992 (js2-add-to-string c)
5993 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
5994 (setq c (js2-get-char))
5995 (js2-add-to-string c)
5996 (if (eq (js2-peek-char) ?>)
5997 (progn
5998 (setq c (js2-get-char)) ;; Skip >
5999 (js2-add-to-string c)
6000 (throw 'return t))
6001 (throw 'continue nil)))
6002 (setq c (js2-get-char))))
6003 (js2-xml-discard-string)
6004 nil)))
6005
6006 (defun js2-read-entity ()
6007 (let ((decl-tags 1)
6008 c)
6009 (catch 'return
6010 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6011 (js2-add-to-string c)
6012 (case c
6013 (?<
6014 (incf decl-tags))
6015 (?>
6016 (decf decl-tags)
6017 (if (zerop decl-tags)
6018 (throw 'return t)))))
6019 (js2-xml-discard-string)
6020 nil)))
6021
6022 (defun js2-read-PI ()
6023 "Scan an XML processing instruction."
6024 (let (c)
6025 (catch 'return
6026 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6027 (js2-add-to-string c)
6028 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6029 (setq c (js2-get-char)) ;; Skip >
6030 (js2-add-to-string c)
6031 (throw 'return t)))
6032 (js2-xml-discard-string)
6033 nil)))
6034
6035 (defun js2-scanner-get-line ()
6036 "Return the text of the current scan line."
6037 (buffer-substring (point-at-bol) (point-at-eol)))
6038
6039 ;;; Highlighting
6040
6041 (defun js2-set-face (beg end face &optional record)
6042 "Fontify a region. If RECORD is non-nil, record for later."
6043 (when (plusp js2-highlight-level)
6044 (setq beg (min (point-max) beg)
6045 beg (max (point-min) beg)
6046 end (min (point-max) end)
6047 end (max (point-min) end))
6048 (if record
6049 (push (list beg end face) js2-mode-fontifications)
6050 (put-text-property beg end 'font-lock-face face))))
6051
6052 (defun js2-set-kid-face (pos kid len face)
6053 "Set-face on a child node.
6054 POS is absolute buffer position of parent.
6055 KID is the child node.
6056 LEN is the length to fontify.
6057 FACE is the face to fontify with."
6058 (js2-set-face (+ pos (js2-node-pos kid))
6059 (+ pos (js2-node-pos kid) (js2-node-len kid))
6060 face))
6061
6062 (defsubst js2-fontify-kwd (start length)
6063 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6064
6065 (defsubst js2-clear-face (beg end)
6066 (remove-text-properties beg end '(font-lock-face nil
6067 help-echo nil
6068 point-entered nil
6069 c-in-sws nil)))
6070
6071 (defconst js2-ecma-global-props
6072 (concat "^"
6073 (regexp-opt
6074 '("Infinity" "NaN" "undefined" "arguments") t)
6075 "$")
6076 "Value properties of the Ecma-262 Global Object.
6077 Shown at or above `js2-highlight-level' 2.")
6078
6079 ;; might want to add the name "arguments" to this list?
6080 (defconst js2-ecma-object-props
6081 (concat "^"
6082 (regexp-opt
6083 '("prototype" "__proto__" "__parent__") t)
6084 "$")
6085 "Value properties of the Ecma-262 Object constructor.
6086 Shown at or above `js2-highlight-level' 2.")
6087
6088 (defconst js2-ecma-global-funcs
6089 (concat
6090 "^"
6091 (regexp-opt
6092 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6093 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6094 "$")
6095 "Function properties of the Ecma-262 Global object.
6096 Shown at or above `js2-highlight-level' 2.")
6097
6098 (defconst js2-ecma-number-props
6099 (concat "^"
6100 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6101 "NEGATIVE_INFINITY"
6102 "POSITIVE_INFINITY") t)
6103 "$")
6104 "Properties of the Ecma-262 Number constructor.
6105 Shown at or above `js2-highlight-level' 2.")
6106
6107 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6108 "Properties of the Ecma-262 Date constructor.
6109 Shown at or above `js2-highlight-level' 2.")
6110
6111 (defconst js2-ecma-math-props
6112 (concat "^"
6113 (regexp-opt
6114 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6115 t)
6116 "$")
6117 "Properties of the Ecma-262 Math object.
6118 Shown at or above `js2-highlight-level' 2.")
6119
6120 (defconst js2-ecma-math-funcs
6121 (concat "^"
6122 (regexp-opt
6123 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6124 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6125 "$")
6126 "Function properties of the Ecma-262 Math object.
6127 Shown at or above `js2-highlight-level' 2.")
6128
6129 (defconst js2-ecma-function-props
6130 (concat
6131 "^"
6132 (regexp-opt
6133 '(;; properties of the Object prototype object
6134 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6135 "toLocaleString" "toString" "valueOf"
6136 ;; properties of the Function prototype object
6137 "apply" "call"
6138 ;; properties of the Array prototype object
6139 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6140 "splice" "unshift"
6141 ;; properties of the String prototype object
6142 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6143 "localeCompare" "match" "replace" "search" "split" "substring"
6144 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6145 "toUpperCase"
6146 ;; properties of the Number prototype object
6147 "toExponential" "toFixed" "toPrecision"
6148 ;; properties of the Date prototype object
6149 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6150 "getMinutes" "getMonth" "getSeconds" "getTime"
6151 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6152 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6153 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6154 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6155 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6156 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6157 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6158 "toTimeString" "toUTCString"
6159 ;; properties of the RegExp prototype object
6160 "exec" "test"
6161 ;; properties of the JSON prototype object
6162 "parse" "stringify"
6163 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6164 "toSource" "__defineGetter__" "__defineSetter__"
6165 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6166 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6167 t)
6168 "$")
6169 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6170 Shown at or above `js2-highlight-level' 3.")
6171
6172 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6173 (let ((target-name (and target
6174 (js2-name-node-p target)
6175 (js2-name-node-name target)))
6176 (prop-name (if prop (js2-name-node-name prop)))
6177 (level1 (>= js2-highlight-level 1))
6178 (level2 (>= js2-highlight-level 2))
6179 (level3 (>= js2-highlight-level 3))
6180 pos face)
6181 (when level2
6182 (if call-p
6183 (cond
6184 ((and target prop)
6185 (cond
6186 ((and level3 (string-match js2-ecma-function-props prop-name))
6187 (setq face 'font-lock-builtin-face))
6188 ((and target-name prop)
6189 (cond
6190 ((string= target-name "Date")
6191 (if (string-match js2-ecma-date-props prop-name)
6192 (setq face 'font-lock-builtin-face)))
6193 ((string= target-name "Math")
6194 (if (string-match js2-ecma-math-funcs prop-name)
6195 (setq face 'font-lock-builtin-face)))))))
6196 (prop
6197 (if (string-match js2-ecma-global-funcs prop-name)
6198 (setq face 'font-lock-builtin-face))))
6199 (cond
6200 ((and target prop)
6201 (cond
6202 ((string= target-name "Number")
6203 (if (string-match js2-ecma-number-props prop-name)
6204 (setq face 'font-lock-constant-face)))
6205 ((string= target-name "Math")
6206 (if (string-match js2-ecma-math-props prop-name)
6207 (setq face 'font-lock-constant-face)))))
6208 (prop
6209 (if (string-match js2-ecma-object-props prop-name)
6210 (setq face 'font-lock-constant-face)))))
6211 (when face
6212 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6213 (js2-node-pos prop))) ; relative
6214 (+ pos (js2-node-len prop))
6215 face 'record)))))
6216
6217 (defun js2-parse-highlight-member-expr-node (node)
6218 "Perform syntax highlighting of EcmaScript built-in properties.
6219 The variable `js2-highlight-level' governs this highighting."
6220 (let (face target prop name pos end parent call-p callee)
6221 (cond
6222 ;; case 1: simple name, e.g. foo
6223 ((js2-name-node-p node)
6224 (setq name (js2-name-node-name node))
6225 ;; possible for name to be nil in rare cases - saw it when
6226 ;; running js2-mode on an elisp buffer. Might as well try to
6227 ;; make it so js2-mode never barfs.
6228 (when name
6229 (setq face (if (string-match js2-ecma-global-props name)
6230 'font-lock-constant-face))
6231 (when face
6232 (setq pos (js2-node-pos node)
6233 end (+ pos (js2-node-len node)))
6234 (js2-set-face pos end face 'record))))
6235 ;; case 2: property access or function call
6236 ((or (js2-prop-get-node-p node)
6237 ;; highlight function call if expr is a prop-get node
6238 ;; or a plain name (i.e. unqualified function call)
6239 (and (setq call-p (js2-call-node-p node))
6240 (setq callee (js2-call-node-target node)) ; separate setq!
6241 (or (js2-prop-get-node-p callee)
6242 (js2-name-node-p callee))))
6243 (setq parent node
6244 node (if call-p callee node))
6245 (if (and call-p (js2-name-node-p callee))
6246 (setq prop callee)
6247 (setq target (js2-prop-get-node-left node)
6248 prop (js2-prop-get-node-right node)))
6249 (cond
6250 ((js2-name-node-p target)
6251 (if (js2-name-node-p prop)
6252 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6253 (js2-parse-highlight-prop-get parent target prop call-p)
6254 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6255 (js2-parse-highlight-prop-get parent target nil call-p)))
6256 ((js2-name-node-p prop)
6257 ;; case 2c: complex target, simple name, e.g. x[y].bar
6258 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6259
6260 (defun js2-parse-highlight-member-expr-fn-name (expr)
6261 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6262 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6263 We currently only handle the case where the last component is a prop-get
6264 of a simple name. Called before EXPR has a parent node."
6265 (let (pos
6266 (name (and (js2-prop-get-node-p expr)
6267 (js2-prop-get-node-right expr))))
6268 (when (js2-name-node-p name)
6269 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6270 (js2-node-pos name)))
6271 (+ pos (js2-node-len name))
6272 'font-lock-function-name-face
6273 'record))))
6274
6275 ;; source: http://jsdoc.sourceforge.net/
6276 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6277 ;; allows type specifications, and needs work before entering the wild.
6278
6279 (defconst js2-jsdoc-param-tag-regexp
6280 (concat "^\\s-*\\*+\\s-*\\(@"
6281 "\\(?:param\\|argument\\)"
6282 "\\)"
6283 "\\s-*\\({[^}]+}\\)?" ; optional type
6284 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6285 "\\>")
6286 "Matches jsdoc tags with optional type and optional param name.")
6287
6288 (defconst js2-jsdoc-typed-tag-regexp
6289 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6290 (regexp-opt
6291 '("enum"
6292 "extends"
6293 "field"
6294 "id"
6295 "implements"
6296 "lends"
6297 "mods"
6298 "requires"
6299 "return"
6300 "returns"
6301 "throw"
6302 "throws"))
6303 "\\)\\)\\s-*\\({[^}]+}\\)?")
6304 "Matches jsdoc tags with optional type.")
6305
6306 (defconst js2-jsdoc-arg-tag-regexp
6307 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6308 (regexp-opt
6309 '("alias"
6310 "augments"
6311 "borrows"
6312 "bug"
6313 "base"
6314 "config"
6315 "default"
6316 "define"
6317 "exception"
6318 "function"
6319 "member"
6320 "memberOf"
6321 "name"
6322 "namespace"
6323 "property"
6324 "since"
6325 "suppress"
6326 "this"
6327 "throws"
6328 "type"
6329 "version"))
6330 "\\)\\)\\s-+\\([^ \t]+\\)")
6331 "Matches jsdoc tags with a single argument.")
6332
6333 (defconst js2-jsdoc-empty-tag-regexp
6334 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6335 (regexp-opt
6336 '("addon"
6337 "author"
6338 "class"
6339 "const"
6340 "constant"
6341 "constructor"
6342 "constructs"
6343 "deprecated"
6344 "desc"
6345 "description"
6346 "event"
6347 "example"
6348 "exec"
6349 "export"
6350 "fileoverview"
6351 "final"
6352 "function"
6353 "hidden"
6354 "ignore"
6355 "implicitCast"
6356 "inheritDoc"
6357 "inner"
6358 "interface"
6359 "license"
6360 "noalias"
6361 "noshadow"
6362 "notypecheck"
6363 "override"
6364 "owner"
6365 "preserve"
6366 "preserveTry"
6367 "private"
6368 "protected"
6369 "public"
6370 "static"
6371 "supported"
6372 ))
6373 "\\)\\)\\s-*")
6374 "Matches empty jsdoc tags.")
6375
6376 (defconst js2-jsdoc-link-tag-regexp
6377 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6378 "Matches a jsdoc link or code tag.")
6379
6380 (defconst js2-jsdoc-see-tag-regexp
6381 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6382 "Matches a jsdoc @see tag.")
6383
6384 (defconst js2-jsdoc-html-tag-regexp
6385 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6386 "Matches a simple (no attributes) html start- or end-tag.")
6387
6388 (defun js2-jsdoc-highlight-helper ()
6389 (js2-set-face (match-beginning 1)
6390 (match-end 1)
6391 'js2-jsdoc-tag)
6392 (if (match-beginning 2)
6393 (if (save-excursion
6394 (goto-char (match-beginning 2))
6395 (= (char-after) ?{))
6396 (js2-set-face (1+ (match-beginning 2))
6397 (1- (match-end 2))
6398 'js2-jsdoc-type)
6399 (js2-set-face (match-beginning 2)
6400 (match-end 2)
6401 'js2-jsdoc-value)))
6402 (if (match-beginning 3)
6403 (js2-set-face (match-beginning 3)
6404 (match-end 3)
6405 'js2-jsdoc-value)))
6406
6407 (defun js2-highlight-jsdoc (ast)
6408 "Highlight doc comment tags."
6409 (let ((comments (js2-ast-root-comments ast))
6410 beg end)
6411 (save-excursion
6412 (dolist (node comments)
6413 (when (eq (js2-comment-node-format node) 'jsdoc)
6414 (setq beg (js2-node-abs-pos node)
6415 end (+ beg (js2-node-len node)))
6416 (save-restriction
6417 (narrow-to-region beg end)
6418 (dolist (re (list js2-jsdoc-param-tag-regexp
6419 js2-jsdoc-typed-tag-regexp
6420 js2-jsdoc-arg-tag-regexp
6421 js2-jsdoc-link-tag-regexp
6422 js2-jsdoc-see-tag-regexp
6423 js2-jsdoc-empty-tag-regexp))
6424 (goto-char beg)
6425 (while (re-search-forward re nil t)
6426 (js2-jsdoc-highlight-helper)))
6427 ;; simple highlighting for html tags
6428 (goto-char beg)
6429 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6430 (js2-set-face (match-beginning 1)
6431 (match-end 1)
6432 'js2-jsdoc-html-tag-delimiter)
6433 (js2-set-face (match-beginning 2)
6434 (match-end 2)
6435 'js2-jsdoc-html-tag-name)
6436 (js2-set-face (match-beginning 3)
6437 (match-end 3)
6438 'js2-jsdoc-html-tag-delimiter))))))))
6439
6440 (defun js2-highlight-assign-targets (node left right)
6441 "Highlight function properties and external variables."
6442 (let (leftpos end name)
6443 ;; highlight vars and props assigned function values
6444 (when (js2-function-node-p right)
6445 (cond
6446 ;; var foo = function() {...}
6447 ((js2-name-node-p left)
6448 (setq name left))
6449 ;; foo.bar.baz = function() {...}
6450 ((and (js2-prop-get-node-p left)
6451 (js2-name-node-p (js2-prop-get-node-right left)))
6452 (setq name (js2-prop-get-node-right left))))
6453 (when name
6454 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6455 (+ leftpos (js2-node-len name))
6456 'font-lock-function-name-face
6457 'record)))))
6458
6459 (defun js2-record-name-node (node)
6460 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6461 later. NODE must be a name node."
6462 (let (leftpos end)
6463 (push (list node js2-current-scope
6464 (setq leftpos (js2-node-abs-pos node))
6465 (setq end (+ leftpos (js2-node-len node))))
6466 js2-recorded-identifiers)))
6467
6468 (defun js2-highlight-undeclared-vars ()
6469 "After entire parse is finished, look for undeclared variable references.
6470 We have to wait until entire buffer is parsed, since JavaScript permits var
6471 decls to occur after they're used.
6472
6473 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6474 it is considered declared."
6475 (let (name)
6476 (dolist (entry js2-recorded-identifiers)
6477 (destructuring-bind (name-node scope pos end) entry
6478 (setq name (js2-name-node-name name-node))
6479 (unless (or (member name js2-global-externs)
6480 (member name js2-default-externs)
6481 (member name js2-additional-externs)
6482 (js2-get-defining-scope scope name))
6483 (js2-report-warning "msg.undeclared.variable" name pos (- end pos)
6484 'js2-external-variable))))
6485 (setq js2-recorded-identifiers nil)))
6486
6487 ;;; IMenu support
6488
6489 ;; We currently only support imenu, but eventually should support speedbar and
6490 ;; possibly other browsing mechanisms.
6491
6492 ;; The basic strategy is to identify function assignment targets of the form
6493 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6494 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6495 ;; for imenu after parsing is finished.
6496
6497 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6498 ;; JavaScript, and the general problem is undecidable. However, several forms
6499 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6500 ;; include:
6501
6502 ;; function foo() -- function declaration
6503 ;; foo = function() -- function expression assigned to variable
6504 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6505 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6506 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6507 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6508 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6509 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6510 ;; function foo() {function bar() {...}} -- nested function
6511 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6512
6513 ;; This list boils down to a few forms that can be combined recursively.
6514 ;; Top-level named function declarations include both the left-hand (name)
6515 ;; and the right-hand (function value) expressions needed to produce an imenu
6516 ;; entry. The other "right-hand" forms we need to look for are:
6517 ;; - functions declared as props/getters/setters in object literals
6518 ;; - nested named function declarations
6519 ;; The "left-hand" expressions that functions can be assigned to include:
6520 ;; - local/global variables
6521 ;; - nested property-get expressions like a.b.c.d
6522 ;; - element gets like foo[10] or foo['bar'] where the index
6523 ;; expression can be trivially converted to a property name. They
6524 ;; effectively then become property gets.
6525
6526 ;; All the different definition types are canonicalized into the form
6527 ;; foo.bar.baz = position-of-function-keyword
6528
6529 ;; We need to build a trie-like structure for imenu. As an example,
6530 ;; consider the following JavaScript code:
6531
6532 ;; a = function() {...} // function at position 5
6533 ;; b = function() {...} // function at position 25
6534 ;; foo = function() {...} // function at position 100
6535 ;; foo.bar = function() {...} // function at position 200
6536 ;; foo.bar.baz = function() {...} // function at position 300
6537 ;; foo.bar.zab = function() {...} // function at position 400
6538
6539 ;; During parsing we accumulate an entry for each definition in
6540 ;; the variable `js2-imenu-recorder', like so:
6541
6542 ;; '((fn a 5)
6543 ;; (fn b 25)
6544 ;; (fn foo 100)
6545 ;; (fn foo bar 200)
6546 ;; (fn foo bar baz 300)
6547 ;; (fn foo bar zab 400))
6548
6549 ;; Where 'fn' is the respective function node.
6550 ;; After parsing these entries are merged into this alist-trie:
6551
6552 ;; '((a . 1)
6553 ;; (b . 2)
6554 ;; (foo (<definition> . 3)
6555 ;; (bar (<definition> . 6)
6556 ;; (baz . 100)
6557 ;; (zab . 200))))
6558
6559 ;; Note the wacky need for a <definition> name. The token can be anything
6560 ;; that isn't a valid JavaScript identifier, because you might make foo
6561 ;; a function and then start setting properties on it that are also functions.
6562
6563 (defun js2-prop-node-name (node)
6564 "Return the name of a node that may be a property-get/property-name.
6565 If NODE is not a valid name-node, string-node or integral number-node,
6566 returns nil. Otherwise returns the string name/value of the node."
6567 (cond
6568 ((js2-name-node-p node)
6569 (js2-name-node-name node))
6570 ((js2-string-node-p node)
6571 (js2-string-node-value node))
6572 ((and (js2-number-node-p node)
6573 (string-match "^[0-9]+$" (js2-number-node-value node)))
6574 (js2-number-node-value node))
6575 ((js2-this-node-p node)
6576 "this")))
6577
6578 (defun js2-node-qname-component (node)
6579 "Return the name of this node, if it contributes to a qname.
6580 Returns nil if the node doesn't contribute."
6581 (copy-sequence
6582 (or (js2-prop-node-name node)
6583 (if (and (js2-function-node-p node)
6584 (js2-function-node-name node))
6585 (js2-name-node-name (js2-function-node-name node))))))
6586
6587 (defun js2-record-imenu-entry (fn-node qname pos)
6588 "Add an entry to `js2-imenu-recorder'.
6589 FN-NODE should be the current item's function node.
6590
6591 Associate FN-NODE with its QNAME for later lookup.
6592 This is used in postprocessing the chain list. For each chain, we find
6593 the parent function, look up its qname, then prepend a copy of it to the chain."
6594 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6595 (unless js2-imenu-function-map
6596 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6597 (puthash fn-node qname js2-imenu-function-map))
6598
6599 (defun js2-record-imenu-functions (node &optional var)
6600 "Record function definitions for imenu.
6601 NODE is a function node or an object literal.
6602 VAR, if non-nil, is the expression that NODE is being assigned to.
6603 When passed arguments of wrong type, does nothing."
6604 (when js2-parse-ide-mode
6605 (let ((fun-p (js2-function-node-p node))
6606 qname left fname-node pos)
6607 (cond
6608 ;; non-anonymous function declaration?
6609 ((and fun-p
6610 (not var)
6611 (setq fname-node (js2-function-node-name node)))
6612 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6613 ;; for remaining forms, compute left-side tree branch first
6614 ((and var (setq qname (js2-compute-nested-prop-get var)))
6615 (cond
6616 ;; foo.bar.baz = function
6617 (fun-p
6618 (js2-record-imenu-entry node qname (js2-node-pos node)))
6619 ;; foo.bar.baz = object-literal
6620 ;; look for nested functions: {a: {b: function() {...} }}
6621 ((js2-object-node-p node)
6622 ;; Node position here is still absolute, since the parser
6623 ;; passes the assignment target and value expressions
6624 ;; to us before they are added as children of the assignment node.
6625 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6626
6627 (defun js2-compute-nested-prop-get (node)
6628 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6629 component nodes as a list. Otherwise return nil. Element-gets are treated
6630 as property-gets if the index expression is a string, or a positive integer."
6631 (let (left right head)
6632 (cond
6633 ((or (js2-name-node-p node)
6634 (js2-this-node-p node))
6635 (list node))
6636 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6637 ((js2-prop-get-node-p node) ; foo.bar
6638 (setq left (js2-prop-get-node-left node)
6639 right (js2-prop-get-node-right node))
6640 (if (setq head (js2-compute-nested-prop-get left))
6641 (nconc head (list right))))
6642 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6643 (setq left (js2-elem-get-node-target node)
6644 right (js2-elem-get-node-element node))
6645 (if (or (js2-string-node-p right) ; ['bar']
6646 (and (js2-number-node-p right) ; [10]
6647 (string-match "^[0-9]+$"
6648 (js2-number-node-value right))))
6649 (if (setq head (js2-compute-nested-prop-get left))
6650 (nconc head (list right))))))))
6651
6652 (defun js2-record-object-literal (node qname pos)
6653 "Recursively process an object literal looking for functions.
6654 NODE is an object literal that is the right-hand child of an assignment
6655 expression. QNAME is a list of nodes representing the assignment target,
6656 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6657 POS is the absolute position of the node.
6658 We do a depth-first traversal of NODE. For any functions we find,
6659 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6660 (let (left right prop-qname)
6661 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6662 (let ((left (js2-infix-node-left e))
6663 ;; Element positions are relative to the parent position.
6664 (pos (+ pos (js2-node-pos e))))
6665 (cond
6666 ;; foo: function() {...}
6667 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6668 (when (js2-prop-node-name left)
6669 ;; As a policy decision, we record the position of the property,
6670 ;; not the position of the `function' keyword, since the property
6671 ;; is effectively the name of the function.
6672 (js2-record-imenu-entry right (append qname (list left)) pos)))
6673 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6674 ((js2-object-node-p right)
6675 (js2-record-object-literal right
6676 (append qname (list (js2-infix-node-left e)))
6677 (+ pos (js2-node-pos right)))))))))
6678
6679 (defun js2-node-top-level-decl-p (node)
6680 "Return t if NODE's name is defined in the top-level scope.
6681 Also returns t if NODE's name is not defined in any scope, since it implies
6682 that it's an external variable, which must also be in the top-level scope."
6683 (let* ((name (js2-prop-node-name node))
6684 (this-scope (js2-node-get-enclosing-scope node))
6685 defining-scope)
6686 (cond
6687 ((js2-this-node-p node)
6688 nil)
6689 ((null this-scope)
6690 t)
6691 ((setq defining-scope (js2-get-defining-scope this-scope name))
6692 (js2-ast-root-p defining-scope))
6693 (t t))))
6694
6695 (defun js2-wrapper-function-p (node)
6696 "Return t if NODE is a function expression that's immediately invoked.
6697 NODE must be `js2-function-node'."
6698 (let ((parent (js2-node-parent node)))
6699 (or
6700 ;; function(){...}();
6701 (js2-call-node-p parent)
6702 (and (js2-paren-node-p parent)
6703 ;; (function(){...})();
6704 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6705 ;; (function(){...}).call(this);
6706 (and (js2-prop-get-node-p parent)
6707 (member (js2-name-node-name (js2-prop-get-node-right parent))
6708 '("call" "apply"))
6709 (js2-call-node-p (js2-node-parent parent))))))))
6710
6711 (defun js2-browse-postprocess-chains (entries)
6712 "Modify function-declaration name chains after parsing finishes.
6713 Some of the information is only available after the parse tree is complete.
6714 For instance, processing a nested scope requires a parent function node."
6715 (let (result head fn current-fn parent-qname qname p elem)
6716 (dolist (entry entries)
6717 ;; function node goes first
6718 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6719 ;; Examine head's defining scope:
6720 ;; Pre-processed chain, or top-level/external, keep as-is.
6721 (if (or (stringp head) (js2-node-top-level-decl-p head))
6722 (push chain result)
6723 (when (js2-this-node-p head)
6724 (setq chain (cdr chain))) ; discard this-node
6725 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6726 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6727 (when (eq parent-qname 'not-found)
6728 ;; anonymous function expressions are not recorded
6729 ;; during the parse, so we need to handle this case here
6730 (setq parent-qname
6731 (if (js2-wrapper-function-p fn)
6732 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6733 (if (js2-ast-root-p grandparent)
6734 nil
6735 (gethash grandparent js2-imenu-function-map 'skip)))
6736 'skip))
6737 (puthash fn parent-qname js2-imenu-function-map))
6738 (unless (eq parent-qname 'skip)
6739 ;; prefix parent fn qname to this chain.
6740 (let ((qname (append parent-qname chain)))
6741 (puthash current-fn (butlast qname) js2-imenu-function-map)
6742 (push qname result)))))))
6743 ;; finally replace each node in each chain with its name.
6744 (dolist (chain result)
6745 (setq p chain)
6746 (while p
6747 (if (js2-node-p (setq elem (car p)))
6748 (setcar p (js2-node-qname-component elem)))
6749 (setq p (cdr p))))
6750 result))
6751
6752 ;; Merge name chains into a trie-like tree structure of nested lists.
6753 ;; To simplify construction of the trie, we first build it out using the rule
6754 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6755 ;; [key, num-or-list]. The second element can be a number; if so, this key
6756 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6757 ;; associated with the key at this level.) Otherwise the second element is
6758 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6759 ;; a simple recursive formulation.
6760 ;;
6761 ;; js2-mode is building the data structure for imenu. The imenu documentation
6762 ;; claims that it's the structure above, but in practice it wants the children
6763 ;; at the same list level as the key for that level, which is how I've drawn
6764 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6765 ;; list wrapper around the children at each level.
6766 ;;
6767 ;; A completed nested imenu-alist entry looks like this:
6768 ;; '(("foo"
6769 ;; ("<definition>" . 7)
6770 ;; ("bar"
6771 ;; ("a" . 40)
6772 ;; ("b" . 60))))
6773 ;;
6774 ;; In particular, the documentation for `imenu--index-alist' says that
6775 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6776 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6777
6778 (defun js2-treeify (lst)
6779 "Convert (a b c d) to (a ((b ((c d)))))."
6780 (if (null (cddr lst)) ; list length <= 2
6781 lst
6782 (list (car lst) (list (js2-treeify (cdr lst))))))
6783
6784 (defun js2-build-alist-trie (chains trie)
6785 "Merge declaration name chains into a trie-like alist structure for imenu.
6786 CHAINS is the qname chain list produced during parsing. TRIE is a
6787 list of elements built up so far."
6788 (let (head tail pos branch kids)
6789 (dolist (chain chains)
6790 (setq head (car chain)
6791 tail (cdr chain)
6792 pos (if (numberp (car tail)) (car tail))
6793 branch (js2-find-if (lambda (n)
6794 (string= (car n) head))
6795 trie)
6796 kids (second branch))
6797 (cond
6798 ;; case 1: this key isn't in the trie yet
6799 ((null branch)
6800 (if trie
6801 (setcdr (last trie) (list (js2-treeify chain)))
6802 (setq trie (list (js2-treeify chain)))))
6803 ;; case 2: key is present with a single number entry: replace w/ list
6804 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6805 ;; ("<definition>" 20)))
6806 ((numberp kids)
6807 (setcar (cdr branch)
6808 (list (list "<definition-1>" kids)
6809 (if pos
6810 (list "<definition-2>" pos)
6811 (js2-treeify tail)))))
6812 ;; case 3: key is there (with kids), and we're a number entry
6813 (pos
6814 (setcdr (last kids)
6815 (list
6816 (list (format "<definition-%d>"
6817 (1+ (loop for kid in kids
6818 count (eq ?< (aref (car kid) 0)))))
6819 pos))))
6820 ;; case 4: key is there with kids, need to merge in our chain
6821 (t
6822 (js2-build-alist-trie (list tail) kids))))
6823 trie))
6824
6825 (defun js2-flatten-trie (trie)
6826 "Convert TRIE to imenu-format.
6827 Recurses through nodes, and for each one whose second element is a list,
6828 appends the list's flattened elements to the current element. Also
6829 changes the tails into conses. For instance, this pre-flattened trie
6830
6831 '(a ((b 20)
6832 (c ((d 30)
6833 (e 40)))))
6834
6835 becomes
6836
6837 '(a (b . 20)
6838 (c (d . 30)
6839 (e . 40)))
6840
6841 Note that the root of the trie has no key, just a list of chains.
6842 This is also true for the value of any key with multiple children,
6843 e.g. key 'c' in the example above."
6844 (cond
6845 ((listp (car trie))
6846 (mapcar #'js2-flatten-trie trie))
6847 (t
6848 (if (numberp (second trie))
6849 (cons (car trie) (second trie))
6850 ;; else pop list and append its kids
6851 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6852
6853 (defun js2-build-imenu-index ()
6854 "Turn `js2-imenu-recorder' into an imenu data structure."
6855 (unless (eq js2-imenu-recorder 'empty)
6856 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6857 (result (js2-build-alist-trie chains nil)))
6858 (js2-flatten-trie result))))
6859
6860 (defun js2-test-print-chains (chains)
6861 "Print a list of qname chains.
6862 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6863 i.e. one or more nodes, and an integer position as the list tail."
6864 (mapconcat (lambda (chain)
6865 (concat "("
6866 (mapconcat (lambda (elem)
6867 (if (js2-node-p elem)
6868 (or (js2-node-qname-component elem)
6869 "nil")
6870 (number-to-string elem)))
6871 chain
6872 " ")
6873 ")"))
6874 chains
6875 "\n"))
6876
6877 ;;; Parser
6878
6879 (defconst js2-version "1.8.5"
6880 "Version of JavaScript supported.")
6881
6882 (defmacro js2-record-face (face)
6883 "Record a style run of FACE for the current token."
6884 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6885
6886 (defsubst js2-node-end (n)
6887 "Computes the absolute end of node N.
6888 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6889 is only true until the node is added to its parent; i.e., while parsing."
6890 (+ (js2-node-pos n)
6891 (js2-node-len n)))
6892
6893 (defun js2-record-comment ()
6894 "Record a comment in `js2-scanned-comments'."
6895 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6896 :format js2-ts-comment-type)
6897 js2-scanned-comments)
6898 (when js2-parse-ide-mode
6899 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6900 'font-lock-doc-face
6901 'font-lock-comment-face))
6902 (when (memq js2-ts-comment-type '(html preprocessor))
6903 ;; Tell cc-engine the bounds of the comment.
6904 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6905
6906 ;; This function is called depressingly often, so it should be fast.
6907 ;; Most of the time it's looking at the same token it peeked before.
6908 (defun js2-peek-token ()
6909 "Return the next token without consuming it.
6910 If previous token was consumed, calls scanner to get new token.
6911 If previous token was -not- consumed, returns it (idempotent).
6912
6913 This function will not return a newline (js2-EOL) - instead, it
6914 gobbles newlines until it finds a non-newline token, and flags
6915 that token as appearing just after a newline.
6916
6917 This function will also not return a js2-COMMENT. Instead, it
6918 records comments found in `js2-scanned-comments'. If the token
6919 returned by this function immediately follows a jsdoc comment,
6920 the token is flagged as such.
6921
6922 Note that this function always returned the un-flagged token!
6923 The flags, if any, are saved in `js2-current-flagged-token'."
6924 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6925 js2-current-token ; most common case - return already-peeked token
6926 (let ((tt (js2-get-token)) ; call scanner
6927 saw-eol
6928 face)
6929 ;; process comments and whitespace
6930 (while (or (= tt js2-EOL)
6931 (= tt js2-COMMENT))
6932 (if (= tt js2-EOL)
6933 (setq saw-eol t)
6934 (setq saw-eol nil)
6935 (if js2-record-comments
6936 (js2-record-comment)))
6937 (setq tt (js2-get-token))) ; call scanner
6938 (setq js2-current-token tt
6939 js2-current-flagged-token (if saw-eol
6940 (logior tt js2-ti-after-eol)
6941 tt))
6942 ;; perform lexical fontification as soon as token is scanned
6943 (when js2-parse-ide-mode
6944 (cond
6945 ((minusp tt)
6946 (js2-record-face 'js2-error))
6947 ((setq face (aref js2-kwd-tokens tt))
6948 (js2-record-face face))
6949 ((and (= tt js2-NAME)
6950 (equal js2-ts-string "undefined"))
6951 (js2-record-face 'font-lock-constant-face))))
6952 tt))) ; return unflagged token
6953
6954 (defun js2-peek-flagged-token ()
6955 "Return the current token along with any flags set for it."
6956 (js2-peek-token)
6957 js2-current-flagged-token)
6958
6959 (defsubst js2-consume-token ()
6960 (setq js2-current-flagged-token js2-EOF))
6961
6962 (defun js2-next-token ()
6963 (prog1
6964 (js2-peek-token)
6965 (js2-consume-token)))
6966
6967 (defun js2-next-flagged-token ()
6968 (js2-peek-token)
6969 (prog1 js2-current-flagged-token
6970 (js2-consume-token)))
6971
6972 (defun js2-match-token (match)
6973 "Consume and return t if next token matches MATCH, a bytecode.
6974 Returns nil and consumes nothing if MATCH is not the next token."
6975 (if (/= (js2-peek-token) match)
6976 nil
6977 (js2-consume-token)
6978 t))
6979
6980 (defun js2-match-contextual-kwd (name)
6981 "Consume and return t if next token is `js2-NAME', and its
6982 string is NAME. Returns nil and does nothing otherwise."
6983 (if (or (/= (js2-peek-token) js2-NAME)
6984 (not (string= js2-ts-string name)))
6985 nil
6986 (js2-consume-token)
6987 (js2-record-face 'font-lock-keyword-face)
6988 t))
6989
6990 (defun js2-valid-prop-name-token (tt)
6991 (or (= tt js2-NAME)
6992 (when (and js2-allow-keywords-as-property-names
6993 (plusp tt)
6994 (aref js2-kwd-tokens tt))
6995 (js2-save-name-token-data js2-token-beg (js2-token-name tt))
6996 t)))
6997
6998 (defun js2-match-prop-name ()
6999 "Consume token and return t if next token is a valid property name.
7000 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7001 is non-nil and it's a keyword token."
7002 (if (js2-valid-prop-name-token (js2-peek-token))
7003 (progn
7004 (js2-consume-token)
7005 t)
7006 nil))
7007
7008 (defun js2-must-match-prop-name (msg-id &optional pos len)
7009 (if (js2-match-prop-name)
7010 t
7011 (js2-report-error msg-id nil pos len)
7012 nil))
7013
7014 (defun js2-peek-token-or-eol ()
7015 "Return js2-EOL if the current token immediately follows a newline.
7016 Else returns the current token. Used in situations where we don't
7017 consider certain token types valid if they are preceded by a newline.
7018 One example is the postfix ++ or -- operator, which has to be on the
7019 same line as its operand."
7020 (let ((tt (js2-peek-token)))
7021 ;; Check for last peeked token flags
7022 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7023 js2-EOL
7024 tt)))
7025
7026 (defun js2-set-check-for-label ()
7027 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7028 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7029
7030 (defun js2-must-match (token msg-id &optional pos len)
7031 "Match next token to token code TOKEN, or record a syntax error.
7032 MSG-ID is the error message to report if the match fails.
7033 Returns t on match, nil if no match."
7034 (if (js2-match-token token)
7035 t
7036 (js2-report-error msg-id nil pos len)
7037 nil))
7038
7039 (defsubst js2-inside-function ()
7040 (plusp js2-nesting-of-function))
7041
7042 (defun js2-set-requires-activation ()
7043 (if (js2-function-node-p js2-current-script-or-fn)
7044 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7045
7046 (defun js2-check-activation-name (name token)
7047 (when (js2-inside-function)
7048 ;; skip language-version 1.2 check from Rhino
7049 (if (or (string= "arguments" name)
7050 (and js2-compiler-activation-names ; only used in codegen
7051 (gethash name js2-compiler-activation-names)))
7052 (js2-set-requires-activation))))
7053
7054 (defun js2-set-is-generator ()
7055 (if (js2-function-node-p js2-current-script-or-fn)
7056 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7057
7058 (defun js2-must-have-xml ()
7059 (unless js2-compiler-xml-available
7060 (js2-report-error "msg.XML.not.available")))
7061
7062 (defun js2-push-scope (scope)
7063 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7064 (assert (js2-scope-p scope))
7065 (assert (null (js2-scope-parent-scope scope)))
7066 (assert (not (eq js2-current-scope scope)))
7067 (setf (js2-scope-parent-scope scope) js2-current-scope
7068 js2-current-scope scope))
7069
7070 (defsubst js2-pop-scope ()
7071 (setq js2-current-scope
7072 (js2-scope-parent-scope js2-current-scope)))
7073
7074 (defun js2-enter-loop (loop-node)
7075 (push loop-node js2-loop-set)
7076 (push loop-node js2-loop-and-switch-set)
7077 (js2-push-scope loop-node)
7078 ;; Tell the current labeled statement (if any) its statement,
7079 ;; and set the jump target of the first label to the loop.
7080 ;; These are used in `js2-parse-continue' to verify that the
7081 ;; continue target is an actual labeled loop. (And for codegen.)
7082 (when js2-labeled-stmt
7083 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7084 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7085 js2-labeled-stmt))) loop-node)))
7086
7087 (defun js2-exit-loop ()
7088 (pop js2-loop-set)
7089 (pop js2-loop-and-switch-set)
7090 (js2-pop-scope))
7091
7092 (defsubst js2-enter-switch (switch-node)
7093 (push switch-node js2-loop-and-switch-set))
7094
7095 (defsubst js2-exit-switch ()
7096 (pop js2-loop-and-switch-set))
7097
7098 (defun js2-parse (&optional buf cb)
7099 "Tell the js2 parser to parse a region of JavaScript.
7100
7101 BUF is a buffer or buffer name containing the code to parse.
7102 Call `narrow-to-region' first to parse only part of the buffer.
7103
7104 The returned AST root node is given some additional properties:
7105 `node-count' - total number of nodes in the AST
7106 `buffer' - BUF. The buffer it refers to may change or be killed,
7107 so the value is not necessarily reliable.
7108
7109 An optional callback CB can be specified to report parsing
7110 progress. If `(functionp CB)' returns t, it will be called with
7111 the current line number once before parsing begins, then again
7112 each time the lexer reaches a new line number.
7113
7114 CB can also be a list of the form `(symbol cb ...)' to specify
7115 multiple callbacks with different criteria. Each symbol is a
7116 criterion keyword, and the following element is the callback to
7117 call
7118
7119 :line - called whenever the line number changes
7120 :token - called for each new token consumed
7121
7122 The list of criteria could be extended to include entering or
7123 leaving a statement, an expression, or a function definition."
7124 (if (and cb (not (functionp cb)))
7125 (error "criteria callbacks not yet implemented"))
7126 (let ((inhibit-point-motion-hooks t)
7127 (js2-compiler-xml-available (>= js2-language-version 160))
7128 ;; This is a recursive-descent parser, so give it a big stack.
7129 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7130 (max-specpdl-size (max max-specpdl-size 3000))
7131 (case-fold-search nil)
7132 ast)
7133 (message nil) ; clear any error message from previous parse
7134 (with-current-buffer (or buf (current-buffer))
7135 (setq js2-scanned-comments nil
7136 js2-parsed-errors nil
7137 js2-parsed-warnings nil
7138 js2-imenu-recorder nil
7139 js2-imenu-function-map nil
7140 js2-label-set nil)
7141 (js2-init-scanner)
7142 (setq ast (with-silent-modifications
7143 (js2-do-parse)))
7144 (unless js2-ts-hit-eof
7145 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7146 (setf (js2-ast-root-errors ast) js2-parsed-errors
7147 (js2-ast-root-warnings ast) js2-parsed-warnings)
7148 ;; if we didn't find any declarations, put a dummy in this list so we
7149 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7150 (unless js2-imenu-recorder
7151 (setq js2-imenu-recorder 'empty))
7152 (run-hooks 'js2-parse-finished-hook)
7153 ast)))
7154
7155 ;; Corresponds to Rhino's Parser.parse() method.
7156 (defun js2-do-parse ()
7157 "Parse current buffer starting from current point.
7158 Scanner should be initialized."
7159 (let ((pos js2-ts-cursor)
7160 (end js2-ts-cursor) ; in case file is empty
7161 root n tt)
7162 ;; initialize buffer-local parsing vars
7163 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7164 js2-current-script-or-fn root
7165 js2-current-scope root
7166 js2-current-flagged-token js2-EOF
7167 js2-nesting-of-function 0
7168 js2-labeled-stmt nil
7169 js2-recorded-identifiers nil) ; for js2-highlight
7170 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7171 (if (= tt js2-FUNCTION)
7172 (progn
7173 (js2-consume-token)
7174 (setq n (js2-parse-function (if js2-called-by-compile-function
7175 'FUNCTION_EXPRESSION
7176 'FUNCTION_STATEMENT))))
7177 ;; not a function - parse a statement
7178 (setq n (js2-parse-statement)))
7179 ;; add function or statement to script
7180 (setq end (js2-node-end n))
7181 (js2-block-node-push root n))
7182 ;; add comments to root in lexical order
7183 (when js2-scanned-comments
7184 ;; if we find a comment beyond end of normal kids, use its end
7185 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7186 (dolist (comment js2-scanned-comments)
7187 (push comment (js2-ast-root-comments root))
7188 (js2-node-add-children root comment)))
7189 (setf (js2-node-len root) (- end pos))
7190 (setq js2-mode-ast root) ; Make sure this is available for callbacks.
7191 ;; Give extensions a chance to muck with things before highlighting starts.
7192 (let ((js2-additional-externs js2-additional-externs))
7193 (save-excursion
7194 (dolist (callback js2-post-parse-callbacks)
7195 (funcall callback)))
7196 (js2-highlight-undeclared-vars))
7197 root))
7198
7199 (defun js2-function-parser ()
7200 (js2-consume-token)
7201 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7202
7203 (defun js2-parse-function-closure-body (fn-node)
7204 "Parse a JavaScript 1.8 function closure body."
7205 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7206 (if js2-ts-hit-eof
7207 (js2-report-error "msg.no.brace.body" nil
7208 (js2-node-pos fn-node)
7209 (- js2-ts-cursor (js2-node-pos fn-node)))
7210 (js2-node-add-children fn-node
7211 (setf (js2-function-node-body fn-node)
7212 (js2-parse-expr t))))))
7213
7214 (defun js2-parse-function-body (fn-node)
7215 (js2-must-match js2-LC "msg.no.brace.body"
7216 (js2-node-pos fn-node)
7217 (- js2-ts-cursor (js2-node-pos fn-node)))
7218 (let ((pos js2-token-beg) ; LC position
7219 (pn (make-js2-block-node)) ; starts at LC position
7220 tt
7221 end)
7222 (incf js2-nesting-of-function)
7223 (unwind-protect
7224 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7225 (= tt js2-EOF)
7226 (= tt js2-RC)))
7227 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7228 (js2-parse-statement)
7229 (js2-consume-token)
7230 (js2-parse-function 'FUNCTION_STATEMENT))))
7231 (decf js2-nesting-of-function))
7232 (setq end js2-token-end) ; assume no curly and leave at current token
7233 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7234 (setq end js2-token-end))
7235 (setf (js2-node-pos pn) pos
7236 (js2-node-len pn) (- end pos))
7237 (setf (js2-function-node-body fn-node) pn)
7238 (js2-node-add-children fn-node pn)
7239 pn))
7240
7241 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7242 "Declare and fontify destructuring parameters inside NODE.
7243 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7244 (cond
7245 ((js2-name-node-p node)
7246 (let (leftpos)
7247 (js2-define-symbol decl-type (js2-name-node-name node)
7248 node ignore-not-in-block)
7249 (when face
7250 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7251 (+ leftpos (js2-node-len node))
7252 face 'record))))
7253 ((js2-object-node-p node)
7254 (dolist (elem (js2-object-node-elems node))
7255 (js2-define-destruct-symbols
7256 (if (js2-object-prop-node-p elem)
7257 (js2-object-prop-node-right elem)
7258 ;; abbreviated destructuring {a, b}
7259 elem)
7260 decl-type face ignore-not-in-block)))
7261 ((js2-array-node-p node)
7262 (dolist (elem (js2-array-node-elems node))
7263 (when elem
7264 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7265 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7266 (js2-node-len node)))))
7267
7268 (defun js2-parse-function-params (fn-node pos)
7269 (if (js2-match-token js2-RP)
7270 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7271 (let (params len param default-found rest-param-at)
7272 (loop for tt = (js2-peek-token)
7273 do
7274 (cond
7275 ;; destructuring param
7276 ((or (= tt js2-LB) (= tt js2-LC))
7277 (when default-found
7278 (js2-report-error "msg.no.default.after.default.param"))
7279 (setq param (js2-parse-destruct-primary-expr))
7280 (js2-define-destruct-symbols param
7281 js2-LP
7282 'js2-function-param)
7283 (push param params))
7284 ;; variable name
7285 (t
7286 (when (and (>= js2-language-version 200)
7287 (js2-match-token js2-TRIPLEDOT)
7288 (not rest-param-at))
7289 ;; to report errors if there are more parameters
7290 (setq rest-param-at (length params)))
7291 (js2-must-match js2-NAME "msg.no.parm")
7292 (js2-record-face 'js2-function-param)
7293 (setq param (js2-create-name-node))
7294 (js2-define-symbol js2-LP js2-ts-string param)
7295 ;; default parameter value
7296 (when (or (and default-found
7297 (not rest-param-at)
7298 (js2-must-match js2-ASSIGN
7299 "msg.no.default.after.default.param"
7300 (js2-node-pos param)
7301 (js2-node-len param)))
7302 (and (>= js2-language-version 200)
7303 (js2-match-token js2-ASSIGN)))
7304 (let* ((pos (js2-node-pos param))
7305 (tt js2-current-token)
7306 (op-pos (- js2-token-beg pos))
7307 (left param)
7308 (right (js2-parse-assign-expr))
7309 (len (- (js2-node-end right) pos)))
7310 (setq param (make-js2-assign-node
7311 :type tt :pos pos :len len :op-pos op-pos
7312 :left left :right right)
7313 default-found t)
7314 (js2-node-add-children param left right)))
7315 (push param params)))
7316 (when (and rest-param-at (> (length params) (1+ rest-param-at)))
7317 (js2-report-error "msg.param.after.rest" nil
7318 (js2-node-pos param) (js2-node-len param)))
7319 while
7320 (js2-match-token js2-COMMA))
7321 (when (js2-must-match js2-RP "msg.no.paren.after.parms")
7322 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7323 (when rest-param-at
7324 (setf (js2-function-node-rest-p fn-node) t))
7325 (dolist (p params)
7326 (js2-node-add-children fn-node p)
7327 (push p (js2-function-node-params fn-node))))))
7328
7329 (defun js2-check-inconsistent-return-warning (fn-node name)
7330 "Possibly show inconsistent-return warning.
7331 Last token scanned is the close-curly for the function body."
7332 (when (and js2-mode-show-strict-warnings
7333 js2-strict-inconsistent-return-warning
7334 (not (js2-has-consistent-return-usage
7335 (js2-function-node-body fn-node))))
7336 ;; Have it extend from close-curly to bol or beginning of block.
7337 (let ((pos (save-excursion
7338 (goto-char js2-token-end)
7339 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7340 (point-at-bol))))
7341 (end js2-token-end))
7342 (if (plusp (js2-name-node-length name))
7343 (js2-add-strict-warning "msg.no.return.value"
7344 (js2-name-node-name name) pos end)
7345 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7346
7347 (defun js2-parse-function (function-type)
7348 "Function parser. FUNCTION-TYPE is a symbol."
7349 (let ((pos js2-token-beg) ; start of 'function' keyword
7350 name name-beg name-end fn-node lp
7351 (synthetic-type function-type)
7352 member-expr-node)
7353 ;; parse function name, expression, or non-name (anonymous)
7354 (cond
7355 ;; function foo(...)
7356 ((js2-match-token js2-NAME)
7357 (setq name (js2-create-name-node t)
7358 name-beg js2-token-beg
7359 name-end js2-token-end)
7360 (unless (js2-match-token js2-LP)
7361 (when js2-allow-member-expr-as-function-name
7362 ;; function foo.bar(...)
7363 (setq member-expr-node name
7364 name nil
7365 member-expr-node (js2-parse-member-expr-tail
7366 nil member-expr-node)))
7367 (js2-must-match js2-LP "msg.no.paren.parms")))
7368 ((js2-match-token js2-LP)
7369 nil) ; anonymous function: leave name as null
7370 (t
7371 ;; function random-member-expr(...)
7372 (when js2-allow-member-expr-as-function-name
7373 ;; Note that memberExpr can not start with '(' like
7374 ;; in function (1+2).toString(), because 'function (' already
7375 ;; processed as anonymous function
7376 (setq member-expr-node (js2-parse-member-expr)))
7377 (js2-must-match js2-LP "msg.no.paren.parms")))
7378 (if (= js2-current-token js2-LP) ; eventually matched LP?
7379 (setq lp js2-token-beg))
7380 (if member-expr-node
7381 (progn
7382 (setq synthetic-type 'FUNCTION_EXPRESSION)
7383 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7384 (if name
7385 (js2-set-face name-beg name-end
7386 'font-lock-function-name-face 'record)))
7387 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7388 (plusp (js2-name-node-length name)))
7389 ;; Function statements define a symbol in the enclosing scope
7390 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7391 (setf fn-node (make-js2-function-node :pos pos
7392 :name name
7393 :form function-type
7394 :lp (if lp (- lp pos))))
7395 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7396 ;; 1. Nested functions are not affected by the dynamic scope flag
7397 ;; as dynamic scope is already a parent of their scope.
7398 ;; 2. Functions defined under the with statement also immune to
7399 ;; this setup, in which case dynamic scope is ignored in favor
7400 ;; of the with object.
7401 (setf (js2-function-node-ignore-dynamic fn-node) t))
7402 ;; dynamically bind all the per-function variables
7403 (let ((js2-current-script-or-fn fn-node)
7404 (js2-current-scope fn-node)
7405 (js2-nesting-of-with 0)
7406 (js2-end-flags 0)
7407 js2-label-set
7408 js2-loop-set
7409 js2-loop-and-switch-set)
7410 (js2-parse-function-params fn-node pos)
7411 (if (and (>= js2-language-version 180)
7412 (/= (js2-peek-token) js2-LC))
7413 (js2-parse-function-closure-body fn-node)
7414 (js2-parse-function-body fn-node))
7415 (if name
7416 (js2-node-add-children fn-node name))
7417 (js2-check-inconsistent-return-warning fn-node name)
7418 ;; Function expressions define a name only in the body of the
7419 ;; function, and only if not hidden by a parameter name
7420 (if (and name
7421 (eq synthetic-type 'FUNCTION_EXPRESSION)
7422 (null (js2-scope-get-symbol js2-current-scope
7423 (js2-name-node-name name))))
7424 (js2-define-symbol js2-FUNCTION
7425 (js2-name-node-name name)
7426 fn-node))
7427 (if (and name
7428 (not (eq function-type 'FUNCTION_EXPRESSION)))
7429 (js2-record-imenu-functions fn-node)))
7430 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7431 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7432 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7433 ;; We wait until after parsing the function to set its parent scope,
7434 ;; since `js2-define-symbol' needs the defining-scope check to stop
7435 ;; at the function boundary when checking for redeclarations.
7436 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7437 fn-node))
7438
7439 (defun js2-parse-statements (&optional parent)
7440 "Parse a statement list. Last token consumed must be js2-LC.
7441
7442 PARENT can be a `js2-block-node', in which case the statements are
7443 appended to PARENT. Otherwise a new `js2-block-node' is created
7444 and returned.
7445
7446 This function does not match the closing js2-RC: the caller
7447 matches the RC so it can provide a suitable error message if not
7448 matched. This means it's up to the caller to set the length of
7449 the node to include the closing RC. The node start pos is set to
7450 the absolute buffer start position, and the caller should fix it
7451 up to be relative to the parent node. All children of this block
7452 node are given relative start positions and correct lengths."
7453 (let ((pn (or parent (make-js2-block-node)))
7454 tt)
7455 (setf (js2-node-pos pn) js2-token-beg)
7456 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7457 (/= tt js2-RC))
7458 (js2-block-node-push pn (js2-parse-statement)))
7459 pn))
7460
7461 (defun js2-parse-statement ()
7462 (let (tt pn beg end)
7463 ;; coarse-grained user-interrupt check - needs work
7464 (and js2-parse-interruptable-p
7465 (zerop (% (incf js2-parse-stmt-count)
7466 js2-statements-per-pause))
7467 (input-pending-p)
7468 (throw 'interrupted t))
7469 (setq pn (js2-statement-helper))
7470 ;; no-side-effects warning check
7471 (unless (js2-node-has-side-effects pn)
7472 (setq end (js2-node-end pn))
7473 (save-excursion
7474 (goto-char end)
7475 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7476 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7477 pn))
7478
7479 ;; These correspond to the switch cases in Parser.statementHelper
7480 (defconst js2-parsers
7481 (let ((parsers (make-vector js2-num-tokens
7482 #'js2-parse-expr-stmt)))
7483 (aset parsers js2-BREAK #'js2-parse-break)
7484 (aset parsers js2-CONST #'js2-parse-const-var)
7485 (aset parsers js2-CONTINUE #'js2-parse-continue)
7486 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7487 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7488 (aset parsers js2-DO #'js2-parse-do)
7489 (aset parsers js2-FOR #'js2-parse-for)
7490 (aset parsers js2-FUNCTION #'js2-function-parser)
7491 (aset parsers js2-IF #'js2-parse-if)
7492 (aset parsers js2-LC #'js2-parse-block)
7493 (aset parsers js2-LET #'js2-parse-let-stmt)
7494 (aset parsers js2-NAME #'js2-parse-name-or-label)
7495 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7496 (aset parsers js2-SEMI #'js2-parse-semi)
7497 (aset parsers js2-SWITCH #'js2-parse-switch)
7498 (aset parsers js2-THROW #'js2-parse-throw)
7499 (aset parsers js2-TRY #'js2-parse-try)
7500 (aset parsers js2-VAR #'js2-parse-const-var)
7501 (aset parsers js2-WHILE #'js2-parse-while)
7502 (aset parsers js2-WITH #'js2-parse-with)
7503 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7504 parsers)
7505 "A vector mapping token types to parser functions.")
7506
7507 (defun js2-parse-warn-missing-semi (beg end)
7508 (and js2-mode-show-strict-warnings
7509 js2-strict-missing-semi-warning
7510 (js2-add-strict-warning
7511 "msg.missing.semi" nil
7512 ;; back up to beginning of statement or line
7513 (max beg (save-excursion
7514 (goto-char end)
7515 (point-at-bol)))
7516 end)))
7517
7518 (defconst js2-no-semi-insertion
7519 (list js2-IF
7520 js2-SWITCH
7521 js2-WHILE
7522 js2-DO
7523 js2-FOR
7524 js2-TRY
7525 js2-WITH
7526 js2-LC
7527 js2-ERROR
7528 js2-SEMI
7529 js2-FUNCTION)
7530 "List of tokens that don't do automatic semicolon insertion.")
7531
7532 (defconst js2-autoinsert-semi-and-warn
7533 (list js2-ERROR js2-EOF js2-RC))
7534
7535 (defun js2-statement-helper ()
7536 (let* ((tt (js2-peek-token))
7537 (first-tt tt)
7538 (beg js2-token-beg)
7539 (parser (if (= tt js2-ERROR)
7540 #'js2-parse-semi
7541 (aref js2-parsers tt)))
7542 pn
7543 tt-flagged)
7544 ;; If the statement is set, then it's been told its label by now.
7545 (and js2-labeled-stmt
7546 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7547 (setq js2-labeled-stmt nil))
7548 (setq pn (funcall parser))
7549 ;; Don't do auto semi insertion for certain statement types.
7550 (unless (or (memq first-tt js2-no-semi-insertion)
7551 (js2-labeled-stmt-node-p pn))
7552 (js2-auto-insert-semicolon pn))
7553 pn))
7554
7555 (defun js2-auto-insert-semicolon (pn)
7556 (let* ((tt-flagged (js2-peek-flagged-token))
7557 (tt (logand tt-flagged js2-clear-ti-mask))
7558 (pos (js2-node-pos pn)))
7559 (cond
7560 ((= tt js2-SEMI)
7561 ;; Consume ';' as a part of expression
7562 (js2-consume-token)
7563 ;; extend the node bounds to include the semicolon.
7564 (setf (js2-node-len pn) (- js2-token-end pos)))
7565 ((memq tt js2-autoinsert-semi-and-warn)
7566 ;; Autoinsert ;
7567 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7568 (t
7569 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7570 ;; Report error if no EOL or autoinsert ';' otherwise
7571 (js2-report-error "msg.no.semi.stmt")
7572 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7573
7574 (defun js2-parse-condition ()
7575 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7576 The parens are discarded and the expression node is returned.
7577 The `pos' field of the return value is set to an absolute position
7578 that must be fixed up by the caller.
7579 Return value is a list (EXPR LP RP), with absolute paren positions."
7580 (let (pn lp rp)
7581 (if (js2-must-match js2-LP "msg.no.paren.cond")
7582 (setq lp js2-token-beg))
7583 (setq pn (js2-parse-expr))
7584 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7585 (setq rp js2-token-beg))
7586 ;; Report strict warning on code like "if (a = 7) ..."
7587 (if (and js2-strict-cond-assign-warning
7588 (js2-assign-node-p pn))
7589 (js2-add-strict-warning "msg.equal.as.assign" nil
7590 (js2-node-pos pn)
7591 (+ (js2-node-pos pn)
7592 (js2-node-len pn))))
7593 (list pn lp rp)))
7594
7595 (defun js2-parse-if ()
7596 "Parser for if-statement. Last matched token must be js2-IF."
7597 (let ((pos js2-token-beg)
7598 cond if-true if-false else-pos end pn)
7599 (js2-consume-token)
7600 (setq cond (js2-parse-condition)
7601 if-true (js2-parse-statement)
7602 if-false (if (js2-match-token js2-ELSE)
7603 (progn
7604 (setq else-pos (- js2-token-beg pos))
7605 (js2-parse-statement)))
7606 end (js2-node-end (or if-false if-true))
7607 pn (make-js2-if-node :pos pos
7608 :len (- end pos)
7609 :condition (car cond)
7610 :then-part if-true
7611 :else-part if-false
7612 :else-pos else-pos
7613 :lp (js2-relpos (second cond) pos)
7614 :rp (js2-relpos (third cond) pos)))
7615 (js2-node-add-children pn (car cond) if-true if-false)
7616 pn))
7617
7618 (defun js2-parse-switch ()
7619 "Parser for if-statement. Last matched token must be js2-SWITCH."
7620 (let ((pos js2-token-beg)
7621 tt pn discriminant has-default case-expr case-node
7622 case-pos cases stmt lp rp)
7623 (js2-consume-token)
7624 (if (js2-must-match js2-LP "msg.no.paren.switch")
7625 (setq lp js2-token-beg))
7626 (setq discriminant (js2-parse-expr)
7627 pn (make-js2-switch-node :discriminant discriminant
7628 :pos pos
7629 :lp (js2-relpos lp pos)))
7630 (js2-node-add-children pn discriminant)
7631 (js2-enter-switch pn)
7632 (unwind-protect
7633 (progn
7634 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7635 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7636 (js2-must-match js2-LC "msg.no.brace.switch")
7637 (catch 'break
7638 (while t
7639 (setq tt (js2-next-token)
7640 case-pos js2-token-beg)
7641 (cond
7642 ((= tt js2-RC)
7643 (setf (js2-node-len pn) (- js2-token-end pos))
7644 (throw 'break nil)) ; done
7645 ((= tt js2-CASE)
7646 (setq case-expr (js2-parse-expr))
7647 (js2-must-match js2-COLON "msg.no.colon.case"))
7648 ((= tt js2-DEFAULT)
7649 (if has-default
7650 (js2-report-error "msg.double.switch.default"))
7651 (setq has-default t
7652 case-expr nil)
7653 (js2-must-match js2-COLON "msg.no.colon.case"))
7654 (t
7655 (js2-report-error "msg.bad.switch")
7656 (throw 'break nil)))
7657 (setq case-node (make-js2-case-node :pos case-pos
7658 :len (- js2-token-end case-pos)
7659 :expr case-expr))
7660 (js2-node-add-children case-node case-expr)
7661 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7662 (/= tt js2-CASE)
7663 (/= tt js2-DEFAULT)
7664 (/= tt js2-EOF))
7665 (setf stmt (js2-parse-statement)
7666 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7667 (js2-block-node-push case-node stmt))
7668 (push case-node cases)))
7669 ;; add cases last, as pushing reverses the order to be correct
7670 (dolist (kid cases)
7671 (js2-node-add-children pn kid)
7672 (push kid (js2-switch-node-cases pn)))
7673 pn) ; return value
7674 (js2-exit-switch))))
7675
7676 (defun js2-parse-while ()
7677 "Parser for while-statement. Last matched token must be js2-WHILE."
7678 (let ((pos js2-token-beg)
7679 (pn (make-js2-while-node))
7680 cond body)
7681 (js2-consume-token)
7682 (js2-enter-loop pn)
7683 (unwind-protect
7684 (progn
7685 (setf cond (js2-parse-condition)
7686 (js2-while-node-condition pn) (car cond)
7687 body (js2-parse-statement)
7688 (js2-while-node-body pn) body
7689 (js2-node-len pn) (- (js2-node-end body) pos)
7690 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7691 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7692 (js2-node-add-children pn body (car cond)))
7693 (js2-exit-loop))
7694 pn))
7695
7696 (defun js2-parse-do ()
7697 "Parser for do-statement. Last matched token must be js2-DO."
7698 (let ((pos js2-token-beg)
7699 (pn (make-js2-do-node))
7700 cond body end)
7701 (js2-consume-token)
7702 (js2-enter-loop pn)
7703 (unwind-protect
7704 (progn
7705 (setq body (js2-parse-statement))
7706 (js2-must-match js2-WHILE "msg.no.while.do")
7707 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7708 cond (js2-parse-condition)
7709 (js2-do-node-condition pn) (car cond)
7710 (js2-do-node-body pn) body
7711 end js2-ts-cursor
7712 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7713 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7714 (js2-node-add-children pn (car cond) body))
7715 (js2-exit-loop))
7716 ;; Always auto-insert semicolon to follow SpiderMonkey:
7717 ;; It is required by ECMAScript but is ignored by the rest of
7718 ;; world; see bug 238945
7719 (if (js2-match-token js2-SEMI)
7720 (setq end js2-ts-cursor))
7721 (setf (js2-node-len pn) (- end pos))
7722 pn))
7723
7724 (defun js2-parse-for ()
7725 "Parser for for-statement. Last matched token must be js2-FOR.
7726 Parses for, for-in, and for each-in statements."
7727 (let ((for-pos js2-token-beg)
7728 pn is-for-each is-for-in-or-of is-for-of
7729 in-pos each-pos tmp-pos
7730 init ; Node init is also foo in 'foo in object'
7731 cond ; Node cond is also object in 'foo in object'
7732 incr ; 3rd section of for-loop initializer
7733 body tt lp rp)
7734 (js2-consume-token)
7735 ;; See if this is a for each () instead of just a for ()
7736 (when (js2-match-token js2-NAME)
7737 (if (string= "each" js2-ts-string)
7738 (progn
7739 (setq is-for-each t
7740 each-pos (- js2-token-beg for-pos)) ; relative
7741 (js2-record-face 'font-lock-keyword-face))
7742 (js2-report-error "msg.no.paren.for")))
7743 (if (js2-must-match js2-LP "msg.no.paren.for")
7744 (setq lp (- js2-token-beg for-pos)))
7745 (setq tt (js2-peek-token))
7746 ;; 'for' makes local scope
7747 (js2-push-scope (make-js2-scope))
7748 (unwind-protect
7749 ;; parse init clause
7750 (let ((js2-in-for-init t)) ; set as dynamic variable
7751 (cond
7752 ((= tt js2-SEMI)
7753 (setq init (make-js2-empty-expr-node)))
7754 ((or (= tt js2-VAR) (= tt js2-LET))
7755 (js2-consume-token)
7756 (setq init (js2-parse-variables tt js2-token-beg)))
7757 (t
7758 (setq init (js2-parse-expr)))))
7759 (if (or (js2-match-token js2-IN)
7760 (and (>= js2-language-version 200)
7761 (js2-match-contextual-kwd "of")
7762 (setq is-for-of t)))
7763 (setq is-for-in-or-of t
7764 in-pos (- js2-token-beg for-pos)
7765 ;; scope of iteration target object is not the scope we've created above.
7766 ;; stash current scope temporary.
7767 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7768 (js2-parse-expr))) ; object over which we're iterating
7769 ;; else ordinary for loop - parse cond and incr
7770 (js2-must-match js2-SEMI "msg.no.semi.for")
7771 (setq cond (if (= (js2-peek-token) js2-SEMI)
7772 (make-js2-empty-expr-node) ; no loop condition
7773 (js2-parse-expr)))
7774 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7775 (setq tmp-pos js2-token-end
7776 incr (if (= (js2-peek-token) js2-RP)
7777 (make-js2-empty-expr-node :pos tmp-pos)
7778 (js2-parse-expr))))
7779 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7780 (setq rp (- js2-token-beg for-pos)))
7781 (if (not is-for-in-or-of)
7782 (setq pn (make-js2-for-node :init init
7783 :condition cond
7784 :update incr
7785 :lp lp
7786 :rp rp))
7787 ;; cond could be null if 'in obj' got eaten by the init node.
7788 (if (js2-infix-node-p init)
7789 ;; it was (foo in bar) instead of (var foo in bar)
7790 (setq cond (js2-infix-node-right init)
7791 init (js2-infix-node-left init))
7792 (if (and (js2-var-decl-node-p init)
7793 (> (length (js2-var-decl-node-kids init)) 1))
7794 (js2-report-error "msg.mult.index")))
7795 (setq pn (make-js2-for-in-node :iterator init
7796 :object cond
7797 :in-pos in-pos
7798 :foreach-p is-for-each
7799 :each-pos each-pos
7800 :forof-p is-for-of
7801 :lp lp
7802 :rp rp)))
7803 (unwind-protect
7804 (progn
7805 (js2-enter-loop pn)
7806 ;; We have to parse the body -after- creating the loop node,
7807 ;; so that the loop node appears in the js2-loop-set, allowing
7808 ;; break/continue statements to find the enclosing loop.
7809 (setf body (js2-parse-statement)
7810 (js2-loop-node-body pn) body
7811 (js2-node-pos pn) for-pos
7812 (js2-node-len pn) (- (js2-node-end body) for-pos))
7813 (js2-node-add-children pn init cond incr body))
7814 ;; finally
7815 (js2-exit-loop))
7816 (js2-pop-scope))
7817 pn))
7818
7819 (defun js2-parse-try ()
7820 "Parser for try-statement. Last matched token must be js2-TRY."
7821 (let ((try-pos js2-token-beg)
7822 try-end
7823 try-block
7824 catch-blocks
7825 finally-block
7826 saw-default-catch
7827 peek
7828 param
7829 catch-cond
7830 catch-node
7831 guard-kwd
7832 catch-pos
7833 finally-pos
7834 pn
7835 block
7836 lp
7837 rp)
7838 (js2-consume-token)
7839 (if (/= (js2-peek-token) js2-LC)
7840 (js2-report-error "msg.no.brace.try"))
7841 (setq try-block (js2-parse-statement)
7842 try-end (js2-node-end try-block)
7843 peek (js2-peek-token))
7844 (cond
7845 ((= peek js2-CATCH)
7846 (while (js2-match-token js2-CATCH)
7847 (setq catch-pos js2-token-beg
7848 guard-kwd nil
7849 catch-cond nil
7850 lp nil
7851 rp nil)
7852 (if saw-default-catch
7853 (js2-report-error "msg.catch.unreachable"))
7854 (if (js2-must-match js2-LP "msg.no.paren.catch")
7855 (setq lp (- js2-token-beg catch-pos)))
7856 (js2-push-scope (make-js2-scope))
7857 (let ((tt (js2-peek-token)))
7858 (cond
7859 ;; destructuring pattern
7860 ;; catch ({ message, file }) { ... }
7861 ((or (= tt js2-LB) (= tt js2-LC))
7862 (setq param (js2-parse-destruct-primary-expr))
7863 (js2-define-destruct-symbols param js2-LET nil))
7864 ;; simple name
7865 (t
7866 (js2-must-match js2-NAME "msg.bad.catchcond")
7867 (setq param (js2-create-name-node))
7868 (js2-define-symbol js2-LET js2-ts-string param))))
7869 ;; pattern guard
7870 (if (js2-match-token js2-IF)
7871 (setq guard-kwd (- js2-token-beg catch-pos)
7872 catch-cond (js2-parse-expr))
7873 (setq saw-default-catch t))
7874 (if (js2-must-match js2-RP "msg.bad.catchcond")
7875 (setq rp (- js2-token-beg catch-pos)))
7876 (js2-must-match js2-LC "msg.no.brace.catchblock")
7877 (setq block (js2-parse-statements)
7878 try-end (js2-node-end block)
7879 catch-node (make-js2-catch-node :pos catch-pos
7880 :param param
7881 :guard-expr catch-cond
7882 :guard-kwd guard-kwd
7883 :block block
7884 :lp lp
7885 :rp rp))
7886 (js2-pop-scope)
7887 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7888 (setq try-end js2-token-beg))
7889 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7890 (js2-node-len catch-node) (- try-end catch-pos))
7891 (js2-node-add-children catch-node param catch-cond block)
7892 (push catch-node catch-blocks)))
7893 ((/= peek js2-FINALLY)
7894 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7895 (js2-node-pos try-block)
7896 (- (setq try-end (js2-node-end try-block))
7897 (js2-node-pos try-block)))))
7898 (when (js2-match-token js2-FINALLY)
7899 (setq finally-pos js2-token-beg
7900 block (js2-parse-statement)
7901 try-end (js2-node-end block)
7902 finally-block (make-js2-finally-node :pos finally-pos
7903 :len (- try-end finally-pos)
7904 :body block))
7905 (js2-node-add-children finally-block block))
7906 (setq pn (make-js2-try-node :pos try-pos
7907 :len (- try-end try-pos)
7908 :try-block try-block
7909 :finally-block finally-block))
7910 (js2-node-add-children pn try-block finally-block)
7911 ;; push them onto the try-node, which reverses and corrects their order
7912 (dolist (cb catch-blocks)
7913 (js2-node-add-children pn cb)
7914 (push cb (js2-try-node-catch-clauses pn)))
7915 pn))
7916
7917 (defun js2-parse-throw ()
7918 "Parser for throw-statement. Last matched token must be js2-THROW."
7919 (let ((pos js2-token-beg)
7920 expr pn)
7921 (js2-consume-token)
7922 (if (= (js2-peek-token-or-eol) js2-EOL)
7923 ;; ECMAScript does not allow new lines before throw expression,
7924 ;; see bug 256617
7925 (js2-report-error "msg.bad.throw.eol"))
7926 (setq expr (js2-parse-expr)
7927 pn (make-js2-throw-node :pos pos
7928 :len (- (js2-node-end expr) pos)
7929 :expr expr))
7930 (js2-node-add-children pn expr)
7931 pn))
7932
7933 (defun js2-match-jump-label-name (label-name)
7934 "If break/continue specified a label, return that label's labeled stmt.
7935 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7936 does not match an existing label, reports an error and returns nil."
7937 (let ((bundle (cdr (assoc label-name js2-label-set))))
7938 (if (null bundle)
7939 (js2-report-error "msg.undef.label"))
7940 bundle))
7941
7942 (defun js2-parse-break ()
7943 "Parser for break-statement. Last matched token must be js2-BREAK."
7944 (let ((pos js2-token-beg)
7945 (end js2-token-end)
7946 break-target ; statement to break from
7947 break-label ; in "break foo", name-node representing the foo
7948 labels ; matching labeled statement to break to
7949 pn)
7950 (js2-consume-token) ; `break'
7951 (when (eq (js2-peek-token-or-eol) js2-NAME)
7952 (js2-consume-token)
7953 (setq break-label (js2-create-name-node)
7954 end (js2-node-end break-label)
7955 ;; matchJumpLabelName only matches if there is one
7956 labels (js2-match-jump-label-name js2-ts-string)
7957 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7958 (unless (or break-target break-label)
7959 ;; no break target specified - try for innermost enclosing loop/switch
7960 (if (null js2-loop-and-switch-set)
7961 (unless break-label
7962 (js2-report-error "msg.bad.break" nil pos (length "break")))
7963 (setq break-target (car js2-loop-and-switch-set))))
7964 (setq pn (make-js2-break-node :pos pos
7965 :len (- end pos)
7966 :label break-label
7967 :target break-target))
7968 (js2-node-add-children pn break-label) ; but not break-target
7969 pn))
7970
7971 (defun js2-parse-continue ()
7972 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7973 (let ((pos js2-token-beg)
7974 (end js2-token-end)
7975 label ; optional user-specified label, a `js2-name-node'
7976 labels ; current matching labeled stmt, if any
7977 target ; the `js2-loop-node' target of this continue stmt
7978 pn)
7979 (js2-consume-token) ; `continue'
7980 (when (= (js2-peek-token-or-eol) js2-NAME)
7981 (js2-consume-token)
7982 (setq label (js2-create-name-node)
7983 end (js2-node-end label)
7984 ;; matchJumpLabelName only matches if there is one
7985 labels (js2-match-jump-label-name js2-ts-string)))
7986 (cond
7987 ((null labels) ; no current label to go to
7988 (if (null js2-loop-set) ; no loop to continue to
7989 (js2-report-error "msg.continue.outside" nil pos
7990 (length "continue"))
7991 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7992 (t
7993 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7994 (setq target (js2-labeled-stmt-node-stmt labels))
7995 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7996 (setq pn (make-js2-continue-node :pos pos
7997 :len (- end pos)
7998 :label label
7999 :target target))
8000 (js2-node-add-children pn label) ; but not target - it's not our child
8001 pn))
8002
8003 (defun js2-parse-with ()
8004 "Parser for with-statement. Last matched token must be js2-WITH."
8005 (js2-consume-token)
8006 (let ((pos js2-token-beg)
8007 obj body pn lp rp)
8008 (if (js2-must-match js2-LP "msg.no.paren.with")
8009 (setq lp js2-token-beg))
8010 (setq obj (js2-parse-expr))
8011 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8012 (setq rp js2-token-beg))
8013 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8014 (setq body (js2-parse-statement)))
8015 (setq pn (make-js2-with-node :pos pos
8016 :len (- (js2-node-end body) pos)
8017 :object obj
8018 :body body
8019 :lp (js2-relpos lp pos)
8020 :rp (js2-relpos rp pos)))
8021 (js2-node-add-children pn obj body)
8022 pn))
8023
8024 (defun js2-parse-const-var ()
8025 "Parser for var- or const-statement.
8026 Last matched token must be js2-CONST or js2-VAR."
8027 (let ((tt (js2-peek-token))
8028 (pos js2-token-beg)
8029 expr pn)
8030 (js2-consume-token)
8031 (setq expr (js2-parse-variables tt js2-token-beg)
8032 pn (make-js2-expr-stmt-node :pos pos
8033 :len (- (js2-node-end expr) pos)
8034 :expr expr))
8035 (js2-node-add-children pn expr)
8036 pn))
8037
8038 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8039 (let ((pn (make-js2-expr-stmt-node :pos pos
8040 :len (js2-node-len expr)
8041 :type (if (js2-inside-function)
8042 js2-EXPR_VOID
8043 js2-EXPR_RESULT)
8044 :expr expr)))
8045 (if add-child
8046 (js2-node-add-children pn expr))
8047 pn))
8048
8049 (defun js2-parse-let-stmt ()
8050 "Parser for let-statement. Last matched token must be js2-LET."
8051 (js2-consume-token)
8052 (let ((pos js2-token-beg)
8053 expr pn)
8054 (if (= (js2-peek-token) js2-LP)
8055 ;; let expression in statement context
8056 (setq expr (js2-parse-let pos 'statement)
8057 pn (js2-wrap-with-expr-stmt pos expr t))
8058 ;; else we're looking at a statement like let x=6, y=7;
8059 (setf expr (js2-parse-variables js2-LET pos)
8060 pn (js2-wrap-with-expr-stmt pos expr t)
8061 (js2-node-type pn) js2-EXPR_RESULT))
8062 pn))
8063
8064 (defun js2-parse-ret-yield ()
8065 (js2-parse-return-or-yield (js2-peek-token) nil))
8066
8067 (defconst js2-parse-return-stmt-enders
8068 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8069
8070 (defsubst js2-now-all-set (before after mask)
8071 "Return whether or not the bits in the mask have changed to all set.
8072 BEFORE is bits before change, AFTER is bits after change, and MASK is
8073 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8074 but not BEFORE."
8075 (and (/= (logand before mask) mask)
8076 (= (logand after mask) mask)))
8077
8078 (defun js2-parse-return-or-yield (tt expr-context)
8079 (let ((pos js2-token-beg)
8080 (end js2-token-end)
8081 (before js2-end-flags)
8082 (inside-function (js2-inside-function))
8083 e ret name)
8084 (unless inside-function
8085 (js2-report-error (if (eq tt js2-RETURN)
8086 "msg.bad.return"
8087 "msg.bad.yield")))
8088 (js2-consume-token)
8089 ;; This is ugly, but we don't want to require a semicolon.
8090 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8091 (setq e (js2-parse-expr)
8092 end (js2-node-end e)))
8093 (cond
8094 ((eq tt js2-RETURN)
8095 (js2-set-flag js2-end-flags (if (null e)
8096 js2-end-returns
8097 js2-end-returns-value))
8098 (setq ret (make-js2-return-node :pos pos
8099 :len (- end pos)
8100 :retval e))
8101 (js2-node-add-children ret e)
8102 ;; See if we need a strict mode warning.
8103 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8104 ;; more thorough and accurate than this before/after flag check.
8105 ;; E.g. if there's a finally-block that always returns, we shouldn't
8106 ;; show a warning generated by inconsistent returns in the catch blocks.
8107 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8108 ;; so we know which returns/yields to highlight, and we should get rid of
8109 ;; all the checking in `js2-parse-return-or-yield'.
8110 (if (and js2-strict-inconsistent-return-warning
8111 (js2-now-all-set before js2-end-flags
8112 (logior js2-end-returns js2-end-returns-value)))
8113 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8114 (t
8115 (unless (js2-inside-function)
8116 (js2-report-error "msg.bad.yield"))
8117 (js2-set-flag js2-end-flags js2-end-yields)
8118 (setq ret (make-js2-yield-node :pos pos
8119 :len (- end pos)
8120 :value e))
8121 (js2-node-add-children ret e)
8122 (unless expr-context
8123 (setq e ret
8124 ret (js2-wrap-with-expr-stmt pos e t))
8125 (js2-set-requires-activation)
8126 (js2-set-is-generator))))
8127 ;; see if we are mixing yields and value returns.
8128 (when (and inside-function
8129 (js2-now-all-set before js2-end-flags
8130 (logior js2-end-yields js2-end-returns-value)))
8131 (setq name (js2-function-name js2-current-script-or-fn))
8132 (if (zerop (length name))
8133 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8134 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8135 ret))
8136
8137 (defun js2-parse-debugger ()
8138 (js2-consume-token)
8139 (make-js2-keyword-node :type js2-DEBUGGER))
8140
8141 (defun js2-parse-block ()
8142 "Parser for a curly-delimited statement block.
8143 Last token matched must be `js2-LC'."
8144 (let ((pos js2-token-beg)
8145 (pn (make-js2-scope)))
8146 (js2-consume-token)
8147 (js2-push-scope pn)
8148 (unwind-protect
8149 (progn
8150 (js2-parse-statements pn)
8151 (js2-must-match js2-RC "msg.no.brace.block")
8152 (setf (js2-node-len pn) (- js2-token-end pos)))
8153 (js2-pop-scope))
8154 pn))
8155
8156 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8157 (defun js2-parse-semi ()
8158 "Parse a statement or handle an error.
8159 Last matched token is `js2-SEMI' or `js2-ERROR'."
8160 (let ((tt (js2-peek-token)) pos len)
8161 (js2-consume-token)
8162 (if (eq tt js2-SEMI)
8163 (make-js2-empty-expr-node :len 1)
8164 (setq pos js2-token-beg
8165 len (- js2-token-beg pos))
8166 (js2-report-error "msg.syntax" nil pos len)
8167 (make-js2-error-node :pos pos :len len))))
8168
8169 (defun js2-parse-default-xml-namespace ()
8170 "Parse a `default xml namespace = <expr>' e4x statement."
8171 (let ((pos js2-token-beg)
8172 end len expr unary es)
8173 (js2-consume-token)
8174 (js2-must-have-xml)
8175 (js2-set-requires-activation)
8176 (setq len (- js2-ts-cursor pos))
8177 (unless (and (js2-match-token js2-NAME)
8178 (string= js2-ts-string "xml"))
8179 (js2-report-error "msg.bad.namespace" nil pos len))
8180 (unless (and (js2-match-token js2-NAME)
8181 (string= js2-ts-string "namespace"))
8182 (js2-report-error "msg.bad.namespace" nil pos len))
8183 (unless (js2-match-token js2-ASSIGN)
8184 (js2-report-error "msg.bad.namespace" nil pos len))
8185 (setq expr (js2-parse-expr)
8186 end (js2-node-end expr)
8187 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8188 :pos pos
8189 :len (- end pos)
8190 :operand expr))
8191 (js2-node-add-children unary expr)
8192 (make-js2-expr-stmt-node :pos pos
8193 :len (- end pos)
8194 :expr unary)))
8195
8196 (defun js2-record-label (label bundle)
8197 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8198 (js2-consume-token)
8199 (let ((name (js2-label-node-name label))
8200 labeled-stmt
8201 dup)
8202 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8203 ;; flag both labels if possible when used in editing mode
8204 (if (and js2-parse-ide-mode
8205 (setq dup (js2-get-label-by-name labeled-stmt name)))
8206 (js2-report-error "msg.dup.label" nil
8207 (js2-node-abs-pos dup) (js2-node-len dup)))
8208 (js2-report-error "msg.dup.label" nil
8209 (js2-node-pos label) (js2-node-len label)))
8210 (js2-labeled-stmt-node-add-label bundle label)
8211 (js2-node-add-children bundle label)
8212 ;; Add one reference to the bundle per label in `js2-label-set'
8213 (push (cons name bundle) js2-label-set)))
8214
8215 (defun js2-parse-name-or-label ()
8216 "Parser for identifier or label. Last token matched must be js2-NAME.
8217 Called when we found a name in a statement context. If it's a label, we gather
8218 up any following labels and the next non-label statement into a
8219 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8220 expression and return it wrapped in a `js2-expr-stmt-node'."
8221 (let ((pos js2-token-beg)
8222 (end js2-token-end)
8223 expr stmt pn bundle
8224 (continue t))
8225 ;; set check for label and call down to `js2-parse-primary-expr'
8226 (js2-set-check-for-label)
8227 (setq expr (js2-parse-expr))
8228 (if (/= (js2-node-type expr) js2-LABEL)
8229 ;; Parsed non-label expression - wrap with expression stmt.
8230 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8231 ;; else parsed a label
8232 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8233 (js2-record-label expr bundle)
8234 ;; look for more labels
8235 (while (and continue (= (js2-peek-token) js2-NAME))
8236 (js2-set-check-for-label)
8237 (setq expr (js2-parse-expr))
8238 (if (/= (js2-node-type expr) js2-LABEL)
8239 (progn
8240 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8241 continue nil)
8242 (js2-auto-insert-semicolon stmt))
8243 (js2-record-label expr bundle)))
8244 ;; no more labels; now parse the labeled statement
8245 (unwind-protect
8246 (unless stmt
8247 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8248 (setq stmt (js2-statement-helper))))
8249 ;; remove the labels for this statement from the global set
8250 (dolist (label (js2-labeled-stmt-node-labels bundle))
8251 (setq js2-label-set (remove label js2-label-set))))
8252 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8253 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8254 (js2-node-add-children bundle stmt)
8255 bundle)))
8256
8257 (defun js2-parse-expr-stmt ()
8258 "Default parser in statement context, if no recognized statement found."
8259 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8260
8261 (defun js2-parse-variables (decl-type pos)
8262 "Parse a comma-separated list of variable declarations.
8263 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8264
8265 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8266 For 'var' or 'const', the keyword should be the token last scanned.
8267
8268 POS is the position where the node should start. It's sometimes the
8269 var/const/let keyword, and other times the beginning of the first token
8270 in the first variable declaration.
8271
8272 Returns the parsed `js2-var-decl-node' expression node."
8273 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8274 :pos pos))
8275 destructuring kid-pos tt init name end nbeg nend vi
8276 (continue t))
8277 ;; Example:
8278 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8279 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8280 ;; var {a, b} = baz;
8281 (while continue
8282 (setq destructuring nil
8283 name nil
8284 tt (js2-peek-token)
8285 kid-pos js2-token-beg
8286 end js2-token-end
8287 init nil)
8288 (if (or (= tt js2-LB) (= tt js2-LC))
8289 ;; Destructuring assignment, e.g., var [a, b] = ...
8290 (setq destructuring (js2-parse-destruct-primary-expr)
8291 end (js2-node-end destructuring))
8292 ;; Simple variable name
8293 (when (js2-must-match js2-NAME "msg.bad.var")
8294 (setq name (js2-create-name-node)
8295 nbeg js2-token-beg
8296 nend js2-token-end
8297 end nend)
8298 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8299 (when (js2-match-token js2-ASSIGN)
8300 (setq init (js2-parse-assign-expr)
8301 end (js2-node-end init))
8302 (js2-record-imenu-functions init name))
8303 (when name
8304 (js2-set-face nbeg nend (if (js2-function-node-p init)
8305 'font-lock-function-name-face
8306 'font-lock-variable-name-face)
8307 'record))
8308 (setq vi (make-js2-var-init-node :pos kid-pos
8309 :len (- end kid-pos)
8310 :type decl-type))
8311 (if destructuring
8312 (progn
8313 (if (and (null init) (not js2-in-for-init))
8314 (js2-report-error "msg.destruct.assign.no.init"))
8315 (js2-define-destruct-symbols destructuring
8316 decl-type
8317 'font-lock-variable-name-face)
8318 (setf (js2-var-init-node-target vi) destructuring))
8319 (setf (js2-var-init-node-target vi) name))
8320 (setf (js2-var-init-node-initializer vi) init)
8321 (js2-node-add-children vi name destructuring init)
8322 (js2-block-node-push result vi)
8323 (unless (js2-match-token js2-COMMA)
8324 (setq continue nil)))
8325 (setf (js2-node-len result) (- end pos))
8326 result))
8327
8328 (defun js2-parse-let (pos &optional stmt-p)
8329 "Parse a let expression or statement.
8330 A let-expression is of the form `let (vars) expr'.
8331 A let-statment is of the form `let (vars) {statements}'.
8332 The third form of let is a variable declaration list, handled
8333 by `js2-parse-variables'."
8334 (let ((pn (make-js2-let-node :pos pos))
8335 beg vars body)
8336 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8337 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8338 (js2-push-scope pn)
8339 (unwind-protect
8340 (progn
8341 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8342 (if (js2-must-match js2-RP "msg.no.paren.let")
8343 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8344 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8345 ;; let statement
8346 (progn
8347 (js2-consume-token)
8348 (setf beg js2-token-beg ; position stmt at LC
8349 body (js2-parse-statements))
8350 (js2-must-match js2-RC "msg.no.curly.let")
8351 (setf (js2-node-len body) (- js2-token-end beg)
8352 (js2-node-len pn) (- js2-token-end pos)
8353 (js2-let-node-body pn) body
8354 (js2-node-type pn) js2-LET))
8355 ;; let expression
8356 (setf body (js2-parse-expr)
8357 (js2-node-len pn) (- (js2-node-end body) pos)
8358 (js2-let-node-body pn) body))
8359 (js2-node-add-children pn vars body))
8360 (js2-pop-scope))
8361 pn))
8362
8363 (defun js2-define-new-symbol (decl-type name node &optional scope)
8364 (js2-scope-put-symbol (or scope js2-current-scope)
8365 name
8366 (make-js2-symbol decl-type name node)))
8367
8368 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8369 "Define a symbol in the current scope.
8370 If NODE is non-nil, it is the AST node associated with the symbol."
8371 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8372 (symbol (if defining-scope
8373 (js2-scope-get-symbol defining-scope name)))
8374 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8375 (cond
8376 ((and symbol ; already defined
8377 (or (= sdt js2-CONST) ; old version is const
8378 (= decl-type js2-CONST) ; new version is const
8379 ;; two let-bound vars in this block have same name
8380 (and (= sdt js2-LET)
8381 (eq defining-scope js2-current-scope))))
8382 (js2-report-error
8383 (cond
8384 ((= sdt js2-CONST) "msg.const.redecl")
8385 ((= sdt js2-LET) "msg.let.redecl")
8386 ((= sdt js2-VAR) "msg.var.redecl")
8387 ((= sdt js2-FUNCTION) "msg.function.redecl")
8388 (t "msg.parm.redecl"))
8389 name))
8390 ((= decl-type js2-LET)
8391 (if (and (not ignore-not-in-block)
8392 (or (= (js2-node-type js2-current-scope) js2-IF)
8393 (js2-loop-node-p js2-current-scope)))
8394 (js2-report-error "msg.let.decl.not.in.block")
8395 (js2-define-new-symbol decl-type name node)))
8396 ((or (= decl-type js2-VAR)
8397 (= decl-type js2-CONST)
8398 (= decl-type js2-FUNCTION))
8399 (if symbol
8400 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8401 (js2-add-strict-warning "msg.var.redecl" name)
8402 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8403 (js2-add-strict-warning "msg.var.hides.arg" name)))
8404 (js2-define-new-symbol decl-type name node
8405 js2-current-script-or-fn)))
8406 ((= decl-type js2-LP)
8407 (if symbol
8408 ;; must be duplicate parameter. Second parameter hides the
8409 ;; first, so go ahead and add the second pararameter
8410 (js2-report-warning "msg.dup.parms" name))
8411 (js2-define-new-symbol decl-type name node))
8412 (t (js2-code-bug)))))
8413
8414 (defun js2-parse-expr (&optional oneshot)
8415 (let* ((pn (js2-parse-assign-expr))
8416 (pos (js2-node-pos pn))
8417 left
8418 right
8419 op-pos)
8420 (while (and (not oneshot)
8421 (js2-match-token js2-COMMA))
8422 (setq op-pos (- js2-token-beg pos)) ; relative
8423 (if (= (js2-peek-token) js2-YIELD)
8424 (js2-report-error "msg.yield.parenthesized"))
8425 (setq right (js2-parse-assign-expr)
8426 left pn
8427 pn (make-js2-infix-node :type js2-COMMA
8428 :pos pos
8429 :len (- js2-ts-cursor pos)
8430 :op-pos op-pos
8431 :left left
8432 :right right))
8433 (js2-node-add-children pn left right))
8434 pn))
8435
8436 (defun js2-parse-assign-expr ()
8437 (let ((tt (js2-peek-token))
8438 (pos js2-token-beg)
8439 pn left right op-pos)
8440 (if (= tt js2-YIELD)
8441 (js2-parse-return-or-yield tt t)
8442 ;; not yield - parse assignment expression
8443 (setq pn (js2-parse-cond-expr)
8444 tt (js2-peek-token))
8445 (when (and (<= js2-first-assign tt)
8446 (<= tt js2-last-assign))
8447 ;; tt express assignment (=, |=, ^=, ..., %=)
8448 (js2-consume-token)
8449 (setq op-pos (- js2-token-beg pos) ; relative
8450 left pn
8451 right (js2-parse-assign-expr)
8452 pn (make-js2-assign-node :type tt
8453 :pos pos
8454 :len (- (js2-node-end right) pos)
8455 :op-pos op-pos
8456 :left left
8457 :right right))
8458 (when js2-parse-ide-mode
8459 (js2-highlight-assign-targets pn left right)
8460 (js2-record-imenu-functions right left))
8461 ;; do this last so ide checks above can use absolute positions
8462 (js2-node-add-children pn left right))
8463 pn)))
8464
8465 (defun js2-parse-cond-expr ()
8466 (let ((pos js2-token-beg)
8467 (pn (js2-parse-or-expr))
8468 test-expr
8469 if-true
8470 if-false
8471 q-pos
8472 c-pos)
8473 (when (js2-match-token js2-HOOK)
8474 (setq q-pos (- js2-token-beg pos)
8475 if-true (js2-parse-assign-expr))
8476 (js2-must-match js2-COLON "msg.no.colon.cond")
8477 (setq c-pos (- js2-token-beg pos)
8478 if-false (js2-parse-assign-expr)
8479 test-expr pn
8480 pn (make-js2-cond-node :pos pos
8481 :len (- (js2-node-end if-false) pos)
8482 :test-expr test-expr
8483 :true-expr if-true
8484 :false-expr if-false
8485 :q-pos q-pos
8486 :c-pos c-pos))
8487 (js2-node-add-children pn test-expr if-true if-false))
8488 pn))
8489
8490 (defun js2-make-binary (type left parser)
8491 "Helper for constructing a binary-operator AST node.
8492 LEFT is the left-side-expression, already parsed, and the
8493 binary operator should have just been matched.
8494 PARSER is a function to call to parse the right operand,
8495 or a `js2-node' struct if it has already been parsed."
8496 (let* ((pos (js2-node-pos left))
8497 (op-pos (- js2-token-beg pos))
8498 (right (if (js2-node-p parser)
8499 parser
8500 (funcall parser)))
8501 (pn (make-js2-infix-node :type type
8502 :pos pos
8503 :len (- (js2-node-end right) pos)
8504 :op-pos op-pos
8505 :left left
8506 :right right)))
8507 (js2-node-add-children pn left right)
8508 pn))
8509
8510 (defun js2-parse-or-expr ()
8511 (let ((pn (js2-parse-and-expr)))
8512 (when (js2-match-token js2-OR)
8513 (setq pn (js2-make-binary js2-OR
8514 pn
8515 'js2-parse-or-expr)))
8516 pn))
8517
8518 (defun js2-parse-and-expr ()
8519 (let ((pn (js2-parse-bit-or-expr)))
8520 (when (js2-match-token js2-AND)
8521 (setq pn (js2-make-binary js2-AND
8522 pn
8523 'js2-parse-and-expr)))
8524 pn))
8525
8526 (defun js2-parse-bit-or-expr ()
8527 (let ((pn (js2-parse-bit-xor-expr)))
8528 (while (js2-match-token js2-BITOR)
8529 (setq pn (js2-make-binary js2-BITOR
8530 pn
8531 'js2-parse-bit-xor-expr)))
8532 pn))
8533
8534 (defun js2-parse-bit-xor-expr ()
8535 (let ((pn (js2-parse-bit-and-expr)))
8536 (while (js2-match-token js2-BITXOR)
8537 (setq pn (js2-make-binary js2-BITXOR
8538 pn
8539 'js2-parse-bit-and-expr)))
8540 pn))
8541
8542 (defun js2-parse-bit-and-expr ()
8543 (let ((pn (js2-parse-eq-expr)))
8544 (while (js2-match-token js2-BITAND)
8545 (setq pn (js2-make-binary js2-BITAND
8546 pn
8547 'js2-parse-eq-expr)))
8548 pn))
8549
8550 (defconst js2-parse-eq-ops
8551 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8552
8553 (defun js2-parse-eq-expr ()
8554 (let ((pn (js2-parse-rel-expr))
8555 tt)
8556 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8557 (js2-consume-token)
8558 (setq pn (js2-make-binary tt
8559 pn
8560 'js2-parse-rel-expr)))
8561 pn))
8562
8563 (defconst js2-parse-rel-ops
8564 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8565
8566 (defun js2-parse-rel-expr ()
8567 (let ((pn (js2-parse-shift-expr))
8568 (continue t)
8569 tt)
8570 (while continue
8571 (setq tt (js2-peek-token))
8572 (cond
8573 ((and js2-in-for-init (= tt js2-IN))
8574 (setq continue nil))
8575 ((memq tt js2-parse-rel-ops)
8576 (js2-consume-token)
8577 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8578 (t
8579 (setq continue nil))))
8580 pn))
8581
8582 (defconst js2-parse-shift-ops
8583 (list js2-LSH js2-URSH js2-RSH))
8584
8585 (defun js2-parse-shift-expr ()
8586 (let ((pn (js2-parse-add-expr))
8587 tt
8588 (continue t))
8589 (while continue
8590 (setq tt (js2-peek-token))
8591 (if (memq tt js2-parse-shift-ops)
8592 (progn
8593 (js2-consume-token)
8594 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8595 (setq continue nil)))
8596 pn))
8597
8598 (defun js2-parse-add-expr ()
8599 (let ((pn (js2-parse-mul-expr))
8600 tt
8601 (continue t))
8602 (while continue
8603 (setq tt (js2-peek-token))
8604 (if (or (= tt js2-ADD) (= tt js2-SUB))
8605 (progn
8606 (js2-consume-token)
8607 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8608 (setq continue nil)))
8609 pn))
8610
8611 (defconst js2-parse-mul-ops
8612 (list js2-MUL js2-DIV js2-MOD))
8613
8614 (defun js2-parse-mul-expr ()
8615 (let ((pn (js2-parse-unary-expr))
8616 tt
8617 (continue t))
8618 (while continue
8619 (setq tt (js2-peek-token))
8620 (if (memq tt js2-parse-mul-ops)
8621 (progn
8622 (js2-consume-token)
8623 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8624 (setq continue nil)))
8625 pn))
8626
8627 (defun js2-make-unary (type parser &rest args)
8628 "Make a unary node of type TYPE.
8629 PARSER is either a node (for postfix operators) or a function to call
8630 to parse the operand (for prefix operators)."
8631 (let* ((pos js2-token-beg)
8632 (postfix (js2-node-p parser))
8633 (expr (if postfix
8634 parser
8635 (apply parser args)))
8636 end
8637 pn)
8638 (if postfix ; e.g. i++
8639 (setq pos (js2-node-pos expr)
8640 end js2-token-end)
8641 (setq end (js2-node-end expr)))
8642 (setq pn (make-js2-unary-node :type type
8643 :pos pos
8644 :len (- end pos)
8645 :operand expr))
8646 (js2-node-add-children pn expr)
8647 pn))
8648
8649 (defconst js2-incrementable-node-types
8650 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8651 "Node types that can be the operand of a ++ or -- operator.")
8652
8653 (defun js2-check-bad-inc-dec (tt beg end unary)
8654 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8655 js2-incrementable-node-types)
8656 (js2-report-error (if (= tt js2-INC)
8657 "msg.bad.incr"
8658 "msg.bad.decr")
8659 nil beg (- end beg))))
8660
8661 (defun js2-parse-unary-expr ()
8662 (let ((tt (js2-peek-token))
8663 pn expr beg end)
8664 (cond
8665 ((or (= tt js2-VOID)
8666 (= tt js2-NOT)
8667 (= tt js2-BITNOT)
8668 (= tt js2-TYPEOF))
8669 (js2-consume-token)
8670 (js2-make-unary tt 'js2-parse-unary-expr))
8671 ((= tt js2-ADD)
8672 (js2-consume-token)
8673 ;; Convert to special POS token in decompiler and parse tree
8674 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8675 ((= tt js2-SUB)
8676 (js2-consume-token)
8677 ;; Convert to special NEG token in decompiler and parse tree
8678 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8679 ((or (= tt js2-INC)
8680 (= tt js2-DEC))
8681 (js2-consume-token)
8682 (prog1
8683 (setq beg js2-token-beg
8684 end js2-token-end
8685 expr (js2-make-unary tt 'js2-parse-member-expr t))
8686 (js2-check-bad-inc-dec tt beg end expr)))
8687 ((= tt js2-DELPROP)
8688 (js2-consume-token)
8689 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8690 ((= tt js2-ERROR)
8691 (js2-consume-token)
8692 (make-js2-error-node)) ; try to continue
8693 ((and (= tt js2-LT)
8694 js2-compiler-xml-available)
8695 ;; XML stream encountered in expression.
8696 (js2-consume-token)
8697 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8698 (t
8699 (setq pn (js2-parse-member-expr t)
8700 ;; Don't look across a newline boundary for a postfix incop.
8701 tt (js2-peek-token-or-eol))
8702 (when (or (= tt js2-INC) (= tt js2-DEC))
8703 (js2-consume-token)
8704 (setf expr pn
8705 pn (js2-make-unary tt expr))
8706 (js2-node-set-prop pn 'postfix t)
8707 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8708 pn))))
8709
8710 (defun js2-parse-xml-initializer ()
8711 "Parse an E4X XML initializer.
8712 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8713 Then I'll postprocess the result, depending on whether we're in IDE
8714 mode or codegen mode, and generate the appropriate rewritten AST.
8715 IDE mode uses a rich AST that models the XML structure. Codegen mode
8716 just concatenates everything and makes a new XML or XMLList out of it."
8717 (let ((tt (js2-get-first-xml-token))
8718 pn-xml pn expr kids expr-pos
8719 (continue t)
8720 (first-token t))
8721 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8722 (js2-report-error "msg.syntax"))
8723 (setq pn-xml (make-js2-xml-node))
8724 (while continue
8725 (if first-token
8726 (setq first-token nil)
8727 (setq tt (js2-get-next-xml-token)))
8728 (cond
8729 ;; js2-XML means we found a {expr} in the XML stream.
8730 ;; The js2-ts-string is the XML up to the left-curly.
8731 ((= tt js2-XML)
8732 (push (make-js2-string-node :pos js2-token-beg
8733 :len (- js2-ts-cursor js2-token-beg))
8734 kids)
8735 (js2-must-match js2-LC "msg.syntax")
8736 (setq expr-pos js2-ts-cursor
8737 expr (if (eq (js2-peek-token) js2-RC)
8738 (make-js2-empty-expr-node :pos expr-pos)
8739 (js2-parse-expr)))
8740 (js2-must-match js2-RC "msg.syntax")
8741 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8742 :len (js2-node-len expr)
8743 :expr expr))
8744 (js2-node-add-children pn expr)
8745 (push pn kids))
8746 ;; a js2-XMLEND token means we hit the final close-tag.
8747 ((= tt js2-XMLEND)
8748 (push (make-js2-string-node :pos js2-token-beg
8749 :len (- js2-ts-cursor js2-token-beg))
8750 kids)
8751 (dolist (kid (nreverse kids))
8752 (js2-block-node-push pn-xml kid))
8753 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8754 (js2-node-pos pn-xml))
8755 continue nil))
8756 (t
8757 (js2-report-error "msg.syntax")
8758 (setq continue nil))))
8759 pn-xml))
8760
8761
8762 (defun js2-parse-argument-list ()
8763 "Parse an argument list and return it as a Lisp list of nodes.
8764 Returns the list in reverse order. Consumes the right-paren token."
8765 (let (result)
8766 (unless (js2-match-token js2-RP)
8767 (loop do
8768 (if (= (js2-peek-token) js2-YIELD)
8769 (js2-report-error "msg.yield.parenthesized"))
8770 (push (js2-parse-assign-expr) result)
8771 while
8772 (js2-match-token js2-COMMA))
8773 (js2-must-match js2-RP "msg.no.paren.arg")
8774 result)))
8775
8776 (defun js2-parse-member-expr (&optional allow-call-syntax)
8777 (let ((tt (js2-peek-token))
8778 pn pos target args beg end init tail)
8779 (if (/= tt js2-NEW)
8780 (setq pn (js2-parse-primary-expr))
8781 ;; parse a 'new' expression
8782 (js2-consume-token)
8783 (setq pos js2-token-beg
8784 beg pos
8785 target (js2-parse-member-expr)
8786 end (js2-node-end target)
8787 pn (make-js2-new-node :pos pos
8788 :target target
8789 :len (- end pos)))
8790 (js2-node-add-children pn target)
8791 (when (js2-match-token js2-LP)
8792 ;; Add the arguments to pn, if any are supplied.
8793 (setf beg pos ; start of "new" keyword
8794 pos js2-token-beg
8795 args (nreverse (js2-parse-argument-list))
8796 (js2-new-node-args pn) args
8797 end js2-token-end
8798 (js2-new-node-lp pn) (- pos beg)
8799 (js2-new-node-rp pn) (- end 1 beg))
8800 (apply #'js2-node-add-children pn args))
8801 (when (and js2-allow-rhino-new-expr-initializer
8802 (js2-match-token js2-LC))
8803 (setf init (js2-parse-object-literal)
8804 end (js2-node-end init)
8805 (js2-new-node-initializer pn) init)
8806 (js2-node-add-children pn init))
8807 (setf (js2-node-len pn) (- end beg))) ; end outer if
8808 (js2-parse-member-expr-tail allow-call-syntax pn)))
8809
8810 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8811 "Parse a chain of property/array accesses or function calls.
8812 Includes parsing for E4X operators like `..' and `.@'.
8813 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8814 Returns an expression tree that includes PN, the parent node."
8815 (let ((beg (js2-node-pos pn))
8816 tt
8817 (continue t))
8818 (while continue
8819 (setq tt (js2-peek-token))
8820 (cond
8821 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8822 (setq pn (js2-parse-property-access tt pn)))
8823 ((= tt js2-DOTQUERY)
8824 (setq pn (js2-parse-dot-query pn)))
8825 ((= tt js2-LB)
8826 (setq pn (js2-parse-element-get pn)))
8827 ((= tt js2-LP)
8828 (if allow-call-syntax
8829 (setq pn (js2-parse-function-call pn))
8830 (setq continue nil)))
8831 (t
8832 (setq continue nil))))
8833 (if (>= js2-highlight-level 2)
8834 (js2-parse-highlight-member-expr-node pn))
8835 pn))
8836
8837 (defun js2-parse-dot-query (pn)
8838 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8839 Last token parsed must be `js2-DOTQUERY'."
8840 (let ((pos (js2-node-pos pn))
8841 op-pos expr end)
8842 (js2-consume-token)
8843 (js2-must-have-xml)
8844 (js2-set-requires-activation)
8845 (setq op-pos js2-token-beg
8846 expr (js2-parse-expr)
8847 end (js2-node-end expr)
8848 pn (make-js2-xml-dot-query-node :left pn
8849 :pos pos
8850 :op-pos op-pos
8851 :right expr))
8852 (js2-node-add-children pn
8853 (js2-xml-dot-query-node-left pn)
8854 (js2-xml-dot-query-node-right pn))
8855 (if (js2-must-match js2-RP "msg.no.paren")
8856 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8857 end js2-token-end))
8858 (setf (js2-node-len pn) (- end pos))
8859 pn))
8860
8861 (defun js2-parse-element-get (pn)
8862 "Parse an element-get expression, e.g. foo[bar].
8863 Last token parsed must be `js2-RB'."
8864 (let ((lb js2-token-beg)
8865 (pos (js2-node-pos pn))
8866 rb expr)
8867 (js2-consume-token)
8868 (setq expr (js2-parse-expr))
8869 (if (js2-must-match js2-RB "msg.no.bracket.index")
8870 (setq rb js2-token-beg))
8871 (setq pn (make-js2-elem-get-node :target pn
8872 :pos pos
8873 :element expr
8874 :lb (js2-relpos lb pos)
8875 :rb (js2-relpos rb pos)
8876 :len (- js2-token-end pos)))
8877 (js2-node-add-children pn
8878 (js2-elem-get-node-target pn)
8879 (js2-elem-get-node-element pn))
8880 pn))
8881
8882 (defun js2-parse-function-call (pn)
8883 (let (args
8884 (pos (js2-node-pos pn)))
8885 (js2-consume-token)
8886 (setq pn (make-js2-call-node :pos pos
8887 :target pn
8888 :lp (- js2-token-beg pos)))
8889 (js2-node-add-children pn (js2-call-node-target pn))
8890 ;; Add the arguments to pn, if any are supplied.
8891 (setf args (nreverse (js2-parse-argument-list))
8892 (js2-call-node-rp pn) (- js2-token-beg pos)
8893 (js2-call-node-args pn) args)
8894 (apply #'js2-node-add-children pn args)
8895 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8896 pn))
8897
8898 (defun js2-parse-property-access (tt pn)
8899 "Parse a property access, XML descendants access, or XML attr access."
8900 (let ((member-type-flags 0)
8901 (dot-pos js2-token-beg)
8902 (dot-len (if (= tt js2-DOTDOT) 2 1))
8903 name
8904 ref ; right side of . or .. operator
8905 result)
8906 (js2-consume-token)
8907 (when (= tt js2-DOTDOT)
8908 (js2-must-have-xml)
8909 (setq member-type-flags js2-descendants-flag))
8910 (if (not js2-compiler-xml-available)
8911 (progn
8912 (js2-must-match-prop-name "msg.no.name.after.dot")
8913 (setq name (js2-create-name-node t js2-GETPROP)
8914 result (make-js2-prop-get-node :left pn
8915 :pos js2-token-beg
8916 :right name
8917 :len (- js2-token-end
8918 js2-token-beg)))
8919 (js2-node-add-children result pn name)
8920 result)
8921 ;; otherwise look for XML operators
8922 (setf result (if (= tt js2-DOT)
8923 (make-js2-prop-get-node)
8924 (make-js2-infix-node :type js2-DOTDOT))
8925 (js2-node-pos result) (js2-node-pos pn)
8926 (js2-infix-node-op-pos result) dot-pos
8927 (js2-infix-node-left result) pn ; do this after setting position
8928 tt (js2-next-token))
8929 (cond
8930 ;; needed for generator.throw()
8931 ((= tt js2-THROW)
8932 (js2-save-name-token-data js2-token-beg "throw")
8933 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8934 ;; handles: name, ns::name, ns::*, ns::[expr]
8935 ((js2-valid-prop-name-token tt)
8936 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8937 ;; handles: *, *::name, *::*, *::[expr]
8938 ((= tt js2-MUL)
8939 (js2-save-name-token-data js2-token-beg "*")
8940 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8941 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8942 ((= tt js2-XMLATTR)
8943 (setq result (js2-parse-attribute-access)))
8944 (t
8945 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8946 (if ref
8947 (setf (js2-node-len result) (- (js2-node-end ref)
8948 (js2-node-pos result))
8949 (js2-infix-node-right result) ref))
8950 (if (js2-infix-node-p result)
8951 (js2-node-add-children result
8952 (js2-infix-node-left result)
8953 (js2-infix-node-right result)))
8954 result)))
8955
8956 (defun js2-parse-attribute-access ()
8957 "Parse an E4X XML attribute expression.
8958 This includes expressions of the forms:
8959
8960 @attr @ns::attr @ns::*
8961 @* @*::attr @*::*
8962 @[expr] @*::[expr] @ns::[expr]
8963
8964 Called if we peeked an '@' token."
8965 (let ((tt (js2-next-token))
8966 (at-pos js2-token-beg))
8967 (cond
8968 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8969 ((js2-valid-prop-name-token tt)
8970 (js2-parse-property-name at-pos js2-ts-string 0))
8971 ;; handles: @*, @*::name, @*::*, @*::[expr]
8972 ((= tt js2-MUL)
8973 (js2-save-name-token-data js2-token-beg "*")
8974 (js2-parse-property-name js2-token-beg "*" 0))
8975 ;; handles @[expr]
8976 ((= tt js2-LB)
8977 (js2-parse-xml-elem-ref at-pos))
8978 (t
8979 (js2-report-error "msg.no.name.after.xmlAttr")
8980 ;; Avoid cascaded errors that happen if we make an error node here.
8981 (js2-save-name-token-data js2-token-beg "")
8982 (js2-parse-property-name js2-token-beg "" 0)))))
8983
8984 (defun js2-parse-property-name (at-pos s member-type-flags)
8985 "Check if :: follows name in which case it becomes qualified name.
8986
8987 AT-POS is a natural number if we just read an '@' token, else nil.
8988 S is the name or string that was matched: an identifier, 'throw' or '*'.
8989 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8990
8991 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8992 operator, or the name is followed by ::. For a plain name, returns a
8993 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8994 (let ((pos (or at-pos js2-token-beg))
8995 colon-pos
8996 (name (js2-create-name-node t js2-current-token))
8997 ns tt ref pn)
8998 (catch 'return
8999 (when (js2-match-token js2-COLONCOLON)
9000 (setq ns name
9001 colon-pos js2-token-beg
9002 tt (js2-next-token))
9003 (cond
9004 ;; handles name::name
9005 ((js2-valid-prop-name-token tt)
9006 (setq name (js2-create-name-node)))
9007 ;; handles name::*
9008 ((= tt js2-MUL)
9009 (js2-save-name-token-data js2-token-beg "*")
9010 (setq name (js2-create-name-node)))
9011 ;; handles name::[expr]
9012 ((= tt js2-LB)
9013 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9014 (t
9015 (js2-report-error "msg.no.name.after.coloncolon"))))
9016 (if (and (null ns) (zerop member-type-flags))
9017 name
9018 (prog1
9019 (setq pn
9020 (make-js2-xml-prop-ref-node :pos pos
9021 :len (- (js2-node-end name) pos)
9022 :at-pos at-pos
9023 :colon-pos colon-pos
9024 :propname name))
9025 (js2-node-add-children pn name))))))
9026
9027 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9028 "Parse the [expr] portion of an xml element reference.
9029 For instance, @[expr], @*::[expr], or ns::[expr]."
9030 (let* ((lb js2-token-beg)
9031 (pos (or at-pos lb))
9032 rb
9033 (expr (js2-parse-expr))
9034 (end (js2-node-end expr))
9035 pn)
9036 (if (js2-must-match js2-RB "msg.no.bracket.index")
9037 (setq rb js2-token-beg
9038 end js2-token-end))
9039 (prog1
9040 (setq pn
9041 (make-js2-xml-elem-ref-node :pos pos
9042 :len (- end pos)
9043 :namespace namespace
9044 :colon-pos colon-pos
9045 :at-pos at-pos
9046 :expr expr
9047 :lb (js2-relpos lb pos)
9048 :rb (js2-relpos rb pos)))
9049 (js2-node-add-children pn namespace expr))))
9050
9051 (defun js2-parse-destruct-primary-expr ()
9052 (let ((js2-is-in-destructuring t))
9053 (js2-parse-primary-expr)))
9054
9055 (defun js2-parse-primary-expr ()
9056 "Parse a literal (leaf) expression of some sort.
9057 Includes complex literals such as functions, object-literals,
9058 array-literals, array comprehensions and regular expressions."
9059 (let ((tt-flagged (js2-next-flagged-token))
9060 pn ; parent node (usually return value)
9061 tt
9062 px-pos ; paren-expr pos
9063 len
9064 flags ; regexp flags
9065 expr)
9066 (setq tt js2-current-token)
9067 (cond
9068 ((= tt js2-FUNCTION)
9069 (js2-parse-function 'FUNCTION_EXPRESSION))
9070 ((= tt js2-LB)
9071 (js2-parse-array-literal))
9072 ((= tt js2-LC)
9073 (js2-parse-object-literal))
9074 ((= tt js2-LET)
9075 (js2-parse-let js2-token-beg))
9076 ((= tt js2-LP)
9077 (setq px-pos js2-token-beg
9078 expr (js2-parse-expr))
9079 (js2-must-match js2-RP "msg.no.paren")
9080 (setq pn (make-js2-paren-node :pos px-pos
9081 :expr expr
9082 :len (- js2-token-end px-pos)))
9083 (js2-node-add-children pn (js2-paren-node-expr pn))
9084 pn)
9085 ((= tt js2-XMLATTR)
9086 (js2-must-have-xml)
9087 (js2-parse-attribute-access))
9088 ((= tt js2-NAME)
9089 (js2-parse-name tt-flagged tt))
9090 ((= tt js2-NUMBER)
9091 (make-js2-number-node))
9092 ((= tt js2-STRING)
9093 (prog1
9094 (make-js2-string-node)
9095 (js2-record-face 'font-lock-string-face)))
9096 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9097 ;; Got / or /= which in this context means a regexp literal
9098 (setq px-pos js2-token-beg)
9099 (js2-read-regexp tt)
9100 (setq flags js2-ts-regexp-flags
9101 js2-ts-regexp-flags nil)
9102 (prog1
9103 (make-js2-regexp-node :pos px-pos
9104 :len (- js2-ts-cursor px-pos)
9105 :value js2-ts-string
9106 :flags flags)
9107 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9108 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9109 ((or (= tt js2-NULL)
9110 (= tt js2-THIS)
9111 (= tt js2-FALSE)
9112 (= tt js2-TRUE))
9113 (make-js2-keyword-node :type tt))
9114 ((= tt js2-RESERVED)
9115 (js2-report-error "msg.reserved.id")
9116 (make-js2-name-node))
9117 ((= tt js2-ERROR)
9118 ;; the scanner or one of its subroutines reported the error.
9119 (make-js2-error-node))
9120 ((= tt js2-EOF)
9121 (setq px-pos (point-at-bol)
9122 len (- js2-ts-cursor px-pos))
9123 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9124 (make-js2-error-node :pos px-pos :len len))
9125 (t
9126 (js2-report-error "msg.syntax")
9127 (make-js2-error-node)))))
9128
9129 (defun js2-parse-name (tt-flagged tt)
9130 (let ((name js2-ts-string)
9131 (name-pos js2-token-beg)
9132 node)
9133 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9134 (= (js2-peek-token) js2-COLON))
9135 (prog1
9136 ;; Do not consume colon, it is used as unwind indicator
9137 ;; to return to statementHelper.
9138 (make-js2-label-node :pos name-pos
9139 :len (- js2-token-end name-pos)
9140 :name name)
9141 (js2-set-face name-pos
9142 js2-token-end
9143 'font-lock-variable-name-face 'record))
9144 ;; Otherwise not a label, just a name. Unfortunately peeking
9145 ;; the next token to check for a colon has biffed js2-token-beg
9146 ;; and js2-token-end. We store the name's bounds in buffer vars
9147 ;; and `js2-create-name-node' uses them.
9148 (js2-save-name-token-data name-pos name)
9149 (setq node (if js2-compiler-xml-available
9150 (js2-parse-property-name nil name 0)
9151 (js2-create-name-node 'check-activation)))
9152 (if js2-highlight-external-variables
9153 (js2-record-name-node node))
9154 node)))
9155
9156 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9157 (js2-add-strict-warning
9158 msg nil
9159 ;; back up from comma to beginning of line or array/objlit
9160 (max (if elems
9161 (js2-node-pos (car elems))
9162 pos)
9163 (save-excursion
9164 (goto-char comma-pos)
9165 (back-to-indentation)
9166 (point)))
9167 comma-pos))
9168
9169 (defun js2-parse-array-literal ()
9170 (let ((pos js2-token-beg)
9171 (end js2-token-end)
9172 (after-lb-or-comma t)
9173 after-comma tt elems pn
9174 (continue t))
9175 (unless js2-is-in-destructuring
9176 (js2-push-scope (make-js2-scope))) ; for array comp
9177 (while continue
9178 (setq tt (js2-peek-token))
9179 (cond
9180 ;; comma
9181 ((= tt js2-COMMA)
9182 (js2-consume-token)
9183 (setq after-comma js2-token-end)
9184 (if (not after-lb-or-comma)
9185 (setq after-lb-or-comma t)
9186 (push nil elems)))
9187 ;; end of array
9188 ((or (= tt js2-RB)
9189 (= tt js2-EOF)) ; prevent infinite loop
9190 (if (= tt js2-EOF)
9191 (js2-report-error "msg.no.bracket.arg" nil pos)
9192 (js2-consume-token))
9193 (setq continue nil
9194 end js2-token-end
9195 pn (make-js2-array-node :pos pos
9196 :len (- js2-ts-cursor pos)
9197 :elems (nreverse elems)))
9198 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9199 (when (and after-comma (not js2-is-in-destructuring))
9200 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9201 pos elems after-comma)))
9202 ;; destructuring binding
9203 (js2-is-in-destructuring
9204 (push (if (or (= tt js2-LC)
9205 (= tt js2-LB)
9206 (= tt js2-NAME))
9207 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9208 (js2-parse-destruct-primary-expr)
9209 ;; invalid pattern
9210 (js2-consume-token)
9211 (js2-report-error "msg.bad.var")
9212 (make-js2-error-node))
9213 elems)
9214 (setq after-lb-or-comma nil
9215 after-comma nil))
9216 ;; array comp
9217 ((and (>= js2-language-version 170)
9218 (= tt js2-FOR) ; check for array comprehension
9219 (not after-lb-or-comma) ; "for" can't follow a comma
9220 elems ; must have at least 1 element
9221 (not (cdr elems))) ; but no 2nd element
9222 (setf continue nil
9223 pn (js2-parse-array-comprehension (car elems) pos)))
9224
9225 ;; another element
9226 (t
9227 (unless after-lb-or-comma
9228 (js2-report-error "msg.no.bracket.arg"))
9229 (push (js2-parse-assign-expr) elems)
9230 (setq after-lb-or-comma nil
9231 after-comma nil))))
9232 (unless js2-is-in-destructuring
9233 (js2-pop-scope))
9234 pn))
9235
9236 (defun js2-parse-array-comprehension (expr pos)
9237 "Parse a JavaScript 1.7 Array Comprehension.
9238 EXPR is the first expression after the opening left-bracket.
9239 POS is the beginning of the LB token preceding EXPR.
9240 We should have just parsed the 'for' keyword before calling this function."
9241 (let (loops loop first prev filter if-pos result)
9242 (while (= (js2-peek-token) js2-FOR)
9243 (let ((prev (car loops))) ; rearrange scope chain
9244 (push (setq loop (js2-parse-array-comp-loop)) loops)
9245 (if prev ; each loop is parent scope to the next one
9246 (setf (js2-scope-parent-scope loop) prev)
9247 ; first loop takes expr scope's parent
9248 (setf (js2-scope-parent-scope (setq first loop))
9249 (js2-scope-parent-scope js2-current-scope)))))
9250 ;; set expr scope's parent to the last loop
9251 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9252 (when (= (js2-peek-token) js2-IF)
9253 (js2-consume-token)
9254 (setq if-pos (- js2-token-beg pos) ; relative
9255 filter (js2-parse-condition)))
9256 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9257 (setq result (make-js2-array-comp-node :pos pos
9258 :len (- js2-ts-cursor pos)
9259 :result expr
9260 :loops (nreverse loops)
9261 :filter (car filter)
9262 :lp (js2-relpos (second filter) pos)
9263 :rp (js2-relpos (third filter) pos)
9264 :if-pos if-pos))
9265 (apply #'js2-node-add-children result expr (car filter)
9266 (js2-array-comp-node-loops result))
9267 (setq js2-current-scope first) ; pop to the first loop
9268 result))
9269
9270 (defun js2-parse-array-comp-loop ()
9271 "Parse a 'for [each] (foo [in|of] bar)' expression in an Array comprehension.
9272 Last token peeked should be the initial FOR."
9273 (let ((pos js2-token-beg)
9274 (pn (make-js2-array-comp-loop-node))
9275 tt iter obj foreach-p forof-p in-pos each-pos lp rp)
9276 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9277 (js2-push-scope pn)
9278 (unwind-protect
9279 (progn
9280 (when (js2-match-token js2-NAME)
9281 (if (string= js2-ts-string "each")
9282 (progn
9283 (setq foreach-p t
9284 each-pos (- js2-token-beg pos)) ; relative
9285 (js2-record-face 'font-lock-keyword-face))
9286 (js2-report-error "msg.no.paren.for")))
9287 (if (js2-must-match js2-LP "msg.no.paren.for")
9288 (setq lp (- js2-token-beg pos)))
9289 (setq tt (js2-peek-token))
9290 (cond
9291 ((or (= tt js2-LB)
9292 (= tt js2-LC))
9293 (setq iter (js2-parse-destruct-primary-expr))
9294 (js2-define-destruct-symbols iter js2-LET
9295 'font-lock-variable-name-face t))
9296 ((js2-match-token js2-NAME)
9297 (setq iter (js2-create-name-node)))
9298 (t
9299 (js2-report-error "msg.bad.var")))
9300 ;; Define as a let since we want the scope of the variable to
9301 ;; be restricted to the array comprehension
9302 (if (js2-name-node-p iter)
9303 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9304 (if (or (js2-match-token js2-IN)
9305 (and (>= js2-language-version 200)
9306 (js2-match-contextual-kwd "of")
9307 (setq forof-p t)))
9308 (setq in-pos (- js2-token-beg pos))
9309 (js2-report-error "msg.in.after.for.name"))
9310 (setq obj (js2-parse-expr))
9311 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9312 (setq rp (- js2-token-beg pos)))
9313 (setf (js2-node-pos pn) pos
9314 (js2-node-len pn) (- js2-ts-cursor pos)
9315 (js2-array-comp-loop-node-iterator pn) iter
9316 (js2-array-comp-loop-node-object pn) obj
9317 (js2-array-comp-loop-node-in-pos pn) in-pos
9318 (js2-array-comp-loop-node-each-pos pn) each-pos
9319 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9320 (js2-array-comp-loop-node-forof-p pn) forof-p
9321 (js2-array-comp-loop-node-lp pn) lp
9322 (js2-array-comp-loop-node-rp pn) rp)
9323 (js2-node-add-children pn iter obj))
9324 (js2-pop-scope))
9325 pn))
9326
9327 (defun js2-parse-object-literal ()
9328 (let ((pos js2-token-beg)
9329 tt elems result after-comma
9330 (continue t))
9331 (while continue
9332 (setq tt (js2-peek-token))
9333 (cond
9334 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9335 ;; {get foo() {...}}, or {set foo(x) {...}}
9336 ((or (js2-valid-prop-name-token tt)
9337 (= tt js2-STRING))
9338 (setq after-comma nil
9339 result (js2-parse-named-prop tt))
9340 (if (and (null result)
9341 (not js2-recover-from-parse-errors))
9342 (setq continue nil)
9343 (push result elems)))
9344 ;; {12: x} or {10.7: x}
9345 ((= tt js2-NUMBER)
9346 (js2-consume-token)
9347 (setq after-comma nil)
9348 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9349 ;; trailing comma
9350 ((= tt js2-RC)
9351 (setq continue nil)
9352 (if after-comma
9353 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9354 pos elems after-comma)))
9355 (t
9356 (js2-report-error "msg.bad.prop")
9357 (unless js2-recover-from-parse-errors
9358 (setq continue nil)))) ; end switch
9359 (if (js2-match-token js2-COMMA)
9360 (setq after-comma js2-token-end)
9361 (setq continue nil))) ; end loop
9362 (js2-must-match js2-RC "msg.no.brace.prop")
9363 (setq result (make-js2-object-node :pos pos
9364 :len (- js2-ts-cursor pos)
9365 :elems (nreverse elems)))
9366 (apply #'js2-node-add-children result (js2-object-node-elems result))
9367 result))
9368
9369 (defun js2-parse-named-prop (tt)
9370 "Parse a name, string, or getter/setter object property.
9371 When `js2-is-in-destructuring' is t, forms like {a, b, c} will be permitted."
9372 (js2-consume-token)
9373 (let ((string-prop (and (= tt js2-STRING)
9374 (make-js2-string-node)))
9375 expr
9376 (ppos js2-token-beg)
9377 (pend js2-token-end)
9378 (name (js2-create-name-node))
9379 (prop js2-ts-string))
9380 (cond
9381 ;; getter/setter prop
9382 ((and (= tt js2-NAME)
9383 (= (js2-peek-token) js2-NAME)
9384 (or (string= prop "get")
9385 (string= prop "set")))
9386 (js2-consume-token)
9387 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9388 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9389 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9390 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9391 ;; Abbreviated destructuring binding, e.g. {a, b} = c;
9392 ;; XXX: To be honest, the value of `js2-is-in-destructuring' becomes t only
9393 ;; when patterns are used in variable declarations, function parameters,
9394 ;; catch-clause, and iterators.
9395 ;; We have to set `js2-is-in-destructuring' to t when the current
9396 ;; expressions are on the left side of any assignment, but it's difficult
9397 ;; because it requires looking ahead of expression.
9398 ((and js2-is-in-destructuring
9399 (= tt js2-NAME)
9400 (let ((ctk (js2-peek-token)))
9401 (or (= ctk js2-COMMA)
9402 (= ctk js2-RC)
9403 (js2-valid-prop-name-token ctk))))
9404 name)
9405 ;; regular prop
9406 (t
9407 (prog1
9408 (setq expr (js2-parse-plain-property (or string-prop name)))
9409 (js2-set-face ppos pend
9410 (if (js2-function-node-p
9411 (js2-object-prop-node-right expr))
9412 'font-lock-function-name-face
9413 'font-lock-variable-name-face)
9414 'record))))))
9415
9416 (defun js2-parse-plain-property (prop)
9417 "Parse a non-getter/setter property in an object literal.
9418 PROP is the node representing the property: a number, name or string."
9419 (js2-must-match js2-COLON "msg.no.colon.prop")
9420 (let* ((pos (js2-node-pos prop))
9421 (colon (- js2-token-beg pos))
9422 (expr (js2-parse-assign-expr))
9423 (result (make-js2-object-prop-node
9424 :pos pos
9425 ;; don't include last consumed token in length
9426 :len (- (+ (js2-node-pos expr)
9427 (js2-node-len expr))
9428 pos)
9429 :left prop
9430 :right expr
9431 :op-pos colon)))
9432 (js2-node-add-children result prop expr)
9433 result))
9434
9435 (defun js2-parse-getter-setter-prop (pos prop get-p)
9436 "Parse getter or setter property in an object literal.
9437 JavaScript syntax is:
9438
9439 { get foo() {...}, set foo(x) {...} }
9440
9441 and expression closure style is also supported
9442
9443 { get foo() x, set foo(x) _x = x }
9444
9445 POS is the start position of the `get' or `set' keyword.
9446 PROP is the `js2-name-node' representing the property name.
9447 GET-P is non-nil if the keyword was `get'."
9448 (let ((type (if get-p js2-GET js2-SET))
9449 result end
9450 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9451 ;; it has to be an anonymous function, as we already parsed the name
9452 (if (/= (js2-node-type fn) js2-FUNCTION)
9453 (js2-report-error "msg.bad.prop")
9454 (if (plusp (length (js2-function-name fn)))
9455 (js2-report-error "msg.bad.prop")))
9456 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9457 (setq end (js2-node-end fn)
9458 result (make-js2-getter-setter-node :type type
9459 :pos pos
9460 :len (- end pos)
9461 :left prop
9462 :right fn))
9463 (js2-node-add-children result prop fn)
9464 result))
9465
9466 (defun js2-create-name-node (&optional check-activation-p token)
9467 "Create a name node using the token info from last scanned name.
9468 In some cases we need to either synthesize a name node, or we lost
9469 the name token information by peeking. If the TOKEN parameter is
9470 not `js2-NAME', then we use the token info saved in instance vars."
9471 (let ((beg js2-token-beg)
9472 (s js2-ts-string)
9473 name)
9474 (when (/= js2-current-token js2-NAME)
9475 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9476 s js2-prev-name-token-string
9477 js2-prev-name-token-start nil
9478 js2-prev-name-token-string nil))
9479 (setq name (make-js2-name-node :pos beg
9480 :name s
9481 :len (length s)))
9482 (if check-activation-p
9483 (js2-check-activation-name s (or token js2-NAME)))
9484 name))
9485
9486 ;;; Indentation support
9487
9488 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9489 ;; Karl cleverly deduces that the desired indentation level is often a
9490 ;; function of paren/bracket/brace nesting depth, which can be determined
9491 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9492 ;; then does some equally clever checks to see if we're in the context of a
9493 ;; substatement of a possibly braceless statement keyword such as if, while,
9494 ;; or finally. This approach yields pretty good results.
9495
9496 ;; The indenter is often "wrong", however, and needs to be overridden.
9497 ;; The right long-term solution is probably to emulate (or integrate
9498 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9499 ;; parse tree from `js2-parse' is present, which is not true at the
9500 ;; moment the user is typing, computing indentation is still thousands
9501 ;; of lines of code to handle every possible syntactic edge case.
9502
9503 ;; In the meantime, the compromise solution is that we offer a "bounce
9504 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9505 ;; current line indent among various likely guess points. This approach
9506 ;; is far from perfect, but should at least make it slightly easier to
9507 ;; move the line towards its desired indentation when manually
9508 ;; overriding Karl's heuristic nesting guesser.
9509
9510 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9511 ;; extensions such as `let' and Array comprehensions. Major kudos to
9512 ;; Karl for coming up with the initial approach, which packs a lot of
9513 ;; punch for so little code.
9514
9515 (defconst js2-possibly-braceless-keywords-re
9516 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9517 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9518 "try" "while" "with" "let")))
9519 "Regular expression matching keywords that are optionally
9520 followed by an opening brace.")
9521
9522 (defconst js2-indent-operator-re
9523 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9524 (regexp-opt '("in" "instanceof") 'words))
9525 "Regular expression matching operators that affect indentation
9526 of continued expressions.")
9527
9528 (defconst js2-declaration-keyword-re
9529 (regexp-opt '("var" "let" "const") 'words)
9530 "Regular expression matching variable declaration keywords.")
9531
9532 ;; This function has horrible results if you're typing an array
9533 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9534 ;; in conjunction with electric-indent, so just disabling it.
9535 (defsubst js2-code-at-bol-p ()
9536 "Return t if the first character on line is non-whitespace."
9537 nil)
9538
9539 (defun js2-insert-and-indent (key)
9540 "Run command bound to KEY and indent current line.
9541 Runs the command bound to KEY in the global keymap and indents
9542 the current line."
9543 (interactive (list (this-command-keys)))
9544 (let ((cmd (lookup-key (current-global-map) key)))
9545 (if (commandp cmd)
9546 (call-interactively cmd)))
9547 ;; don't do the electric keys inside comments or strings,
9548 ;; and don't do bounce-indent with them.
9549 (let ((parse-state (syntax-ppss (point)))
9550 (js2-bounce-indent-p (js2-code-at-bol-p)))
9551 (unless (or (nth 3 parse-state)
9552 (nth 4 parse-state))
9553 (indent-according-to-mode))))
9554
9555 (defun js2-re-search-forward-inner (regexp &optional bound count)
9556 "Auxiliary function for `js2-re-search-forward'."
9557 (let (parse saved-point)
9558 (while (> count 0)
9559 (re-search-forward regexp bound)
9560 (setq parse (if saved-point
9561 (parse-partial-sexp saved-point (point))
9562 (syntax-ppss (point))))
9563 (cond ((nth 3 parse)
9564 (re-search-forward
9565 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9566 (save-excursion (end-of-line) (point)) t))
9567 ((nth 7 parse)
9568 (forward-line))
9569 ((or (nth 4 parse)
9570 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9571 (re-search-forward "\\*/"))
9572 (t
9573 (setq count (1- count))))
9574 (setq saved-point (point))))
9575 (point))
9576
9577 (defun js2-re-search-forward (regexp &optional bound noerror count)
9578 "Search forward but ignore strings and comments.
9579 Invokes `re-search-forward' but treats the buffer as if strings
9580 and comments have been removed."
9581 (let ((saved-point (point))
9582 (search-expr
9583 (cond ((null count)
9584 '(js2-re-search-forward-inner regexp bound 1))
9585 ((< count 0)
9586 '(js2-re-search-backward-inner regexp bound (- count)))
9587 ((> count 0)
9588 '(js2-re-search-forward-inner regexp bound count)))))
9589 (condition-case err
9590 (eval search-expr)
9591 (search-failed
9592 (goto-char saved-point)
9593 (unless noerror
9594 (error (error-message-string err)))))))
9595
9596 (defun js2-re-search-backward-inner (regexp &optional bound count)
9597 "Auxiliary function for `js2-re-search-backward'."
9598 (let (parse)
9599 (while (> count 0)
9600 (re-search-backward regexp bound)
9601 (setq parse (syntax-ppss (point)))
9602 (cond ((nth 3 parse)
9603 (re-search-backward
9604 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9605 (line-beginning-position) t))
9606 ((nth 7 parse)
9607 (goto-char (nth 8 parse)))
9608 ((or (nth 4 parse)
9609 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9610 (re-search-backward "/\\*"))
9611 (t
9612 (setq count (1- count))))))
9613 (point))
9614
9615 (defun js2-re-search-backward (regexp &optional bound noerror count)
9616 "Search backward but ignore strings and comments.
9617 Invokes `re-search-backward' but treats the buffer as if strings
9618 and comments have been removed."
9619 (let ((saved-point (point))
9620 (search-expr
9621 (cond ((null count)
9622 '(js2-re-search-backward-inner regexp bound 1))
9623 ((< count 0)
9624 '(js2-re-search-forward-inner regexp bound (- count)))
9625 ((> count 0)
9626 '(js2-re-search-backward-inner regexp bound count)))))
9627 (condition-case err
9628 (eval search-expr)
9629 (search-failed
9630 (goto-char saved-point)
9631 (unless noerror
9632 (error (error-message-string err)))))))
9633
9634 (defun js2-looking-at-operator-p ()
9635 "Return non-nil if text after point is a non-comma operator."
9636 (and (looking-at js2-indent-operator-re)
9637 (or (not (looking-at ":"))
9638 (save-excursion
9639 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9640 (looking-at "?"))))))
9641
9642 (defun js2-continued-expression-p ()
9643 "Return non-nil if the current line continues an expression."
9644 (save-excursion
9645 (back-to-indentation)
9646 (or (js2-looking-at-operator-p)
9647 (when (catch 'found
9648 (while (and (re-search-backward "\n" nil t)
9649 (let ((state (syntax-ppss)))
9650 (when (nth 4 state)
9651 (goto-char (nth 8 state))) ;; skip comments
9652 (skip-chars-backward " \t")
9653 (if (bolp)
9654 t
9655 (throw 'found t))))))
9656 (backward-char)
9657 (when (js2-looking-at-operator-p)
9658 (backward-char)
9659 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9660
9661 (defun js2-end-of-do-while-loop-p ()
9662 "Return non-nil if word after point is `while' of a do-while
9663 statement, else returns nil. A braceless do-while statement
9664 spanning several lines requires that the start of the loop is
9665 indented to the same column as the current line."
9666 (interactive)
9667 (save-excursion
9668 (when (looking-at "\\s-*\\<while\\>")
9669 (if (save-excursion
9670 (skip-chars-backward "[ \t\n]*}")
9671 (looking-at "[ \t\n]*}"))
9672 (save-excursion
9673 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9674 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9675 (or (looking-at "\\<do\\>")
9676 (let ((saved-indent (current-indentation)))
9677 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9678 (/= (current-indentation) saved-indent)))
9679 (and (looking-at "[ \t]*\\<do\\>")
9680 (not (js2-re-search-forward
9681 "\\<while\\>" (point-at-eol) t))
9682 (= (current-indentation) saved-indent))))))))
9683
9684 (defun js2-multiline-decl-indentation ()
9685 "Return the declaration indentation column if the current line belongs
9686 to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
9687 (let (forward-sexp-function ; use Lisp version
9688 at-opening-bracket)
9689 (save-excursion
9690 (back-to-indentation)
9691 (when (not (looking-at js2-declaration-keyword-re))
9692 (when (looking-at js2-indent-operator-re)
9693 (goto-char (match-end 0))) ; continued expressions are ok
9694 (while (and (not at-opening-bracket)
9695 (not (bobp))
9696 (let ((pos (point)))
9697 (save-excursion
9698 (js2-backward-sws)
9699 (or (eq (char-before) ?,)
9700 (and (not (eq (char-before) ?\;))
9701 (and
9702 (prog2 (skip-chars-backward "[[:punct:]]")
9703 (looking-at js2-indent-operator-re)
9704 (js2-backward-sws))
9705 (not (eq (char-before) ?\;))))
9706 (js2-same-line pos)))))
9707 (condition-case err
9708 (backward-sexp)
9709 (scan-error (setq at-opening-bracket t))))
9710 (when (looking-at js2-declaration-keyword-re)
9711 (goto-char (match-end 0))
9712 (1+ (current-column)))))))
9713
9714 (defun js2-ctrl-statement-indentation ()
9715 "Return the proper indentation of current line if it is a control statement.
9716 Returns an indentation if this line starts the body of a control
9717 statement without braces, else returns nil."
9718 (let (forward-sexp-function)
9719 (save-excursion
9720 (back-to-indentation)
9721 (when (and (not (js2-same-line (point-min)))
9722 (not (looking-at "{"))
9723 (js2-re-search-backward "[[:graph:]]" nil t)
9724 (not (looking-at "[{([]"))
9725 (progn
9726 (forward-char)
9727 (when (= (char-before) ?\))
9728 ;; scan-sexps sometimes throws an error
9729 (ignore-errors (backward-sexp))
9730 (skip-chars-backward " \t" (point-at-bol)))
9731 (let ((pt (point)))
9732 (back-to-indentation)
9733 (and (looking-at js2-possibly-braceless-keywords-re)
9734 (= (match-end 0) pt)
9735 (not (js2-end-of-do-while-loop-p))))))
9736 (+ (current-indentation) js2-basic-offset)))))
9737
9738 (defun js2-indent-in-array-comp (parse-status)
9739 "Return non-nil if we think we're in an array comprehension.
9740 In particular, return the buffer position of the first `for' kwd."
9741 (let ((bracket (nth 1 parse-status))
9742 (end (point)))
9743 (when bracket
9744 (save-excursion
9745 (goto-char bracket)
9746 (when (looking-at "\\[")
9747 (forward-char 1)
9748 (js2-forward-sws)
9749 (if (looking-at "[[{]")
9750 (let (forward-sexp-function) ; use Lisp version
9751 (forward-sexp) ; skip destructuring form
9752 (js2-forward-sws)
9753 (if (and (/= (char-after) ?,) ; regular array
9754 (looking-at "for"))
9755 (match-beginning 0)))
9756 ;; to skip arbitrary expressions we need the parser,
9757 ;; so we'll just guess at it.
9758 (if (and (> end (point)) ; not empty literal
9759 (re-search-forward "[^,]]* \\(for\\) " end t)
9760 ;; not inside comment or string literal
9761 (let ((state (parse-partial-sexp bracket (point))))
9762 (not (or (nth 3 state) (nth 4 state)))))
9763 (match-beginning 1))))))))
9764
9765 (defun js2-array-comp-indentation (parse-status for-kwd)
9766 (if (js2-same-line for-kwd)
9767 ;; first continuation line
9768 (save-excursion
9769 (goto-char (nth 1 parse-status))
9770 (forward-char 1)
9771 (skip-chars-forward " \t")
9772 (current-column))
9773 (save-excursion
9774 (goto-char for-kwd)
9775 (current-column))))
9776
9777 (defun js2-proper-indentation (parse-status)
9778 "Return the proper indentation for the current line."
9779 (save-excursion
9780 (back-to-indentation)
9781 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9782 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9783 (continued-expr-p (js2-continued-expression-p))
9784 (declaration-indent (and js2-pretty-multiline-declarations
9785 (js2-multiline-decl-indentation)))
9786 (bracket (nth 1 parse-status))
9787 beg)
9788 (cond
9789 ;; indent array comprehension continuation lines specially
9790 ((and bracket
9791 (>= js2-language-version 170)
9792 (not (js2-same-line bracket))
9793 (setq beg (js2-indent-in-array-comp parse-status))
9794 (>= (point) (save-excursion
9795 (goto-char beg)
9796 (point-at-bol)))) ; at or after first loop?
9797 (js2-array-comp-indentation parse-status beg))
9798
9799 (ctrl-stmt-indent)
9800
9801 ((and declaration-indent continued-expr-p)
9802 (+ declaration-indent js2-basic-offset))
9803
9804 (declaration-indent)
9805
9806 (bracket
9807 (goto-char bracket)
9808 (cond
9809 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9810 (when (save-excursion (skip-chars-backward " \t)")
9811 (looking-at ")"))
9812 (backward-list))
9813 (back-to-indentation)
9814 (and (eq js2-pretty-multiline-declarations 'all)
9815 (looking-at js2-declaration-keyword-re)
9816 (goto-char (1+ (match-end 0))))
9817 (cond (same-indent-p
9818 (current-column))
9819 (continued-expr-p
9820 (+ (current-column) (* 2 js2-basic-offset)))
9821 (t
9822 (+ (current-column) js2-basic-offset))))
9823 (t
9824 (unless same-indent-p
9825 (forward-char)
9826 (skip-chars-forward " \t"))
9827 (current-column))))
9828
9829 (continued-expr-p js2-basic-offset)
9830
9831 (t 0)))))
9832
9833 (defun js2-lineup-comment (parse-status)
9834 "Indent a multi-line block comment continuation line."
9835 (let* ((beg (nth 8 parse-status))
9836 (first-line (js2-same-line beg))
9837 (offset (save-excursion
9838 (goto-char beg)
9839 (if (looking-at "/\\*")
9840 (+ 1 (current-column))
9841 0))))
9842 (unless first-line
9843 (indent-line-to offset))))
9844
9845 (defun js2-backward-sws ()
9846 "Move backward through whitespace and comments."
9847 (interactive)
9848 (while (forward-comment -1)))
9849
9850 (defun js2-forward-sws ()
9851 "Move forward through whitespace and comments."
9852 (interactive)
9853 (while (forward-comment 1)))
9854
9855 (defun js2-current-indent (&optional pos)
9856 "Return column of indentation on current line.
9857 If POS is non-nil, go to that point and return indentation for that line."
9858 (save-excursion
9859 (if pos
9860 (goto-char pos))
9861 (back-to-indentation)
9862 (current-column)))
9863
9864 (defun js2-arglist-close ()
9865 "Return non-nil if we're on a line beginning with a close-paren/brace."
9866 (save-excursion
9867 (goto-char (point-at-bol))
9868 (js2-forward-sws)
9869 (looking-at "[])}]")))
9870
9871 (defun js2-indent-looks-like-label-p ()
9872 (goto-char (point-at-bol))
9873 (js2-forward-sws)
9874 (looking-at (concat js2-mode-identifier-re ":")))
9875
9876 (defun js2-indent-in-objlit-p (parse-status)
9877 "Return non-nil if this looks like an object-literal entry."
9878 (let ((start (nth 1 parse-status)))
9879 (and
9880 start
9881 (save-excursion
9882 (and (zerop (forward-line -1))
9883 (not (< (point) start)) ; crossed a {} boundary
9884 (js2-indent-looks-like-label-p)))
9885 (save-excursion
9886 (js2-indent-looks-like-label-p)))))
9887
9888 ;; If prev line looks like foobar({ then we're passing an object
9889 ;; literal to a function call, and people pretty much always want to
9890 ;; de-dent back to the previous line, so move the 'basic-offset'
9891 ;; position to the front.
9892 (defun js2-indent-objlit-arg-p (parse-status)
9893 (save-excursion
9894 (back-to-indentation)
9895 (js2-backward-sws)
9896 (and (eq (1- (point)) (nth 1 parse-status))
9897 (eq (char-before) ?{)
9898 (progn
9899 (forward-char -1)
9900 (skip-chars-backward " \t")
9901 (eq (char-before) ?\()))))
9902
9903 (defun js2-indent-case-block-p ()
9904 (save-excursion
9905 (back-to-indentation)
9906 (js2-backward-sws)
9907 (goto-char (point-at-bol))
9908 (skip-chars-forward " \t")
9909 (looking-at "case\\s-.+:")))
9910
9911 (defun js2-syntax-bol ()
9912 "Return the point at the first non-whitespace char on the line.
9913 Returns `point-at-bol' if the line is empty."
9914 (save-excursion
9915 (beginning-of-line)
9916 (skip-chars-forward " \t")
9917 (point)))
9918
9919 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9920 "Cycle among alternate computed indentation positions.
9921 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9922 of the buffer to the current point. NORMAL-COL is the indentation
9923 column computed by the heuristic guesser based on current paren,
9924 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9925 in reverse."
9926 (let ((cur-indent (js2-current-indent))
9927 (old-buffer-undo-list buffer-undo-list)
9928 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9929 (current-line (save-excursion
9930 (forward-line 0) ; move to bol
9931 (1+ (count-lines (point-min) (point)))))
9932 positions pos main-pos anchor arglist-cont same-indent
9933 prev-line-col basic-offset computed-pos)
9934 ;; temporarily don't record undo info, if user requested this
9935 (when js2-mode-indent-inhibit-undo
9936 (setq buffer-undo-list t))
9937 (unwind-protect
9938 (progn
9939 ;; First likely point: indent from beginning of previous code line
9940 (push (setq basic-offset
9941 (+ (save-excursion
9942 (back-to-indentation)
9943 (js2-backward-sws)
9944 (back-to-indentation)
9945 (setq prev-line-col (current-column)))
9946 js2-basic-offset))
9947 positions)
9948
9949 ;; (First + epsilon) likely point: indent 2x from beginning of
9950 ;; previous code line. Google does it this way.
9951 (push (setq basic-offset
9952 (+ (save-excursion
9953 (back-to-indentation)
9954 (js2-backward-sws)
9955 (back-to-indentation)
9956 (setq prev-line-col (current-column)))
9957 (* 2 js2-basic-offset)))
9958 positions)
9959
9960 ;; Second likely point: indent from assign-expr RHS. This
9961 ;; is just a crude guess based on finding " = " on the previous
9962 ;; line containing actual code.
9963 (setq pos (save-excursion
9964 (forward-line -1)
9965 (goto-char (point-at-bol))
9966 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9967 (point-at-eol) t)
9968 (goto-char (match-end 1))
9969 (skip-chars-forward " \t\r\n")
9970 (current-column))))
9971 (when pos
9972 (incf pos js2-basic-offset)
9973 (push pos positions))
9974
9975 ;; Third likely point: same indent as previous line of code.
9976 ;; Make it the first likely point if we're not on an
9977 ;; arglist-close line and previous line ends in a comma, or
9978 ;; both this line and prev line look like object-literal
9979 ;; elements.
9980 (setq pos (save-excursion
9981 (goto-char (point-at-bol))
9982 (js2-backward-sws)
9983 (back-to-indentation)
9984 (prog1
9985 (current-column)
9986 ;; while we're here, look for trailing comma
9987 (if (save-excursion
9988 (goto-char (point-at-eol))
9989 (js2-backward-sws)
9990 (eq (char-before) ?,))
9991 (setq arglist-cont (1- (point)))))))
9992 (when pos
9993 (if (and (or arglist-cont
9994 (js2-indent-in-objlit-p parse-status))
9995 (not (js2-arglist-close)))
9996 (setq same-indent pos))
9997 (push pos positions))
9998
9999 ;; Fourth likely point: first preceding code with less indentation.
10000 ;; than the immediately preceding code line.
10001 (setq pos (save-excursion
10002 (back-to-indentation)
10003 (js2-backward-sws)
10004 (back-to-indentation)
10005 (setq anchor (current-column))
10006 (while (and (zerop (forward-line -1))
10007 (>= (progn
10008 (back-to-indentation)
10009 (current-column))
10010 anchor)))
10011 (setq pos (current-column))))
10012 (push pos positions)
10013
10014 ;; nesting-heuristic position, main by default
10015 (push (setq main-pos normal-col) positions)
10016
10017 ;; delete duplicates and sort positions list
10018 (setq positions (sort (delete-dups positions) '<))
10019
10020 ;; comma-list continuation lines: prev line indent takes precedence
10021 (if same-indent
10022 (setq main-pos same-indent))
10023
10024 ;; common special cases where we want to indent in from previous line
10025 (if (or (js2-indent-case-block-p)
10026 (js2-indent-objlit-arg-p parse-status))
10027 (setq main-pos basic-offset))
10028
10029 ;; if bouncing backwards, reverse positions list
10030 (if backwards
10031 (setq positions (reverse positions)))
10032
10033 ;; record whether we're already sitting on one of the alternatives
10034 (setq pos (member cur-indent positions))
10035
10036 (cond
10037 ;; case 0: we're one one of the alternatives and this is the
10038 ;; first time they've pressed TAB on this line (best-guess).
10039 ((and js2-mode-indent-ignore-first-tab
10040 pos
10041 ;; first time pressing TAB on this line?
10042 (not (eq js2-mode-last-indented-line current-line)))
10043 ;; do nothing
10044 (setq computed-pos nil))
10045 ;; case 1: only one computed position => use it
10046 ((null (cdr positions))
10047 (setq computed-pos 0))
10048 ;; case 2: not on any of the computed spots => use main spot
10049 ((not pos)
10050 (setq computed-pos (js2-position main-pos positions)))
10051 ;; case 3: on last position: cycle to first position
10052 ((null (cdr pos))
10053 (setq computed-pos 0))
10054 ;; case 4: on intermediate position: cycle to next position
10055 (t
10056 (setq computed-pos (js2-position (second pos) positions))))
10057
10058 ;; see if any hooks want to indent; otherwise we do it
10059 (loop with result = nil
10060 for hook in js2-indent-hook
10061 while (null result)
10062 do
10063 (setq result (funcall hook positions computed-pos))
10064 finally do
10065 (unless (or result (null computed-pos))
10066 (indent-line-to (nth computed-pos positions)))))
10067
10068 ;; finally
10069 (if js2-mode-indent-inhibit-undo
10070 (setq buffer-undo-list old-buffer-undo-list))
10071 ;; see commentary for `js2-mode-last-indented-line'
10072 (setq js2-mode-last-indented-line current-line))))
10073
10074 (defun js2-indent-bounce-backwards ()
10075 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10076 cycles between the computed indentation positions in reverse order."
10077 (interactive)
10078 (js2-indent-line t))
10079
10080 (defun js2-1-line-comment-continuation-p ()
10081 "Return t if we're in a 1-line comment continuation.
10082 If so, we don't ever want to use bounce-indent."
10083 (save-excursion
10084 (and (progn
10085 (forward-line 0)
10086 (looking-at "\\s-*//"))
10087 (progn
10088 (forward-line -1)
10089 (forward-line 0)
10090 (when (looking-at "\\s-*$")
10091 (js2-backward-sws)
10092 (forward-line 0))
10093 (looking-at "\\s-*//")))))
10094
10095 (defun js2-indent-line (&optional bounce-backwards)
10096 "Indent the current line as JavaScript source text."
10097 (interactive)
10098 (let (parse-status current-indent offset indent-col moved
10099 ;; Don't whine about errors/warnings when we're indenting.
10100 ;; This has to be set before calling parse-partial-sexp below.
10101 (inhibit-point-motion-hooks t))
10102 (setq parse-status (save-excursion
10103 (syntax-ppss (point-at-bol)))
10104 offset (- (point) (save-excursion
10105 (back-to-indentation)
10106 (point))))
10107 (js2-with-underscore-as-word-syntax
10108 (if (nth 4 parse-status)
10109 (js2-lineup-comment parse-status)
10110 (setq indent-col (js2-proper-indentation parse-status))
10111 ;; See comments below about `js2-mode-last-indented-line'.
10112 (cond
10113 ;; bounce-indenting is disabled during electric-key indent.
10114 ;; It doesn't work well on first line of buffer.
10115 ((and js2-bounce-indent-p
10116 (not (js2-same-line (point-min)))
10117 (not (js2-1-line-comment-continuation-p)))
10118 (js2-bounce-indent indent-col parse-status bounce-backwards))
10119 ;; just indent to the guesser's likely spot
10120 (t (indent-line-to indent-col))))
10121 (when (plusp offset)
10122 (forward-char offset)))))
10123
10124 (defun js2-indent-region (start end)
10125 "Indent the region, but don't use bounce indenting."
10126 (let ((js2-bounce-indent-p nil)
10127 (indent-region-function nil)
10128 (after-change-functions (remq 'js2-mode-edit
10129 after-change-functions)))
10130 (indent-region start end nil) ; nil for byte-compiler
10131 (js2-mode-edit start end (- end start))))
10132
10133 (defvar js2-minor-mode-map
10134 (let ((map (make-sparse-keymap)))
10135 (define-key map (kbd "C-c C-`") #'js2-next-error)
10136 (define-key map [mouse-1] #'js2-mode-show-node)
10137 map)
10138 "Keymap used when `js2-minor-mode' is active.")
10139
10140 ;;;###autoload
10141 (define-minor-mode js2-minor-mode
10142 "Minor mode for running js2 as a background linter.
10143 This allows you to use a different major mode for JavaScript editing,
10144 such as `espresso-mode', while retaining the asynchronous error/warning
10145 highlighting features of `js2-mode'."
10146 :group 'js2-mode
10147 :lighter " js-lint"
10148 (if js2-minor-mode
10149 (js2-minor-mode-enter)
10150 (js2-minor-mode-exit)))
10151
10152 (defun js2-minor-mode-enter ()
10153 "Initialization for `js2-minor-mode'."
10154 (set (make-local-variable 'max-lisp-eval-depth)
10155 (max max-lisp-eval-depth 3000))
10156 (setq next-error-function #'js2-next-error)
10157 (setq js2-default-externs
10158 (append js2-ecma-262-externs
10159 (if js2-include-browser-externs js2-browser-externs)
10160 (if js2-include-gears-externs js2-gears-externs)
10161 (if js2-include-rhino-externs js2-rhino-externs)))
10162 ;; Experiment: make reparse-delay longer for longer files.
10163 (if (plusp js2-dynamic-idle-timer-adjust)
10164 (setq js2-idle-timer-delay
10165 (* js2-idle-timer-delay
10166 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10167 (setq js2-mode-buffer-dirty-p t
10168 js2-mode-parsing nil)
10169 (set (make-local-variable 'js2-highlight-level) 0) ; no syntax highlighting
10170 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10171 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10172 (js2-reparse))
10173
10174 (defun js2-minor-mode-exit ()
10175 "Turn off `js2-minor-mode'."
10176 (setq next-error-function nil)
10177 (remove-hook 'after-change-functions #'js2-mode-edit t)
10178 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10179 (when js2-mode-node-overlay
10180 (delete-overlay js2-mode-node-overlay)
10181 (setq js2-mode-node-overlay nil))
10182 (js2-remove-overlays)
10183 (setq js2-mode-ast nil))
10184
10185 (defvar js2-source-buffer nil "Linked source buffer for diagnostics view")
10186 (make-variable-buffer-local 'js2-source-buffer)
10187
10188 (defun* js2-display-error-list ()
10189 "Display a navigable buffer listing parse errors/warnings."
10190 (interactive)
10191 (unless (js2-have-errors-p)
10192 (message "No errors")
10193 (return-from js2-display-error-list))
10194 (labels ((annotate-list
10195 (lst type)
10196 "Add diagnostic TYPE and line number to errs list"
10197 (mapcar (lambda (err)
10198 (list err type (line-number-at-pos (nth 1 err))))
10199 lst)))
10200 (let* ((srcbuf (current-buffer))
10201 (errbuf (get-buffer-create "*js-lint*"))
10202 (errors (annotate-list
10203 (when js2-mode-ast (js2-ast-root-errors js2-mode-ast))
10204 'js2-error)) ; must be a valid face name
10205 (warnings (annotate-list
10206 (when js2-mode-ast (js2-ast-root-warnings js2-mode-ast))
10207 'js2-warning)) ; must be a valid face name
10208 (all-errs (sort (append errors warnings)
10209 (lambda (e1 e2) (< (cadar e1) (cadar e2))))))
10210 (with-current-buffer errbuf
10211 (let ((inhibit-read-only t))
10212 (erase-buffer)
10213 (dolist (err all-errs)
10214 (destructuring-bind ((msg-key beg end &rest) type line) err
10215 (insert-text-button
10216 (format "line %d: %s" line (js2-get-msg msg-key))
10217 'face type
10218 'follow-link "\C-m"
10219 'action 'js2-error-buffer-jump
10220 'js2-msg (js2-get-msg msg-key)
10221 'js2-pos beg)
10222 (insert "\n"))))
10223 (js2-error-buffer-mode)
10224 (setq js2-source-buffer srcbuf)
10225 (pop-to-buffer errbuf)
10226 (goto-char (point-min))
10227 (unless (eobp)
10228 (js2-error-buffer-view))))))
10229
10230 (defvar js2-error-buffer-mode-map
10231 (let ((map (make-sparse-keymap)))
10232 (define-key map "n" #'js2-error-buffer-next)
10233 (define-key map "p" #'js2-error-buffer-prev)
10234 (define-key map (kbd "RET") #'js2-error-buffer-jump)
10235 (define-key map "o" #'js2-error-buffer-view)
10236 (define-key map "q" #'js2-error-buffer-quit)
10237 map)
10238 "Keymap used for js2 diagnostics buffers.")
10239
10240 (defun js2-error-buffer-mode ()
10241 "Major mode for js2 diagnostics buffers.
10242 Selecting an error will jump it to the corresponding source-buffer error.
10243 \\{js2-error-buffer-mode-map}"
10244 (interactive)
10245 (setq major-mode 'js2-error-buffer-mode
10246 mode-name "JS Lint Diagnostics")
10247 (use-local-map js2-error-buffer-mode-map)
10248 (setq truncate-lines t)
10249 (set-buffer-modified-p nil)
10250 (setq buffer-read-only t)
10251 (run-hooks 'js2-error-buffer-mode-hook))
10252
10253 (defun js2-error-buffer-next ()
10254 "Move to next error and view it."
10255 (interactive)
10256 (when (zerop (forward-line 1))
10257 (js2-error-buffer-view)))
10258
10259 (defun js2-error-buffer-prev ()
10260 "Move to previous error and view it."
10261 (interactive)
10262 (when (zerop (forward-line -1))
10263 (js2-error-buffer-view)))
10264
10265 (defun js2-error-buffer-quit ()
10266 "Kill the current buffer."
10267 (interactive)
10268 (kill-buffer))
10269
10270 (defun js2-error-buffer-jump (&rest ignored)
10271 "Jump cursor to current error in source buffer."
10272 (interactive)
10273 (when (js2-error-buffer-view)
10274 (pop-to-buffer js2-source-buffer)))
10275
10276 (defun js2-error-buffer-view ()
10277 "Scroll source buffer to show error at current line."
10278 (interactive)
10279 (cond
10280 ((not (eq major-mode 'js2-error-buffer-mode))
10281 (message "Not in a js2 errors buffer"))
10282 ((not (buffer-live-p js2-source-buffer))
10283 (message "Source buffer has been killed"))
10284 ((not (wholenump (get-text-property (point) 'js2-pos)))
10285 (message "There does not seem to be an error here"))
10286 (t
10287 (let ((pos (get-text-property (point) 'js2-pos))
10288 (msg (get-text-property (point) 'js2-msg)))
10289 (save-selected-window
10290 (pop-to-buffer js2-source-buffer)
10291 (goto-char pos)
10292 (message msg))))))
10293
10294 ;;;###autoload
10295 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10296 ;; FIXME: Should derive from js-mode.
10297 "Major mode for editing JavaScript code."
10298 (setq comment-start "//" ; used by comment-region; don't change it
10299 comment-end "")
10300 (set (make-local-variable 'max-lisp-eval-depth)
10301 (max max-lisp-eval-depth 3000))
10302 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10303 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10304 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10305 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10306 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10307 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10308 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10309 ;; for characters inside regexp literals.
10310 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10311 ;; this is necessary to make `show-paren-function' work properly
10312 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10313 ;; needed for M-x rgrep, among other things
10314 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10315
10316 (set (make-local-variable 'electric-indent-chars)
10317 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10318 electric-indent-chars))
10319 (set (make-local-variable 'electric-layout-rules)
10320 '((?\; . after) (?\{ . after) (?\} . before)))
10321
10322 ;; some variables needed by cc-engine for paragraph-fill, etc.
10323 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10324 c-comment-start-regexp "/[*/]\\|\\s|"
10325 c-line-comment-starter "//"
10326 c-paragraph-start js2-paragraph-start
10327 c-paragraph-separate "$"
10328 comment-start-skip js2-comment-start-skip
10329 c-syntactic-ws-start js2-syntactic-ws-start
10330 c-syntactic-ws-end js2-syntactic-ws-end
10331 c-syntactic-eol js2-syntactic-eol)
10332
10333 (let ((c-buffer-is-cc-mode t))
10334 ;; Copied from `js-mode'. Also see Bug#6071.
10335 (make-local-variable 'paragraph-start)
10336 (make-local-variable 'paragraph-separate)
10337 (make-local-variable 'paragraph-ignore-fill-prefix)
10338 (make-local-variable 'adaptive-fill-mode)
10339 (make-local-variable 'adaptive-fill-regexp)
10340 (c-setup-paragraph-variables))
10341
10342 (setq js2-default-externs
10343 (append js2-ecma-262-externs
10344 (if js2-include-browser-externs js2-browser-externs)
10345 (if js2-include-gears-externs js2-gears-externs)
10346 (if js2-include-rhino-externs js2-rhino-externs)))
10347
10348 (setq font-lock-defaults '(nil t))
10349
10350 ;; Experiment: make reparse-delay longer for longer files.
10351 (when (plusp js2-dynamic-idle-timer-adjust)
10352 (setq js2-idle-timer-delay
10353 (* js2-idle-timer-delay
10354 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10355
10356 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10357 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10358 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10359 (setq next-error-function #'js2-next-error)
10360 (imenu-add-to-menubar (concat "IM-" mode-name))
10361 (add-to-invisibility-spec '(js2-outline . t))
10362 (set (make-local-variable 'line-move-ignore-invisible) t)
10363 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10364
10365 (setq js2-mode-functions-hidden nil
10366 js2-mode-comments-hidden nil
10367 js2-mode-buffer-dirty-p t
10368 js2-mode-parsing nil)
10369 (js2-reparse))
10370
10371 (defun js2-mode-exit ()
10372 "Exit `js2-mode' and clean up."
10373 (interactive)
10374 (when js2-mode-node-overlay
10375 (delete-overlay js2-mode-node-overlay)
10376 (setq js2-mode-node-overlay nil))
10377 (js2-remove-overlays)
10378 (setq js2-mode-ast nil)
10379 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10380 (remove-from-invisibility-spec '(js2-outline . t))
10381 (js2-mode-show-all)
10382 (with-silent-modifications
10383 (js2-clear-face (point-min) (point-max))))
10384
10385 (defun js2-mode-reset-timer ()
10386 "Cancel any existing parse timer and schedule a new one."
10387 (if js2-mode-parse-timer
10388 (cancel-timer js2-mode-parse-timer))
10389 (setq js2-mode-parsing nil)
10390 (let ((timer (timer-create)))
10391 (setq js2-mode-parse-timer timer)
10392 (timer-set-function timer 'js2-mode-idle-reparse (list (current-buffer)))
10393 (timer-set-idle-time timer js2-idle-timer-delay)
10394 ;; http://debbugs.gnu.org/cgi/bugreport.cgi?bug=12326
10395 (timer-activate-when-idle timer nil)))
10396
10397 (defun js2-mode-idle-reparse (buffer)
10398 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10399 it to be reparsed when the buffer is selected."
10400 (if (eq buffer (current-buffer))
10401 (js2-reparse)
10402 ;; reparse when the buffer is selected again
10403 (with-current-buffer buffer
10404 (add-hook 'window-configuration-change-hook
10405 #'js2-mode-idle-reparse-inner
10406 nil t))))
10407
10408 (defun js2-mode-idle-reparse-inner ()
10409 (remove-hook 'window-configuration-change-hook
10410 #'js2-mode-idle-reparse-inner
10411 t)
10412 (js2-reparse))
10413
10414 (defun js2-mode-edit (beg end len)
10415 "Schedule a new parse after buffer is edited.
10416 Buffer edit spans from BEG to END and is of length LEN."
10417 (setq js2-mode-buffer-dirty-p t)
10418 (js2-mode-hide-overlay)
10419 (js2-mode-reset-timer))
10420
10421 (defun js2-minor-mode-edit (beg end len)
10422 "Callback for buffer edits in `js2-mode'.
10423 Schedules a new parse after buffer is edited.
10424 Buffer edit spans from BEG to END and is of length LEN."
10425 (setq js2-mode-buffer-dirty-p t)
10426 (js2-mode-hide-overlay)
10427 (js2-mode-reset-timer))
10428
10429 (defun js2-reparse (&optional force)
10430 "Re-parse current buffer after user finishes some data entry.
10431 If we get any user input while parsing, including cursor motion,
10432 we discard the parse and reschedule it. If FORCE is nil, then the
10433 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10434 (let (time
10435 interrupted-p
10436 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10437 (unless js2-mode-parsing
10438 (setq js2-mode-parsing t)
10439 (unwind-protect
10440 (when (or js2-mode-buffer-dirty-p force)
10441 (js2-remove-overlays)
10442 (with-silent-modifications
10443 (setq js2-mode-buffer-dirty-p nil
10444 js2-mode-fontifications nil
10445 js2-mode-deferred-properties nil)
10446 (if js2-mode-verbose-parse-p
10447 (message "parsing..."))
10448 (setq time
10449 (js2-time
10450 (setq interrupted-p
10451 (catch 'interrupted
10452 (js2-parse)
10453 ;; if parsing is interrupted, comments and regex
10454 ;; literals stay ignored by `parse-partial-sexp'
10455 (remove-text-properties (point-min) (point-max)
10456 '(syntax-table))
10457 (js2-mode-apply-deferred-properties)
10458 (js2-mode-remove-suppressed-warnings)
10459 (js2-mode-show-warnings)
10460 (js2-mode-show-errors)
10461 (if (>= js2-highlight-level 1)
10462 (js2-highlight-jsdoc js2-mode-ast))
10463 nil))))
10464 (if interrupted-p
10465 (progn
10466 ;; unfinished parse => try again
10467 (setq js2-mode-buffer-dirty-p t)
10468 (js2-mode-reset-timer))
10469 (if js2-mode-verbose-parse-p
10470 (message "Parse time: %s" time)))))
10471 (setq js2-mode-parsing nil)
10472 (unless interrupted-p
10473 (setq js2-mode-parse-timer nil))))))
10474
10475 (defun js2-mode-show-node (event)
10476 "Debugging aid: highlight selected AST node on mouse click."
10477 (interactive "e")
10478 (mouse-set-point event)
10479 (setq deactivate-mark t)
10480 (when js2-mode-show-overlay
10481 (let ((node (js2-node-at-point))
10482 beg end)
10483 (if (null node)
10484 (message "No node found at location %s" (point))
10485 (setq beg (js2-node-abs-pos node)
10486 end (+ beg (js2-node-len node)))
10487 (if js2-mode-node-overlay
10488 (move-overlay js2-mode-node-overlay beg end)
10489 (setq js2-mode-node-overlay (make-overlay beg end))
10490 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10491 (with-silent-modifications
10492 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10493 (message "%s, parent: %s"
10494 (js2-node-short-name node)
10495 (if (js2-node-parent node)
10496 (js2-node-short-name (js2-node-parent node))
10497 "nil"))))))
10498
10499 (defun js2-mode-hide-overlay (&optional p1 p2)
10500 "Remove the debugging overlay when the point moves.
10501 P1 and P2 are the old and new values of point, respectively."
10502 (when js2-mode-node-overlay
10503 (let ((beg (overlay-start js2-mode-node-overlay))
10504 (end (overlay-end js2-mode-node-overlay)))
10505 ;; Sometimes we're called spuriously.
10506 (unless (and p2
10507 (>= p2 beg)
10508 (<= p2 end))
10509 (with-silent-modifications
10510 (remove-text-properties beg end '(point-left nil)))
10511 (delete-overlay js2-mode-node-overlay)
10512 (setq js2-mode-node-overlay nil)))))
10513
10514 (defun js2-mode-reset ()
10515 "Debugging helper: reset everything."
10516 (interactive)
10517 (js2-mode-exit)
10518 (js2-mode))
10519
10520 (defun js2-mode-show-warn-or-err (e face)
10521 "Highlight a warning or error E with FACE.
10522 E is a list of ((MSG-KEY MSG-ARG) BEG LEN OVERRIDE-FACE).
10523 The last element is optional. When present, use instead of FACE."
10524 (let* ((key (first e))
10525 (beg (second e))
10526 (end (+ beg (third e)))
10527 ;; Don't inadvertently go out of bounds.
10528 (beg (max (point-min) (min beg (point-max))))
10529 (end (max (point-min) (min end (point-max))))
10530 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10531 (ovl (make-overlay beg end)))
10532 (overlay-put ovl 'font-lock-face (or (fourth e) face))
10533 (overlay-put ovl 'js2-error t)
10534 (put-text-property beg end 'help-echo (js2-get-msg key))
10535 (put-text-property beg end 'point-entered #'js2-echo-error)))
10536
10537 (defun js2-remove-overlays ()
10538 "Remove overlays from buffer that have a `js2-error' property."
10539 (let ((beg (point-min))
10540 (end (point-max)))
10541 (save-excursion
10542 (dolist (o (overlays-in beg end))
10543 (when (overlay-get o 'js2-error)
10544 (delete-overlay o))))))
10545
10546 (defun js2-error-at-point (&optional pos)
10547 "Return non-nil if there's an error overlay at POS.
10548 Defaults to point."
10549 (loop with pos = (or pos (point))
10550 for o in (overlays-at pos)
10551 thereis (overlay-get o 'js2-error)))
10552
10553 (defun js2-mode-apply-deferred-properties ()
10554 "Apply fontifications and other text properties recorded during parsing."
10555 (when (plusp js2-highlight-level)
10556 ;; We defer clearing faces as long as possible to eliminate flashing.
10557 (js2-clear-face (point-min) (point-max))
10558 ;; Have to reverse the recorded fontifications list so that errors
10559 ;; and warnings overwrite the normal fontifications.
10560 (dolist (f (nreverse js2-mode-fontifications))
10561 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10562 (setq js2-mode-fontifications nil))
10563 (dolist (p js2-mode-deferred-properties)
10564 (apply #'put-text-property p))
10565 (setq js2-mode-deferred-properties nil))
10566
10567 (defun js2-mode-show-errors ()
10568 "Highlight syntax errors."
10569 (when js2-mode-show-parse-errors
10570 (dolist (e (js2-ast-root-errors js2-mode-ast))
10571 (js2-mode-show-warn-or-err e 'js2-error))))
10572
10573 (defun js2-mode-remove-suppressed-warnings ()
10574 "Take suppressed warnings out of the AST warnings list.
10575 This ensures that the counts and `next-error' are correct."
10576 (setf (js2-ast-root-warnings js2-mode-ast)
10577 (js2-delete-if
10578 (lambda (e)
10579 (let ((key (caar e)))
10580 (or
10581 (and (not js2-strict-trailing-comma-warning)
10582 (string-match "trailing\\.comma" key))
10583 (and (not js2-strict-cond-assign-warning)
10584 (string= key "msg.equal.as.assign"))
10585 (and js2-missing-semi-one-line-override
10586 (string= key "msg.missing.semi")
10587 (let* ((beg (second e))
10588 (node (js2-node-at-point beg))
10589 (fn (js2-mode-find-parent-fn node))
10590 (body (and fn (js2-function-node-body fn)))
10591 (lc (and body (js2-node-abs-pos body)))
10592 (rc (and lc (+ lc (js2-node-len body)))))
10593 (and fn
10594 (or (null body)
10595 (save-excursion
10596 (goto-char beg)
10597 (and (js2-same-line lc)
10598 (js2-same-line rc))))))))))
10599 (js2-ast-root-warnings js2-mode-ast))))
10600
10601 (defun js2-mode-show-warnings ()
10602 "Highlight strict-mode warnings."
10603 (when js2-mode-show-strict-warnings
10604 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10605 (js2-mode-show-warn-or-err e 'js2-warning))))
10606
10607 (defun js2-echo-error (old-point new-point)
10608 "Called by point-motion hooks."
10609 (let ((msg (get-text-property new-point 'help-echo)))
10610 (when (and (stringp msg) (or (not (current-message))
10611 (string= (current-message) "Quit")))
10612 (message msg))))
10613
10614 (defalias #'js2-echo-help #'js2-echo-error)
10615
10616 (defun js2-line-break (&optional soft)
10617 "Break line at point and indent, continuing comment if within one.
10618 If inside a string, and `js2-concat-multiline-strings' is not
10619 nil, turn it into concatenation."
10620 (interactive)
10621 (let ((parse-status (syntax-ppss)))
10622 (cond
10623 ;; Check if we're inside a string.
10624 ((nth 3 parse-status)
10625 (if js2-concat-multiline-strings
10626 (js2-mode-split-string parse-status)
10627 (insert "\n")))
10628 ;; Check if inside a block comment.
10629 ((nth 4 parse-status)
10630 (js2-mode-extend-comment (nth 8 parse-status)))
10631 (t
10632 (newline-and-indent)))))
10633
10634 (defun js2-mode-split-string (parse-status)
10635 "Turn a newline in mid-string into a string concatenation.
10636 PARSE-STATUS is as documented in `parse-partial-sexp'."
10637 (let* ((col (current-column))
10638 (quote-char (nth 3 parse-status))
10639 (string-beg (nth 8 parse-status))
10640 (at-eol (eq js2-concat-multiline-strings 'eol)))
10641 (insert quote-char)
10642 (if at-eol
10643 (insert " +\n")
10644 (insert "\n"))
10645 (unless at-eol
10646 (insert "+ "))
10647 (js2-indent-line)
10648 (insert quote-char)
10649 (when (eolp)
10650 (insert quote-char)
10651 (backward-char 1))))
10652
10653 (defun js2-mode-extend-comment (start-pos)
10654 "Indent the line and, when inside a comment block, add comment prefix."
10655 (let (star single col first-line needs-close)
10656 (save-excursion
10657 (back-to-indentation)
10658 (when (< (point) start-pos)
10659 (goto-char start-pos))
10660 (cond
10661 ((looking-at "\\*[^/]")
10662 (setq star t
10663 col (current-column)))
10664 ((looking-at "/\\*")
10665 (setq star t
10666 first-line t
10667 col (1+ (current-column))))
10668 ((looking-at "//")
10669 (setq single t
10670 col (current-column)))))
10671 ;; Heuristic for whether we need to close the comment:
10672 ;; if we've got a parse error here, assume it's an unterminated
10673 ;; comment.
10674 (setq needs-close
10675 (or
10676 (eq (get-text-property (1- (point)) 'point-entered)
10677 'js2-echo-error)
10678 ;; The heuristic above doesn't work well when we're
10679 ;; creating a comment and there's another one downstream,
10680 ;; as our parser thinks this one ends at the end of the
10681 ;; next one. (You can have a /* inside a js block comment.)
10682 ;; So just close it if the next non-ws char isn't a *.
10683 (and first-line
10684 (eolp)
10685 (save-excursion
10686 (skip-chars-forward " \t\r\n")
10687 (not (eq (char-after) ?*))))))
10688 (delete-horizontal-space)
10689 (insert "\n")
10690 (cond
10691 (star
10692 (indent-to col)
10693 (insert "* ")
10694 (if (and first-line needs-close)
10695 (save-excursion
10696 (insert "\n")
10697 (indent-to col)
10698 (insert "*/"))))
10699 ((and single
10700 (save-excursion
10701 (and (zerop (forward-line 1))
10702 (looking-at "\\s-*//"))))
10703 (indent-to col)
10704 (insert "// ")))
10705 ;; Don't need to extend the comment after all.
10706 (js2-indent-line)))
10707
10708 (defun js2-beginning-of-line ()
10709 "Toggle point between bol and first non-whitespace char in line.
10710 Also moves past comment delimiters when inside comments."
10711 (interactive)
10712 (let (node beg)
10713 (cond
10714 ((bolp)
10715 (back-to-indentation))
10716 ((looking-at "//")
10717 (skip-chars-forward "/ \t"))
10718 ((and (eq (char-after) ?*)
10719 (setq node (js2-comment-at-point))
10720 (memq (js2-comment-node-format node) '(jsdoc block))
10721 (save-excursion
10722 (skip-chars-backward " \t")
10723 (bolp)))
10724 (skip-chars-forward "\* \t"))
10725 (t
10726 (goto-char (point-at-bol))))))
10727
10728 (defun js2-end-of-line ()
10729 "Toggle point between eol and last non-whitespace char in line."
10730 (interactive)
10731 (if (eolp)
10732 (skip-chars-backward " \t")
10733 (goto-char (point-at-eol))))
10734
10735 (defsubst js2-mode-inside-string ()
10736 "Return non-nil if inside a string.
10737 Actually returns the quote character that begins the string."
10738 (nth 3 (syntax-ppss)))
10739
10740 (defun js2-mode-inside-comment-or-string ()
10741 "Return non-nil if inside a comment or string."
10742 (or
10743 (let ((comment-start
10744 (save-excursion
10745 (goto-char (point-at-bol))
10746 (if (re-search-forward "//" (point-at-eol) t)
10747 (match-beginning 0)))))
10748 (and comment-start
10749 (<= comment-start (point))))
10750 (let ((parse-state (syntax-ppss)))
10751 (or (nth 3 parse-state)
10752 (nth 4 parse-state)))))
10753
10754
10755 (defun js2-insert-catch-skel (try-pos)
10756 "Complete a try/catch block after inserting a { following a try keyword.
10757 Rationale is that a try always needs a catch or a finally, and the catch is
10758 the more likely of the two.
10759
10760 TRY-POS is the buffer position of the try keyword. The open-curly should
10761 already have been inserted."
10762 (insert "{")
10763 (let ((try-col (save-excursion
10764 (goto-char try-pos)
10765 (current-column))))
10766 (insert "\n")
10767 (undo-boundary)
10768 (js2-indent-line) ;; indent the blank line where cursor will end up
10769 (save-excursion
10770 (insert "\n")
10771 (indent-to try-col)
10772 (insert "} catch (x) {\n\n")
10773 (indent-to try-col)
10774 (insert "}"))))
10775
10776
10777 (defun js2-mode-wait-for-parse (callback)
10778 "Invoke CALLBACK when parsing is finished.
10779 If parsing is already finished, calls CALLBACK immediately."
10780 (if (not js2-mode-buffer-dirty-p)
10781 (funcall callback)
10782 (push callback js2-mode-pending-parse-callbacks)
10783 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10784
10785 (defun js2-mode-parse-finished ()
10786 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10787 ;; We can't let errors propagate up, since it prevents the
10788 ;; `js2-parse' method from completing normally and returning
10789 ;; the ast, which makes things mysteriously not work right.
10790 (unwind-protect
10791 (dolist (cb js2-mode-pending-parse-callbacks)
10792 (condition-case err
10793 (funcall cb)
10794 (error (message "%s" err))))
10795 (setq js2-mode-pending-parse-callbacks nil)))
10796
10797 (defun js2-mode-flag-region (from to flag)
10798 "Hide or show text from FROM to TO, according to FLAG.
10799 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10800 Returns the created overlay if FLAG is non-nil."
10801 (remove-overlays from to 'invisible 'js2-outline)
10802 (when flag
10803 (let ((o (make-overlay from to)))
10804 (overlay-put o 'invisible 'js2-outline)
10805 (overlay-put o 'isearch-open-invisible
10806 'js2-isearch-open-invisible)
10807 o)))
10808
10809 ;; Function to be set as an outline-isearch-open-invisible' property
10810 ;; to the overlay that makes the outline invisible (see
10811 ;; `js2-mode-flag-region').
10812 (defun js2-isearch-open-invisible (overlay)
10813 ;; We rely on the fact that isearch places point on the matched text.
10814 (js2-mode-show-element))
10815
10816 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10817 "Return cons cell of bounds of folding overlay at POS.
10818 Returns nil if not found."
10819 (let ((overlays (overlays-at (or pos (point))))
10820 o)
10821 (while (and overlays
10822 (not o))
10823 (if (overlay-get (car overlays) 'invisible)
10824 (setq o (car overlays))
10825 (setq overlays (cdr overlays))))
10826 (if o
10827 (cons (overlay-start o) (overlay-end o)))))
10828
10829 (defun js2-mode-function-at-point (&optional pos)
10830 "Return the innermost function node enclosing current point.
10831 Returns nil if point is not in a function."
10832 (let ((node (js2-node-at-point pos)))
10833 (while (and node (not (js2-function-node-p node)))
10834 (setq node (js2-node-parent node)))
10835 (if (js2-function-node-p node)
10836 node)))
10837
10838 (defun js2-mode-toggle-element ()
10839 "Hide or show the foldable element at the point."
10840 (interactive)
10841 (let (comment fn pos)
10842 (save-excursion
10843 (cond
10844 ;; /* ... */ comment?
10845 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10846 (if (js2-mode-invisible-overlay-bounds
10847 (setq pos (+ 3 (js2-node-abs-pos comment))))
10848 (progn
10849 (goto-char pos)
10850 (js2-mode-show-element))
10851 (js2-mode-hide-element)))
10852 ;; //-comment?
10853 ((save-excursion
10854 (back-to-indentation)
10855 (looking-at js2-mode-//-comment-re))
10856 (js2-mode-toggle-//-comment))
10857 ;; function?
10858 ((setq fn (js2-mode-function-at-point))
10859 (setq pos (and (js2-function-node-body fn)
10860 (js2-node-abs-pos (js2-function-node-body fn))))
10861 (goto-char (1+ pos))
10862 (if (js2-mode-invisible-overlay-bounds)
10863 (js2-mode-show-element)
10864 (js2-mode-hide-element)))
10865 (t
10866 (message "Nothing at point to hide or show"))))))
10867
10868 (defun js2-mode-hide-element ()
10869 "Fold/hide contents of a block, showing ellipses.
10870 Show the hidden text with \\[js2-mode-show-element]."
10871 (interactive)
10872 (if js2-mode-buffer-dirty-p
10873 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10874 (let (node body beg end)
10875 (cond
10876 ((js2-mode-invisible-overlay-bounds)
10877 (message "already hidden"))
10878 (t
10879 (setq node (js2-node-at-point))
10880 (cond
10881 ((js2-block-comment-p node)
10882 (js2-mode-hide-comment node))
10883 (t
10884 (while (and node (not (js2-function-node-p node)))
10885 (setq node (js2-node-parent node)))
10886 (if (and node
10887 (setq body (js2-function-node-body node)))
10888 (progn
10889 (setq beg (js2-node-abs-pos body)
10890 end (+ beg (js2-node-len body)))
10891 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10892 (message "No collapsable element found at point"))))))))
10893
10894 (defun js2-mode-show-element ()
10895 "Show the hidden element at current point."
10896 (interactive)
10897 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10898 (if bounds
10899 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10900 (message "Nothing to un-hide"))))
10901
10902 (defun js2-mode-show-all ()
10903 "Show all of the text in the buffer."
10904 (interactive)
10905 (js2-mode-flag-region (point-min) (point-max) nil))
10906
10907 (defun js2-mode-toggle-hide-functions ()
10908 (interactive)
10909 (if js2-mode-functions-hidden
10910 (js2-mode-show-functions)
10911 (js2-mode-hide-functions)))
10912
10913 (defun js2-mode-hide-functions ()
10914 "Hides all non-nested function bodies in the buffer.
10915 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10916 to open an individual entry."
10917 (interactive)
10918 (if js2-mode-buffer-dirty-p
10919 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10920 (if (null js2-mode-ast)
10921 (message "Oops - parsing failed")
10922 (setq js2-mode-functions-hidden t)
10923 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10924
10925 (defun js2-mode-function-hider (n endp)
10926 (when (not endp)
10927 (let ((tt (js2-node-type n))
10928 body beg end)
10929 (cond
10930 ((and (= tt js2-FUNCTION)
10931 (setq body (js2-function-node-body n)))
10932 (setq beg (js2-node-abs-pos body)
10933 end (+ beg (js2-node-len body)))
10934 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10935 nil) ; don't process children of function
10936 (t
10937 t))))) ; keep processing other AST nodes
10938
10939 (defun js2-mode-show-functions ()
10940 "Un-hide any folded function bodies in the buffer."
10941 (interactive)
10942 (setq js2-mode-functions-hidden nil)
10943 (save-excursion
10944 (goto-char (point-min))
10945 (while (/= (goto-char (next-overlay-change (point)))
10946 (point-max))
10947 (dolist (o (overlays-at (point)))
10948 (when (and (overlay-get o 'invisible)
10949 (not (overlay-get o 'comment)))
10950 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10951
10952 (defun js2-mode-hide-comment (n)
10953 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10954 3 ; /**
10955 2)) ; /*
10956 (beg (+ (js2-node-abs-pos n) head))
10957 (end (- (+ beg (js2-node-len n)) head 2))
10958 (o (js2-mode-flag-region beg end 'hide)))
10959 (overlay-put o 'comment t)))
10960
10961 (defun js2-mode-toggle-hide-comments ()
10962 "Folds all block comments in the buffer.
10963 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10964 to open an individual entry."
10965 (interactive)
10966 (if js2-mode-comments-hidden
10967 (js2-mode-show-comments)
10968 (js2-mode-hide-comments)))
10969
10970 (defun js2-mode-hide-comments ()
10971 (interactive)
10972 (if js2-mode-buffer-dirty-p
10973 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10974 (if (null js2-mode-ast)
10975 (message "Oops - parsing failed")
10976 (setq js2-mode-comments-hidden t)
10977 (dolist (n (js2-ast-root-comments js2-mode-ast))
10978 (let ((format (js2-comment-node-format n)))
10979 (when (js2-block-comment-p n)
10980 (js2-mode-hide-comment n))))
10981 (js2-mode-hide-//-comments)))
10982
10983 (defun js2-mode-extend-//-comment (direction)
10984 "Find start or end of a block of similar //-comment lines.
10985 DIRECTION is -1 to look back, 1 to look forward.
10986 INDENT is the indentation level to match.
10987 Returns the end-of-line position of the furthest adjacent
10988 //-comment line with the same indentation as the current line.
10989 If there is no such matching line, returns current end of line."
10990 (let ((pos (point-at-eol))
10991 (indent (current-indentation)))
10992 (save-excursion
10993 (while (and (zerop (forward-line direction))
10994 (looking-at js2-mode-//-comment-re)
10995 (eq indent (length (match-string 1))))
10996 (setq pos (point-at-eol))
10997 pos))))
10998
10999 (defun js2-mode-hide-//-comments ()
11000 "Fold adjacent 1-line comments, showing only snippet of first one."
11001 (let (beg end)
11002 (save-excursion
11003 (goto-char (point-min))
11004 (while (re-search-forward js2-mode-//-comment-re nil t)
11005 (setq beg (point)
11006 end (js2-mode-extend-//-comment 1))
11007 (unless (eq beg end)
11008 (overlay-put (js2-mode-flag-region beg end 'hide)
11009 'comment t))
11010 (goto-char end)
11011 (forward-char 1)))))
11012
11013 (defun js2-mode-toggle-//-comment ()
11014 "Fold or un-fold any multi-line //-comment at point.
11015 Caller should have determined that this line starts with a //-comment."
11016 (let* ((beg (point-at-eol))
11017 (end beg))
11018 (save-excursion
11019 (goto-char end)
11020 (if (js2-mode-invisible-overlay-bounds)
11021 (js2-mode-show-element)
11022 ;; else hide the comment
11023 (setq beg (js2-mode-extend-//-comment -1)
11024 end (js2-mode-extend-//-comment 1))
11025 (unless (eq beg end)
11026 (overlay-put (js2-mode-flag-region beg end 'hide)
11027 'comment t))))))
11028
11029 (defun js2-mode-show-comments ()
11030 "Un-hide any hidden comments, leaving other hidden elements alone."
11031 (interactive)
11032 (setq js2-mode-comments-hidden nil)
11033 (save-excursion
11034 (goto-char (point-min))
11035 (while (/= (goto-char (next-overlay-change (point)))
11036 (point-max))
11037 (dolist (o (overlays-at (point)))
11038 (when (overlay-get o 'comment)
11039 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11040
11041 (defun js2-mode-display-warnings-and-errors ()
11042 "Turn on display of warnings and errors."
11043 (interactive)
11044 (setq js2-mode-show-parse-errors t
11045 js2-mode-show-strict-warnings t)
11046 (js2-reparse 'force))
11047
11048 (defun js2-mode-hide-warnings-and-errors ()
11049 "Turn off display of warnings and errors."
11050 (interactive)
11051 (setq js2-mode-show-parse-errors nil
11052 js2-mode-show-strict-warnings nil)
11053 (js2-reparse 'force))
11054
11055 (defun js2-mode-toggle-warnings-and-errors ()
11056 "Toggle the display of warnings and errors.
11057 Some users don't like having warnings/errors reported while they type."
11058 (interactive)
11059 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11060 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11061 (if (called-interactively-p 'any)
11062 (message "warnings and errors %s"
11063 (if js2-mode-show-parse-errors
11064 "enabled"
11065 "disabled")))
11066 (js2-reparse 'force))
11067
11068 (defun js2-mode-customize ()
11069 (interactive)
11070 (customize-group 'js2-mode))
11071
11072 (defun js2-mode-forward-sexp (&optional arg)
11073 "Move forward across one statement or balanced expression.
11074 With ARG, do it that many times. Negative arg -N means
11075 move backward across N balanced expressions."
11076 (interactive "p")
11077 (setq arg (or arg 1))
11078 (save-restriction
11079 (widen) ;; `blink-matching-open' calls `narrow-to-region'
11080 (js2-reparse))
11081 (let ((scan-msg "Containing expression ends prematurely")
11082 node (start (point)) pos lp rp child)
11083 (cond
11084 ;; backward-sexp
11085 ;; could probably make this better for some cases:
11086 ;; - if in statement block (e.g. function body), go to parent
11087 ;; - infix exprs like (foo in bar) - maybe go to beginning
11088 ;; of infix expr if in the right-side expression?
11089 ((and arg (minusp arg))
11090 (dotimes (i (- arg))
11091 (js2-backward-sws)
11092 (forward-char -1) ; enter the node we backed up to
11093 (when (setq node (js2-node-at-point (point) t))
11094 (setq pos (js2-node-abs-pos node))
11095 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11096 (setq lp (car parens)
11097 rp (cdr parens))))
11098 (goto-char
11099 (or (when (and lp (> start lp))
11100 (if (and rp (<= start rp))
11101 (if (setq child (js2-node-closest-child node (point) lp t))
11102 (js2-node-abs-pos child)
11103 (goto-char start)
11104 (signal 'scan-error (list scan-msg lp lp)))
11105 lp))
11106 pos
11107 (point-min)))))
11108 (t
11109 ;; forward-sexp
11110 (js2-forward-sws)
11111 (dotimes (i arg)
11112 (js2-forward-sws)
11113 (when (setq node (js2-node-at-point (point) t))
11114 (setq pos (js2-node-abs-pos node))
11115 (let ((parens (js2-mode-forward-sexp-parens node pos)))
11116 (setq lp (car parens)
11117 rp (cdr parens))))
11118 (goto-char
11119 (or (when (and rp (<= start rp))
11120 (if (> start lp)
11121 (if (setq child (js2-node-closest-child node (point) rp))
11122 (js2-node-abs-end child)
11123 (goto-char start)
11124 (signal 'scan-error (list scan-msg rp (1+ rp))))
11125 (1+ rp)))
11126 (and pos
11127 (+ pos
11128 (js2-node-len
11129 (if (js2-expr-stmt-node-p (js2-node-parent node))
11130 ;; stop after the semicolon
11131 (js2-node-parent node)
11132 node))))
11133 (point-max))))))))
11134
11135 (defun js2-mode-forward-sexp-parens (node abs-pos)
11136 (cond
11137 ((or (js2-array-node-p node)
11138 (js2-object-node-p node)
11139 (js2-array-comp-node-p node)
11140 (memq (aref node 0) '(cl-struct-js2-block-node cl-struct-js2-scope)))
11141 (cons abs-pos (+ abs-pos (js2-node-len node) -1)))
11142 ((js2-paren-expr-node-p node)
11143 (let ((lp (js2-node-lp node))
11144 (rp (js2-node-rp node)))
11145 (cons (when lp (+ abs-pos lp))
11146 (when rp (+ abs-pos rp)))))))
11147
11148 (defun js2-node-closest-child (parent point limit &optional before)
11149 (let* ((parent-pos (js2-node-abs-pos parent))
11150 (rpoint (- point parent-pos))
11151 (rlimit (- limit parent-pos))
11152 (min (min rpoint rlimit))
11153 (max (max rpoint rlimit))
11154 found)
11155 (catch 'done
11156 (js2-visit-ast
11157 parent
11158 (lambda (node end-p)
11159 (if (eq node parent)
11160 t
11161 (let ((pos (js2-node-pos node)) ;; Both relative values.
11162 (end (+ (js2-node-pos node) (js2-node-len node))))
11163 (when (and (>= pos min) (<= end max)
11164 (if before (< pos rpoint) (> end rpoint)))
11165 (setq found node))
11166 (when (> end rpoint)
11167 (throw 'done nil)))
11168 nil))))
11169 found))
11170
11171 (defun js2-errors ()
11172 "Return a list of errors found."
11173 (and js2-mode-ast
11174 (js2-ast-root-errors js2-mode-ast)))
11175
11176 (defun js2-warnings ()
11177 "Return a list of warnings found."
11178 (and js2-mode-ast
11179 (js2-ast-root-warnings js2-mode-ast)))
11180
11181 (defun js2-have-errors-p ()
11182 "Return non-nil if any parse errors or warnings were found."
11183 (or (js2-errors) (js2-warnings)))
11184
11185 (defun js2-errors-and-warnings ()
11186 "Return a copy of the concatenated errors and warnings lists.
11187 They are appended: first the errors, then the warnings.
11188 Entries are of the form (MSG BEG END)."
11189 (when js2-mode-ast
11190 (append (js2-ast-root-errors js2-mode-ast)
11191 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11192
11193 (defun js2-next-error (&optional arg reset)
11194 "Move to next parse error.
11195 Typically invoked via \\[next-error].
11196 ARG is the number of errors, forward or backward, to move.
11197 RESET means start over from the beginning."
11198 (interactive "p")
11199 (if (not (or (js2-errors) (js2-warnings)))
11200 (message "No errors")
11201 (when reset
11202 (goto-char (point-min)))
11203 (let* ((errs (js2-errors-and-warnings))
11204 (continue t)
11205 (start (point))
11206 (count (or arg 1))
11207 (backward (minusp count))
11208 (sorter (if backward '> '<))
11209 (stopper (if backward '< '>))
11210 (count (abs count))
11211 all-errs err)
11212 ;; Sort by start position.
11213 (setq errs (sort errs (lambda (e1 e2)
11214 (funcall sorter (second e1) (second e2))))
11215 all-errs errs)
11216 ;; Find nth error with pos > start.
11217 (while (and errs continue)
11218 (when (funcall stopper (cadar errs) start)
11219 (setq err (car errs))
11220 (if (zerop (decf count))
11221 (setq continue nil)))
11222 (setq errs (cdr errs)))
11223 (if err
11224 (goto-char (second err))
11225 ;; Wrap around to first error.
11226 (goto-char (second (car all-errs)))
11227 ;; If we were already on it, echo msg again.
11228 (if (= (point) start)
11229 (js2-echo-error (point) (point)))))))
11230
11231 (defun js2-down-mouse-3 ()
11232 "Make right-click move the point to the click location.
11233 This makes right-click context menu operations a bit more intuitive.
11234 The point will not move if the region is active, however, to avoid
11235 destroying the region selection."
11236 (interactive)
11237 (when (and js2-move-point-on-right-click
11238 (not mark-active))
11239 (let ((e last-input-event))
11240 (ignore-errors
11241 (goto-char (cadadr e))))))
11242
11243 (defun js2-mode-create-imenu-index ()
11244 "Return an alist for `imenu--index-alist'."
11245 ;; This is built up in `js2-parse-record-imenu' during parsing.
11246 (when js2-mode-ast
11247 ;; if we have an ast but no recorder, they're requesting a rescan
11248 (unless js2-imenu-recorder
11249 (js2-reparse 'force))
11250 (prog1
11251 (js2-build-imenu-index)
11252 (setq js2-imenu-recorder nil
11253 js2-imenu-function-map nil))))
11254
11255 (defun js2-mode-find-tag ()
11256 "Replacement for `find-tag-default'.
11257 `find-tag-default' returns a ridiculous answer inside comments."
11258 (let (beg end)
11259 (js2-with-underscore-as-word-syntax
11260 (save-excursion
11261 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11262 (looking-back "[A-Za-z0-9_$]"))
11263 (setq beg (progn (forward-word -1) (point))
11264 end (progn (forward-word 1) (point)))
11265 (setq beg (progn (forward-word 1) (point))
11266 end (progn (forward-word -1) (point))))
11267 (replace-regexp-in-string
11268 "[\"']" ""
11269 (buffer-substring-no-properties beg end))))))
11270
11271 (defun js2-mode-forward-sibling ()
11272 "Move to the end of the sibling following point in parent.
11273 Returns non-nil if successful, or nil if there was no following sibling."
11274 (let* ((node (js2-node-at-point))
11275 (parent (js2-mode-find-enclosing-fn node))
11276 sib)
11277 (when (setq sib (js2-node-find-child-after (point) parent))
11278 (goto-char (+ (js2-node-abs-pos sib)
11279 (js2-node-len sib))))))
11280
11281 (defun js2-mode-backward-sibling ()
11282 "Move to the beginning of the sibling node preceding point in parent.
11283 Parent is defined as the enclosing script or function."
11284 (let* ((node (js2-node-at-point))
11285 (parent (js2-mode-find-enclosing-fn node))
11286 sib)
11287 (when (setq sib (js2-node-find-child-before (point) parent))
11288 (goto-char (js2-node-abs-pos sib)))))
11289
11290 (defun js2-beginning-of-defun (&optional arg)
11291 "Go to line on which current function starts, and return t on success.
11292 If we're not in a function or already at the beginning of one, go
11293 to beginning of previous script-level element.
11294 With ARG N, do that N times. If N is negative, move forward."
11295 (setq arg (or arg 1))
11296 (if (plusp arg)
11297 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11298 (when (cond
11299 ((js2-function-node-p parent)
11300 (goto-char (js2-node-abs-pos parent)))
11301 (t
11302 (js2-mode-backward-sibling)))
11303 (if (> arg 1)
11304 (js2-beginning-of-defun (1- arg))
11305 t)))
11306 (when (js2-end-of-defun)
11307 (if (>= arg -1)
11308 (js2-beginning-of-defun 1)
11309 (js2-beginning-of-defun (1+ arg))))))
11310
11311 (defun js2-end-of-defun ()
11312 "Go to the char after the last position of the current function
11313 or script-level element."
11314 (let* ((node (js2-node-at-point))
11315 (parent (or (and (js2-function-node-p node) node)
11316 (js2-node-parent-script-or-fn node)))
11317 script)
11318 (unless (js2-function-node-p parent)
11319 ;; Use current script-level node, or, if none, the next one.
11320 (setq script (or parent node)
11321 parent (js2-node-find-child-before (point) script))
11322 (when (or (null parent)
11323 (>= (point) (+ (js2-node-abs-pos parent)
11324 (js2-node-len parent))))
11325 (setq parent (js2-node-find-child-after (point) script))))
11326 (when parent
11327 (goto-char (+ (js2-node-abs-pos parent)
11328 (js2-node-len parent))))))
11329
11330 (defun js2-mark-defun (&optional allow-extend)
11331 "Put mark at end of this function, point at beginning.
11332 The function marked is the one that contains point.
11333
11334 Interactively, if this command is repeated,
11335 or (in Transient Mark mode) if the mark is active,
11336 it marks the next defun after the ones already marked."
11337 (interactive "p")
11338 (let (extended)
11339 (when (and allow-extend
11340 (or (and (eq last-command this-command) (mark t))
11341 (and transient-mark-mode mark-active)))
11342 (let ((sib (save-excursion
11343 (goto-char (mark))
11344 (if (js2-mode-forward-sibling)
11345 (point))))
11346 node)
11347 (if sib
11348 (progn
11349 (set-mark sib)
11350 (setq extended t))
11351 ;; no more siblings - try extending to enclosing node
11352 (goto-char (mark t)))))
11353 (when (not extended)
11354 (let ((node (js2-node-at-point (point) t)) ; skip comments
11355 ast fn stmt parent beg end)
11356 (when (js2-ast-root-p node)
11357 (setq ast node
11358 node (or (js2-node-find-child-after (point) node)
11359 (js2-node-find-child-before (point) node))))
11360 ;; only mark whole buffer if we can't find any children
11361 (if (null node)
11362 (setq node ast))
11363 (if (js2-function-node-p node)
11364 (setq parent node)
11365 (setq fn (js2-mode-find-enclosing-fn node)
11366 stmt (if (or (null fn)
11367 (js2-ast-root-p fn))
11368 (js2-mode-find-first-stmt node))
11369 parent (or stmt fn)))
11370 (setq beg (js2-node-abs-pos parent)
11371 end (+ beg (js2-node-len parent)))
11372 (push-mark beg)
11373 (goto-char end)
11374 (exchange-point-and-mark)))))
11375
11376 (defun js2-narrow-to-defun ()
11377 "Narrow to the function enclosing point."
11378 (interactive)
11379 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11380 (fn (if (js2-script-node-p node)
11381 node
11382 (js2-mode-find-enclosing-fn node)))
11383 (beg (js2-node-abs-pos fn)))
11384 (unless (js2-ast-root-p fn)
11385 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11386
11387 (provide 'js2-mode)
11388
11389 ;;; js2-mode.el ends here