]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Make the mode a better Emacs citizen
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009, 2012 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; Contributors: mooz <stillpedant@gmail.com>
7 ;; Dmitry Gutov <dgutov@yandex.ru>
8 ;; Version: See `js2-mode-version'
9 ;; Keywords: languages, javascript
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; This JavaScript editing mode supports:
29
30 ;; - strict recognition of the Ecma-262 language standard
31 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
32 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
33 ;; - accurate syntax highlighting using a recursive-descent parser
34 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
35 ;; - undeclared-variable warnings using a configurable externs framework
36 ;; - "bouncing" line indentation to choose among alternate indentation points
37 ;; - smart line-wrapping within comments and strings
38 ;; - code folding:
39 ;; - show some or all function bodies as {...}
40 ;; - show some or all block comments as /*...*/
41 ;; - context-sensitive menu bar and popup menus
42 ;; - code browsing using the `imenu' package
43 ;; - typing helpers such as automatic insertion of matching braces/parens
44 ;; - many customization options
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-langs) ; it's here in Emacs 21...
87 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
88
89 (defvar electric-layout-rules)
90
91 ;;; Externs (variables presumed to be defined by the host system)
92
93 (defvar js2-ecma-262-externs
94 (mapcar 'symbol-name
95 '(Array Boolean Date Error EvalError Function Infinity
96 Math NaN Number Object RangeError ReferenceError RegExp
97 String SyntaxError TypeError URIError arguments
98 decodeURI decodeURIComponent encodeURI
99 encodeURIComponent escape eval isFinite isNaN
100 parseFloat parseInt undefined unescape))
101 "Ecma-262 externs. Included in `js2-externs' by default.")
102
103 (defvar js2-browser-externs
104 (mapcar 'symbol-name
105 '(;; DOM level 1
106 Attr CDATASection CharacterData Comment DOMException
107 DOMImplementation Document DocumentFragment
108 DocumentType Element Entity EntityReference
109 ExceptionCode NamedNodeMap Node NodeList Notation
110 ProcessingInstruction Text
111
112 ;; DOM level 2
113 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
114 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
115 HTMLBodyElement HTMLButtonElement HTMLCollection
116 HTMLDListElement HTMLDirectoryElement HTMLDivElement
117 HTMLDocument HTMLElement HTMLFieldSetElement
118 HTMLFontElement HTMLFormElement HTMLFrameElement
119 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
120 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
121 HTMLImageElement HTMLInputElement HTMLIsIndexElement
122 HTMLLIElement HTMLLabelElement HTMLLegendElement
123 HTMLLinkElement HTMLMapElement HTMLMenuElement
124 HTMLMetaElement HTMLModElement HTMLOListElement
125 HTMLObjectElement HTMLOptGroupElement
126 HTMLOptionElement HTMLOptionsCollection
127 HTMLParagraphElement HTMLParamElement HTMLPreElement
128 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
129 HTMLStyleElement HTMLTableCaptionElement
130 HTMLTableCellElement HTMLTableColElement
131 HTMLTableElement HTMLTableRowElement
132 HTMLTableSectionElement HTMLTextAreaElement
133 HTMLTitleElement HTMLUListElement
134
135 ;; DOM level 3
136 DOMConfiguration DOMError DOMException
137 DOMImplementationList DOMImplementationSource
138 DOMLocator DOMStringList NameList TypeInfo
139 UserDataHandler
140
141 ;; Window
142 window alert confirm document java navigator prompt screen
143 self top
144
145 ;; W3C CSS
146 CSSCharsetRule CSSFontFace CSSFontFaceRule
147 CSSImportRule CSSMediaRule CSSPageRule
148 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
149 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
150 CSSValue CSSValueList Counter DOMImplementationCSS
151 DocumentCSS DocumentStyle ElementCSSInlineStyle
152 LinkStyle MediaList RGBColor Rect StyleSheet
153 StyleSheetList ViewCSS
154
155 ;; W3C Event
156 EventListener EventTarget Event DocumentEvent UIEvent
157 MouseEvent MutationEvent KeyboardEvent
158
159 ;; W3C Range
160 DocumentRange Range RangeException
161
162 ;; W3C XML
163 XPathResult XMLHttpRequest))
164 "Browser externs.
165 You can cause these to be included or excluded with the custom
166 variable `js2-include-browser-externs'.")
167
168 (defvar js2-rhino-externs
169 (mapcar 'symbol-name
170 '(Packages importClass importPackage com org java
171 ;; Global object (shell) externs.
172 defineClass deserialize doctest gc help load
173 loadClass print quit readFile readUrl runCommand seal
174 serialize spawn sync toint32 version))
175 "Mozilla Rhino externs.
176 Set `js2-include-rhino-externs' to t to include them.")
177
178 (defvar js2-gears-externs
179 (mapcar 'symbol-name
180 '(
181 ;; TODO(stevey): add these
182 ))
183 "Google Gears externs.
184 Set `js2-include-gears-externs' to t to include them.")
185
186 ;;; Variables
187
188 (defun js2-mark-safe-local (name pred)
189 "Make the variable NAME buffer-local and mark it as safe file-local
190 variable with predicate PRED."
191 (make-variable-buffer-local name)
192 (put name 'safe-local-variable pred))
193
194 (defcustom js2-highlight-level 2
195 "Amount of syntax highlighting to perform.
196 0 or a negative value means do no highlighting.
197 1 adds basic syntax highlighting.
198 2 adds highlighting of some Ecma built-in properties.
199 3 adds highlighting of many Ecma built-in functions."
200 :group 'js2-mode
201 :type '(choice (const :tag "None" 0)
202 (const :tag "Basic" 1)
203 (const :tag "Include Properties" 2)
204 (const :tag "Include Functions" 3)))
205
206 (defvar js2-mode-dev-mode-p nil
207 "Non-nil if running in development mode. Normally nil.")
208
209 (defgroup js2-mode nil
210 "An improved JavaScript mode."
211 :group 'languages)
212
213 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
214 (numberp c-basic-offset))
215 c-basic-offset
216 4)
217 "Number of spaces to indent nested statements.
218 Similar to `c-basic-offset'."
219 :group 'js2-mode
220 :type 'integer)
221 (js2-mark-safe-local 'js2-basic-offset 'integerp)
222
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-consistent-level-indent-inner-bracket-p t
237 "Non-nil to make indentation level inner bracket consistent,
238 regardless of the beginning bracket position."
239 :group 'js2-mode
240 :type 'boolean)
241 (js2-mark-safe-local 'js2-consistent-level-indent-inner-bracket-p 'booleanp)
242
243 (defcustom js2-pretty-multiline-decl-indentation-p t
244 "Non-nil to line up multiline declarations vertically. See the
245 function `js2-multiline-decl-indentation' for details."
246 :group 'js2-mode
247 :type 'boolean)
248 (js2-mark-safe-local 'js2-pretty-multiline-decl-indentation-p 'booleanp)
249
250 (defcustom js2-always-indent-assigned-expr-in-decls-p nil
251 "If both `js2-pretty-multiline-decl-indentation-p' and this are non-nil,
252 always additionally indent function expression or array/object literal
253 assigned in a declaration, even when only one var is declared."
254 :group 'js2-mode
255 :type 'boolean)
256 (js2-mark-safe-local 'js2-always-indent-assigned-expr-in-decls-p 'booleanp)
257
258 (defcustom js2-indent-on-enter-key nil
259 "Non-nil to have Enter/Return key indent the line.
260 This is unusual for Emacs modes but common in IDEs like Eclipse."
261 :type 'boolean
262 :group 'js2-mode)
263
264 (defcustom js2-enter-indents-newline nil
265 "Non-nil to have Enter/Return key indent the newly-inserted line.
266 This is unusual for Emacs modes but common in IDEs like Eclipse."
267 :type 'boolean
268 :group 'js2-mode)
269
270 (defcustom js2-idle-timer-delay 0.2
271 "Delay in secs before re-parsing after user makes changes.
272 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
273 :type 'number
274 :group 'js2-mode)
275 (make-variable-buffer-local 'js2-idle-timer-delay)
276
277 (defcustom js2-dynamic-idle-timer-adjust 0
278 "Positive to adjust `js2-idle-timer-delay' based on file size.
279 The idea is that for short files, parsing is faster so we can be
280 more responsive to user edits without interfering with editing.
281 The buffer length in characters (typically bytes) is divided by
282 this value and used to multiply `js2-idle-timer-delay' for the
283 buffer. For example, a 21k file and 10k adjust yields 21k/10k
284 == 2, so js2-idle-timer-delay is multiplied by 2.
285 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
286 `js2-idle-timer-delay' is not dependent on the file size."
287 :type 'number
288 :group 'js2-mode)
289
290 (defcustom js2-mode-escape-quotes t
291 "Non-nil to disable automatic quote-escaping inside strings."
292 :type 'boolean
293 :group 'js2-mode)
294
295 (defcustom js2-mode-squeeze-spaces t
296 "Non-nil to normalize whitespace when filling in comments.
297 Multiple runs of spaces are converted to a single space."
298 :type 'boolean
299 :group 'js2-mode)
300
301 (defcustom js2-mode-show-parse-errors t
302 "True to highlight parse errors."
303 :type 'boolean
304 :group 'js2-mode)
305
306 (defcustom js2-mode-show-strict-warnings t
307 "Non-nil to emit Ecma strict-mode warnings.
308 Some of the warnings can be individually disabled by other flags,
309 even if this flag is non-nil."
310 :type 'boolean
311 :group 'js2-mode)
312
313 (defcustom js2-strict-trailing-comma-warning t
314 "Non-nil to warn about trailing commas in array literals.
315 Ecma-262 forbids them, but many browsers permit them. IE is the
316 big exception, and can produce bugs if you have trailing commas."
317 :type 'boolean
318 :group 'js2-mode)
319
320 (defcustom js2-strict-missing-semi-warning t
321 "Non-nil to warn about semicolon auto-insertion after statement.
322 Technically this is legal per Ecma-262, but some style guides disallow
323 depending on it."
324 :type 'boolean
325 :group 'js2-mode)
326
327 (defcustom js2-missing-semi-one-line-override nil
328 "Non-nil to permit missing semicolons in one-line functions.
329 In one-liner functions such as `function identity(x) {return x}'
330 people often omit the semicolon for a cleaner look. If you are
331 such a person, you can suppress the missing-semicolon warning
332 by setting this variable to t."
333 :type 'boolean
334 :group 'js2-mode)
335
336 (defcustom js2-strict-inconsistent-return-warning t
337 "Non-nil to warn about mixing returns with value-returns.
338 It's perfectly legal to have a `return' and a `return foo' in the
339 same function, but it's often an indicator of a bug, and it also
340 interferes with type inference (in systems that support it.)"
341 :type 'boolean
342 :group 'js2-mode)
343
344 (defcustom js2-strict-cond-assign-warning t
345 "Non-nil to warn about expressions like if (a = b).
346 This often should have been '==' instead of '='. If the warning
347 is enabled, you can suppress it on a per-expression basis by
348 parenthesizing the expression, e.g. if ((a = b)) ..."
349 :type 'boolean
350 :group 'js2-mode)
351
352 (defcustom js2-strict-cond-assign-warning t
353 "Non-nil to warn about expressions like if (a = b).
354 This often should have been '==' instead of '='. If the warning
355 is enabled, you can suppress it on a per-expression basis by
356 parenthesizing the expression, e.g. if ((a = b)) ..."
357 :type 'boolean
358 :group 'js2-mode)
359
360 (defcustom js2-strict-var-redeclaration-warning t
361 "Non-nil to warn about redeclaring variables in a script or function."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-strict-var-hides-function-arg-warning t
366 "Non-nil to warn about a var decl hiding a function argument."
367 :type 'boolean
368 :group 'js2-mode)
369
370 (defcustom js2-skip-preprocessor-directives nil
371 "Non-nil to treat lines beginning with # as comments.
372 Useful for viewing Mozilla JavaScript source code."
373 :type 'boolean
374 :group 'js2-mode)
375
376 (defcustom js2-language-version 180
377 "Configures what JavaScript language version to recognize.
378 Currently versions 150, 160, 170 and 180 are supported, corresponding
379 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
380 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
381 and 1.8 adds function closures."
382 :type 'integer
383 :group 'js2-mode)
384
385 (defcustom js2-allow-keywords-as-property-names t
386 "If non-nil, you can use JavaScript keywords as object property names.
387 Examples:
388
389 var foo = {int: 5, while: 6, continue: 7};
390 foo.return = 8;
391
392 Ecma-262 forbids this syntax, but many browsers support it."
393 :type 'boolean
394 :group 'js2-mode)
395
396 (defcustom js2-instanceof-has-side-effects nil
397 "If non-nil, treats the instanceof operator as having side effects.
398 This is useful for xulrunner apps."
399 :type 'boolean
400 :group 'js2-mode)
401
402 (defcustom js2-move-point-on-right-click t
403 "Non-nil to move insertion point when you right-click.
404 This makes right-click context menu behavior a bit more intuitive,
405 since menu operations generally apply to the point. The exception
406 is if there is a region selection, in which case the point does -not-
407 move, so cut/copy/paste can work properly.
408
409 Note that IntelliJ moves the point, and Eclipse leaves it alone,
410 so this behavior is customizable."
411 :group 'js2-mode
412 :type 'boolean)
413
414 (defcustom js2-allow-rhino-new-expr-initializer t
415 "Non-nil to support a Rhino's experimental syntactic construct.
416
417 Rhino supports the ability to follow a `new' expression with an object
418 literal, which is used to set additional properties on the new object
419 after calling its constructor. Syntax:
420
421 new <expr> [ ( arglist ) ] [initializer]
422
423 Hence, this expression:
424
425 new Object {a: 1, b: 2}
426
427 results in an Object with properties a=1 and b=2. This syntax is
428 apparently not configurable in Rhino - it's currently always enabled,
429 as of Rhino version 1.7R2."
430 :type 'boolean
431 :group 'js2-mode)
432
433 (defcustom js2-allow-member-expr-as-function-name nil
434 "Non-nil to support experimental Rhino syntax for function names.
435
436 Rhino supports an experimental syntax configured via the Rhino Context
437 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
438
439 function <member-expr> ( [ arg-list ] ) { <body> }
440
441 Where member-expr is a non-parenthesized 'member expression', which
442 is anything at the grammar level of a new-expression or lower, meaning
443 any expression that does not involve infix or unary operators.
444
445 When <member-expr> is not a simple identifier, then it is syntactic
446 sugar for assigning the anonymous function to the <member-expr>. Hence,
447 this code:
448
449 function a.b().c[2] (x, y) { ... }
450
451 is rewritten as:
452
453 a.b().c[2] = function(x, y) {...}
454
455 which doesn't seem particularly useful, but Rhino permits it."
456 :type 'boolean
457 :group 'js2-mode)
458
459 (defvar js2-mode-version 20120416
460 "Release number for `js2-mode'.")
461
462 ;; scanner variables
463
464 (defmacro js2-deflocal (name value &optional comment)
465 "Define a buffer-local variable NAME with VALUE and COMMENT."
466 `(progn
467 (defvar ,name ,value ,comment)
468 (make-variable-buffer-local ',name)))
469
470 ;; We record the start and end position of each token.
471 (js2-deflocal js2-token-beg 1)
472 (js2-deflocal js2-token-end -1)
473
474 (defvar js2-EOF_CHAR -1
475 "Represents end of stream. Distinct from js2-EOF token type.")
476
477 ;; I originally used symbols to represent tokens, but Rhino uses
478 ;; ints and then sets various flag bits in them, so ints it is.
479 ;; The upshot is that we need a `js2-' prefix in front of each name.
480 (defvar js2-ERROR -1)
481 (defvar js2-EOF 0)
482 (defvar js2-EOL 1)
483 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
484 (defvar js2-LEAVEWITH 3)
485 (defvar js2-RETURN 4)
486 (defvar js2-GOTO 5)
487 (defvar js2-IFEQ 6)
488 (defvar js2-IFNE 7)
489 (defvar js2-SETNAME 8)
490 (defvar js2-BITOR 9)
491 (defvar js2-BITXOR 10)
492 (defvar js2-BITAND 11)
493 (defvar js2-EQ 12)
494 (defvar js2-NE 13)
495 (defvar js2-LT 14)
496 (defvar js2-LE 15)
497 (defvar js2-GT 16)
498 (defvar js2-GE 17)
499 (defvar js2-LSH 18)
500 (defvar js2-RSH 19)
501 (defvar js2-URSH 20)
502 (defvar js2-ADD 21) ; infix plus
503 (defvar js2-SUB 22) ; infix minus
504 (defvar js2-MUL 23)
505 (defvar js2-DIV 24)
506 (defvar js2-MOD 25)
507 (defvar js2-NOT 26)
508 (defvar js2-BITNOT 27)
509 (defvar js2-POS 28) ; unary plus
510 (defvar js2-NEG 29) ; unary minus
511 (defvar js2-NEW 30)
512 (defvar js2-DELPROP 31)
513 (defvar js2-TYPEOF 32)
514 (defvar js2-GETPROP 33)
515 (defvar js2-GETPROPNOWARN 34)
516 (defvar js2-SETPROP 35)
517 (defvar js2-GETELEM 36)
518 (defvar js2-SETELEM 37)
519 (defvar js2-CALL 38)
520 (defvar js2-NAME 39) ; an identifier
521 (defvar js2-NUMBER 40)
522 (defvar js2-STRING 41)
523 (defvar js2-NULL 42)
524 (defvar js2-THIS 43)
525 (defvar js2-FALSE 44)
526 (defvar js2-TRUE 45)
527 (defvar js2-SHEQ 46) ; shallow equality (===)
528 (defvar js2-SHNE 47) ; shallow inequality (!==)
529 (defvar js2-REGEXP 48)
530 (defvar js2-BINDNAME 49)
531 (defvar js2-THROW 50)
532 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
533 (defvar js2-IN 52)
534 (defvar js2-INSTANCEOF 53)
535 (defvar js2-LOCAL_LOAD 54)
536 (defvar js2-GETVAR 55)
537 (defvar js2-SETVAR 56)
538 (defvar js2-CATCH_SCOPE 57)
539 (defvar js2-ENUM_INIT_KEYS 58)
540 (defvar js2-ENUM_INIT_VALUES 59)
541 (defvar js2-ENUM_INIT_ARRAY 60)
542 (defvar js2-ENUM_NEXT 61)
543 (defvar js2-ENUM_ID 62)
544 (defvar js2-THISFN 63)
545 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
546 (defvar js2-ARRAYLIT 65) ; array literal
547 (defvar js2-OBJECTLIT 66) ; object literal
548 (defvar js2-GET_REF 67) ; *reference
549 (defvar js2-SET_REF 68) ; *reference = something
550 (defvar js2-DEL_REF 69) ; delete reference
551 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
552 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
553 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
554
555 ;; XML support
556 (defvar js2-DEFAULTNAMESPACE 73)
557 (defvar js2-ESCXMLATTR 74)
558 (defvar js2-ESCXMLTEXT 75)
559 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
560 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
561 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
562 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
563
564 (defvar js2-first-bytecode js2-ENTERWITH)
565 (defvar js2-last-bytecode js2-REF_NS_NAME)
566
567 (defvar js2-TRY 80)
568 (defvar js2-SEMI 81) ; semicolon
569 (defvar js2-LB 82) ; left and right brackets
570 (defvar js2-RB 83)
571 (defvar js2-LC 84) ; left and right curly-braces
572 (defvar js2-RC 85)
573 (defvar js2-LP 86) ; left and right parens
574 (defvar js2-RP 87)
575 (defvar js2-COMMA 88) ; comma operator
576
577 (defvar js2-ASSIGN 89) ; simple assignment (=)
578 (defvar js2-ASSIGN_BITOR 90) ; |=
579 (defvar js2-ASSIGN_BITXOR 91) ; ^=
580 (defvar js2-ASSIGN_BITAND 92) ; &=
581 (defvar js2-ASSIGN_LSH 93) ; <<=
582 (defvar js2-ASSIGN_RSH 94) ; >>=
583 (defvar js2-ASSIGN_URSH 95) ; >>>=
584 (defvar js2-ASSIGN_ADD 96) ; +=
585 (defvar js2-ASSIGN_SUB 97) ; -=
586 (defvar js2-ASSIGN_MUL 98) ; *=
587 (defvar js2-ASSIGN_DIV 99) ; /=
588 (defvar js2-ASSIGN_MOD 100) ; %=
589
590 (defvar js2-first-assign js2-ASSIGN)
591 (defvar js2-last-assign js2-ASSIGN_MOD)
592
593 (defvar js2-HOOK 101) ; conditional (?:)
594 (defvar js2-COLON 102)
595 (defvar js2-OR 103) ; logical or (||)
596 (defvar js2-AND 104) ; logical and (&&)
597 (defvar js2-INC 105) ; increment/decrement (++ --)
598 (defvar js2-DEC 106)
599 (defvar js2-DOT 107) ; member operator (.)
600 (defvar js2-FUNCTION 108) ; function keyword
601 (defvar js2-EXPORT 109) ; export keyword
602 (defvar js2-IMPORT 110) ; import keyword
603 (defvar js2-IF 111) ; if keyword
604 (defvar js2-ELSE 112) ; else keyword
605 (defvar js2-SWITCH 113) ; switch keyword
606 (defvar js2-CASE 114) ; case keyword
607 (defvar js2-DEFAULT 115) ; default keyword
608 (defvar js2-WHILE 116) ; while keyword
609 (defvar js2-DO 117) ; do keyword
610 (defvar js2-FOR 118) ; for keyword
611 (defvar js2-BREAK 119) ; break keyword
612 (defvar js2-CONTINUE 120) ; continue keyword
613 (defvar js2-VAR 121) ; var keyword
614 (defvar js2-WITH 122) ; with keyword
615 (defvar js2-CATCH 123) ; catch keyword
616 (defvar js2-FINALLY 124) ; finally keyword
617 (defvar js2-VOID 125) ; void keyword
618 (defvar js2-RESERVED 126) ; reserved keywords
619
620 (defvar js2-EMPTY 127)
621
622 ;; Types used for the parse tree - never returned by scanner.
623
624 (defvar js2-BLOCK 128) ; statement block
625 (defvar js2-LABEL 129) ; label
626 (defvar js2-TARGET 130)
627 (defvar js2-LOOP 131)
628 (defvar js2-EXPR_VOID 132) ; expression statement in functions
629 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
630 (defvar js2-JSR 134)
631 (defvar js2-SCRIPT 135) ; top-level node for entire script
632 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
633 (defvar js2-USE_STACK 137)
634 (defvar js2-SETPROP_OP 138) ; x.y op= something
635 (defvar js2-SETELEM_OP 139) ; x[y] op= something
636 (defvar js2-LOCAL_BLOCK 140)
637 (defvar js2-SET_REF_OP 141) ; *reference op= something
638
639 ;; For XML support:
640 (defvar js2-DOTDOT 142) ; member operator (..)
641 (defvar js2-COLONCOLON 143) ; namespace::name
642 (defvar js2-XML 144) ; XML type
643 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
644 (defvar js2-XMLATTR 146) ; @
645 (defvar js2-XMLEND 147)
646
647 ;; Optimizer-only tokens
648 (defvar js2-TO_OBJECT 148)
649 (defvar js2-TO_DOUBLE 149)
650
651 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
652 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
653 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
654 (defvar js2-CONST 153)
655 (defvar js2-SETCONST 154)
656 (defvar js2-SETCONSTVAR 155)
657 (defvar js2-ARRAYCOMP 156)
658 (defvar js2-LETEXPR 157)
659 (defvar js2-WITHEXPR 158)
660 (defvar js2-DEBUGGER 159)
661
662 (defvar js2-COMMENT 160)
663 (defvar js2-ENUM 161) ; for "enum" reserved word
664
665 (defconst js2-num-tokens (1+ js2-ENUM))
666
667 (defconst js2-debug-print-trees nil)
668
669 ;; Rhino accepts any string or stream as input. Emacs character
670 ;; processing works best in buffers, so we'll assume the input is a
671 ;; buffer. JavaScript strings can be copied into temp buffers before
672 ;; scanning them.
673
674 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
675 ;; They're the Emacs equivalent of instance variables, more or less.
676
677 (js2-deflocal js2-ts-dirty-line nil
678 "Token stream buffer-local variable.
679 Indicates stuff other than whitespace since start of line.")
680
681 (js2-deflocal js2-ts-regexp-flags nil
682 "Token stream buffer-local variable.")
683
684 (js2-deflocal js2-ts-string ""
685 "Token stream buffer-local variable.
686 Last string scanned.")
687
688 (js2-deflocal js2-ts-number nil
689 "Token stream buffer-local variable.
690 Last literal number scanned.")
691
692 (js2-deflocal js2-ts-hit-eof nil
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-line-start 0
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-lineno 1
699 "Token stream buffer-local variable.")
700
701 (js2-deflocal js2-ts-line-end-char -1
702 "Token stream buffer-local variable.")
703
704 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
705 "Token stream buffer-local variable.
706 Current scan position.")
707
708 (js2-deflocal js2-ts-is-xml-attribute nil
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-xml-is-tag-content nil
712 "Token stream buffer-local variable.")
713
714 (js2-deflocal js2-ts-xml-open-tags-count 0
715 "Token stream buffer-local variable.")
716
717 (js2-deflocal js2-ts-string-buffer nil
718 "Token stream buffer-local variable.
719 List of chars built up while scanning various tokens.")
720
721 (js2-deflocal js2-ts-comment-type nil
722 "Token stream buffer-local variable.")
723
724 ;;; Parser variables
725
726 (js2-deflocal js2-parsed-errors nil
727 "List of errors produced during scanning/parsing.")
728
729 (js2-deflocal js2-parsed-warnings nil
730 "List of warnings produced during scanning/parsing.")
731
732 (js2-deflocal js2-recover-from-parse-errors t
733 "Non-nil to continue parsing after a syntax error.
734
735 In recovery mode, the AST will be built in full, and any error
736 nodes will be flagged with appropriate error information. If
737 this flag is nil, a syntax error will result in an error being
738 signaled.
739
740 The variable is automatically buffer-local, because different
741 modes that use the parser will need different settings.")
742
743 (js2-deflocal js2-parse-hook nil
744 "List of callbacks for receiving parsing progress.")
745
746 (defvar js2-parse-finished-hook nil
747 "List of callbacks to notify when parsing finishes.
748 Not called if parsing was interrupted.")
749
750 (js2-deflocal js2-is-eval-code nil
751 "True if we're evaluating code in a string.
752 If non-nil, the tokenizer will record the token text, and the AST nodes
753 will record their source text. Off by default for IDE modes, since the
754 text is available in the buffer.")
755
756 (defvar js2-parse-ide-mode t
757 "Non-nil if the parser is being used for `js2-mode'.
758 If non-nil, the parser will set text properties for fontification
759 and the syntax table. The value should be nil when using the
760 parser as a frontend to an interpreter or byte compiler.")
761
762 ;;; Parser instance variables (buffer-local vars for js2-parse)
763
764 (defconst js2-clear-ti-mask #xFFFF
765 "Mask to clear token information bits.")
766
767 (defconst js2-ti-after-eol (lsh 1 16)
768 "Flag: first token of the source line.")
769
770 (defconst js2-ti-check-label (lsh 1 17)
771 "Flag: indicates to check for label.")
772
773 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
774
775 (js2-deflocal js2-compiler-generate-debug-info t)
776 (js2-deflocal js2-compiler-use-dynamic-scope nil)
777 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
778 (js2-deflocal js2-compiler-xml-available t)
779 (js2-deflocal js2-compiler-optimization-level 0)
780 (js2-deflocal js2-compiler-generating-source t)
781 (js2-deflocal js2-compiler-strict-mode nil)
782 (js2-deflocal js2-compiler-report-warning-as-error nil)
783 (js2-deflocal js2-compiler-generate-observer-count nil)
784 (js2-deflocal js2-compiler-activation-names nil)
785
786 ;; SKIP: sourceURI
787
788 ;; There's a compileFunction method in Context.java - may need it.
789 (js2-deflocal js2-called-by-compile-function nil
790 "True if `js2-parse' was called by `js2-compile-function'.
791 Will only be used when we finish implementing the interpreter.")
792
793 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
794
795 (js2-deflocal js2-current-flagged-token js2-EOF)
796 (js2-deflocal js2-current-token js2-EOF)
797
798 ;; SKIP: node factory - we're going to just call functions directly,
799 ;; and eventually go to a unified AST format.
800
801 (js2-deflocal js2-nesting-of-function 0)
802
803 (js2-deflocal js2-recorded-identifiers nil
804 "Tracks identifiers found during parsing.")
805
806 (defmacro js2-in-lhs (body)
807 `(let ((js2-is-in-lhs t))
808 ,body))
809
810 (defmacro js2-in-rhs (body)
811 `(let ((js2-is-in-lhs nil))
812 ,body))
813
814 (js2-deflocal js2-is-in-lhs nil
815 "True while parsing lhs statement")
816
817 (defcustom js2-global-externs nil
818 "A list of any extern names you'd like to consider always declared.
819 This list is global and is used by all `js2-mode' files.
820 You can create buffer-local externs list using `js2-additional-externs'.
821
822 There is also a buffer-local variable `js2-default-externs',
823 which is initialized by default to include the Ecma-262 externs
824 and the standard browser externs. The three lists are all
825 checked during highlighting."
826 :type 'list
827 :group 'js2-mode)
828
829 (js2-deflocal js2-default-externs nil
830 "Default external declarations.
831
832 These are currently only used for highlighting undeclared variables,
833 which only worries about top-level (unqualified) references.
834 As js2-mode's processing improves, we will flesh out this list.
835
836 The initial value is set to `js2-ecma-262-externs', unless you
837 have set `js2-include-browser-externs', in which case the browser
838 externs are also included.
839
840 See `js2-additional-externs' for more information.")
841
842 (defcustom js2-include-browser-externs t
843 "Non-nil to include browser externs in the master externs list.
844 If you work on JavaScript files that are not intended for browsers,
845 such as Mozilla Rhino server-side JavaScript, set this to nil.
846 You can always include them on a per-file basis by calling
847 `js2-add-browser-externs' from a function on `js2-mode-hook'.
848
849 See `js2-additional-externs' for more information about externs."
850 :type 'boolean
851 :group 'js2-mode)
852
853 (defcustom js2-include-rhino-externs t
854 "Non-nil to include Mozilla Rhino externs in the master externs list.
855 See `js2-additional-externs' for more information about externs."
856 :type 'boolean
857 :group 'js2-mode)
858
859 (defcustom js2-include-gears-externs t
860 "Non-nil to include Google Gears externs in the master externs list.
861 See `js2-additional-externs' for more information about externs."
862 :type 'boolean
863 :group 'js2-mode)
864
865 (js2-deflocal js2-additional-externs nil
866 "A buffer-local list of additional external declarations.
867 It is used to decide whether variables are considered undeclared
868 for purposes of highlighting.
869
870 Each entry is a Lisp string. The string should be the fully qualified
871 name of an external entity. All externs should be added to this list,
872 so that as js2-mode's processing improves it can take advantage of them.
873
874 You may want to declare your externs in three ways.
875 First, you can add externs that are valid for all your JavaScript files.
876 You should probably do this by adding them to `js2-global-externs', which
877 is a global list used for all js2-mode files.
878
879 Next, you can add a function to `js2-mode-hook' that adds additional
880 externs appropriate for the specific file, perhaps based on its path.
881 These should go in `js2-additional-externs', which is buffer-local.
882
883 Finally, you can add a function to `js2-post-parse-callbacks',
884 which is called after parsing completes, and `root' is bound to
885 the root of the parse tree. At this stage you can set up an AST
886 node visitor using `js2-visit-ast' and examine the parse tree
887 for specific import patterns that may imply the existence of
888 other externs, possibly tied to your build system. These should also
889 be added to `js2-additional-externs'.
890
891 Your post-parse callback may of course also use the simpler and
892 faster (but perhaps less robust) approach of simply scanning the
893 buffer text for your imports, using regular expressions.")
894
895 ;; SKIP: decompiler
896 ;; SKIP: encoded-source
897
898 ;;; The following variables are per-function and should be saved/restored
899 ;;; during function parsing...
900
901 (js2-deflocal js2-current-script-or-fn nil)
902 (js2-deflocal js2-current-scope nil)
903 (js2-deflocal js2-nesting-of-with 0)
904 (js2-deflocal js2-label-set nil
905 "An alist mapping label names to nodes.")
906
907 (js2-deflocal js2-loop-set nil)
908 (js2-deflocal js2-loop-and-switch-set nil)
909 (js2-deflocal js2-has-return-value nil)
910 (js2-deflocal js2-end-flags 0)
911
912 ;;; ...end of per function variables
913
914 ;; Without 2-token lookahead, labels are a problem.
915 ;; These vars store the token info of the last matched name,
916 ;; iff it wasn't the last matched token. Only valid in some contexts.
917 (defvar js2-prev-name-token-start nil)
918 (defvar js2-prev-name-token-string nil)
919
920 (defsubst js2-save-name-token-data (pos name)
921 (setq js2-prev-name-token-start pos
922 js2-prev-name-token-string name))
923
924 ;; These flags enumerate the possible ways a statement/function can
925 ;; terminate. These flags are used by endCheck() and by the Parser to
926 ;; detect inconsistent return usage.
927 ;;
928 ;; END_UNREACHED is reserved for code paths that are assumed to always be
929 ;; able to execute (example: throw, continue)
930 ;;
931 ;; END_DROPS_OFF indicates if the statement can transfer control to the
932 ;; next one. Statement such as return dont. A compound statement may have
933 ;; some branch that drops off control to the next statement.
934 ;;
935 ;; END_RETURNS indicates that the statement can return (without arguments)
936 ;; END_RETURNS_VALUE indicates that the statement can return a value.
937 ;;
938 ;; A compound statement such as
939 ;; if (condition) {
940 ;; return value;
941 ;; }
942 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
943
944 (defconst js2-end-unreached #x0)
945 (defconst js2-end-drops-off #x1)
946 (defconst js2-end-returns #x2)
947 (defconst js2-end-returns-value #x4)
948 (defconst js2-end-yields #x8)
949
950 ;; Rhino awkwardly passes a statementLabel parameter to the
951 ;; statementHelper() function, the main statement parser, which
952 ;; is then used by quite a few of the sub-parsers. We just make
953 ;; it a buffer-local variable and make sure it's cleaned up properly.
954 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
955
956 ;; Similarly, Rhino passes an inForInit boolean through about half
957 ;; the expression parsers. We use a dynamically-scoped variable,
958 ;; which makes it easier to funcall the parsers individually without
959 ;; worrying about whether they take the parameter or not.
960 (js2-deflocal js2-in-for-init nil)
961 (js2-deflocal js2-temp-name-counter 0)
962 (js2-deflocal js2-parse-stmt-count 0)
963
964 (defsubst js2-get-next-temp-name ()
965 (format "$%d" (incf js2-temp-name-counter)))
966
967 (defvar js2-parse-interruptable-p t
968 "Set this to nil to force parse to continue until finished.
969 This will mostly be useful for interpreters.")
970
971 (defvar js2-statements-per-pause 50
972 "Pause after this many statements to check for user input.
973 If user input is pending, stop the parse and discard the tree.
974 This makes for a smoother user experience for large files.
975 You may have to wait a second or two before the highlighting
976 and error-reporting appear, but you can always type ahead if
977 you wish. This appears to be more or less how Eclipse, IntelliJ
978 and other editors work.")
979
980 (js2-deflocal js2-record-comments t
981 "Instructs the scanner to record comments in `js2-scanned-comments'.")
982
983 (js2-deflocal js2-scanned-comments nil
984 "List of all comments from the current parse.")
985
986 (defcustom js2-mode-indent-inhibit-undo nil
987 "Non-nil to disable collection of Undo information when indenting lines.
988 Some users have requested this behavior. It's nil by default because
989 other Emacs modes don't work this way."
990 :type 'boolean
991 :group 'js2-mode)
992
993 (defcustom js2-mode-indent-ignore-first-tab nil
994 "If non-nil, ignore first TAB keypress if we look indented properly.
995 It's fairly common for users to navigate to an already-indented line
996 and press TAB for reassurance that it's been indented. For this class
997 of users, we want the first TAB press on a line to be ignored if the
998 line is already indented to one of the precomputed alternatives.
999
1000 This behavior is only partly implemented. If you TAB-indent a line,
1001 navigate to another line, and then navigate back, it fails to clear
1002 the last-indented variable, so it thinks you've already hit TAB once,
1003 and performs the indent. A full solution would involve getting on the
1004 point-motion hooks for the entire buffer. If we come across another
1005 use cases that requires watching point motion, I'll consider doing it.
1006
1007 If you set this variable to nil, then the TAB key will always change
1008 the indentation of the current line, if more than one alternative
1009 indentation spot exists."
1010 :type 'boolean
1011 :group 'js2-mode)
1012
1013 (defvar js2-indent-hook nil
1014 "A hook for user-defined indentation rules.
1015
1016 Functions on this hook should expect two arguments: (LIST INDEX)
1017 The LIST argument is the list of computed indentation points for
1018 the current line. INDEX is the list index of the indentation point
1019 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1020 indent function is not going to change the current line indentation.
1021
1022 If a hook function on this list returns a non-nil value, then
1023 `js2-bounce-indent' assumes the hook function has performed its own
1024 indentation, and will do nothing. If all hook functions on the list
1025 return nil, then `js2-bounce-indent' will use its computed indentation
1026 and reindent the line.
1027
1028 When hook functions on this hook list are called, the variable
1029 `js2-mode-ast' may or may not be set, depending on whether the
1030 parse tree is available. If the variable is nil, you can pass a
1031 callback to `js2-mode-wait-for-parse', and your callback will be
1032 called after the new parse tree is built. This can take some time
1033 in large files.")
1034
1035 (defface js2-warning-face
1036 `((((class color) (background light))
1037 (:underline "orange"))
1038 (((class color) (background dark))
1039 (:underline "orange"))
1040 (t (:underline t)))
1041 "Face for JavaScript warnings."
1042 :group 'js2-mode)
1043
1044 (defface js2-error-face
1045 `((((class color) (background light))
1046 (:foreground "red"))
1047 (((class color) (background dark))
1048 (:foreground "red"))
1049 (t (:foreground "red")))
1050 "Face for JavaScript errors."
1051 :group 'js2-mode)
1052
1053 (defface js2-jsdoc-tag-face
1054 '((t :foreground "SlateGray"))
1055 "Face used to highlight @whatever tags in jsdoc comments."
1056 :group 'js2-mode)
1057
1058 (defface js2-jsdoc-type-face
1059 '((t :foreground "SteelBlue"))
1060 "Face used to highlight {FooBar} types in jsdoc comments."
1061 :group 'js2-mode)
1062
1063 (defface js2-jsdoc-value-face
1064 '((t :foreground "PeachPuff3"))
1065 "Face used to highlight tag values in jsdoc comments."
1066 :group 'js2-mode)
1067
1068 (defface js2-function-param-face
1069 '((t :foreground "SeaGreen"))
1070 "Face used to highlight function parameters in javascript."
1071 :group 'js2-mode)
1072
1073 (defface js2-instance-member-face
1074 '((t :foreground "DarkOrchid"))
1075 "Face used to highlight instance variables in javascript.
1076 Not currently used."
1077 :group 'js2-mode)
1078
1079 (defface js2-private-member-face
1080 '((t :foreground "PeachPuff3"))
1081 "Face used to highlight calls to private methods in javascript.
1082 Not currently used."
1083 :group 'js2-mode)
1084
1085 (defface js2-private-function-call-face
1086 '((t :foreground "goldenrod"))
1087 "Face used to highlight calls to private functions in javascript.
1088 Not currently used."
1089 :group 'js2-mode)
1090
1091 (defface js2-jsdoc-html-tag-name-face
1092 '((((class color) (min-colors 88) (background light))
1093 (:foreground "rosybrown"))
1094 (((class color) (min-colors 8) (background dark))
1095 (:foreground "yellow"))
1096 (((class color) (min-colors 8) (background light))
1097 (:foreground "magenta")))
1098 "Face used to highlight jsdoc html tag names"
1099 :group 'js2-mode)
1100
1101 (defface js2-jsdoc-html-tag-delimiter-face
1102 '((((class color) (min-colors 88) (background light))
1103 (:foreground "dark khaki"))
1104 (((class color) (min-colors 8) (background dark))
1105 (:foreground "green"))
1106 (((class color) (min-colors 8) (background light))
1107 (:foreground "green")))
1108 "Face used to highlight brackets in jsdoc html tags."
1109 :group 'js2-mode)
1110
1111
1112 (defcustom js2-post-parse-callbacks nil
1113 "A list of callback functions invoked after parsing finishes.
1114 Currently, the main use for this function is to add synthetic
1115 declarations to `js2-recorded-identifiers', which see."
1116 :type 'list
1117 :group 'js2-mode)
1118
1119 (defface js2-external-variable-face
1120 '((t :foreground "orange"))
1121 "Face used to highlight undeclared variable identifiers.
1122 An undeclared variable is any variable not declared with var or let
1123 in the current scope or any lexically enclosing scope. If you use
1124 such a variable, then you are either expecting it to originate from
1125 another file, or you've got a potential bug."
1126 :group 'js2-mode)
1127
1128 (defcustom js2-highlight-external-variables t
1129 "Non-nil to highlight undeclared variable identifiers."
1130 :type 'boolean
1131 :group 'js2-mode)
1132
1133 (defcustom js2-auto-insert-catch-block t
1134 "Non-nil to insert matching catch block on open-curly after `try'."
1135 :type 'boolean
1136 :group 'js2-mode)
1137
1138 (defvar js2-mode-map
1139 (let ((map (make-sparse-keymap))
1140 keys)
1141 (define-key map [mouse-1] #'js2-mode-show-node)
1142 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1143 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1144 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1145 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1146 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1147 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1148 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1149 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1150 (when js2-bounce-indent-p
1151 (define-key map (kbd "<backtab>") #'js2-indent-bounce-backwards))
1152
1153 (define-key map [menu-bar javascript]
1154 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1155
1156 (define-key map [menu-bar javascript customize-js2-mode]
1157 '(menu-item "Customize js2-mode" js2-mode-customize
1158 :help "Customize the behavior of this mode"))
1159
1160 (define-key map [menu-bar javascript js2-force-refresh]
1161 '(menu-item "Force buffer refresh" js2-mode-reset
1162 :help "Re-parse the buffer from scratch"))
1163
1164 (define-key map [menu-bar javascript separator-2]
1165 '("--"))
1166
1167 (define-key map [menu-bar javascript next-error]
1168 '(menu-item "Next warning or error" next-error
1169 :enabled (and js2-mode-ast
1170 (or (js2-ast-root-errors js2-mode-ast)
1171 (js2-ast-root-warnings js2-mode-ast)))
1172 :help "Move to next warning or error"))
1173
1174 (define-key map [menu-bar javascript display-errors]
1175 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1176 :visible (not js2-mode-show-parse-errors)
1177 :help "Turn on display of warnings and errors"))
1178
1179 (define-key map [menu-bar javascript hide-errors]
1180 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1181 :visible js2-mode-show-parse-errors
1182 :help "Turn off display of warnings and errors"))
1183
1184 (define-key map [menu-bar javascript separator-1]
1185 '("--"))
1186
1187 (define-key map [menu-bar javascript js2-toggle-function]
1188 '(menu-item "Show/collapse element" js2-mode-toggle-element
1189 :help "Hide or show function body or comment"))
1190
1191 (define-key map [menu-bar javascript show-comments]
1192 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1193 :visible js2-mode-comments-hidden
1194 :help "Expand all hidden block comments"))
1195
1196 (define-key map [menu-bar javascript hide-comments]
1197 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1198 :visible (not js2-mode-comments-hidden)
1199 :help "Show block comments as /*...*/"))
1200
1201 (define-key map [menu-bar javascript show-all-functions]
1202 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1203 :visible js2-mode-functions-hidden
1204 :help "Expand all hidden function bodies"))
1205
1206 (define-key map [menu-bar javascript hide-all-functions]
1207 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1208 :visible (not js2-mode-functions-hidden)
1209 :help "Show {...} for all top-level function bodies"))
1210
1211 map)
1212 "Keymap used in `js2-mode' buffers.")
1213
1214 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1215
1216 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1217 "Matches a //-comment line. Must be first non-whitespace on line.
1218 First match-group is the leading whitespace.")
1219
1220 (defvar js2-mode-hook nil)
1221
1222 (js2-deflocal js2-mode-ast nil "Private variable.")
1223 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1224 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1225 (js2-deflocal js2-mode-parsing nil "Private variable.")
1226 (js2-deflocal js2-mode-node-overlay nil)
1227
1228 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1229 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1230
1231 (js2-deflocal js2-mode-fontifications nil "Private variable")
1232 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1233 (js2-deflocal js2-imenu-recorder nil "Private variable")
1234 (js2-deflocal js2-imenu-function-map nil "Private variable")
1235
1236 (defvar js2-paragraph-start
1237 "\\(@[a-zA-Z]+\\>\\|$\\)")
1238
1239 ;; Note that we also set a 'c-in-sws text property in html comments,
1240 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1241 (defvar js2-syntactic-ws-start
1242 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1243
1244 (defvar js2-syntactic-ws-end
1245 "\\s \\|[\n\r/]\\|\\s!")
1246
1247 (defvar js2-syntactic-eol
1248 (concat "\\s *\\(/\\*[^*\n\r]*"
1249 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1250 "\\*+/\\s *\\)*"
1251 "\\(//\\|/\\*[^*\n\r]*"
1252 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1253 "\\|\\\\$\\|$\\)")
1254 "Copied from `java-mode'. Needed for some cc-engine functions.")
1255
1256 (defvar js2-comment-prefix-regexp
1257 "//+\\|\\**")
1258
1259 (defvar js2-comment-start-skip
1260 "\\(//+\\|/\\*+\\)\\s *")
1261
1262 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1263 "Non-nil to emit status messages during parsing.")
1264
1265 (defvar js2-mode-functions-hidden nil "Private variable.")
1266 (defvar js2-mode-comments-hidden nil "Private variable.")
1267
1268 (defvar js2-mode-syntax-table
1269 (let ((table (make-syntax-table)))
1270 (c-populate-syntax-table table)
1271 table)
1272 "Syntax table used in `js2-mode' buffers.")
1273
1274 (defvar js2-mode-abbrev-table nil
1275 "Abbrev table in use in `js2-mode' buffers.")
1276 (define-abbrev-table 'js2-mode-abbrev-table ())
1277
1278 (defvar js2-mode-pending-parse-callbacks nil
1279 "List of functions waiting to be notified that parse is finished.")
1280
1281 (defvar js2-mode-last-indented-line -1)
1282
1283 ;;; Localizable error and warning messages
1284
1285 ;; Messages are copied from Rhino's Messages.properties.
1286 ;; Many of the Java-specific messages have been elided.
1287 ;; Add any js2-specific ones at the end, so we can keep
1288 ;; this file synced with changes to Rhino's.
1289
1290 (defvar js2-message-table
1291 (make-hash-table :test 'equal :size 250)
1292 "Contains localized messages for `js2-mode'.")
1293
1294 ;; TODO(stevey): construct this table at compile-time.
1295 (defmacro js2-msg (key &rest strings)
1296 `(puthash ,key (funcall #'concat ,@strings)
1297 js2-message-table))
1298
1299 (defun js2-get-msg (msg-key)
1300 "Look up a localized message.
1301 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1302 the correct number of ARGS must be provided."
1303 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1304 (args (if (listp msg-key) (cdr msg-key)))
1305 (msg (gethash key js2-message-table)))
1306 (if msg
1307 (apply #'format msg args)
1308 key))) ; default to showing the key
1309
1310 (js2-msg "msg.dup.parms"
1311 "Duplicate parameter name '%s'.")
1312
1313 (js2-msg "msg.too.big.jump"
1314 "Program too complex: jump offset too big.")
1315
1316 (js2-msg "msg.too.big.index"
1317 "Program too complex: internal index exceeds 64K limit.")
1318
1319 (js2-msg "msg.while.compiling.fn"
1320 "Encountered code generation error while compiling function '%s': %s")
1321
1322 (js2-msg "msg.while.compiling.script"
1323 "Encountered code generation error while compiling script: %s")
1324
1325 ;; Context
1326 (js2-msg "msg.ctor.not.found"
1327 "Constructor for '%s' not found.")
1328
1329 (js2-msg "msg.not.ctor"
1330 "'%s' is not a constructor.")
1331
1332 ;; FunctionObject
1333 (js2-msg "msg.varargs.ctor"
1334 "Method or constructor '%s' must be static "
1335 "with the signature (Context cx, Object[] args, "
1336 "Function ctorObj, boolean inNewExpr) "
1337 "to define a variable arguments constructor.")
1338
1339 (js2-msg "msg.varargs.fun"
1340 "Method '%s' must be static with the signature "
1341 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1342 "to define a variable arguments function.")
1343
1344 (js2-msg "msg.incompat.call"
1345 "Method '%s' called on incompatible object.")
1346
1347 (js2-msg "msg.bad.parms"
1348 "Unsupported parameter type '%s' in method '%s'.")
1349
1350 (js2-msg "msg.bad.method.return"
1351 "Unsupported return type '%s' in method '%s'.")
1352
1353 (js2-msg "msg.bad.ctor.return"
1354 "Construction of objects of type '%s' is not supported.")
1355
1356 (js2-msg "msg.no.overload"
1357 "Method '%s' occurs multiple times in class '%s'.")
1358
1359 (js2-msg "msg.method.not.found"
1360 "Method '%s' not found in '%s'.")
1361
1362 ;; IRFactory
1363
1364 (js2-msg "msg.bad.for.in.lhs"
1365 "Invalid left-hand side of for..in loop.")
1366
1367 (js2-msg "msg.mult.index"
1368 "Only one variable allowed in for..in loop.")
1369
1370 (js2-msg "msg.bad.for.in.destruct"
1371 "Left hand side of for..in loop must be an array of "
1372 "length 2 to accept key/value pair.")
1373
1374 (js2-msg "msg.cant.convert"
1375 "Can't convert to type '%s'.")
1376
1377 (js2-msg "msg.bad.assign.left"
1378 "Invalid assignment left-hand side.")
1379
1380 (js2-msg "msg.bad.decr"
1381 "Invalid decerement operand.")
1382
1383 (js2-msg "msg.bad.incr"
1384 "Invalid increment operand.")
1385
1386 (js2-msg "msg.bad.yield"
1387 "yield must be in a function.")
1388
1389 (js2-msg "msg.yield.parenthesized"
1390 "yield expression must be parenthesized.")
1391
1392 ;; NativeGlobal
1393 (js2-msg "msg.cant.call.indirect"
1394 "Function '%s' must be called directly, and not by way of a "
1395 "function of another name.")
1396
1397 (js2-msg "msg.eval.nonstring"
1398 "Calling eval() with anything other than a primitive "
1399 "string value will simply return the value. "
1400 "Is this what you intended?")
1401
1402 (js2-msg "msg.eval.nonstring.strict"
1403 "Calling eval() with anything other than a primitive "
1404 "string value is not allowed in strict mode.")
1405
1406 (js2-msg "msg.bad.destruct.op"
1407 "Invalid destructuring assignment operator")
1408
1409 ;; NativeCall
1410 (js2-msg "msg.only.from.new"
1411 "'%s' may only be invoked from a `new' expression.")
1412
1413 (js2-msg "msg.deprec.ctor"
1414 "The '%s' constructor is deprecated.")
1415
1416 ;; NativeFunction
1417 (js2-msg "msg.no.function.ref.found"
1418 "no source found to decompile function reference %s")
1419
1420 (js2-msg "msg.arg.isnt.array"
1421 "second argument to Function.prototype.apply must be an array")
1422
1423 ;; NativeGlobal
1424 (js2-msg "msg.bad.esc.mask"
1425 "invalid string escape mask")
1426
1427 ;; NativeRegExp
1428 (js2-msg "msg.bad.quant"
1429 "Invalid quantifier %s")
1430
1431 (js2-msg "msg.overlarge.backref"
1432 "Overly large back reference %s")
1433
1434 (js2-msg "msg.overlarge.min"
1435 "Overly large minimum %s")
1436
1437 (js2-msg "msg.overlarge.max"
1438 "Overly large maximum %s")
1439
1440 (js2-msg "msg.zero.quant"
1441 "Zero quantifier %s")
1442
1443 (js2-msg "msg.max.lt.min"
1444 "Maximum %s less than minimum")
1445
1446 (js2-msg "msg.unterm.quant"
1447 "Unterminated quantifier %s")
1448
1449 (js2-msg "msg.unterm.paren"
1450 "Unterminated parenthetical %s")
1451
1452 (js2-msg "msg.unterm.class"
1453 "Unterminated character class %s")
1454
1455 (js2-msg "msg.bad.range"
1456 "Invalid range in character class.")
1457
1458 (js2-msg "msg.trail.backslash"
1459 "Trailing \\ in regular expression.")
1460
1461 (js2-msg "msg.re.unmatched.right.paren"
1462 "unmatched ) in regular expression.")
1463
1464 (js2-msg "msg.no.regexp"
1465 "Regular expressions are not available.")
1466
1467 (js2-msg "msg.bad.backref"
1468 "back-reference exceeds number of capturing parentheses.")
1469
1470 (js2-msg "msg.bad.regexp.compile"
1471 "Only one argument may be specified if the first "
1472 "argument to RegExp.prototype.compile is a RegExp object.")
1473
1474 ;; Parser
1475 (js2-msg "msg.got.syntax.errors"
1476 "Compilation produced %s syntax errors.")
1477
1478 (js2-msg "msg.var.redecl"
1479 "TypeError: redeclaration of var %s.")
1480
1481 (js2-msg "msg.const.redecl"
1482 "TypeError: redeclaration of const %s.")
1483
1484 (js2-msg "msg.let.redecl"
1485 "TypeError: redeclaration of variable %s.")
1486
1487 (js2-msg "msg.parm.redecl"
1488 "TypeError: redeclaration of formal parameter %s.")
1489
1490 (js2-msg "msg.fn.redecl"
1491 "TypeError: redeclaration of function %s.")
1492
1493 (js2-msg "msg.let.decl.not.in.block"
1494 "SyntaxError: let declaration not directly within block")
1495
1496 ;; NodeTransformer
1497 (js2-msg "msg.dup.label"
1498 "duplicated label")
1499
1500 (js2-msg "msg.undef.label"
1501 "undefined label")
1502
1503 (js2-msg "msg.bad.break"
1504 "unlabelled break must be inside loop or switch")
1505
1506 (js2-msg "msg.continue.outside"
1507 "continue must be inside loop")
1508
1509 (js2-msg "msg.continue.nonloop"
1510 "continue can only use labels of iteration statements")
1511
1512 (js2-msg "msg.bad.throw.eol"
1513 "Line terminator is not allowed between the throw "
1514 "keyword and throw expression.")
1515
1516 (js2-msg "msg.no.paren.parms"
1517 "missing ( before function parameters.")
1518
1519 (js2-msg "msg.no.parm"
1520 "missing formal parameter")
1521
1522 (js2-msg "msg.no.paren.after.parms"
1523 "missing ) after formal parameters")
1524
1525 (js2-msg "msg.no.brace.body"
1526 "missing '{' before function body")
1527
1528 (js2-msg "msg.no.brace.after.body"
1529 "missing } after function body")
1530
1531 (js2-msg "msg.no.paren.cond"
1532 "missing ( before condition")
1533
1534 (js2-msg "msg.no.paren.after.cond"
1535 "missing ) after condition")
1536
1537 (js2-msg "msg.no.semi.stmt"
1538 "missing ; before statement")
1539
1540 (js2-msg "msg.missing.semi"
1541 "missing ; after statement")
1542
1543 (js2-msg "msg.no.name.after.dot"
1544 "missing name after . operator")
1545
1546 (js2-msg "msg.no.name.after.coloncolon"
1547 "missing name after :: operator")
1548
1549 (js2-msg "msg.no.name.after.dotdot"
1550 "missing name after .. operator")
1551
1552 (js2-msg "msg.no.name.after.xmlAttr"
1553 "missing name after .@")
1554
1555 (js2-msg "msg.no.bracket.index"
1556 "missing ] in index expression")
1557
1558 (js2-msg "msg.no.paren.switch"
1559 "missing ( before switch expression")
1560
1561 (js2-msg "msg.no.paren.after.switch"
1562 "missing ) after switch expression")
1563
1564 (js2-msg "msg.no.brace.switch"
1565 "missing '{' before switch body")
1566
1567 (js2-msg "msg.bad.switch"
1568 "invalid switch statement")
1569
1570 (js2-msg "msg.no.colon.case"
1571 "missing : after case expression")
1572
1573 (js2-msg "msg.double.switch.default"
1574 "double default label in the switch statement")
1575
1576 (js2-msg "msg.no.while.do"
1577 "missing while after do-loop body")
1578
1579 (js2-msg "msg.no.paren.for"
1580 "missing ( after for")
1581
1582 (js2-msg "msg.no.semi.for"
1583 "missing ; after for-loop initializer")
1584
1585 (js2-msg "msg.no.semi.for.cond"
1586 "missing ; after for-loop condition")
1587
1588 (js2-msg "msg.in.after.for.name"
1589 "missing in after for")
1590
1591 (js2-msg "msg.no.paren.for.ctrl"
1592 "missing ) after for-loop control")
1593
1594 (js2-msg "msg.no.paren.with"
1595 "missing ( before with-statement object")
1596
1597 (js2-msg "msg.no.paren.after.with"
1598 "missing ) after with-statement object")
1599
1600 (js2-msg "msg.no.paren.after.let"
1601 "missing ( after let")
1602
1603 (js2-msg "msg.no.paren.let"
1604 "missing ) after variable list")
1605
1606 (js2-msg "msg.no.curly.let"
1607 "missing } after let statement")
1608
1609 (js2-msg "msg.bad.return"
1610 "invalid return")
1611
1612 (js2-msg "msg.no.brace.block"
1613 "missing } in compound statement")
1614
1615 (js2-msg "msg.bad.label"
1616 "invalid label")
1617
1618 (js2-msg "msg.bad.var"
1619 "missing variable name")
1620
1621 (js2-msg "msg.bad.var.init"
1622 "invalid variable initialization")
1623
1624 (js2-msg "msg.no.colon.cond"
1625 "missing : in conditional expression")
1626
1627 (js2-msg "msg.no.paren.arg"
1628 "missing ) after argument list")
1629
1630 (js2-msg "msg.no.bracket.arg"
1631 "missing ] after element list")
1632
1633 (js2-msg "msg.bad.prop"
1634 "invalid property id")
1635
1636 (js2-msg "msg.no.colon.prop"
1637 "missing : after property id")
1638
1639 (js2-msg "msg.no.brace.prop"
1640 "missing } after property list")
1641
1642 (js2-msg "msg.no.paren"
1643 "missing ) in parenthetical")
1644
1645 (js2-msg "msg.reserved.id"
1646 "identifier is a reserved word")
1647
1648 (js2-msg "msg.no.paren.catch"
1649 "missing ( before catch-block condition")
1650
1651 (js2-msg "msg.bad.catchcond"
1652 "invalid catch block condition")
1653
1654 (js2-msg "msg.catch.unreachable"
1655 "any catch clauses following an unqualified catch are unreachable")
1656
1657 (js2-msg "msg.no.brace.try"
1658 "missing '{' before try block")
1659
1660 (js2-msg "msg.no.brace.catchblock"
1661 "missing '{' before catch-block body")
1662
1663 (js2-msg "msg.try.no.catchfinally"
1664 "'try' without 'catch' or 'finally'")
1665
1666 (js2-msg "msg.no.return.value"
1667 "function %s does not always return a value")
1668
1669 (js2-msg "msg.anon.no.return.value"
1670 "anonymous function does not always return a value")
1671
1672 (js2-msg "msg.return.inconsistent"
1673 "return statement is inconsistent with previous usage")
1674
1675 (js2-msg "msg.generator.returns"
1676 "TypeError: generator function '%s' returns a value")
1677
1678 (js2-msg "msg.anon.generator.returns"
1679 "TypeError: anonymous generator function returns a value")
1680
1681 (js2-msg "msg.syntax"
1682 "syntax error")
1683
1684 (js2-msg "msg.unexpected.eof"
1685 "Unexpected end of file")
1686
1687 (js2-msg "msg.XML.bad.form"
1688 "illegally formed XML syntax")
1689
1690 (js2-msg "msg.XML.not.available"
1691 "XML runtime not available")
1692
1693 (js2-msg "msg.too.deep.parser.recursion"
1694 "Too deep recursion while parsing")
1695
1696 (js2-msg "msg.no.side.effects"
1697 "Code has no side effects")
1698
1699 (js2-msg "msg.extra.trailing.comma"
1700 "Trailing comma is not legal in an ECMA-262 object initializer")
1701
1702 (js2-msg "msg.array.trailing.comma"
1703 "Trailing comma yields different behavior across browsers")
1704
1705 (js2-msg "msg.equal.as.assign"
1706 (concat "Test for equality (==) mistyped as assignment (=)?"
1707 " (parenthesize to suppress warning)"))
1708
1709 (js2-msg "msg.var.hides.arg"
1710 "Variable %s hides argument")
1711
1712 (js2-msg "msg.destruct.assign.no.init"
1713 "Missing = in destructuring declaration")
1714
1715 ;; ScriptRuntime
1716 (js2-msg "msg.no.properties"
1717 "%s has no properties.")
1718
1719 (js2-msg "msg.invalid.iterator"
1720 "Invalid iterator value")
1721
1722 (js2-msg "msg.iterator.primitive"
1723 "__iterator__ returned a primitive value")
1724
1725 (js2-msg "msg.assn.create.strict"
1726 "Assignment to undeclared variable %s")
1727
1728 (js2-msg "msg.ref.undefined.prop"
1729 "Reference to undefined property '%s'")
1730
1731 (js2-msg "msg.prop.not.found"
1732 "Property %s not found.")
1733
1734 (js2-msg "msg.invalid.type"
1735 "Invalid JavaScript value of type %s")
1736
1737 (js2-msg "msg.primitive.expected"
1738 "Primitive type expected (had %s instead)")
1739
1740 (js2-msg "msg.namespace.expected"
1741 "Namespace object expected to left of :: (found %s instead)")
1742
1743 (js2-msg "msg.null.to.object"
1744 "Cannot convert null to an object.")
1745
1746 (js2-msg "msg.undef.to.object"
1747 "Cannot convert undefined to an object.")
1748
1749 (js2-msg "msg.cyclic.value"
1750 "Cyclic %s value not allowed.")
1751
1752 (js2-msg "msg.is.not.defined"
1753 "'%s' is not defined.")
1754
1755 (js2-msg "msg.undef.prop.read"
1756 "Cannot read property '%s' from %s")
1757
1758 (js2-msg "msg.undef.prop.write"
1759 "Cannot set property '%s' of %s to '%s'")
1760
1761 (js2-msg "msg.undef.prop.delete"
1762 "Cannot delete property '%s' of %s")
1763
1764 (js2-msg "msg.undef.method.call"
1765 "Cannot call method '%s' of %s")
1766
1767 (js2-msg "msg.undef.with"
1768 "Cannot apply 'with' to %s")
1769
1770 (js2-msg "msg.isnt.function"
1771 "%s is not a function, it is %s.")
1772
1773 (js2-msg "msg.isnt.function.in"
1774 "Cannot call property %s in object %s. "
1775 "It is not a function, it is '%s'.")
1776
1777 (js2-msg "msg.function.not.found"
1778 "Cannot find function %s.")
1779
1780 (js2-msg "msg.function.not.found.in"
1781 "Cannot find function %s in object %s.")
1782
1783 (js2-msg "msg.isnt.xml.object"
1784 "%s is not an xml object.")
1785
1786 (js2-msg "msg.no.ref.to.get"
1787 "%s is not a reference to read reference value.")
1788
1789 (js2-msg "msg.no.ref.to.set"
1790 "%s is not a reference to set reference value to %s.")
1791
1792 (js2-msg "msg.no.ref.from.function"
1793 "Function %s can not be used as the left-hand "
1794 "side of assignment or as an operand of ++ or -- operator.")
1795
1796 (js2-msg "msg.bad.default.value"
1797 "Object's getDefaultValue() method returned an object.")
1798
1799 (js2-msg "msg.instanceof.not.object"
1800 "Can't use instanceof on a non-object.")
1801
1802 (js2-msg "msg.instanceof.bad.prototype"
1803 "'prototype' property of %s is not an object.")
1804
1805 (js2-msg "msg.bad.radix"
1806 "illegal radix %s.")
1807
1808 ;; ScriptableObject
1809 (js2-msg "msg.default.value"
1810 "Cannot find default value for object.")
1811
1812 (js2-msg "msg.zero.arg.ctor"
1813 "Cannot load class '%s' which has no zero-parameter constructor.")
1814
1815 (js2-msg "msg.ctor.multiple.parms"
1816 "Can't define constructor or class %s since more than "
1817 "one constructor has multiple parameters.")
1818
1819 (js2-msg "msg.extend.scriptable"
1820 "%s must extend ScriptableObject in order to define property %s.")
1821
1822 (js2-msg "msg.bad.getter.parms"
1823 "In order to define a property, getter %s must have zero "
1824 "parameters or a single ScriptableObject parameter.")
1825
1826 (js2-msg "msg.obj.getter.parms"
1827 "Expected static or delegated getter %s to take "
1828 "a ScriptableObject parameter.")
1829
1830 (js2-msg "msg.getter.static"
1831 "Getter and setter must both be static or neither be static.")
1832
1833 (js2-msg "msg.setter.return"
1834 "Setter must have void return type: %s")
1835
1836 (js2-msg "msg.setter2.parms"
1837 "Two-parameter setter must take a ScriptableObject as "
1838 "its first parameter.")
1839
1840 (js2-msg "msg.setter1.parms"
1841 "Expected single parameter setter for %s")
1842
1843 (js2-msg "msg.setter2.expected"
1844 "Expected static or delegated setter %s to take two parameters.")
1845
1846 (js2-msg "msg.setter.parms"
1847 "Expected either one or two parameters for setter.")
1848
1849 (js2-msg "msg.setter.bad.type"
1850 "Unsupported parameter type '%s' in setter '%s'.")
1851
1852 (js2-msg "msg.add.sealed"
1853 "Cannot add a property to a sealed object: %s.")
1854
1855 (js2-msg "msg.remove.sealed"
1856 "Cannot remove a property from a sealed object: %s.")
1857
1858 (js2-msg "msg.modify.sealed"
1859 "Cannot modify a property of a sealed object: %s.")
1860
1861 (js2-msg "msg.modify.readonly"
1862 "Cannot modify readonly property: %s.")
1863
1864 ;; TokenStream
1865 (js2-msg "msg.missing.exponent"
1866 "missing exponent")
1867
1868 (js2-msg "msg.caught.nfe"
1869 "number format error")
1870
1871 (js2-msg "msg.unterminated.string.lit"
1872 "unterminated string literal")
1873
1874 (js2-msg "msg.unterminated.comment"
1875 "unterminated comment")
1876
1877 (js2-msg "msg.unterminated.re.lit"
1878 "unterminated regular expression literal")
1879
1880 (js2-msg "msg.invalid.re.flag"
1881 "invalid flag after regular expression")
1882
1883 (js2-msg "msg.no.re.input.for"
1884 "no input for %s")
1885
1886 (js2-msg "msg.illegal.character"
1887 "illegal character")
1888
1889 (js2-msg "msg.invalid.escape"
1890 "invalid Unicode escape sequence")
1891
1892 (js2-msg "msg.bad.namespace"
1893 "not a valid default namespace statement. "
1894 "Syntax is: default xml namespace = EXPRESSION;")
1895
1896 ;; TokensStream warnings
1897 (js2-msg "msg.bad.octal.literal"
1898 "illegal octal literal digit %s; "
1899 "interpreting it as a decimal digit")
1900
1901 (js2-msg "msg.reserved.keyword"
1902 "illegal usage of future reserved keyword %s; "
1903 "interpreting it as ordinary identifier")
1904
1905 (js2-msg "msg.script.is.not.constructor"
1906 "Script objects are not constructors.")
1907
1908 ;; Arrays
1909 (js2-msg "msg.arraylength.bad"
1910 "Inappropriate array length.")
1911
1912 ;; Arrays
1913 (js2-msg "msg.arraylength.too.big"
1914 "Array length %s exceeds supported capacity limit.")
1915
1916 ;; URI
1917 (js2-msg "msg.bad.uri"
1918 "Malformed URI sequence.")
1919
1920 ;; Number
1921 (js2-msg "msg.bad.precision"
1922 "Precision %s out of range.")
1923
1924 ;; NativeGenerator
1925 (js2-msg "msg.send.newborn"
1926 "Attempt to send value to newborn generator")
1927
1928 (js2-msg "msg.already.exec.gen"
1929 "Already executing generator")
1930
1931 (js2-msg "msg.StopIteration.invalid"
1932 "StopIteration may not be changed to an arbitrary object.")
1933
1934 ;; Interpreter
1935 (js2-msg "msg.yield.closing"
1936 "Yield from closing generator")
1937
1938 ;;; Utilities
1939
1940 (defun js2-delete-if (predicate list)
1941 "Remove all items satisfying PREDICATE in LIST."
1942 (loop for item in list
1943 if (not (funcall predicate item))
1944 collect item))
1945
1946 (defun js2-position (element list)
1947 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1948 Returns nil if element is not found in the list."
1949 (let ((count 0)
1950 found)
1951 (while (and list (not found))
1952 (if (eq element (car list))
1953 (setq found t)
1954 (setq count (1+ count)
1955 list (cdr list))))
1956 (if found count)))
1957
1958 (defun js2-find-if (predicate list)
1959 "Find first item satisfying PREDICATE in LIST."
1960 (let (result)
1961 (while (and list (not result))
1962 (if (funcall predicate (car list))
1963 (setq result (car list)))
1964 (setq list (cdr list)))
1965 result))
1966
1967 (defmacro js2-time (form)
1968 "Evaluate FORM, discard result, and return elapsed time in sec."
1969 (declare (debug t))
1970 (let ((beg (make-symbol "--js2-time-beg--"))
1971 (delta (make-symbol "--js2-time-end--")))
1972 `(let ((,beg (current-time))
1973 ,delta)
1974 ,form
1975 (/ (truncate (* (- (float-time (current-time))
1976 (float-time ,beg))
1977 10000))
1978 10000.0))))
1979
1980 (defsubst js2-same-line (pos)
1981 "Return t if POS is on the same line as current point."
1982 (and (>= pos (point-at-bol))
1983 (<= pos (point-at-eol))))
1984
1985 (defun js2-same-line-2 (p1 p2)
1986 "Return t if P1 is on the same line as P2."
1987 (save-excursion
1988 (goto-char p1)
1989 (js2-same-line p2)))
1990
1991 (defun js2-code-bug ()
1992 "Signal an error when we encounter an unexpected code path."
1993 (error "failed assertion"))
1994
1995 (defsubst js2-record-text-property (beg end prop value)
1996 "Record a text property to set when parsing finishes."
1997 (push (list beg end prop value) js2-mode-deferred-properties))
1998
1999 ;; I'd like to associate errors with nodes, but for now the
2000 ;; easiest thing to do is get the context info from the last token.
2001 (defun js2-record-parse-error (msg &optional arg pos len)
2002 (push (list (list msg arg)
2003 (or pos js2-token-beg)
2004 (or len (- js2-token-end js2-token-beg)))
2005 js2-parsed-errors))
2006
2007 (defun js2-report-error (msg &optional msg-arg pos len)
2008 "Signal a syntax error or record a parse error."
2009 (if js2-recover-from-parse-errors
2010 (js2-record-parse-error msg msg-arg pos len)
2011 (signal 'js2-syntax-error
2012 (list msg
2013 js2-ts-lineno
2014 (save-excursion
2015 (goto-char js2-ts-cursor)
2016 (current-column))
2017 js2-ts-hit-eof))))
2018
2019 (defun js2-report-warning (msg &optional msg-arg pos len)
2020 (if js2-compiler-report-warning-as-error
2021 (js2-report-error msg msg-arg pos len)
2022 (push (list (list msg msg-arg)
2023 (or pos js2-token-beg)
2024 (or len (- js2-token-end js2-token-beg)))
2025 js2-parsed-warnings)))
2026
2027 (defun js2-add-strict-warning (msg-id &optional msg-arg beg end)
2028 (if js2-compiler-strict-mode
2029 (js2-report-warning msg-id msg-arg beg
2030 (and beg end (- end beg)))))
2031
2032 (put 'js2-syntax-error 'error-conditions
2033 '(error syntax-error js2-syntax-error))
2034 (put 'js2-syntax-error 'error-message "Syntax error")
2035
2036 (put 'js2-parse-error 'error-conditions
2037 '(error parse-error js2-parse-error))
2038 (put 'js2-parse-error 'error-message "Parse error")
2039
2040 (defmacro js2-clear-flag (flags flag)
2041 `(setq ,flags (logand ,flags (lognot ,flag))))
2042
2043 (defmacro js2-set-flag (flags flag)
2044 "Logical-or FLAG into FLAGS."
2045 `(setq ,flags (logior ,flags ,flag)))
2046
2047 (defsubst js2-flag-set-p (flags flag)
2048 (/= 0 (logand flags flag)))
2049
2050 (defsubst js2-flag-not-set-p (flags flag)
2051 (zerop (logand flags flag)))
2052
2053 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2054 "Evaluate BODY with the _ character set to be word-syntax."
2055 (declare (indent 0) (debug t))
2056 (let ((old-syntax (make-symbol "old-syntax")))
2057 `(let ((,old-syntax (string (char-syntax ?_))))
2058 (unwind-protect
2059 (progn
2060 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2061 ,@body)
2062 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2063
2064 (defsubst js2-char-uppercase-p (c)
2065 "Return t if C is an uppercase character.
2066 Handles unicode and latin chars properly."
2067 (/= c (downcase c)))
2068
2069 (defsubst js2-char-lowercase-p (c)
2070 "Return t if C is an uppercase character.
2071 Handles unicode and latin chars properly."
2072 (/= c (upcase c)))
2073
2074 ;;; AST struct and function definitions
2075
2076 ;; flags for ast node property 'member-type (used for e4x operators)
2077 (defvar js2-property-flag #x1 "Property access: element is valid name.")
2078 (defvar js2-attribute-flag #x2 "x.@y or x..@y.")
2079 (defvar js2-descendants-flag #x4 "x..y or x..@i.")
2080
2081 (defsubst js2-relpos (pos anchor)
2082 "Convert POS to be relative to ANCHOR.
2083 If POS is nil, returns nil."
2084 (and pos (- pos anchor)))
2085
2086 (defun js2-make-pad (indent)
2087 (if (zerop indent)
2088 ""
2089 (make-string (* indent js2-basic-offset) ? )))
2090
2091 (defun js2-visit-ast (node callback)
2092 "Visit every node in ast NODE with visitor CALLBACK.
2093
2094 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2095 called twice: once to visit the node, and again after all the node's
2096 children have been processed. The END-P argument is nil on the first
2097 call and non-nil on the second call. The return value of the callback
2098 affects the traversal: if non-nil, the children of NODE are processed.
2099 If the callback returns nil, or if the node has no children, then the
2100 callback is called immediately with a non-nil END-P argument.
2101
2102 The node traversal is approximately lexical-order, although there
2103 are currently no guarantees around this."
2104 (when node
2105 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2106 ;; visit the node
2107 (when (funcall callback node nil)
2108 ;; visit the kids
2109 (cond
2110 ((eq vfunc 'js2-visit-none)
2111 nil) ; don't even bother calling it
2112 ;; Each AST node type has to define a `js2-visitor' function
2113 ;; that takes a node and a callback, and calls `js2-visit-ast'
2114 ;; on each child of the node.
2115 (vfunc
2116 (funcall vfunc node callback))
2117 (t
2118 (error "%s does not define a visitor-traversal function"
2119 (aref node 0)))))
2120 ;; call the end-visit
2121 (funcall callback node t))))
2122
2123 (defstruct (js2-node
2124 (:constructor nil)) ; abstract
2125 "Base AST node type."
2126 (type -1) ; token type
2127 (pos -1) ; start position of this AST node in parsed input
2128 (len 1) ; num characters spanned by the node
2129 props ; optional node property list (an alist)
2130 parent) ; link to parent node; null for root
2131
2132 (defsubst js2-node-get-prop (node prop &optional default)
2133 (or (cadr (assoc prop (js2-node-props node))) default))
2134
2135 (defsubst js2-node-set-prop (node prop value)
2136 (setf (js2-node-props node)
2137 (cons (list prop value) (js2-node-props node))))
2138
2139 (defun js2-fixup-starts (n nodes)
2140 "Adjust the start positions of NODES to be relative to N.
2141 Any node in the list may be nil, for convenience."
2142 (dolist (node nodes)
2143 (when node
2144 (setf (js2-node-pos node) (- (js2-node-pos node)
2145 (js2-node-pos n))))))
2146
2147 (defun js2-node-add-children (parent &rest nodes)
2148 "Set parent node of NODES to PARENT, and return PARENT.
2149 Does nothing if we're not recording parent links.
2150 If any given node in NODES is nil, doesn't record that link."
2151 (js2-fixup-starts parent nodes)
2152 (dolist (node nodes)
2153 (and node
2154 (setf (js2-node-parent node) parent))))
2155
2156 ;; Non-recursive since it's called a frightening number of times.
2157 (defun js2-node-abs-pos (n)
2158 (let ((pos (js2-node-pos n)))
2159 (while (setq n (js2-node-parent n))
2160 (setq pos (+ pos (js2-node-pos n))))
2161 pos))
2162
2163 (defsubst js2-node-abs-end (n)
2164 "Return absolute buffer position of end of N."
2165 (+ (js2-node-abs-pos n) (js2-node-len n)))
2166
2167 ;; It's important to make sure block nodes have a Lisp list for the
2168 ;; child nodes, to limit printing recursion depth in an AST that
2169 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2170 ;; a sufficiently large vector tree.
2171
2172 (defstruct (js2-block-node
2173 (:include js2-node)
2174 (:constructor nil)
2175 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2176 (pos js2-token-beg)
2177 len
2178 props
2179 kids)))
2180 "A block of statements."
2181 kids) ; a Lisp list of the child statement nodes
2182
2183 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2184 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2185
2186 (defun js2-visit-block (ast callback)
2187 "Visit the `js2-block-node' children of AST."
2188 (dolist (kid (js2-block-node-kids ast))
2189 (js2-visit-ast kid callback)))
2190
2191 (defun js2-print-block (n i)
2192 (let ((pad (js2-make-pad i)))
2193 (insert pad "{\n")
2194 (dolist (kid (js2-block-node-kids n))
2195 (js2-print-ast kid (1+ i)))
2196 (insert pad "}")))
2197
2198 (defstruct (js2-scope
2199 (:include js2-block-node)
2200 (:constructor nil)
2201 (:constructor make-js2-scope (&key (type js2-BLOCK)
2202 (pos js2-token-beg)
2203 len
2204 kids)))
2205 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2206 ;; I don't have one of those handy, so I'll use an alist for now.
2207 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2208 ;; and is much lighter-weight to construct (both CPU and mem).
2209 ;; The keys are interned strings (symbols) for faster lookup.
2210 ;; Should switch to hybrid alist/hashtable eventually.
2211 symbol-table ; an alist of (symbol . js2-symbol)
2212 parent-scope ; a `js2-scope'
2213 top) ; top-level `js2-scope' (script/function)
2214
2215 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2216 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2217
2218 (defun js2-scope-set-parent-scope (scope parent)
2219 (setf (js2-scope-parent-scope scope) parent
2220 (js2-scope-top scope) (if (null parent)
2221 scope
2222 (js2-scope-top parent))))
2223
2224 (defun js2-node-get-enclosing-scope (node)
2225 "Return the innermost `js2-scope' node surrounding NODE.
2226 Returns nil if there is no enclosing scope node."
2227 (let ((parent (js2-node-parent node)))
2228 (while (not (js2-scope-p parent))
2229 (setq parent (js2-node-parent parent)))
2230 parent))
2231
2232 (defun js2-get-defining-scope (scope name)
2233 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2234 Returns `js2-scope' in which NAME is defined, or nil if not found."
2235 (let ((sym (if (symbolp name)
2236 name
2237 (intern name)))
2238 table
2239 result
2240 (continue t))
2241 (while (and scope continue)
2242 (if (and (setq table (js2-scope-symbol-table scope))
2243 (assq sym table))
2244 (setq continue nil
2245 result scope)
2246 (setq scope (js2-scope-parent-scope scope))))
2247 result))
2248
2249 (defun js2-scope-get-symbol (scope name)
2250 "Return symbol table entry for NAME in SCOPE.
2251 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2252 (and (js2-scope-symbol-table scope)
2253 (cdr (assq (if (symbolp name)
2254 name
2255 (intern name))
2256 (js2-scope-symbol-table scope)))))
2257
2258 (defun js2-scope-put-symbol (scope name symbol)
2259 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2260 NAME can be a Lisp symbol or string. SYMBOL is a `js2-symbol'."
2261 (let* ((table (js2-scope-symbol-table scope))
2262 (sym (if (symbolp name) name (intern name)))
2263 (entry (assq sym table)))
2264 (if entry
2265 (setcdr entry symbol)
2266 (push (cons sym symbol)
2267 (js2-scope-symbol-table scope)))))
2268
2269 (defstruct (js2-symbol
2270 (:constructor nil)
2271 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2272 "A symbol table entry."
2273 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2274 ;; js2-LET, or js2-CONST
2275 decl-type
2276 name ; string
2277 ast-node) ; a `js2-node'
2278
2279 (defstruct (js2-error-node
2280 (:include js2-node)
2281 (:constructor nil) ; silence emacs21 byte-compiler
2282 (:constructor make-js2-error-node (&key (type js2-ERROR)
2283 (pos js2-token-beg)
2284 len)))
2285 "AST node representing a parse error.")
2286
2287 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2288 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2289
2290 (defstruct (js2-script-node
2291 (:include js2-scope)
2292 (:constructor nil)
2293 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2294 (pos js2-token-beg)
2295 len
2296 var-decls
2297 fun-decls)))
2298 functions ; Lisp list of nested functions
2299 regexps ; Lisp list of (string . flags)
2300 symbols ; alist (every symbol gets unique index)
2301 (param-count 0)
2302 var-names ; vector of string names
2303 consts ; bool-vector matching var-decls
2304 (temp-number 0)) ; for generating temp variables
2305
2306 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2307 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2308
2309 (defun js2-print-script (node indent)
2310 (dolist (kid (js2-block-node-kids node))
2311 (js2-print-ast kid indent)))
2312
2313 (defstruct (js2-ast-root
2314 (:include js2-script-node)
2315 (:constructor nil)
2316 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2317 (pos js2-token-beg)
2318 len
2319 buffer)))
2320 "The root node of a js2 AST."
2321 buffer ; the source buffer from which the code was parsed
2322 comments ; a Lisp list of comments, ordered by start position
2323 errors ; a Lisp list of errors found during parsing
2324 warnings ; a Lisp list of warnings found during parsing
2325 node-count) ; number of nodes in the tree, including the root
2326
2327 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2328 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2329
2330 (defun js2-visit-ast-root (ast callback)
2331 (dolist (kid (js2-ast-root-kids ast))
2332 (js2-visit-ast kid callback))
2333 (dolist (comment (js2-ast-root-comments ast))
2334 (js2-visit-ast comment callback)))
2335
2336 (defstruct (js2-comment-node
2337 (:include js2-node)
2338 (:constructor nil)
2339 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2340 (pos js2-token-beg)
2341 len
2342 (format js2-ts-comment-type))))
2343 format) ; 'line, 'block, 'jsdoc or 'html
2344
2345 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2346 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2347
2348 (defun js2-print-comment (n i)
2349 ;; We really ought to link end-of-line comments to their nodes.
2350 ;; Or maybe we could add a new comment type, 'endline.
2351 (insert (js2-make-pad i)
2352 (js2-node-string n)))
2353
2354 (defstruct (js2-expr-stmt-node
2355 (:include js2-node)
2356 (:constructor nil)
2357 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2358 (pos js2-ts-cursor)
2359 len
2360 expr)))
2361 "An expression statement."
2362 expr)
2363
2364 (defsubst js2-expr-stmt-node-set-has-result (node)
2365 "Change NODE type to `js2-EXPR_RESULT'. Used for code generation."
2366 (setf (js2-node-type node) js2-EXPR_RESULT))
2367
2368 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2369 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2370
2371 (defun js2-visit-expr-stmt-node (n v)
2372 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2373
2374 (defun js2-print-expr-stmt-node (n indent)
2375 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2376 (insert ";\n"))
2377
2378 (defstruct (js2-loop-node
2379 (:include js2-scope)
2380 (:constructor nil))
2381 "Abstract supertype of loop nodes."
2382 body ; a `js2-block-node'
2383 lp ; position of left-paren, nil if omitted
2384 rp) ; position of right-paren, nil if omitted
2385
2386 (defstruct (js2-do-node
2387 (:include js2-loop-node)
2388 (:constructor nil)
2389 (:constructor make-js2-do-node (&key (type js2-DO)
2390 (pos js2-token-beg)
2391 len
2392 body
2393 condition
2394 while-pos
2395 lp
2396 rp)))
2397 "AST node for do-loop."
2398 condition ; while (expression)
2399 while-pos) ; buffer position of 'while' keyword
2400
2401 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2402 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2403
2404 (defun js2-visit-do-node (n v)
2405 (js2-visit-ast (js2-do-node-body n) v)
2406 (js2-visit-ast (js2-do-node-condition n) v))
2407
2408 (defun js2-print-do-node (n i)
2409 (let ((pad (js2-make-pad i)))
2410 (insert pad "do {\n")
2411 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2412 (js2-print-ast kid (1+ i)))
2413 (insert pad "} while (")
2414 (js2-print-ast (js2-do-node-condition n) 0)
2415 (insert ");\n")))
2416
2417 (defstruct (js2-while-node
2418 (:include js2-loop-node)
2419 (:constructor nil)
2420 (:constructor make-js2-while-node (&key (type js2-WHILE)
2421 (pos js2-token-beg)
2422 len body
2423 condition lp
2424 rp)))
2425 "AST node for while-loop."
2426 condition) ; while-condition
2427
2428 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2429 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2430
2431 (defun js2-visit-while-node (n v)
2432 (js2-visit-ast (js2-while-node-condition n) v)
2433 (js2-visit-ast (js2-while-node-body n) v))
2434
2435 (defun js2-print-while-node (n i)
2436 (let ((pad (js2-make-pad i)))
2437 (insert pad "while (")
2438 (js2-print-ast (js2-while-node-condition n) 0)
2439 (insert ") {\n")
2440 (js2-print-body (js2-while-node-body n) (1+ i))
2441 (insert pad "}\n")))
2442
2443 (defstruct (js2-for-node
2444 (:include js2-loop-node)
2445 (:constructor nil)
2446 (:constructor make-js2-for-node (&key (type js2-FOR)
2447 (pos js2-ts-cursor)
2448 len body init
2449 condition
2450 update lp rp)))
2451 "AST node for a C-style for-loop."
2452 init ; initialization expression
2453 condition ; loop condition
2454 update) ; update clause
2455
2456 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2457 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2458
2459 (defun js2-visit-for-node (n v)
2460 (js2-visit-ast (js2-for-node-init n) v)
2461 (js2-visit-ast (js2-for-node-condition n) v)
2462 (js2-visit-ast (js2-for-node-update n) v)
2463 (js2-visit-ast (js2-for-node-body n) v))
2464
2465 (defun js2-print-for-node (n i)
2466 (let ((pad (js2-make-pad i)))
2467 (insert pad "for (")
2468 (js2-print-ast (js2-for-node-init n) 0)
2469 (insert "; ")
2470 (js2-print-ast (js2-for-node-condition n) 0)
2471 (insert "; ")
2472 (js2-print-ast (js2-for-node-update n) 0)
2473 (insert ") {\n")
2474 (js2-print-body (js2-for-node-body n) (1+ i))
2475 (insert pad "}\n")))
2476
2477 (defstruct (js2-for-in-node
2478 (:include js2-loop-node)
2479 (:constructor nil)
2480 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2481 (pos js2-ts-cursor)
2482 len body
2483 iterator
2484 object
2485 in-pos
2486 each-pos
2487 foreach-p lp
2488 rp)))
2489 "AST node for a for..in loop."
2490 iterator ; [var] foo in ...
2491 object ; object over which we're iterating
2492 in-pos ; buffer position of 'in' keyword
2493 each-pos ; buffer position of 'each' keyword, if foreach-p
2494 foreach-p) ; t if it's a for-each loop
2495
2496 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2497 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2498
2499 (defun js2-visit-for-in-node (n v)
2500 (js2-visit-ast (js2-for-in-node-iterator n) v)
2501 (js2-visit-ast (js2-for-in-node-object n) v)
2502 (js2-visit-ast (js2-for-in-node-body n) v))
2503
2504 (defun js2-print-for-in-node (n i)
2505 (let ((pad (js2-make-pad i))
2506 (foreach (js2-for-in-node-foreach-p n)))
2507 (insert pad "for ")
2508 (if foreach
2509 (insert "each "))
2510 (insert "(")
2511 (js2-print-ast (js2-for-in-node-iterator n) 0)
2512 (insert " in ")
2513 (js2-print-ast (js2-for-in-node-object n) 0)
2514 (insert ") {\n")
2515 (js2-print-body (js2-for-in-node-body n) (1+ i))
2516 (insert pad "}\n")))
2517
2518 (defstruct (js2-return-node
2519 (:include js2-node)
2520 (:constructor nil)
2521 (:constructor make-js2-return-node (&key (type js2-RETURN)
2522 (pos js2-ts-cursor)
2523 len
2524 retval)))
2525 "AST node for a return statement."
2526 retval) ; expression to return, or 'undefined
2527
2528 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2529 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2530
2531 (defun js2-visit-return-node (n v)
2532 (js2-visit-ast (js2-return-node-retval n) v))
2533
2534 (defun js2-print-return-node (n i)
2535 (insert (js2-make-pad i) "return")
2536 (when (js2-return-node-retval n)
2537 (insert " ")
2538 (js2-print-ast (js2-return-node-retval n) 0))
2539 (insert ";\n"))
2540
2541 (defstruct (js2-if-node
2542 (:include js2-node)
2543 (:constructor nil)
2544 (:constructor make-js2-if-node (&key (type js2-IF)
2545 (pos js2-ts-cursor)
2546 len condition
2547 then-part
2548 else-pos
2549 else-part lp
2550 rp)))
2551 "AST node for an if-statement."
2552 condition ; expression
2553 then-part ; statement or block
2554 else-pos ; optional buffer position of 'else' keyword
2555 else-part ; optional statement or block
2556 lp ; position of left-paren, nil if omitted
2557 rp) ; position of right-paren, nil if omitted
2558
2559 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2560 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2561
2562 (defun js2-visit-if-node (n v)
2563 (js2-visit-ast (js2-if-node-condition n) v)
2564 (js2-visit-ast (js2-if-node-then-part n) v)
2565 (js2-visit-ast (js2-if-node-else-part n) v))
2566
2567 (defun js2-print-if-node (n i)
2568 (let ((pad (js2-make-pad i))
2569 (then-part (js2-if-node-then-part n))
2570 (else-part (js2-if-node-else-part n)))
2571 (insert pad "if (")
2572 (js2-print-ast (js2-if-node-condition n) 0)
2573 (insert ") {\n")
2574 (js2-print-body then-part (1+ i))
2575 (insert pad "}")
2576 (cond
2577 ((not else-part)
2578 (insert "\n"))
2579 ((js2-if-node-p else-part)
2580 (insert " else ")
2581 (js2-print-body else-part i))
2582 (t
2583 (insert " else {\n")
2584 (js2-print-body else-part (1+ i))
2585 (insert pad "}\n")))))
2586
2587 (defstruct (js2-try-node
2588 (:include js2-node)
2589 (:constructor nil)
2590 (:constructor make-js2-try-node (&key (type js2-TRY)
2591 (pos js2-ts-cursor)
2592 len
2593 try-block
2594 catch-clauses
2595 finally-block)))
2596 "AST node for a try-statement."
2597 try-block
2598 catch-clauses ; a Lisp list of `js2-catch-node'
2599 finally-block) ; a `js2-finally-node'
2600
2601 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2602 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2603
2604 (defun js2-visit-try-node (n v)
2605 (js2-visit-ast (js2-try-node-try-block n) v)
2606 (dolist (clause (js2-try-node-catch-clauses n))
2607 (js2-visit-ast clause v))
2608 (js2-visit-ast (js2-try-node-finally-block n) v))
2609
2610 (defun js2-print-try-node (n i)
2611 (let ((pad (js2-make-pad i))
2612 (catches (js2-try-node-catch-clauses n))
2613 (finally (js2-try-node-finally-block n)))
2614 (insert pad "try {\n")
2615 (js2-print-body (js2-try-node-try-block n) (1+ i))
2616 (insert pad "}")
2617 (when catches
2618 (dolist (catch catches)
2619 (js2-print-ast catch i)))
2620 (if finally
2621 (js2-print-ast finally i)
2622 (insert "\n"))))
2623
2624 (defstruct (js2-catch-node
2625 (:include js2-node)
2626 (:constructor nil)
2627 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2628 (pos js2-ts-cursor)
2629 len
2630 param
2631 guard-kwd
2632 guard-expr
2633 block lp
2634 rp)))
2635 "AST node for a catch clause."
2636 param ; destructuring form or simple name node
2637 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2638 guard-expr ; catch condition, a `js2-node'
2639 block ; statements, a `js2-block-node'
2640 lp ; buffer position of left-paren, nil if omitted
2641 rp) ; buffer position of right-paren, nil if omitted
2642
2643 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2644 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2645
2646 (defun js2-visit-catch-node (n v)
2647 (js2-visit-ast (js2-catch-node-param n) v)
2648 (when (js2-catch-node-guard-kwd n)
2649 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2650 (js2-visit-ast (js2-catch-node-block n) v))
2651
2652 (defun js2-print-catch-node (n i)
2653 (let ((pad (js2-make-pad i))
2654 (guard-kwd (js2-catch-node-guard-kwd n))
2655 (guard-expr (js2-catch-node-guard-expr n)))
2656 (insert " catch (")
2657 (js2-print-ast (js2-catch-node-param n) 0)
2658 (when guard-kwd
2659 (insert " if ")
2660 (js2-print-ast guard-expr 0))
2661 (insert ") {\n")
2662 (js2-print-body (js2-catch-node-block n) (1+ i))
2663 (insert pad "}")))
2664
2665 (defstruct (js2-finally-node
2666 (:include js2-node)
2667 (:constructor nil)
2668 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2669 (pos js2-ts-cursor)
2670 len body)))
2671 "AST node for a finally clause."
2672 body) ; a `js2-node', often but not always a block node
2673
2674 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2675 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2676
2677 (defun js2-visit-finally-node (n v)
2678 (js2-visit-ast (js2-finally-node-body n) v))
2679
2680 (defun js2-print-finally-node (n i)
2681 (let ((pad (js2-make-pad i)))
2682 (insert " finally {\n")
2683 (js2-print-body (js2-finally-node-body n) (1+ i))
2684 (insert pad "}\n")))
2685
2686 (defstruct (js2-switch-node
2687 (:include js2-node)
2688 (:constructor nil)
2689 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2690 (pos js2-ts-cursor)
2691 len
2692 discriminant
2693 cases lp
2694 rp)))
2695 "AST node for a switch statement."
2696 discriminant ; a `js2-node' (switch expression)
2697 cases ; a Lisp list of `js2-case-node'
2698 lp ; position of open-paren for discriminant, nil if omitted
2699 rp) ; position of close-paren for discriminant, nil if omitted
2700
2701 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2702 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2703
2704 (defun js2-visit-switch-node (n v)
2705 (js2-visit-ast (js2-switch-node-discriminant n) v)
2706 (dolist (c (js2-switch-node-cases n))
2707 (js2-visit-ast c v)))
2708
2709 (defun js2-print-switch-node (n i)
2710 (let ((pad (js2-make-pad i))
2711 (cases (js2-switch-node-cases n)))
2712 (insert pad "switch (")
2713 (js2-print-ast (js2-switch-node-discriminant n) 0)
2714 (insert ") {\n")
2715 (dolist (case cases)
2716 (js2-print-ast case i))
2717 (insert pad "}\n")))
2718
2719 (defstruct (js2-case-node
2720 (:include js2-block-node)
2721 (:constructor nil)
2722 (:constructor make-js2-case-node (&key (type js2-CASE)
2723 (pos js2-ts-cursor)
2724 len kids expr)))
2725 "AST node for a case clause of a switch statement."
2726 expr) ; the case expression (nil for default)
2727
2728 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2729 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2730
2731 (defun js2-visit-case-node (n v)
2732 (js2-visit-ast (js2-case-node-expr n) v)
2733 (js2-visit-block n v))
2734
2735 (defun js2-print-case-node (n i)
2736 (let ((pad (js2-make-pad i))
2737 (expr (js2-case-node-expr n)))
2738 (insert pad)
2739 (if (null expr)
2740 (insert "default:\n")
2741 (insert "case ")
2742 (js2-print-ast expr 0)
2743 (insert ":\n"))
2744 (dolist (kid (js2-case-node-kids n))
2745 (js2-print-ast kid (1+ i)))))
2746
2747 (defstruct (js2-throw-node
2748 (:include js2-node)
2749 (:constructor nil)
2750 (:constructor make-js2-throw-node (&key (type js2-THROW)
2751 (pos js2-ts-cursor)
2752 len expr)))
2753 "AST node for a throw statement."
2754 expr) ; the expression to throw
2755
2756 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2757 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2758
2759 (defun js2-visit-throw-node (n v)
2760 (js2-visit-ast (js2-throw-node-expr n) v))
2761
2762 (defun js2-print-throw-node (n i)
2763 (insert (js2-make-pad i) "throw ")
2764 (js2-print-ast (js2-throw-node-expr n) 0)
2765 (insert ";\n"))
2766
2767 (defstruct (js2-with-node
2768 (:include js2-node)
2769 (:constructor nil)
2770 (:constructor make-js2-with-node (&key (type js2-WITH)
2771 (pos js2-ts-cursor)
2772 len object
2773 body lp rp)))
2774 "AST node for a with-statement."
2775 object
2776 body
2777 lp ; buffer position of left-paren around object, nil if omitted
2778 rp) ; buffer position of right-paren around object, nil if omitted
2779
2780 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2781 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2782
2783 (defun js2-visit-with-node (n v)
2784 (js2-visit-ast (js2-with-node-object n) v)
2785 (js2-visit-ast (js2-with-node-body n) v))
2786
2787 (defun js2-print-with-node (n i)
2788 (let ((pad (js2-make-pad i)))
2789 (insert pad "with (")
2790 (js2-print-ast (js2-with-node-object n) 0)
2791 (insert ") {\n")
2792 (js2-print-body (js2-with-node-body n) (1+ i))
2793 (insert pad "}\n")))
2794
2795 (defstruct (js2-label-node
2796 (:include js2-node)
2797 (:constructor nil)
2798 (:constructor make-js2-label-node (&key (type js2-LABEL)
2799 (pos js2-ts-cursor)
2800 len name)))
2801 "AST node for a statement label or case label."
2802 name ; a string
2803 loop) ; for validating and code-generating continue-to-label
2804
2805 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2806 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2807
2808 (defun js2-print-label (n i)
2809 (insert (js2-make-pad i)
2810 (js2-label-node-name n)
2811 ":\n"))
2812
2813 (defstruct (js2-labeled-stmt-node
2814 (:include js2-node)
2815 (:constructor nil)
2816 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2817 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2818 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2819 (pos js2-ts-cursor)
2820 len labels stmt)))
2821 "AST node for a statement with one or more labels.
2822 Multiple labels for a statement are collapsed into the labels field."
2823 labels ; Lisp list of `js2-label-node'
2824 stmt) ; the statement these labels are for
2825
2826 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2827 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2828
2829 (defun js2-get-label-by-name (lbl-stmt name)
2830 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2831 Returns nil if no such label is in the list."
2832 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2833 result)
2834 (while (and label-list (not result))
2835 (if (string= (js2-label-node-name (car label-list)) name)
2836 (setq result (car label-list))
2837 (setq label-list (cdr label-list))))
2838 result))
2839
2840 (defun js2-visit-labeled-stmt (n v)
2841 (dolist (label (js2-labeled-stmt-node-labels n))
2842 (js2-visit-ast label v))
2843 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2844
2845 (defun js2-print-labeled-stmt (n i)
2846 (dolist (label (js2-labeled-stmt-node-labels n))
2847 (js2-print-ast label i))
2848 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2849
2850 (defun js2-labeled-stmt-node-contains (node label)
2851 "Return t if NODE contains LABEL in its label set.
2852 NODE is a `js2-labels-node'. LABEL is an identifier."
2853 (loop for nl in (js2-labeled-stmt-node-labels node)
2854 if (string= label (js2-label-node-name nl))
2855 return t
2856 finally return nil))
2857
2858 (defsubst js2-labeled-stmt-node-add-label (node label)
2859 "Add a `js2-label-node' to the label set for this statement."
2860 (setf (js2-labeled-stmt-node-labels node)
2861 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2862
2863 (defstruct (js2-jump-node
2864 (:include js2-node)
2865 (:constructor nil))
2866 "Abstract supertype of break and continue nodes."
2867 label ; `js2-name-node' for location of label identifier, if present
2868 target) ; target js2-labels-node or loop/switch statement
2869
2870 (defun js2-visit-jump-node (n v)
2871 ;; We don't visit the target, since it's a back-link.
2872 (js2-visit-ast (js2-jump-node-label n) v))
2873
2874 (defstruct (js2-break-node
2875 (:include js2-jump-node)
2876 (:constructor nil)
2877 (:constructor make-js2-break-node (&key (type js2-BREAK)
2878 (pos js2-ts-cursor)
2879 len label target)))
2880 "AST node for a break statement.
2881 The label field is a `js2-name-node', possibly nil, for the named label
2882 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2883 is the target of the break - a label node or enclosing loop/switch statement.")
2884
2885 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2886 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2887
2888 (defun js2-print-break-node (n i)
2889 (insert (js2-make-pad i) "break")
2890 (when (js2-break-node-label n)
2891 (insert " ")
2892 (js2-print-ast (js2-break-node-label n) 0))
2893 (insert ";\n"))
2894
2895 (defstruct (js2-continue-node
2896 (:include js2-jump-node)
2897 (:constructor nil)
2898 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2899 (pos js2-ts-cursor)
2900 len label target)))
2901 "AST node for a continue statement.
2902 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2903 It is nil if continue specifies no label. The target field is the jump target:
2904 a `js2-label-node' or the innermost enclosing loop.")
2905
2906 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2907 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2908
2909 (defun js2-print-continue-node (n i)
2910 (insert (js2-make-pad i) "continue")
2911 (when (js2-continue-node-label n)
2912 (insert " ")
2913 (js2-print-ast (js2-continue-node-label n) 0))
2914 (insert ";\n"))
2915
2916 (defstruct (js2-function-node
2917 (:include js2-script-node)
2918 (:constructor nil)
2919 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2920 (pos js2-ts-cursor)
2921 len
2922 (ftype 'FUNCTION)
2923 (form 'FUNCTION_STATEMENT)
2924 (name "")
2925 params body
2926 lp rp)))
2927 "AST node for a function declaration.
2928 The `params' field is a Lisp list of nodes. Each node is either a simple
2929 `js2-name-node', or if it's a destructuring-assignment parameter, a
2930 `js2-array-node' or `js2-object-node'."
2931 ftype ; FUNCTION, GETTER or SETTER
2932 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2933 name ; function name (a `js2-name-node', or nil if anonymous)
2934 params ; a Lisp list of destructuring forms or simple name nodes
2935 body ; a `js2-block-node' or expression node (1.8 only)
2936 lp ; position of arg-list open-paren, or nil if omitted
2937 rp ; position of arg-list close-paren, or nil if omitted
2938 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
2939 needs-activation ; t if we need an activation object for this frame
2940 is-generator ; t if this function contains a yield
2941 member-expr) ; nonstandard Ecma extension from Rhino
2942
2943 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
2944 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
2945
2946 (defun js2-visit-function-node (n v)
2947 (js2-visit-ast (js2-function-node-name n) v)
2948 (dolist (p (js2-function-node-params n))
2949 (js2-visit-ast p v))
2950 (js2-visit-ast (js2-function-node-body n) v))
2951
2952 (defun js2-print-function-node (n i)
2953 (let ((pad (js2-make-pad i))
2954 (getter (js2-node-get-prop n 'GETTER_SETTER))
2955 (name (js2-function-node-name n))
2956 (params (js2-function-node-params n))
2957 (body (js2-function-node-body n))
2958 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
2959 (unless getter
2960 (insert pad "function"))
2961 (when name
2962 (insert " ")
2963 (js2-print-ast name 0))
2964 (insert "(")
2965 (loop with len = (length params)
2966 for param in params
2967 for count from 1
2968 do
2969 (js2-print-ast param 0)
2970 (if (< count len)
2971 (insert ", ")))
2972 (insert ") {")
2973 (unless expr
2974 (insert "\n"))
2975 ;; TODO: fix this to be smarter about indenting, etc.
2976 (js2-print-body body (1+ i))
2977 (insert pad "}")
2978 (unless expr
2979 (insert "\n"))))
2980
2981 (defun js2-function-name (node)
2982 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
2983 (and (js2-function-node-name node)
2984 (js2-name-node-name (js2-function-node-name node))))
2985
2986 ;; Having this be an expression node makes it more flexible.
2987 ;; There are IDE contexts, such as indentation in a for-loop initializer,
2988 ;; that work better if you assume it's an expression. Whenever we have
2989 ;; a standalone var/const declaration, we just wrap with an expr stmt.
2990 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
2991 (defstruct (js2-var-decl-node
2992 (:include js2-node)
2993 (:constructor nil)
2994 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
2995 (pos js2-token-beg)
2996 len kids
2997 decl-type)))
2998 "AST node for a variable declaration list (VAR, CONST or LET).
2999 The node bounds differ depending on the declaration type. For VAR or
3000 CONST declarations, the bounds include the var/const keyword. For LET
3001 declarations, the node begins at the position of the first child."
3002 kids ; a Lisp list of `js2-var-init-node' structs.
3003 decl-type) ; js2-VAR, js2-CONST or js2-LET
3004
3005 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3006 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3007
3008 (defun js2-visit-var-decl (n v)
3009 (dolist (kid (js2-var-decl-node-kids n))
3010 (js2-visit-ast kid v)))
3011
3012 (defun js2-print-var-decl (n i)
3013 (let ((pad (js2-make-pad i))
3014 (tt (js2-var-decl-node-decl-type n)))
3015 (insert pad)
3016 (insert (cond
3017 ((= tt js2-VAR) "var ")
3018 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3019 ((= tt js2-CONST) "const ")
3020 (t
3021 (error "malformed var-decl node"))))
3022 (loop with kids = (js2-var-decl-node-kids n)
3023 with len = (length kids)
3024 for kid in kids
3025 for count from 1
3026 do
3027 (js2-print-ast kid 0)
3028 (if (< count len)
3029 (insert ", ")))))
3030
3031 (defstruct (js2-var-init-node
3032 (:include js2-node)
3033 (:constructor nil)
3034 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3035 (pos js2-ts-cursor)
3036 len target
3037 initializer)))
3038 "AST node for a variable declaration.
3039 The type field will be js2-CONST for a const decl."
3040 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3041 initializer) ; initializer expression, a `js2-node'
3042
3043 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3044 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3045
3046 (defun js2-visit-var-init-node (n v)
3047 (js2-visit-ast (js2-var-init-node-target n) v)
3048 (js2-visit-ast (js2-var-init-node-initializer n) v))
3049
3050 (defun js2-print-var-init-node (n i)
3051 (let ((pad (js2-make-pad i))
3052 (name (js2-var-init-node-target n))
3053 (init (js2-var-init-node-initializer n)))
3054 (insert pad)
3055 (js2-print-ast name 0)
3056 (when init
3057 (insert " = ")
3058 (js2-print-ast init 0))))
3059
3060 (defstruct (js2-cond-node
3061 (:include js2-node)
3062 (:constructor nil)
3063 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3064 (pos js2-ts-cursor)
3065 len
3066 test-expr
3067 true-expr
3068 false-expr
3069 q-pos c-pos)))
3070 "AST node for the ternary operator"
3071 test-expr
3072 true-expr
3073 false-expr
3074 q-pos ; buffer position of ?
3075 c-pos) ; buffer position of :
3076
3077 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3078 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3079
3080 (defun js2-visit-cond-node (n v)
3081 (js2-visit-ast (js2-cond-node-test-expr n) v)
3082 (js2-visit-ast (js2-cond-node-true-expr n) v)
3083 (js2-visit-ast (js2-cond-node-false-expr n) v))
3084
3085 (defun js2-print-cond-node (n i)
3086 (let ((pad (js2-make-pad i)))
3087 (insert pad)
3088 (js2-print-ast (js2-cond-node-test-expr n) 0)
3089 (insert " ? ")
3090 (js2-print-ast (js2-cond-node-true-expr n) 0)
3091 (insert " : ")
3092 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3093
3094 (defstruct (js2-infix-node
3095 (:include js2-node)
3096 (:constructor nil)
3097 (:constructor make-js2-infix-node (&key type
3098 (pos js2-ts-cursor)
3099 len op-pos
3100 left right)))
3101 "Represents infix expressions.
3102 Includes assignment ops like `|=', and the comma operator.
3103 The type field inherited from `js2-node' holds the operator."
3104 op-pos ; buffer position where operator begins
3105 left ; any `js2-node'
3106 right) ; any `js2-node'
3107
3108 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3109 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3110
3111 (defun js2-visit-infix-node (n v)
3112 (js2-visit-ast (js2-infix-node-left n) v)
3113 (js2-visit-ast (js2-infix-node-right n) v))
3114
3115 (defconst js2-operator-tokens
3116 (let ((table (make-hash-table :test 'eq))
3117 (tokens
3118 (list (cons js2-IN "in")
3119 (cons js2-TYPEOF "typeof")
3120 (cons js2-INSTANCEOF "instanceof")
3121 (cons js2-DELPROP "delete")
3122 (cons js2-COMMA ",")
3123 (cons js2-COLON ":")
3124 (cons js2-OR "||")
3125 (cons js2-AND "&&")
3126 (cons js2-INC "++")
3127 (cons js2-DEC "--")
3128 (cons js2-BITOR "|")
3129 (cons js2-BITXOR "^")
3130 (cons js2-BITAND "&")
3131 (cons js2-EQ "==")
3132 (cons js2-NE "!=")
3133 (cons js2-LT "<")
3134 (cons js2-LE "<=")
3135 (cons js2-GT ">")
3136 (cons js2-GE ">=")
3137 (cons js2-LSH "<<")
3138 (cons js2-RSH ">>")
3139 (cons js2-URSH ">>>")
3140 (cons js2-ADD "+") ; infix plus
3141 (cons js2-SUB "-") ; infix minus
3142 (cons js2-MUL "*")
3143 (cons js2-DIV "/")
3144 (cons js2-MOD "%")
3145 (cons js2-NOT "!")
3146 (cons js2-BITNOT "~")
3147 (cons js2-POS "+") ; unary plus
3148 (cons js2-NEG "-") ; unary minus
3149 (cons js2-SHEQ "===") ; shallow equality
3150 (cons js2-SHNE "!==") ; shallow inequality
3151 (cons js2-ASSIGN "=")
3152 (cons js2-ASSIGN_BITOR "|=")
3153 (cons js2-ASSIGN_BITXOR "^=")
3154 (cons js2-ASSIGN_BITAND "&=")
3155 (cons js2-ASSIGN_LSH "<<=")
3156 (cons js2-ASSIGN_RSH ">>=")
3157 (cons js2-ASSIGN_URSH ">>>=")
3158 (cons js2-ASSIGN_ADD "+=")
3159 (cons js2-ASSIGN_SUB "-=")
3160 (cons js2-ASSIGN_MUL "*=")
3161 (cons js2-ASSIGN_DIV "/=")
3162 (cons js2-ASSIGN_MOD "%="))))
3163 (loop for (k . v) in tokens do
3164 (puthash k v table))
3165 table))
3166
3167 (defun js2-print-infix-node (n i)
3168 (let* ((tt (js2-node-type n))
3169 (op (gethash tt js2-operator-tokens)))
3170 (unless op
3171 (error "unrecognized infix operator %s" (js2-node-type n)))
3172 (insert (js2-make-pad i))
3173 (js2-print-ast (js2-infix-node-left n) 0)
3174 (unless (= tt js2-COMMA)
3175 (insert " "))
3176 (insert op)
3177 (insert " ")
3178 (js2-print-ast (js2-infix-node-right n) 0)))
3179
3180 (defstruct (js2-assign-node
3181 (:include js2-infix-node)
3182 (:constructor nil)
3183 (:constructor make-js2-assign-node (&key type
3184 (pos js2-ts-cursor)
3185 len op-pos
3186 left right)))
3187 "Represents any assignment.
3188 The type field holds the actual assignment operator.")
3189
3190 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3191 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3192
3193 (defstruct (js2-unary-node
3194 (:include js2-node)
3195 (:constructor nil)
3196 (:constructor make-js2-unary-node (&key type ; required
3197 (pos js2-ts-cursor)
3198 len operand)))
3199 "AST node type for unary operator nodes.
3200 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3201 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3202 property is added if the operator follows the operand."
3203 operand) ; a `js2-node' expression
3204
3205 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3206 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3207
3208 (defun js2-visit-unary-node (n v)
3209 (js2-visit-ast (js2-unary-node-operand n) v))
3210
3211 (defun js2-print-unary-node (n i)
3212 (let* ((tt (js2-node-type n))
3213 (op (gethash tt js2-operator-tokens))
3214 (postfix (js2-node-get-prop n 'postfix)))
3215 (unless op
3216 (error "unrecognized unary operator %s" tt))
3217 (insert (js2-make-pad i))
3218 (unless postfix
3219 (insert op))
3220 (if (or (= tt js2-TYPEOF)
3221 (= tt js2-DELPROP))
3222 (insert " "))
3223 (js2-print-ast (js2-unary-node-operand n) 0)
3224 (when postfix
3225 (insert op))))
3226
3227 (defstruct (js2-let-node
3228 (:include js2-scope)
3229 (:constructor nil)
3230 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3231 (pos js2-token-beg)
3232 len vars body
3233 lp rp)))
3234 "AST node for a let expression or a let statement.
3235 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3236 vars ; a `js2-var-decl-node'
3237 body ; a `js2-node' representing the expression or body block
3238 lp
3239 rp)
3240
3241 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3242 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3243
3244 (defun js2-visit-let-node (n v)
3245 (js2-visit-ast (js2-let-node-vars n) v)
3246 (js2-visit-ast (js2-let-node-body n) v))
3247
3248 (defun js2-print-let-node (n i)
3249 (insert (js2-make-pad i) "let (")
3250 (js2-print-ast (js2-let-node-vars n) 0)
3251 (insert ") ")
3252 (js2-print-ast (js2-let-node-body n) i))
3253
3254 (defstruct (js2-keyword-node
3255 (:include js2-node)
3256 (:constructor nil)
3257 (:constructor make-js2-keyword-node (&key type
3258 (pos js2-token-beg)
3259 (len (- js2-ts-cursor pos)))))
3260 "AST node representing a literal keyword such as `null'.
3261 Used for `null', `this', `true', `false' and `debugger'.
3262 The node type is set to js2-NULL, js2-THIS, etc.")
3263
3264 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3265 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3266
3267 (defun js2-print-keyword-node (n i)
3268 (insert (js2-make-pad i)
3269 (let ((tt (js2-node-type n)))
3270 (cond
3271 ((= tt js2-THIS) "this")
3272 ((= tt js2-NULL) "null")
3273 ((= tt js2-TRUE) "true")
3274 ((= tt js2-FALSE) "false")
3275 ((= tt js2-DEBUGGER) "debugger")
3276 (t (error "Invalid keyword literal type: %d" tt))))))
3277
3278 (defsubst js2-this-node-p (node)
3279 "Return t if NODE is a `js2-literal-node' of type js2-THIS."
3280 (eq (js2-node-type node) js2-THIS))
3281
3282 (defstruct (js2-new-node
3283 (:include js2-node)
3284 (:constructor nil)
3285 (:constructor make-js2-new-node (&key (type js2-NEW)
3286 (pos js2-token-beg)
3287 len target
3288 args initializer
3289 lp rp)))
3290 "AST node for new-expression such as new Foo()."
3291 target ; an identifier or reference
3292 args ; a Lisp list of argument nodes
3293 lp ; position of left-paren, nil if omitted
3294 rp ; position of right-paren, nil if omitted
3295 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3296
3297 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3298 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3299
3300 (defun js2-visit-new-node (n v)
3301 (js2-visit-ast (js2-new-node-target n) v)
3302 (dolist (arg (js2-new-node-args n))
3303 (js2-visit-ast arg v))
3304 (js2-visit-ast (js2-new-node-initializer n) v))
3305
3306 (defun js2-print-new-node (n i)
3307 (insert (js2-make-pad i) "new ")
3308 (js2-print-ast (js2-new-node-target n))
3309 (insert "(")
3310 (js2-print-list (js2-new-node-args n))
3311 (insert ")")
3312 (when (js2-new-node-initializer n)
3313 (insert " ")
3314 (js2-print-ast (js2-new-node-initializer n))))
3315
3316 (defstruct (js2-name-node
3317 (:include js2-node)
3318 (:constructor nil)
3319 (:constructor make-js2-name-node (&key (type js2-NAME)
3320 (pos js2-token-beg)
3321 (len (- js2-ts-cursor
3322 js2-token-beg))
3323 (name js2-ts-string))))
3324 "AST node for a JavaScript identifier"
3325 name ; a string
3326 scope) ; a `js2-scope' (optional, used for codegen)
3327
3328 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3329 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3330
3331 (defun js2-print-name-node (n i)
3332 (insert (js2-make-pad i)
3333 (js2-name-node-name n)))
3334
3335 (defsubst js2-name-node-length (node)
3336 "Return identifier length of NODE, a `js2-name-node'.
3337 Returns 0 if NODE is nil or its identifier field is nil."
3338 (if node
3339 (length (js2-name-node-name node))
3340 0))
3341
3342 (defstruct (js2-number-node
3343 (:include js2-node)
3344 (:constructor nil)
3345 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3346 (pos js2-token-beg)
3347 (len (- js2-ts-cursor
3348 js2-token-beg))
3349 (value js2-ts-string)
3350 (num-value js2-ts-number))))
3351 "AST node for a number literal."
3352 value ; the original string, e.g. "6.02e23"
3353 num-value) ; the parsed number value
3354
3355 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3356 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3357
3358 (defun js2-print-number-node (n i)
3359 (insert (js2-make-pad i)
3360 (number-to-string (js2-number-node-num-value n))))
3361
3362 (defstruct (js2-regexp-node
3363 (:include js2-node)
3364 (:constructor nil)
3365 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3366 (pos js2-token-beg)
3367 (len (- js2-ts-cursor
3368 js2-token-beg))
3369 value flags)))
3370 "AST node for a regular expression literal."
3371 value ; the regexp string, without // delimiters
3372 flags) ; a string of flags, e.g. `mi'.
3373
3374 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3375 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3376
3377 (defun js2-print-regexp (n i)
3378 (insert (js2-make-pad i)
3379 "/"
3380 (js2-regexp-node-value n)
3381 "/")
3382 (if (js2-regexp-node-flags n)
3383 (insert (js2-regexp-node-flags n))))
3384
3385 (defstruct (js2-string-node
3386 (:include js2-node)
3387 (:constructor nil)
3388 (:constructor make-js2-string-node (&key (type js2-STRING)
3389 (pos js2-token-beg)
3390 (len (- js2-ts-cursor
3391 js2-token-beg))
3392 (value js2-ts-string))))
3393 "String literal.
3394 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3395 You can tell the quote type by looking at the first character."
3396 value) ; the characters of the string, including the quotes
3397
3398 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3399 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3400
3401 (defun js2-print-string-node (n i)
3402 (insert (js2-make-pad i)
3403 (js2-node-string n)))
3404
3405 (defstruct (js2-array-node
3406 (:include js2-node)
3407 (:constructor nil)
3408 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3409 (pos js2-ts-cursor)
3410 len elems)))
3411 "AST node for an array literal."
3412 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3413
3414 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3415 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3416
3417 (defun js2-visit-array-node (n v)
3418 (dolist (e (js2-array-node-elems n))
3419 (js2-visit-ast e v))) ; Can be nil; e.g. [a, ,b].
3420
3421 (defun js2-print-array-node (n i)
3422 (insert (js2-make-pad i) "[")
3423 (js2-print-list (js2-array-node-elems n))
3424 (insert "]"))
3425
3426 (defstruct (js2-object-node
3427 (:include js2-node)
3428 (:constructor nil)
3429 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3430 (pos js2-ts-cursor)
3431 len
3432 elems)))
3433 "AST node for an object literal expression.
3434 `elems' is a list of either `js2-object-prop-node' or `js2-name-node'.
3435 The latter represents abbreviation in destructuring expressions."
3436 elems)
3437
3438 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3439 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3440
3441 (defun js2-visit-object-node (n v)
3442 (dolist (e (js2-object-node-elems n))
3443 (js2-visit-ast e v)))
3444
3445 (defun js2-print-object-node (n i)
3446 (insert (js2-make-pad i) "{")
3447 (js2-print-list (js2-object-node-elems n))
3448 (insert "}"))
3449
3450 (defstruct (js2-object-prop-node
3451 (:include js2-infix-node)
3452 (:constructor nil)
3453 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3454 (pos js2-ts-cursor)
3455 len left
3456 right op-pos)))
3457 "AST node for an object literal prop:value entry.
3458 The `left' field is the property: a name node, string node or number node.
3459 The `right' field is a `js2-node' representing the initializer value.")
3460
3461 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3462 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3463
3464 (defun js2-print-object-prop-node (n i)
3465 (insert (js2-make-pad i))
3466 (js2-print-ast (js2-object-prop-node-left n) 0)
3467 (insert ":")
3468 (js2-print-ast (js2-object-prop-node-right n) 0))
3469
3470 (defstruct (js2-getter-setter-node
3471 (:include js2-infix-node)
3472 (:constructor nil)
3473 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3474 (pos js2-ts-cursor)
3475 len left right)))
3476 "AST node for a getter/setter property in an object literal.
3477 The `left' field is the `js2-name-node' naming the getter/setter prop.
3478 The `right' field is always an anonymous `js2-function-node' with a node
3479 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3480
3481 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3482 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3483
3484 (defun js2-print-getter-setter (n i)
3485 (let ((pad (js2-make-pad i))
3486 (left (js2-getter-setter-node-left n))
3487 (right (js2-getter-setter-node-right n)))
3488 (insert pad)
3489 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3490 (js2-print-ast left 0)
3491 (js2-print-ast right 0)))
3492
3493 (defstruct (js2-prop-get-node
3494 (:include js2-infix-node)
3495 (:constructor nil)
3496 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3497 (pos js2-ts-cursor)
3498 len left right)))
3499 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3500
3501 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3502 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3503
3504 (defun js2-visit-prop-get-node (n v)
3505 (js2-visit-ast (js2-prop-get-node-left n) v)
3506 (js2-visit-ast (js2-prop-get-node-right n) v))
3507
3508 (defun js2-print-prop-get-node (n i)
3509 (insert (js2-make-pad i))
3510 (js2-print-ast (js2-prop-get-node-left n) 0)
3511 (insert ".")
3512 (js2-print-ast (js2-prop-get-node-right n) 0))
3513
3514 (defstruct (js2-elem-get-node
3515 (:include js2-node)
3516 (:constructor nil)
3517 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3518 (pos js2-ts-cursor)
3519 len target element
3520 lb rb)))
3521 "AST node for an array index expression such as foo[bar]."
3522 target ; a `js2-node' - the expression preceding the "."
3523 element ; a `js2-node' - the expression in brackets
3524 lb ; position of left-bracket, nil if omitted
3525 rb) ; position of right-bracket, nil if omitted
3526
3527 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3528 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3529
3530 (defun js2-visit-elem-get-node (n v)
3531 (js2-visit-ast (js2-elem-get-node-target n) v)
3532 (js2-visit-ast (js2-elem-get-node-element n) v))
3533
3534 (defun js2-print-elem-get-node (n i)
3535 (insert (js2-make-pad i))
3536 (js2-print-ast (js2-elem-get-node-target n) 0)
3537 (insert "[")
3538 (js2-print-ast (js2-elem-get-node-element n) 0)
3539 (insert "]"))
3540
3541 (defstruct (js2-call-node
3542 (:include js2-node)
3543 (:constructor nil)
3544 (:constructor make-js2-call-node (&key (type js2-CALL)
3545 (pos js2-ts-cursor)
3546 len target args
3547 lp rp)))
3548 "AST node for a JavaScript function call."
3549 target ; a `js2-node' evaluating to the function to call
3550 args ; a Lisp list of `js2-node' arguments
3551 lp ; position of open-paren, or nil if missing
3552 rp) ; position of close-paren, or nil if missing
3553
3554 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3555 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3556
3557 (defun js2-visit-call-node (n v)
3558 (js2-visit-ast (js2-call-node-target n) v)
3559 (dolist (arg (js2-call-node-args n))
3560 (js2-visit-ast arg v)))
3561
3562 (defun js2-print-call-node (n i)
3563 (insert (js2-make-pad i))
3564 (js2-print-ast (js2-call-node-target n) 0)
3565 (insert "(")
3566 (js2-print-list (js2-call-node-args n))
3567 (insert ")"))
3568
3569 (defstruct (js2-yield-node
3570 (:include js2-node)
3571 (:constructor nil)
3572 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3573 (pos js2-ts-cursor)
3574 len value)))
3575 "AST node for yield statement or expression."
3576 value) ; optional: value to be yielded
3577
3578 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3579 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3580
3581 (defun js2-visit-yield-node (n v)
3582 (js2-visit-ast (js2-yield-node-value n) v))
3583
3584 (defun js2-print-yield-node (n i)
3585 (insert (js2-make-pad i))
3586 (insert "yield")
3587 (when (js2-yield-node-value n)
3588 (insert " ")
3589 (js2-print-ast (js2-yield-node-value n) 0)))
3590
3591 (defstruct (js2-paren-node
3592 (:include js2-node)
3593 (:constructor nil)
3594 (:constructor make-js2-paren-node (&key (type js2-LP)
3595 (pos js2-ts-cursor)
3596 len expr)))
3597 "AST node for a parenthesized expression.
3598 In particular, used when the parens are syntactically optional,
3599 as opposed to required parens such as those enclosing an if-conditional."
3600 expr) ; `js2-node'
3601
3602 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3603 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3604
3605 (defun js2-visit-paren-node (n v)
3606 (js2-visit-ast (js2-paren-node-expr n) v))
3607
3608 (defun js2-print-paren-node (n i)
3609 (insert (js2-make-pad i))
3610 (insert "(")
3611 (js2-print-ast (js2-paren-node-expr n) 0)
3612 (insert ")"))
3613
3614 (defstruct (js2-array-comp-node
3615 (:include js2-scope)
3616 (:constructor nil)
3617 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3618 (pos js2-ts-cursor)
3619 len result
3620 loops filter
3621 if-pos lp rp)))
3622 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3623 result ; result expression (just after left-bracket)
3624 loops ; a Lisp list of `js2-array-comp-loop-node'
3625 filter ; guard/filter expression
3626 if-pos ; buffer pos of 'if' keyword, if present, else nil
3627 lp ; buffer position of if-guard left-paren, or nil if not present
3628 rp) ; buffer position of if-guard right-paren, or nil if not present
3629
3630 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3631 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3632
3633 (defun js2-visit-array-comp-node (n v)
3634 (js2-visit-ast (js2-array-comp-node-result n) v)
3635 (dolist (l (js2-array-comp-node-loops n))
3636 (js2-visit-ast l v))
3637 (js2-visit-ast (js2-array-comp-node-filter n) v))
3638
3639 (defun js2-print-array-comp-node (n i)
3640 (let ((pad (js2-make-pad i))
3641 (result (js2-array-comp-node-result n))
3642 (loops (js2-array-comp-node-loops n))
3643 (filter (js2-array-comp-node-filter n)))
3644 (insert pad "[")
3645 (js2-print-ast result 0)
3646 (dolist (l loops)
3647 (insert " ")
3648 (js2-print-ast l 0))
3649 (when filter
3650 (insert " if (")
3651 (js2-print-ast filter 0))
3652 (insert ")]")))
3653
3654 (defstruct (js2-array-comp-loop-node
3655 (:include js2-for-in-node)
3656 (:constructor nil)
3657 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3658 (pos js2-ts-cursor)
3659 len iterator
3660 object in-pos
3661 foreach-p
3662 each-pos
3663 lp rp)))
3664 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3665
3666 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3667 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3668
3669 (defun js2-visit-array-comp-loop (n v)
3670 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3671 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3672
3673 (defun js2-print-array-comp-loop (n i)
3674 (insert "for (")
3675 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3676 (insert " in ")
3677 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3678 (insert ")"))
3679
3680 (defstruct (js2-empty-expr-node
3681 (:include js2-node)
3682 (:constructor nil)
3683 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3684 (pos js2-token-beg)
3685 len)))
3686 "AST node for an empty expression.")
3687
3688 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3689 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3690
3691 (defstruct (js2-xml-node
3692 (:include js2-block-node)
3693 (:constructor nil)
3694 (:constructor make-js2-xml-node (&key (type js2-XML)
3695 (pos js2-token-beg)
3696 len kids)))
3697 "AST node for initial parse of E4X literals.
3698 The kids field is a list of XML fragments, each a `js2-string-node' or
3699 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3700
3701 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3702 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3703
3704 (defun js2-print-xml-node (n i)
3705 (dolist (kid (js2-xml-node-kids n))
3706 (js2-print-ast kid i)))
3707
3708 (defstruct (js2-xml-js-expr-node
3709 (:include js2-xml-node)
3710 (:constructor nil)
3711 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3712 (pos js2-ts-cursor)
3713 len expr)))
3714 "AST node for an embedded JavaScript {expression} in an E4X literal.
3715 The start and end fields correspond to the curly-braces."
3716 expr) ; a `js2-expr-node' of some sort
3717
3718 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3719 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3720
3721 (defun js2-visit-xml-js-expr (n v)
3722 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3723
3724 (defun js2-print-xml-js-expr (n i)
3725 (insert (js2-make-pad i))
3726 (insert "{")
3727 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3728 (insert "}"))
3729
3730 (defstruct (js2-xml-dot-query-node
3731 (:include js2-infix-node)
3732 (:constructor nil)
3733 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3734 (pos js2-ts-cursor)
3735 op-pos len left
3736 right rp)))
3737 "AST node for an E4X foo.(bar) filter expression.
3738 Note that the left-paren is automatically the character immediately
3739 following the dot (.) in the operator. No whitespace is permitted
3740 between the dot and the lp by the scanner."
3741 rp)
3742
3743 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3744 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3745
3746 (defun js2-print-xml-dot-query (n i)
3747 (insert (js2-make-pad i))
3748 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3749 (insert ".(")
3750 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3751 (insert ")"))
3752
3753 (defstruct (js2-xml-ref-node
3754 (:include js2-node)
3755 (:constructor nil)) ; abstract
3756 "Base type for E4X XML attribute-access or property-get expressions.
3757 Such expressions can take a variety of forms. The general syntax has
3758 three parts:
3759
3760 - (optional) an @ (specifying an attribute access)
3761 - (optional) a namespace (a `js2-name-node') and double-colon
3762 - (required) either a `js2-name-node' or a bracketed [expression]
3763
3764 The property-name expressions (examples: ns::name, @name) are
3765 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3766 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3767
3768 This node type (or more specifically, its subclasses) will sometimes
3769 be the right-hand child of a `js2-prop-get-node' or a
3770 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3771 The `js2-xml-ref-node' may also be a standalone primary expression with
3772 no explicit target, which is valid in certain expression contexts such as
3773
3774 company..employee.(@id < 100)
3775
3776 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3777 expression whose parent is a `js2-xml-dot-query-node'."
3778 namespace
3779 at-pos
3780 colon-pos)
3781
3782 (defsubst js2-xml-ref-node-attr-access-p (node)
3783 "Return non-nil if this expression began with an @-token."
3784 (and (numberp (js2-xml-ref-node-at-pos node))
3785 (plusp (js2-xml-ref-node-at-pos node))))
3786
3787 (defstruct (js2-xml-prop-ref-node
3788 (:include js2-xml-ref-node)
3789 (:constructor nil)
3790 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3791 (pos js2-token-beg)
3792 len propname
3793 namespace at-pos
3794 colon-pos)))
3795 "AST node for an E4X XML [expr] property-ref expression.
3796 The JavaScript syntax is an optional @, an optional ns::, and a name.
3797
3798 [ '@' ] [ name '::' ] name
3799
3800 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3801 @ns::*, @*::attr, @*::*, and @*.
3802
3803 The node starts at the @ token, if present. Otherwise it starts at the
3804 namespace name. The node bounds extend through the closing right-bracket,
3805 or if it is missing due to a syntax error, through the end of the index
3806 expression."
3807 propname)
3808
3809 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3810 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3811
3812 (defun js2-visit-xml-prop-ref-node (n v)
3813 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3814 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3815
3816 (defun js2-print-xml-prop-ref-node (n i)
3817 (insert (js2-make-pad i))
3818 (if (js2-xml-ref-node-attr-access-p n)
3819 (insert "@"))
3820 (when (js2-xml-prop-ref-node-namespace n)
3821 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3822 (insert "::"))
3823 (if (js2-xml-prop-ref-node-propname n)
3824 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3825
3826 (defstruct (js2-xml-elem-ref-node
3827 (:include js2-xml-ref-node)
3828 (:constructor nil)
3829 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3830 (pos js2-token-beg)
3831 len expr lb rb
3832 namespace at-pos
3833 colon-pos)))
3834 "AST node for an E4X XML [expr] member-ref expression.
3835 Syntax:
3836
3837 [ '@' ] [ name '::' ] '[' expr ']'
3838
3839 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3840
3841 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3842 is not a legal E4X XML element-ref expression, since it's already used
3843 for standard JavaScript element-get array indexing. Hence, a
3844 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3845 non-nil namespace node, or both.
3846
3847 The node starts at the @ token, if present. Otherwise it starts
3848 at the namespace name. The node bounds extend through the closing
3849 right-bracket, or if it is missing due to a syntax error, through the
3850 end of the index expression."
3851 expr ; the bracketed index expression
3852 lb
3853 rb)
3854
3855 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3856 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3857
3858 (defun js2-visit-xml-elem-ref-node (n v)
3859 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3860 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3861
3862 (defun js2-print-xml-elem-ref-node (n i)
3863 (insert (js2-make-pad i))
3864 (if (js2-xml-ref-node-attr-access-p n)
3865 (insert "@"))
3866 (when (js2-xml-elem-ref-node-namespace n)
3867 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3868 (insert "::"))
3869 (insert "[")
3870 (if (js2-xml-elem-ref-node-expr n)
3871 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3872 (insert "]"))
3873
3874 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3875
3876 (defstruct (js2-xml-start-tag-node
3877 (:include js2-xml-node)
3878 (:constructor nil)
3879 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3880 (pos js2-ts-cursor)
3881 len name attrs kids
3882 empty-p)))
3883 "AST node for an XML start-tag. Not currently used.
3884 The `kids' field is a Lisp list of child content nodes."
3885 name ; a `js2-xml-name-node'
3886 attrs ; a Lisp list of `js2-xml-attr-node'
3887 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3888
3889 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3890 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3891
3892 (defun js2-visit-xml-start-tag (n v)
3893 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3894 (dolist (attr (js2-xml-start-tag-node-attrs n))
3895 (js2-visit-ast attr v))
3896 (js2-visit-block n v))
3897
3898 (defun js2-print-xml-start-tag (n i)
3899 (insert (js2-make-pad i) "<")
3900 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3901 (when (js2-xml-start-tag-node-attrs n)
3902 (insert " ")
3903 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3904 (insert ">"))
3905
3906 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3907 ;; and add the end-tag to the kids list of the parent as well.
3908 (defstruct (js2-xml-end-tag-node
3909 (:include js2-xml-node)
3910 (:constructor nil)
3911 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3912 (pos js2-ts-cursor)
3913 len name)))
3914 "AST node for an XML end-tag. Not currently used."
3915 name) ; a `js2-xml-name-node'
3916
3917 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3918 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3919
3920 (defun js2-visit-xml-end-tag (n v)
3921 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3922
3923 (defun js2-print-xml-end-tag (n i)
3924 (insert (js2-make-pad i))
3925 (insert "</")
3926 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3927 (insert ">"))
3928
3929 (defstruct (js2-xml-name-node
3930 (:include js2-xml-node)
3931 (:constructor nil)
3932 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3933 (pos js2-ts-cursor)
3934 len namespace kids)))
3935 "AST node for an E4X XML name. Not currently used.
3936 Any XML name can be qualified with a namespace, hence the namespace field.
3937 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3938 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3939 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3940 namespace) ; a `js2-string-node'
3941
3942 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3943 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3944
3945 (defun js2-visit-xml-name-node (n v)
3946 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3947
3948 (defun js2-print-xml-name-node (n i)
3949 (insert (js2-make-pad i))
3950 (when (js2-xml-name-node-namespace n)
3951 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3952 (insert "::"))
3953 (dolist (kid (js2-xml-name-node-kids n))
3954 (js2-print-ast kid 0)))
3955
3956 (defstruct (js2-xml-pi-node
3957 (:include js2-xml-node)
3958 (:constructor nil)
3959 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3960 (pos js2-ts-cursor)
3961 len name attrs)))
3962 "AST node for an E4X XML processing instruction. Not currently used."
3963 name ; a `js2-xml-name-node'
3964 attrs) ; a list of `js2-xml-attr-node'
3965
3966 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3967 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3968
3969 (defun js2-visit-xml-pi-node (n v)
3970 (js2-visit-ast (js2-xml-pi-node-name n) v)
3971 (dolist (attr (js2-xml-pi-node-attrs n))
3972 (js2-visit-ast attr v)))
3973
3974 (defun js2-print-xml-pi-node (n i)
3975 (insert (js2-make-pad i) "<?")
3976 (js2-print-ast (js2-xml-pi-node-name n))
3977 (when (js2-xml-pi-node-attrs n)
3978 (insert " ")
3979 (js2-print-list (js2-xml-pi-node-attrs n)))
3980 (insert "?>"))
3981
3982 (defstruct (js2-xml-cdata-node
3983 (:include js2-xml-node)
3984 (:constructor nil)
3985 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3986 (pos js2-ts-cursor)
3987 len content)))
3988 "AST node for a CDATA escape section. Not currently used."
3989 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3990
3991 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3992 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3993
3994 (defun js2-visit-xml-cdata-node (n v)
3995 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3996
3997 (defun js2-print-xml-cdata-node (n i)
3998 (insert (js2-make-pad i))
3999 (js2-print-ast (js2-xml-cdata-node-content n)))
4000
4001 (defstruct (js2-xml-attr-node
4002 (:include js2-xml-node)
4003 (:constructor nil)
4004 (:constructor make-js2-attr-node (&key (type js2-XML)
4005 (pos js2-ts-cursor)
4006 len name value
4007 eq-pos quote-type)))
4008 "AST node representing a foo='bar' XML attribute value. Not yet used."
4009 name ; a `js2-xml-name-node'
4010 value ; a `js2-xml-name-node'
4011 eq-pos ; buffer position of "=" sign
4012 quote-type) ; 'single or 'double
4013
4014 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4015 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4016
4017 (defun js2-visit-xml-attr-node (n v)
4018 (js2-visit-ast (js2-xml-attr-node-name n) v)
4019 (js2-visit-ast (js2-xml-attr-node-value n) v))
4020
4021 (defun js2-print-xml-attr-node (n i)
4022 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4023 "'"
4024 "\"")))
4025 (insert (js2-make-pad i))
4026 (js2-print-ast (js2-xml-attr-node-name n) 0)
4027 (insert "=" quote)
4028 (js2-print-ast (js2-xml-attr-node-value n) 0)
4029 (insert quote)))
4030
4031 (defstruct (js2-xml-text-node
4032 (:include js2-xml-node)
4033 (:constructor nil)
4034 (:constructor make-js2-text-node (&key (type js2-XML)
4035 (pos js2-ts-cursor)
4036 len content)))
4037 "AST node for an E4X XML text node. Not currently used."
4038 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4039
4040 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4041 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4042
4043 (defun js2-visit-xml-text-node (n v)
4044 (js2-visit-ast (js2-xml-text-node-content n) v))
4045
4046 (defun js2-print-xml-text-node (n i)
4047 (insert (js2-make-pad i))
4048 (dolist (kid (js2-xml-text-node-content n))
4049 (js2-print-ast kid)))
4050
4051 (defstruct (js2-xml-comment-node
4052 (:include js2-xml-node)
4053 (:constructor nil)
4054 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4055 (pos js2-ts-cursor)
4056 len)))
4057 "AST node for E4X XML comment. Not currently used.")
4058
4059 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4060 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4061
4062 (defun js2-print-xml-comment (n i)
4063 (insert (js2-make-pad i)
4064 (js2-node-string n)))
4065
4066 ;;; Node utilities
4067
4068 (defsubst js2-node-line (n)
4069 "Fetch the source line number at the start of node N.
4070 This is O(n) in the length of the source buffer; use prudently."
4071 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4072
4073 (defsubst js2-block-node-kid (n i)
4074 "Return child I of node N, or nil if there aren't that many."
4075 (nth i (js2-block-node-kids n)))
4076
4077 (defsubst js2-block-node-first (n)
4078 "Return first child of block node N, or nil if there is none."
4079 (first (js2-block-node-kids n)))
4080
4081 (defun js2-node-root (n)
4082 "Return the root of the AST containing N.
4083 If N has no parent pointer, returns N."
4084 (let ((parent (js2-node-parent n)))
4085 (if parent
4086 (js2-node-root parent)
4087 n)))
4088
4089 (defun js2-node-position-in-parent (node &optional parent)
4090 "Return the position of NODE in parent's block-kids list.
4091 PARENT can be supplied if known. Positioned returned is zero-indexed.
4092 Returns 0 if NODE is not a child of a block statement, or if NODE
4093 is not a statement node."
4094 (let ((p (or parent (js2-node-parent node)))
4095 (i 0))
4096 (if (not (js2-block-node-p p))
4097 i
4098 (or (js2-position node (js2-block-node-kids p))
4099 0))))
4100
4101 (defsubst js2-node-short-name (n)
4102 "Return the short name of node N as a string, e.g. `js2-if-node'."
4103 (substring (symbol-name (aref n 0))
4104 (length "cl-struct-")))
4105
4106 (defun js2-node-child-list (node)
4107 "Return the child list for NODE, a Lisp list of nodes.
4108 Works for block nodes, array nodes, obj literals, funarg lists,
4109 var decls and try nodes (for catch clauses). Note that you should call
4110 `js2-block-node-kids' on the function body for the body statements.
4111 Returns nil for zero-length child lists or unsupported nodes."
4112 (cond
4113 ((js2-function-node-p node)
4114 (js2-function-node-params node))
4115 ((js2-block-node-p node)
4116 (js2-block-node-kids node))
4117 ((js2-try-node-p node)
4118 (js2-try-node-catch-clauses node))
4119 ((js2-array-node-p node)
4120 (js2-array-node-elems node))
4121 ((js2-object-node-p node)
4122 (js2-object-node-elems node))
4123 ((js2-call-node-p node)
4124 (js2-call-node-args node))
4125 ((js2-new-node-p node)
4126 (js2-new-node-args node))
4127 ((js2-var-decl-node-p node)
4128 (js2-var-decl-node-kids node))
4129 (t
4130 nil)))
4131
4132 (defun js2-node-set-child-list (node kids)
4133 "Set the child list for NODE to KIDS."
4134 (cond
4135 ((js2-function-node-p node)
4136 (setf (js2-function-node-params node) kids))
4137 ((js2-block-node-p node)
4138 (setf (js2-block-node-kids node) kids))
4139 ((js2-try-node-p node)
4140 (setf (js2-try-node-catch-clauses node) kids))
4141 ((js2-array-node-p node)
4142 (setf (js2-array-node-elems node) kids))
4143 ((js2-object-node-p node)
4144 (setf (js2-object-node-elems node) kids))
4145 ((js2-call-node-p node)
4146 (setf (js2-call-node-args node) kids))
4147 ((js2-new-node-p node)
4148 (setf (js2-new-node-args node) kids))
4149 ((js2-var-decl-node-p node)
4150 (setf (js2-var-decl-node-kids node) kids))
4151 (t
4152 (error "Unsupported node type: %s" (js2-node-short-name node))))
4153 kids)
4154
4155 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4156 (defconst js2-paren-expr-nodes
4157 '(cl-struct-js2-array-comp-loop-node
4158 cl-struct-js2-array-comp-node
4159 cl-struct-js2-call-node
4160 cl-struct-js2-catch-node
4161 cl-struct-js2-do-node
4162 cl-struct-js2-elem-get-node
4163 cl-struct-js2-for-in-node
4164 cl-struct-js2-for-node
4165 cl-struct-js2-function-node
4166 cl-struct-js2-if-node
4167 cl-struct-js2-let-node
4168 cl-struct-js2-new-node
4169 cl-struct-js2-paren-node
4170 cl-struct-js2-switch-node
4171 cl-struct-js2-while-node
4172 cl-struct-js2-with-node
4173 cl-struct-js2-xml-dot-query-node)
4174 "Node types that can have a parenthesized child expression.
4175 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4176
4177 (defsubst js2-paren-expr-node-p (node)
4178 "Return t for nodes that typically have a parenthesized child expression.
4179 Useful for computing the indentation anchors for arg-lists and conditions.
4180 Note that it may return a false positive, for instance when NODE is
4181 a `js2-new-node' and there are no arguments or parentheses."
4182 (memq (aref node 0) js2-paren-expr-nodes))
4183
4184 ;; Fake polymorphism... yech.
4185 (defun js2-node-lp (node)
4186 "Return relative left-paren position for NODE, if applicable.
4187 For `js2-elem-get-node' structs, returns left-bracket position.
4188 Note that the position may be nil in the case of a parse error."
4189 (cond
4190 ((js2-elem-get-node-p node)
4191 (js2-elem-get-node-lb node))
4192 ((js2-loop-node-p node)
4193 (js2-loop-node-lp node))
4194 ((js2-function-node-p node)
4195 (js2-function-node-lp node))
4196 ((js2-if-node-p node)
4197 (js2-if-node-lp node))
4198 ((js2-new-node-p node)
4199 (js2-new-node-lp node))
4200 ((js2-call-node-p node)
4201 (js2-call-node-lp node))
4202 ((js2-paren-node-p node)
4203 (js2-node-pos node))
4204 ((js2-switch-node-p node)
4205 (js2-switch-node-lp node))
4206 ((js2-catch-node-p node)
4207 (js2-catch-node-lp node))
4208 ((js2-let-node-p node)
4209 (js2-let-node-lp node))
4210 ((js2-array-comp-node-p node)
4211 (js2-array-comp-node-lp node))
4212 ((js2-with-node-p node)
4213 (js2-with-node-lp node))
4214 ((js2-xml-dot-query-node-p node)
4215 (1+ (js2-infix-node-op-pos node)))
4216 (t
4217 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4218
4219 ;; Fake polymorphism... blech.
4220 (defun js2-node-rp (node)
4221 "Return relative right-paren position for NODE, if applicable.
4222 For `js2-elem-get-node' structs, returns right-bracket position.
4223 Note that the position may be nil in the case of a parse error."
4224 (cond
4225 ((js2-elem-get-node-p node)
4226 (js2-elem-get-node-lb node))
4227 ((js2-loop-node-p node)
4228 (js2-loop-node-rp node))
4229 ((js2-function-node-p node)
4230 (js2-function-node-rp node))
4231 ((js2-if-node-p node)
4232 (js2-if-node-rp node))
4233 ((js2-new-node-p node)
4234 (js2-new-node-rp node))
4235 ((js2-call-node-p node)
4236 (js2-call-node-rp node))
4237 ((js2-paren-node-p node)
4238 (+ (js2-node-pos node) (js2-node-len node)))
4239 ((js2-switch-node-p node)
4240 (js2-switch-node-rp node))
4241 ((js2-catch-node-p node)
4242 (js2-catch-node-rp node))
4243 ((js2-let-node-p node)
4244 (js2-let-node-rp node))
4245 ((js2-array-comp-node-p node)
4246 (js2-array-comp-node-rp node))
4247 ((js2-with-node-p node)
4248 (js2-with-node-rp node))
4249 ((js2-xml-dot-query-node-p node)
4250 (1+ (js2-xml-dot-query-node-rp node)))
4251 (t
4252 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4253
4254 (defsubst js2-node-first-child (node)
4255 "Return the first element of `js2-node-child-list' for NODE."
4256 (car (js2-node-child-list node)))
4257
4258 (defsubst js2-node-last-child (node)
4259 "Return the last element of `js2-node-last-child' for NODE."
4260 (car (last (js2-node-child-list node))))
4261
4262 (defun js2-node-prev-sibling (node)
4263 "Return the previous statement in parent.
4264 Works for parents supported by `js2-node-child-list'.
4265 Returns nil if NODE is not in the parent, or PARENT is
4266 not a supported node, or if NODE is the first child."
4267 (let* ((p (js2-node-parent node))
4268 (kids (js2-node-child-list p))
4269 (sib (car kids)))
4270 (while (and kids
4271 (not (eq node (cadr kids))))
4272 (setq kids (cdr kids)
4273 sib (car kids)))
4274 sib))
4275
4276 (defun js2-node-next-sibling (node)
4277 "Return the next statement in parent block.
4278 Returns nil if NODE is not in the block, or PARENT is not
4279 a block node, or if NODE is the last statement."
4280 (let* ((p (js2-node-parent node))
4281 (kids (js2-node-child-list p)))
4282 (while (and kids
4283 (not (eq node (car kids))))
4284 (setq kids (cdr kids)))
4285 (cadr kids)))
4286
4287 (defun js2-node-find-child-before (pos parent &optional after)
4288 "Find the last child that starts before POS in parent.
4289 If AFTER is non-nil, returns first child starting after POS.
4290 POS is an absolute buffer position. PARENT is any node
4291 supported by `js2-node-child-list'.
4292 Returns nil if no applicable child is found."
4293 (let ((kids (if (js2-function-node-p parent)
4294 (js2-block-node-kids (js2-function-node-body parent))
4295 (js2-node-child-list parent)))
4296 (beg (if (js2-function-node-p parent)
4297 (js2-node-abs-pos (js2-function-node-body parent))
4298 (js2-node-abs-pos parent)))
4299 kid result fn
4300 (continue t))
4301 (setq fn (if after '>= '<))
4302 (while (and kids continue)
4303 (setq kid (car kids))
4304 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4305 (setq result kid
4306 continue (if after nil t))
4307 (setq continue (if after t nil)))
4308 (setq kids (cdr kids)))
4309 result))
4310
4311 (defun js2-node-find-child-after (pos parent)
4312 "Find first child that starts after POS in parent.
4313 POS is an absolute buffer position. PARENT is any node
4314 supported by `js2-node-child-list'.
4315 Returns nil if no applicable child is found."
4316 (js2-node-find-child-before pos parent 'after))
4317
4318 (defun js2-node-replace-child (pos parent new-node)
4319 "Replace node at index POS in PARENT with NEW-NODE.
4320 Only works for parents supported by `js2-node-child-list'."
4321 (let ((kids (js2-node-child-list parent))
4322 (i 0))
4323 (while (< i pos)
4324 (setq kids (cdr kids)
4325 i (1+ i)))
4326 (setcar kids new-node)
4327 (js2-node-add-children parent new-node)))
4328
4329 (defun js2-node-buffer (n)
4330 "Return the buffer associated with AST N.
4331 Returns nil if the buffer is not set as a property on the root
4332 node, or if parent links were not recorded during parsing."
4333 (let ((root (js2-node-root n)))
4334 (and root
4335 (js2-ast-root-p root)
4336 (js2-ast-root-buffer root))))
4337
4338 (defun js2-block-node-push (n kid)
4339 "Push js2-node KID onto the end of js2-block-node N's child list.
4340 KID is always added to the -end- of the kids list.
4341 Function also calls `js2-node-add-children' to add the parent link."
4342 (let ((kids (js2-node-child-list n)))
4343 (if kids
4344 (setcdr kids (nconc (cdr kids) (list kid)))
4345 (js2-node-set-child-list n (list kid)))
4346 (js2-node-add-children n kid)))
4347
4348 (defun js2-node-string (node)
4349 (with-current-buffer (or (js2-node-buffer node)
4350 (error "No buffer available for node %s" node))
4351 (let ((pos (js2-node-abs-pos node)))
4352 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4353
4354 ;; Container for storing the node we're looking for in a traversal.
4355 (js2-deflocal js2-discovered-node nil)
4356
4357 ;; Keep track of absolute node position during traversals.
4358 (js2-deflocal js2-visitor-offset nil)
4359
4360 (js2-deflocal js2-node-search-point nil)
4361
4362 (when js2-mode-dev-mode-p
4363 (defun js2-find-node-at-point ()
4364 (interactive)
4365 (let ((node (js2-node-at-point)))
4366 (message "%s" (or node "No node found at point"))))
4367 (defun js2-node-name-at-point ()
4368 (interactive)
4369 (let ((node (js2-node-at-point)))
4370 (message "%s" (if node
4371 (js2-node-short-name node)
4372 "No node found at point.")))))
4373
4374 (defun js2-node-at-point (&optional pos skip-comments)
4375 "Return AST node at POS, a buffer position, defaulting to current point.
4376 The `js2-mode-ast' variable must be set to the current parse tree.
4377 Signals an error if the AST (`js2-mode-ast') is nil.
4378 Always returns a node - if it can't find one, it returns the root.
4379 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4380 (let ((ast js2-mode-ast)
4381 result)
4382 (unless ast
4383 (error "No JavaScript AST available"))
4384 ;; Look through comments first, since they may be inside nodes that
4385 ;; would otherwise report a match.
4386 (setq pos (or pos (point))
4387 result (if (> pos (js2-node-abs-end ast))
4388 ast
4389 (if (not skip-comments)
4390 (js2-comment-at-point pos))))
4391 (unless result
4392 (setq js2-discovered-node nil
4393 js2-visitor-offset 0
4394 js2-node-search-point pos)
4395 (unwind-protect
4396 (catch 'js2-visit-done
4397 (js2-visit-ast ast #'js2-node-at-point-visitor))
4398 (setq js2-visitor-offset nil
4399 js2-node-search-point nil))
4400 (setq result js2-discovered-node))
4401 ;; may have found a comment beyond end of last child node,
4402 ;; since visiting the ast-root looks at the comment-list last.
4403 (if (and skip-comments
4404 (js2-comment-node-p result))
4405 (setq result nil))
4406 (or result js2-mode-ast)))
4407
4408 (defun js2-node-at-point-visitor (node end-p)
4409 (let ((rel-pos (js2-node-pos node))
4410 abs-pos
4411 abs-end
4412 (point js2-node-search-point))
4413 (cond
4414 (end-p
4415 ;; this evaluates to a non-nil return value, even if it's zero
4416 (decf js2-visitor-offset rel-pos))
4417 ;; we already looked for comments before visiting, and don't want them now
4418 ((js2-comment-node-p node)
4419 nil)
4420 (t
4421 (setq abs-pos (incf js2-visitor-offset rel-pos)
4422 ;; we only want to use the node if the point is before
4423 ;; the last character position in the node, so we decrement
4424 ;; the absolute end by 1.
4425 abs-end (+ abs-pos (js2-node-len node) -1))
4426 (cond
4427 ;; If this node starts after search-point, stop the search.
4428 ((> abs-pos point)
4429 (throw 'js2-visit-done nil))
4430 ;; If this node ends before the search-point, don't check kids.
4431 ((> point abs-end)
4432 nil)
4433 (t
4434 ;; Otherwise point is within this node, possibly in a child.
4435 (setq js2-discovered-node node)
4436 t)))))) ; keep processing kids to look for more specific match
4437
4438 (defsubst js2-block-comment-p (node)
4439 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4440 (and (js2-comment-node-p node)
4441 (memq (js2-comment-node-format node) '(jsdoc block))))
4442
4443 ;; TODO: put the comments in a vector and binary-search them instead
4444 (defun js2-comment-at-point (&optional pos)
4445 "Look through scanned comment nodes for one containing POS.
4446 POS is a buffer position that defaults to current point.
4447 Function returns nil if POS was not in any comment node."
4448 (let ((ast js2-mode-ast)
4449 (x (or pos (point)))
4450 beg end)
4451 (unless ast
4452 (error "No JavaScript AST available"))
4453 (catch 'done
4454 ;; Comments are stored in lexical order.
4455 (dolist (comment (js2-ast-root-comments ast) nil)
4456 (setq beg (js2-node-abs-pos comment)
4457 end (+ beg (js2-node-len comment)))
4458 (if (and (>= x beg)
4459 (<= x end))
4460 (throw 'done comment))))))
4461
4462 (defun js2-mode-find-parent-fn (node)
4463 "Find function enclosing NODE.
4464 Returns nil if NODE is not inside a function."
4465 (setq node (js2-node-parent node))
4466 (while (and node (not (js2-function-node-p node)))
4467 (setq node (js2-node-parent node)))
4468 (and (js2-function-node-p node) node))
4469
4470 (defun js2-mode-find-enclosing-fn (node)
4471 "Find function or root enclosing NODE."
4472 (if (js2-ast-root-p node)
4473 node
4474 (setq node (js2-node-parent node))
4475 (while (not (or (js2-ast-root-p node)
4476 (js2-function-node-p node)))
4477 (setq node (js2-node-parent node)))
4478 node))
4479
4480 (defun js2-mode-find-enclosing-node (beg end)
4481 "Find script or function fully enclosing BEG and END."
4482 (let ((node (js2-node-at-point beg))
4483 pos
4484 (continue t))
4485 (while continue
4486 (if (or (js2-ast-root-p node)
4487 (and (js2-function-node-p node)
4488 (<= (setq pos (js2-node-abs-pos node)) beg)
4489 (>= (+ pos (js2-node-len node)) end)))
4490 (setq continue nil)
4491 (setq node (js2-node-parent node))))
4492 node))
4493
4494 (defun js2-node-parent-script-or-fn (node)
4495 "Find script or function immediately enclosing NODE.
4496 If NODE is the ast-root, returns nil."
4497 (if (js2-ast-root-p node)
4498 nil
4499 (setq node (js2-node-parent node))
4500 (while (and node (not (or (js2-function-node-p node)
4501 (js2-script-node-p node))))
4502 (setq node (js2-node-parent node)))
4503 node))
4504
4505 (defun js2-nested-function-p (node)
4506 "Return t if NODE is a nested function, or is inside a nested function."
4507 (unless (js2-ast-root-p node)
4508 (js2-function-node-p (if (js2-function-node-p node)
4509 (js2-node-parent-script-or-fn node)
4510 (js2-node-parent-script-or-fn
4511 (js2-node-parent-script-or-fn node))))))
4512
4513 (defun js2-function-param-node-p (node)
4514 "Return non-nil if NODE is a param node of a `js2-function-node'."
4515 (let ((parent (js2-node-parent node)))
4516 (and parent
4517 (js2-function-node-p parent)
4518 (memq node (js2-function-node-params parent)))))
4519
4520 (defun js2-mode-shift-kids (kids start offset)
4521 (dolist (kid kids)
4522 (if (> (js2-node-pos kid) start)
4523 (incf (js2-node-pos kid) offset))))
4524
4525 (defun js2-mode-shift-children (parent start offset)
4526 "Update start-positions of all children of PARENT beyond START."
4527 (let ((root (js2-node-root parent)))
4528 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4529 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4530
4531 (defun js2-node-is-descendant (node ancestor)
4532 "Return t if NODE is a descendant of ANCESTOR."
4533 (while (and node
4534 (not (eq node ancestor)))
4535 (setq node (js2-node-parent node)))
4536 node)
4537
4538 ;;; visitor infrastructure
4539
4540 (defun js2-visit-none (node callback)
4541 "Visitor for AST node that have no node children."
4542 nil)
4543
4544 (defun js2-print-none (node indent)
4545 "Visitor for AST node with no printed representation.")
4546
4547 (defun js2-print-body (node indent)
4548 "Print a statement, or a block without braces."
4549 (if (js2-block-node-p node)
4550 (dolist (kid (js2-block-node-kids node))
4551 (js2-print-ast kid indent))
4552 (js2-print-ast node indent)))
4553
4554 (defun js2-print-list (args &optional delimiter)
4555 (loop with len = (length args)
4556 for arg in args
4557 for count from 1
4558 do
4559 (js2-print-ast arg 0)
4560 (if (< count len)
4561 (insert (or delimiter ", ")))))
4562
4563 (defun js2-print-tree (ast)
4564 "Prints an AST to the current buffer.
4565 Makes `js2-ast-parent-nodes' available to the printer functions."
4566 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4567 (js2-print-ast ast)))
4568
4569 (defun js2-print-ast (node &optional indent)
4570 "Helper function for printing AST nodes.
4571 Requires `js2-ast-parent-nodes' to be non-nil.
4572 You should use `js2-print-tree' instead of this function."
4573 (let ((printer (get (aref node 0) 'js2-printer))
4574 (i (or indent 0))
4575 (pos (js2-node-abs-pos node)))
4576 ;; TODO: wedge comments in here somewhere
4577 (if printer
4578 (funcall printer node i))))
4579
4580 (defconst js2-side-effecting-tokens
4581 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4582 (dolist (tt (list js2-ASSIGN
4583 js2-ASSIGN_ADD
4584 js2-ASSIGN_BITAND
4585 js2-ASSIGN_BITOR
4586 js2-ASSIGN_BITXOR
4587 js2-ASSIGN_DIV
4588 js2-ASSIGN_LSH
4589 js2-ASSIGN_MOD
4590 js2-ASSIGN_MUL
4591 js2-ASSIGN_RSH
4592 js2-ASSIGN_SUB
4593 js2-ASSIGN_URSH
4594 js2-BLOCK
4595 js2-BREAK
4596 js2-CALL
4597 js2-CATCH
4598 js2-CATCH_SCOPE
4599 js2-CONST
4600 js2-CONTINUE
4601 js2-DEBUGGER
4602 js2-DEC
4603 js2-DELPROP
4604 js2-DEL_REF
4605 js2-DO
4606 js2-ELSE
4607 js2-EMPTY
4608 js2-ENTERWITH
4609 js2-EXPORT
4610 js2-EXPR_RESULT
4611 js2-FINALLY
4612 js2-FOR
4613 js2-FUNCTION
4614 js2-GOTO
4615 js2-IF
4616 js2-IFEQ
4617 js2-IFNE
4618 js2-IMPORT
4619 js2-INC
4620 js2-JSR
4621 js2-LABEL
4622 js2-LEAVEWITH
4623 js2-LET
4624 js2-LETEXPR
4625 js2-LOCAL_BLOCK
4626 js2-LOOP
4627 js2-NEW
4628 js2-REF_CALL
4629 js2-RETHROW
4630 js2-RETURN
4631 js2-RETURN_RESULT
4632 js2-SEMI
4633 js2-SETELEM
4634 js2-SETELEM_OP
4635 js2-SETNAME
4636 js2-SETPROP
4637 js2-SETPROP_OP
4638 js2-SETVAR
4639 js2-SET_REF
4640 js2-SET_REF_OP
4641 js2-SWITCH
4642 js2-TARGET
4643 js2-THROW
4644 js2-TRY
4645 js2-VAR
4646 js2-WHILE
4647 js2-WITH
4648 js2-WITHEXPR
4649 js2-YIELD))
4650 (aset tokens tt t))
4651 (if js2-instanceof-has-side-effects
4652 (aset tokens js2-INSTANCEOF t))
4653 tokens))
4654
4655 (defun js2-node-has-side-effects (node)
4656 "Return t if NODE has side effects."
4657 (when node ; makes it easier to handle malformed expressions
4658 (let ((tt (js2-node-type node)))
4659 (cond
4660 ;; This doubtless needs some work, since EXPR_VOID is used
4661 ;; in several ways in Rhino and I may not have caught them all.
4662 ;; I'll wait for people to notice incorrect warnings.
4663 ((and (= tt js2-EXPR_VOID)
4664 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4665 (let ((expr (js2-expr-stmt-node-expr node)))
4666 (or (js2-node-has-side-effects expr)
4667 (when (js2-string-node-p expr)
4668 (string= "use strict" (js2-string-node-value expr))))))
4669 ((= tt js2-COMMA)
4670 (js2-node-has-side-effects (js2-infix-node-right node)))
4671 ((or (= tt js2-AND)
4672 (= tt js2-OR))
4673 (or (js2-node-has-side-effects (js2-infix-node-right node))
4674 (js2-node-has-side-effects (js2-infix-node-left node))))
4675 ((= tt js2-HOOK)
4676 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4677 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4678 ((js2-paren-node-p node)
4679 (js2-node-has-side-effects (js2-paren-node-expr node)))
4680 ((= tt js2-ERROR) ; avoid cascaded error messages
4681 nil)
4682 (t
4683 (aref js2-side-effecting-tokens tt))))))
4684
4685 (defun js2-member-expr-leftmost-name (node)
4686 "For an expr such as foo.bar.baz, return leftmost node foo.
4687 NODE is any `js2-node' object. If it represents a member expression,
4688 which is any sequence of property gets, element-gets, function calls,
4689 or xml descendants/filter operators, then we look at the lexically
4690 leftmost (first) node in the chain. If it is a name-node we return it.
4691 Note that NODE can be a raw name-node and it will be returned as well.
4692 If NODE is not a name-node or member expression, or if it is a member
4693 expression whose leftmost target is not a name node, returns nil."
4694 (let ((continue t)
4695 result)
4696 (while (and continue (not result))
4697 (cond
4698 ((js2-name-node-p node)
4699 (setq result node))
4700 ((js2-prop-get-node-p node)
4701 (setq node (js2-prop-get-node-left node)))
4702 ;; TODO: handle call-nodes, xml-nodes, others?
4703 (t
4704 (setq continue nil))))
4705 result))
4706
4707 (defconst js2-stmt-node-types
4708 (list js2-BLOCK
4709 js2-BREAK
4710 js2-CONTINUE
4711 js2-DEFAULT ; e4x "default xml namespace" statement
4712 js2-DO
4713 js2-EXPR_RESULT
4714 js2-EXPR_VOID
4715 js2-FOR
4716 js2-IF
4717 js2-RETURN
4718 js2-SWITCH
4719 js2-THROW
4720 js2-TRY
4721 js2-WHILE
4722 js2-WITH)
4723 "Node types that only appear in statement contexts.
4724 The list does not include nodes that always appear as the child
4725 of another specific statement type, such as switch-cases,
4726 catch and finally blocks, and else-clauses. The list also excludes
4727 nodes like yield, let and var, which may appear in either expression
4728 or statement context, and in the latter context always have a
4729 `js2-expr-stmt-node' parent. Finally, the list does not include
4730 functions or scripts, which are treated separately from statements
4731 by the JavaScript parser and runtime.")
4732
4733 (defun js2-stmt-node-p (node)
4734 "Heuristic for figuring out if NODE is a statement.
4735 Some node types can appear in either an expression context or a
4736 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4737 For these node types in a statement context, the parent will be a
4738 `js2-expr-stmt-node'.
4739 Functions aren't included in the check."
4740 (memq (js2-node-type node) js2-stmt-node-types))
4741
4742 (defun js2-mode-find-first-stmt (node)
4743 "Search upward starting from NODE looking for a statement.
4744 For purposes of this function, a `js2-function-node' counts."
4745 (while (not (or (js2-stmt-node-p node)
4746 (js2-function-node-p node)))
4747 (setq node (js2-node-parent node)))
4748 node)
4749
4750 (defun js2-node-parent-stmt (node)
4751 "Return the node's first ancestor that is a statement.
4752 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4753 appearing in a statement context will have a parent that is a
4754 `js2-expr-stmt-node' that will be returned by this function."
4755 (let ((parent (js2-node-parent node)))
4756 (if (or (null parent)
4757 (js2-stmt-node-p parent)
4758 (and (js2-function-node-p parent)
4759 (not (eq (js2-function-node-form parent)
4760 'FUNCTION_EXPRESSION))))
4761 parent
4762 (js2-node-parent-stmt parent))))
4763
4764 ;; In the Mozilla Rhino sources, Roshan James writes:
4765 ;; Does consistent-return analysis on the function body when strict mode is
4766 ;; enabled.
4767 ;;
4768 ;; function (x) { return (x+1) }
4769 ;;
4770 ;; is ok, but
4771 ;;
4772 ;; function (x) { if (x < 0) return (x+1); }
4773 ;;
4774 ;; is not because the function can potentially return a value when the
4775 ;; condition is satisfied and if not, the function does not explicitly
4776 ;; return a value.
4777 ;;
4778 ;; This extends to checking mismatches such as "return" and "return <value>"
4779 ;; used in the same function. Warnings are not emitted if inconsistent
4780 ;; returns exist in code that can be statically shown to be unreachable.
4781 ;; Ex.
4782 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4783 ;;
4784 ;; emits no warning. However if the loop had a break statement, then a
4785 ;; warning would be emitted.
4786 ;;
4787 ;; The consistency analysis looks at control structures such as loops, ifs,
4788 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4789 ;; warns the user about an inconsistent set of termination possibilities.
4790 ;;
4791 ;; These flags enumerate the possible ways a statement/function can
4792 ;; terminate. These flags are used by endCheck() and by the Parser to
4793 ;; detect inconsistent return usage.
4794 ;;
4795 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4796 ;; able to execute (example: throw, continue)
4797 ;;
4798 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4799 ;; next one. Statement such as return dont. A compound statement may have
4800 ;; some branch that drops off control to the next statement.
4801 ;;
4802 ;; END_RETURNS indicates that the statement can return with no value.
4803 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4804 ;;
4805 ;; A compound statement such as
4806 ;; if (condition) {
4807 ;; return value;
4808 ;; }
4809 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4810
4811 (defconst js2-END_UNREACHED 0)
4812 (defconst js2-END_DROPS_OFF 1)
4813 (defconst js2-END_RETURNS 2)
4814 (defconst js2-END_RETURNS_VALUE 4)
4815 (defconst js2-END_YIELDS 8)
4816
4817 (defun js2-has-consistent-return-usage (node)
4818 "Check that every return usage in a function body is consistent.
4819 Returns t if the function satisfies strict mode requirement."
4820 (let ((n (js2-end-check node)))
4821 ;; either it doesn't return a value in any branch...
4822 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4823 ;; or it returns a value (or is unreached) at every branch
4824 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4825 js2-END_RETURNS
4826 js2-END_YIELDS)))))
4827
4828 (defun js2-end-check-if (node)
4829 "Ensure that return usage in then/else blocks is consistent.
4830 If there is no else block, then the return statement can fall through.
4831 Returns logical OR of END_* flags"
4832 (let ((th (js2-if-node-then-part node))
4833 (el (js2-if-node-else-part node)))
4834 (if (null th)
4835 js2-END_UNREACHED
4836 (logior (js2-end-check th) (if el
4837 (js2-end-check el)
4838 js2-END_DROPS_OFF)))))
4839
4840 (defun js2-end-check-switch (node)
4841 "Consistency of return statements is checked between the case statements.
4842 If there is no default, then the switch can fall through. If there is a
4843 default, we check to see if all code paths in the default return or if
4844 there is a code path that can fall through.
4845 Returns logical OR of END_* flags."
4846 (let ((rv js2-END_UNREACHED)
4847 default-case)
4848 ;; examine the cases
4849 (catch 'break
4850 (dolist (c (js2-switch-node-cases node))
4851 (if (js2-case-node-expr c)
4852 (js2-set-flag rv (js2-end-check-block c))
4853 (setq default-case c)
4854 (throw 'break nil))))
4855 ;; we don't care how the cases drop into each other
4856 (js2-clear-flag rv js2-END_DROPS_OFF)
4857 ;; examine the default
4858 (js2-set-flag rv (if default-case
4859 (js2-end-check default-case)
4860 js2-END_DROPS_OFF))
4861 rv))
4862
4863 (defun js2-end-check-try (node)
4864 "If the block has a finally, return consistency is checked in the
4865 finally block. If all code paths in the finally return, then the
4866 returns in the try-catch blocks don't matter. If there is a code path
4867 that does not return or if there is no finally block, the returns
4868 of the try and catch blocks are checked for mismatch.
4869 Returns logical OR of END_* flags."
4870 (let ((finally (js2-try-node-finally-block node))
4871 rv)
4872 ;; check the finally if it exists
4873 (setq rv (if finally
4874 (js2-end-check (js2-finally-node-body finally))
4875 js2-END_DROPS_OFF))
4876 ;; If the finally block always returns, then none of the returns
4877 ;; in the try or catch blocks matter.
4878 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4879 (js2-clear-flag rv js2-END_DROPS_OFF)
4880 ;; examine the try block
4881 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4882 ;; check each catch block
4883 (dolist (cb (js2-try-node-catch-clauses node))
4884 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4885 rv))
4886
4887 (defun js2-end-check-loop (node)
4888 "Return statement in the loop body must be consistent.
4889 The default assumption for any kind of a loop is that it will eventually
4890 terminate. The only exception is a loop with a constant true condition.
4891 Code that follows such a loop is examined only if one can determine
4892 statically that there is a break out of the loop.
4893
4894 for(... ; ... ; ...) {}
4895 for(... in ... ) {}
4896 while(...) { }
4897 do { } while(...)
4898
4899 Returns logical OR of END_* flags."
4900 (let ((rv (js2-end-check (js2-loop-node-body node)))
4901 (condition (cond
4902 ((js2-while-node-p node)
4903 (js2-while-node-condition node))
4904 ((js2-do-node-p node)
4905 (js2-do-node-condition node))
4906 ((js2-for-node-p node)
4907 (js2-for-node-condition node)))))
4908
4909 ;; check to see if the loop condition is always true
4910 (if (and condition
4911 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4912 (js2-clear-flag rv js2-END_DROPS_OFF))
4913
4914 ;; look for effect of breaks
4915 (js2-set-flag rv (js2-node-get-prop node
4916 'CONTROL_BLOCK_PROP
4917 js2-END_UNREACHED))
4918 rv))
4919
4920 (defun js2-end-check-block (node)
4921 "A general block of code is examined statement by statement.
4922 If any statement (even a compound one) returns in all branches, then
4923 subsequent statements are not examined.
4924 Returns logical OR of END_* flags."
4925 (let* ((rv js2-END_DROPS_OFF)
4926 (kids (js2-block-node-kids node))
4927 (n (car kids)))
4928 ;; Check each statment. If the statement can continue onto the next
4929 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4930 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4931 (js2-clear-flag rv js2-END_DROPS_OFF)
4932 (js2-set-flag rv (js2-end-check n))
4933 (setq kids (cdr kids)
4934 n (car kids)))
4935 rv))
4936
4937 (defun js2-end-check-label (node)
4938 "A labeled statement implies that there may be a break to the label.
4939 The function processes the labeled statement and then checks the
4940 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4941 particular label.
4942 Returns logical OR of END_* flags."
4943 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4944 (logior rv (js2-node-get-prop node
4945 'CONTROL_BLOCK_PROP
4946 js2-END_UNREACHED))))
4947
4948 (defun js2-end-check-break (node)
4949 "When a break is encountered annotate the statement being broken
4950 out of by setting its CONTROL_BLOCK_PROP property.
4951 Returns logical OR of END_* flags."
4952 (and (js2-break-node-target node)
4953 (js2-node-set-prop (js2-break-node-target node)
4954 'CONTROL_BLOCK_PROP
4955 js2-END_DROPS_OFF))
4956 js2-END_UNREACHED)
4957
4958 (defun js2-end-check (node)
4959 "Examine the body of a function, doing a basic reachability analysis.
4960 Returns a combination of flags END_* flags that indicate
4961 how the function execution can terminate. These constitute only the
4962 pessimistic set of termination conditions. It is possible that at
4963 runtime certain code paths will never be actually taken. Hence this
4964 analysis will flag errors in cases where there may not be errors.
4965 Returns logical OR of END_* flags"
4966 (let (kid)
4967 (cond
4968 ((js2-break-node-p node)
4969 (js2-end-check-break node))
4970 ((js2-expr-stmt-node-p node)
4971 (if (setq kid (js2-expr-stmt-node-expr node))
4972 (js2-end-check kid)
4973 js2-END_DROPS_OFF))
4974 ((or (js2-continue-node-p node)
4975 (js2-throw-node-p node))
4976 js2-END_UNREACHED)
4977 ((js2-return-node-p node)
4978 (if (setq kid (js2-return-node-retval node))
4979 js2-END_RETURNS_VALUE
4980 js2-END_RETURNS))
4981 ((js2-loop-node-p node)
4982 (js2-end-check-loop node))
4983 ((js2-switch-node-p node)
4984 (js2-end-check-switch node))
4985 ((js2-labeled-stmt-node-p node)
4986 (js2-end-check-label node))
4987 ((js2-if-node-p node)
4988 (js2-end-check-if node))
4989 ((js2-try-node-p node)
4990 (js2-end-check-try node))
4991 ((js2-block-node-p node)
4992 (if (null (js2-block-node-kids node))
4993 js2-END_DROPS_OFF
4994 (js2-end-check-block node)))
4995 ((js2-yield-node-p node)
4996 js2-END_YIELDS)
4997 (t
4998 js2-END_DROPS_OFF))))
4999
5000 (defun js2-always-defined-boolean-p (node)
5001 "Check if NODE always evaluates to true or false in boolean context.
5002 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5003 nor always false."
5004 (let ((tt (js2-node-type node))
5005 num)
5006 (cond
5007 ((or (= tt js2-FALSE) (= tt js2-NULL))
5008 'ALWAYS_FALSE)
5009 ((= tt js2-TRUE)
5010 'ALWAYS_TRUE)
5011 ((= tt js2-NUMBER)
5012 (setq num (js2-number-node-num-value node))
5013 (if (and (not (eq num 0.0e+NaN))
5014 (not (zerop num)))
5015 'ALWAYS_TRUE
5016 'ALWAYS_FALSE))
5017 (t
5018 nil))))
5019
5020 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5021 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5022
5023 (defvar js2-tokens nil
5024 "List of all defined token names.") ; initialized in `js2-token-names'
5025
5026 (defconst js2-token-names
5027 (let* ((names (make-vector js2-num-tokens -1))
5028 (case-fold-search nil) ; only match js2-UPPER_CASE
5029 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5030 (loop for sym in syms
5031 for i from 0
5032 do
5033 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5034 (not (boundp sym)))
5035 (aset names (symbol-value sym) ; code, e.g. 152
5036 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5037 (push sym js2-tokens)))
5038 names)
5039 "Vector mapping int values to token string names, sans `js2-' prefix.")
5040
5041 (defun js2-token-name (tok)
5042 "Return a string name for TOK, a token symbol or code.
5043 Signals an error if it's not a recognized token."
5044 (let ((code tok))
5045 (if (symbolp tok)
5046 (setq code (symbol-value tok)))
5047 (if (eq code -1)
5048 "ERROR"
5049 (if (and (numberp code)
5050 (not (minusp code))
5051 (< code js2-num-tokens))
5052 (aref js2-token-names code)
5053 (error "Invalid token: %s" code)))))
5054
5055 (defsubst js2-token-sym (tok)
5056 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5057 (intern (js2-token-name tok)))
5058
5059 (defconst js2-token-codes
5060 (let ((table (make-hash-table :test 'eq :size 256)))
5061 (loop for name across js2-token-names
5062 for sym = (intern (concat "js2-" name))
5063 do
5064 (puthash sym (symbol-value sym) table))
5065 ;; clean up a few that are "wrong" in Rhino's token codes
5066 (puthash 'js2-DELETE js2-DELPROP table)
5067 table)
5068 "Hashtable mapping token symbols to their bytecodes.")
5069
5070 (defsubst js2-token-code (sym)
5071 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5072 (or (gethash sym js2-token-codes)
5073 (error "Invalid token symbol: %s " sym))) ; signal code bug
5074
5075 (defun js2-report-scan-error (msg &optional no-throw beg len)
5076 (setq js2-token-end js2-ts-cursor)
5077 (js2-report-error msg nil
5078 (or beg js2-token-beg)
5079 (or len (- js2-token-end js2-token-beg)))
5080 (unless no-throw
5081 (throw 'return js2-ERROR)))
5082
5083 (defun js2-get-string-from-buffer ()
5084 "Reverse the char accumulator and return it as a string."
5085 (setq js2-token-end js2-ts-cursor)
5086 (if js2-ts-string-buffer
5087 (apply #'string (nreverse js2-ts-string-buffer))
5088 ""))
5089
5090 ;; TODO: could potentially avoid a lot of consing by allocating a
5091 ;; char buffer the way Rhino does.
5092 (defsubst js2-add-to-string (c)
5093 (push c js2-ts-string-buffer))
5094
5095 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5096 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5097 ;; any other character: when it's not part of the current token, we
5098 ;; unget it, allowing it to be read again by the following call.
5099 (defsubst js2-unget-char ()
5100 (decf js2-ts-cursor))
5101
5102 ;; Rhino distinguishes \r and \n line endings. We don't need to
5103 ;; because we only scan from Emacs buffers, which always use \n.
5104 (defun js2-get-char ()
5105 "Read and return the next character from the input buffer.
5106 Increments `js2-ts-lineno' if the return value is a newline char.
5107 Updates `js2-ts-cursor' to the point after the returned char.
5108 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5109 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5110 (let (c)
5111 ;; check for end of buffer
5112 (if (>= js2-ts-cursor (point-max))
5113 (setq js2-ts-hit-eof t
5114 js2-ts-cursor (1+ js2-ts-cursor)
5115 c js2-EOF_CHAR) ; return value
5116 ;; otherwise read next char
5117 (setq c (char-before (incf js2-ts-cursor)))
5118 ;; if we read a newline, update counters
5119 (if (= c ?\n)
5120 (setq js2-ts-line-start js2-ts-cursor
5121 js2-ts-lineno (1+ js2-ts-lineno)))
5122 ;; TODO: skip over format characters
5123 c)))
5124
5125 (defun js2-read-unicode-escape ()
5126 "Read a \\uNNNN sequence from the input.
5127 Assumes the ?\ and ?u have already been read.
5128 Returns the unicode character, or nil if it wasn't a valid character.
5129 Doesn't change the values of any scanner variables."
5130 ;; I really wish I knew a better way to do this, but I can't
5131 ;; find the Emacs function that takes a 16-bit int and converts
5132 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5133 ;; Have to first check that it's 4 hex characters or it may stop
5134 ;; the read early.
5135 (ignore-errors
5136 (let ((s (buffer-substring-no-properties js2-ts-cursor
5137 (+ 4 js2-ts-cursor))))
5138 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5139 (read (concat "?\\u" s))))))
5140
5141 (defun js2-match-char (test)
5142 "Consume and return next character if it matches TEST, a character.
5143 Returns nil and consumes nothing if TEST is not the next character."
5144 (let ((c (js2-get-char)))
5145 (if (eq c test)
5146 t
5147 (js2-unget-char)
5148 nil)))
5149
5150 (defun js2-peek-char ()
5151 (prog1
5152 (js2-get-char)
5153 (js2-unget-char)))
5154
5155 (defun js2-java-identifier-start-p (c)
5156 (or
5157 (memq c '(?$ ?_))
5158 (js2-char-uppercase-p c)
5159 (js2-char-lowercase-p c)))
5160
5161 (defun js2-java-identifier-part-p (c)
5162 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5163 ;; TODO: make me Unicode-friendly. See comments above.
5164 (or
5165 (memq c '(?$ ?_))
5166 (js2-char-uppercase-p c)
5167 (js2-char-lowercase-p c)
5168 (and (>= c ?0) (<= c ?9))))
5169
5170 (defun js2-alpha-p (c)
5171 (cond ((and (<= ?A c) (<= c ?Z)) t)
5172 ((and (<= ?a c) (<= c ?z)) t)
5173 (t nil)))
5174
5175 (defsubst js2-digit-p (c)
5176 (and (<= ?0 c) (<= c ?9)))
5177
5178 (defun js2-js-space-p (c)
5179 (if (<= c 127)
5180 (memq c '(#x20 #x9 #xB #xC #xD))
5181 (or
5182 (eq c #xA0)
5183 ;; TODO: change this nil to check for Unicode space character
5184 nil)))
5185
5186 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5187
5188 (defun js2-skip-line ()
5189 "Skip to end of line."
5190 (let (c)
5191 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5192 (js2-unget-char)
5193 (setq js2-token-end js2-ts-cursor)))
5194
5195 (defun js2-init-scanner (&optional buf line)
5196 "Create token stream for BUF starting on LINE.
5197 BUF defaults to `current-buffer' and LINE defaults to 1.
5198
5199 A buffer can only have one scanner active at a time, which yields
5200 dramatically simpler code than using a defstruct. If you need to
5201 have simultaneous scanners in a buffer, copy the regions to scan
5202 into temp buffers."
5203 (with-current-buffer (or buf (current-buffer))
5204 (setq js2-ts-dirty-line nil
5205 js2-ts-regexp-flags nil
5206 js2-ts-string ""
5207 js2-ts-number nil
5208 js2-ts-hit-eof nil
5209 js2-ts-line-start 0
5210 js2-ts-lineno (or line 1)
5211 js2-ts-line-end-char -1
5212 js2-ts-cursor (point-min)
5213 js2-ts-is-xml-attribute nil
5214 js2-ts-xml-is-tag-content nil
5215 js2-ts-xml-open-tags-count 0
5216 js2-ts-string-buffer nil)))
5217
5218 ;; This function uses the cached op, string and number fields in
5219 ;; TokenStream; if getToken has been called since the passed token
5220 ;; was scanned, the op or string printed may be incorrect.
5221 (defun js2-token-to-string (token)
5222 ;; Not sure where this function is used in Rhino. Not tested.
5223 (if (not js2-debug-print-trees)
5224 ""
5225 (let ((name (js2-token-name token)))
5226 (cond
5227 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5228 (concat name " `" js2-ts-string "'"))
5229 ((eq token js2-NUMBER)
5230 (format "NUMBER %g" js2-ts-number))
5231 (t
5232 name)))))
5233
5234 (defconst js2-keywords
5235 '(break
5236 case catch const continue
5237 debugger default delete do
5238 else enum
5239 false finally for function
5240 if in instanceof import
5241 let
5242 new null
5243 return
5244 switch
5245 this throw true try typeof
5246 var void
5247 while with
5248 yield))
5249
5250 ;; Token names aren't exactly the same as the keywords, unfortunately.
5251 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5252 (defconst js2-kwd-tokens
5253 (let ((table (make-vector js2-num-tokens nil))
5254 (tokens
5255 (list js2-BREAK
5256 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5257 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5258 js2-ELSE
5259 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5260 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5261 js2-LET
5262 js2-NEW js2-NULL
5263 js2-RETURN
5264 js2-SWITCH
5265 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5266 js2-VAR
5267 js2-WHILE js2-WITH
5268 js2-YIELD)))
5269 (dolist (i tokens)
5270 (aset table i 'font-lock-keyword-face))
5271 (aset table js2-STRING 'font-lock-string-face)
5272 (aset table js2-REGEXP 'font-lock-string-face)
5273 (aset table js2-COMMENT 'font-lock-comment-face)
5274 (aset table js2-THIS 'font-lock-builtin-face)
5275 (aset table js2-VOID 'font-lock-constant-face)
5276 (aset table js2-NULL 'font-lock-constant-face)
5277 (aset table js2-TRUE 'font-lock-constant-face)
5278 (aset table js2-FALSE 'font-lock-constant-face)
5279 table)
5280 "Vector whose values are non-nil for tokens that are keywords.
5281 The values are default faces to use for highlighting the keywords.")
5282
5283 (defconst js2-reserved-words
5284 '(abstract
5285 boolean byte
5286 char class
5287 double
5288 enum export extends
5289 final float
5290 goto
5291 implements import int interface
5292 long
5293 native
5294 package private protected public
5295 short static super synchronized
5296 throws transient
5297 volatile))
5298
5299 (defconst js2-keyword-names
5300 (let ((table (make-hash-table :test 'equal)))
5301 (loop for k in js2-keywords
5302 do (puthash
5303 (symbol-name k) ; instanceof
5304 (intern (concat "js2-"
5305 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5306 table))
5307 table)
5308 "JavaScript keywords by name, mapped to their symbols.")
5309
5310 (defconst js2-reserved-word-names
5311 (let ((table (make-hash-table :test 'equal)))
5312 (loop for k in js2-reserved-words
5313 do
5314 (puthash (symbol-name k) 'js2-RESERVED table))
5315 table)
5316 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5317
5318 (defun js2-collect-string (buf)
5319 "Convert BUF, a list of chars, to a string.
5320 Reverses BUF before converting."
5321 (cond
5322 ((stringp buf)
5323 buf)
5324 ((null buf) ; for emacs21 compat
5325 "")
5326 (t
5327 (if buf
5328 (apply #'string (nreverse buf))
5329 ""))))
5330
5331 (defun js2-string-to-keyword (s)
5332 "Return token for S, a string, if S is a keyword or reserved word.
5333 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5334 (or (gethash s js2-keyword-names)
5335 (gethash s js2-reserved-word-names)))
5336
5337 (defsubst js2-ts-set-char-token-bounds ()
5338 "Used when next token is one character."
5339 (setq js2-token-beg (1- js2-ts-cursor)
5340 js2-token-end js2-ts-cursor))
5341
5342 (defsubst js2-ts-return (token)
5343 "Return an N-character TOKEN from `js2-get-token'.
5344 Updates `js2-token-end' accordingly."
5345 (setq js2-token-end js2-ts-cursor)
5346 (throw 'return token))
5347
5348 (defun js2-x-digit-to-int (c accumulator)
5349 "Build up a hex number.
5350 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5351 corresponding number. Otherwise return -1."
5352 (catch 'return
5353 (catch 'check
5354 ;; Use 0..9 < A..Z < a..z
5355 (cond
5356 ((<= c ?9)
5357 (decf c ?0)
5358 (if (<= 0 c)
5359 (throw 'check nil)))
5360 ((<= c ?F)
5361 (when (<= ?A c)
5362 (decf c (- ?A 10))
5363 (throw 'check nil)))
5364 ((<= c ?f)
5365 (when (<= ?a c)
5366 (decf c (- ?a 10))
5367 (throw 'check nil))))
5368 (throw 'return -1))
5369 (logior c (lsh accumulator 4))))
5370
5371 (defun js2-get-token ()
5372 "Return next JavaScript token, an int such as js2-RETURN."
5373 (let (c c1 identifier-start is-unicode-escape-start
5374 contains-escape escape-val escape-start str result base
5375 is-integer quote-char val look-for-slash continue)
5376 (catch 'return
5377 (while t
5378 ;; Eat whitespace, possibly sensitive to newlines.
5379 (setq continue t)
5380 (while continue
5381 (setq c (js2-get-char))
5382 (cond
5383 ((eq c js2-EOF_CHAR)
5384 (js2-ts-set-char-token-bounds)
5385 (throw 'return js2-EOF))
5386 ((eq c ?\n)
5387 (js2-ts-set-char-token-bounds)
5388 (setq js2-ts-dirty-line nil)
5389 (throw 'return js2-EOL))
5390 ((not (js2-js-space-p c))
5391 (if (/= c ?-) ; in case end of HTML comment
5392 (setq js2-ts-dirty-line t))
5393 (setq continue nil))))
5394 ;; Assume the token will be 1 char - fixed up below.
5395 (js2-ts-set-char-token-bounds)
5396 (when (eq c ?@)
5397 (throw 'return js2-XMLATTR))
5398 ;; identifier/keyword/instanceof?
5399 ;; watch out for starting with a <backslash>
5400 (cond
5401 ((eq c ?\\)
5402 (setq c (js2-get-char))
5403 (if (eq c ?u)
5404 (setq identifier-start t
5405 is-unicode-escape-start t
5406 js2-ts-string-buffer nil)
5407 (setq identifier-start nil)
5408 (js2-unget-char)
5409 (setq c ?\\)))
5410 (t
5411 (when (setq identifier-start (js2-java-identifier-start-p c))
5412 (setq js2-ts-string-buffer nil)
5413 (js2-add-to-string c))))
5414 (when identifier-start
5415 (setq contains-escape is-unicode-escape-start)
5416 (catch 'break
5417 (while t
5418 (if is-unicode-escape-start
5419 ;; strictly speaking we should probably push-back
5420 ;; all the bad characters if the <backslash>uXXXX
5421 ;; sequence is malformed. But since there isn't a
5422 ;; correct context(is there?) for a bad Unicode
5423 ;; escape sequence in an identifier, we can report
5424 ;; an error here.
5425 (progn
5426 (setq escape-val 0)
5427 (dotimes (i 4)
5428 (setq c (js2-get-char)
5429 escape-val (js2-x-digit-to-int c escape-val))
5430 ;; Next check takes care of c < 0 and bad escape
5431 (if (minusp escape-val)
5432 (throw 'break nil)))
5433 (if (minusp escape-val)
5434 (js2-report-scan-error "msg.invalid.escape" t))
5435 (js2-add-to-string escape-val)
5436 (setq is-unicode-escape-start nil))
5437 (setq c (js2-get-char))
5438 (cond
5439 ((eq c ?\\)
5440 (setq c (js2-get-char))
5441 (if (eq c ?u)
5442 (setq is-unicode-escape-start t
5443 contains-escape t)
5444 (js2-report-scan-error "msg.illegal.character" t)))
5445 (t
5446 (if (or (eq c js2-EOF_CHAR)
5447 (not (js2-java-identifier-part-p c)))
5448 (throw 'break nil))
5449 (js2-add-to-string c))))))
5450 (js2-unget-char)
5451 (setq str (js2-get-string-from-buffer))
5452 (unless contains-escape
5453 ;; OPT we shouldn't have to make a string (object!) to
5454 ;; check if it's a keyword.
5455 ;; Return the corresponding token if it's a keyword
5456 (when (setq result (js2-string-to-keyword str))
5457 (if (and (< js2-language-version 170)
5458 (memq result '(js2-LET js2-YIELD)))
5459 ;; LET and YIELD are tokens only in 1.7 and later
5460 (setq result 'js2-NAME))
5461 (if (not (eq result 'js2-RESERVED))
5462 (throw 'return (js2-token-code result)))
5463 (js2-report-warning "msg.reserved.keyword" str)))
5464 ;; If we want to intern these as Rhino does, just use (intern str)
5465 (setq js2-ts-string str)
5466 (throw 'return js2-NAME)) ; end identifier/kwd check
5467 ;; is it a number?
5468 (when (or (js2-digit-p c)
5469 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5470 (setq js2-ts-string-buffer nil
5471 base 10)
5472 (when (eq c ?0)
5473 (setq c (js2-get-char))
5474 (cond
5475 ((or (eq c ?x) (eq c ?X))
5476 (setq base 16)
5477 (setq c (js2-get-char)))
5478 ((js2-digit-p c)
5479 (setq base 8))
5480 (t
5481 (js2-add-to-string ?0))))
5482 (if (eq base 16)
5483 (while (<= 0 (js2-x-digit-to-int c 0))
5484 (js2-add-to-string c)
5485 (setq c (js2-get-char)))
5486 (while (and (<= ?0 c) (<= c ?9))
5487 ;; We permit 08 and 09 as decimal numbers, which
5488 ;; makes our behavior a superset of the ECMA
5489 ;; numeric grammar. We might not always be so
5490 ;; permissive, so we warn about it.
5491 (when (and (eq base 8) (>= c ?8))
5492 (js2-report-warning "msg.bad.octal.literal"
5493 (if (eq c ?8) "8" "9"))
5494 (setq base 10))
5495 (js2-add-to-string c)
5496 (setq c (js2-get-char))))
5497 (setq is-integer t)
5498 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5499 (setq is-integer nil)
5500 (when (eq c ?.)
5501 (loop do
5502 (js2-add-to-string c)
5503 (setq c (js2-get-char))
5504 while (js2-digit-p c)))
5505 (when (memq c '(?e ?E))
5506 (js2-add-to-string c)
5507 (setq c (js2-get-char))
5508 (when (memq c '(?+ ?-))
5509 (js2-add-to-string c)
5510 (setq c (js2-get-char)))
5511 (unless (js2-digit-p c)
5512 (js2-report-scan-error "msg.missing.exponent" t))
5513 (loop do
5514 (js2-add-to-string c)
5515 (setq c (js2-get-char))
5516 while (js2-digit-p c))))
5517 (js2-unget-char)
5518 (setq js2-ts-string (js2-get-string-from-buffer)
5519 js2-ts-number
5520 (if (and (eq base 10) (not is-integer))
5521 (string-to-number js2-ts-string)
5522 ;; TODO: call runtime number-parser. Some of it is in
5523 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5524 (string-to-number js2-ts-string)))
5525 (throw 'return js2-NUMBER))
5526 ;; is it a string?
5527 (when (memq c '(?\" ?\'))
5528 ;; We attempt to accumulate a string the fast way, by
5529 ;; building it directly out of the reader. But if there
5530 ;; are any escaped characters in the string, we revert to
5531 ;; building it out of a string buffer.
5532 (setq quote-char c
5533 js2-ts-string-buffer nil
5534 c (js2-get-char))
5535 (catch 'break
5536 (while (/= c quote-char)
5537 (catch 'continue
5538 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5539 (js2-unget-char)
5540 (setq js2-token-end js2-ts-cursor)
5541 (js2-report-error "msg.unterminated.string.lit")
5542 (throw 'return js2-STRING))
5543 (when (eq c ?\\)
5544 ;; We've hit an escaped character
5545 (setq c (js2-get-char))
5546 (case c
5547 (?b (setq c ?\b))
5548 (?f (setq c ?\f))
5549 (?n (setq c ?\n))
5550 (?r (setq c ?\r))
5551 (?t (setq c ?\t))
5552 (?v (setq c ?\v))
5553 (?u
5554 (setq c1 (js2-read-unicode-escape))
5555 (if js2-parse-ide-mode
5556 (if c1
5557 (progn
5558 ;; just copy the string in IDE-mode
5559 (js2-add-to-string ?\\)
5560 (js2-add-to-string ?u)
5561 (dotimes (i 3)
5562 (js2-add-to-string (js2-get-char)))
5563 (setq c (js2-get-char))) ; added at end of loop
5564 ;; flag it as an invalid escape
5565 (js2-report-warning "msg.invalid.escape"
5566 nil (- js2-ts-cursor 2) 6))
5567 ;; Get 4 hex digits; if the u escape is not
5568 ;; followed by 4 hex digits, use 'u' + the
5569 ;; literal character sequence that follows.
5570 (js2-add-to-string ?u)
5571 (setq escape-val 0)
5572 (dotimes (i 4)
5573 (setq c (js2-get-char)
5574 escape-val (js2-x-digit-to-int c escape-val))
5575 (if (minusp escape-val)
5576 (throw 'continue nil))
5577 (js2-add-to-string c))
5578 ;; prepare for replace of stored 'u' sequence by escape value
5579 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5580 c escape-val)))
5581 (?x
5582 ;; Get 2 hex digits, defaulting to 'x'+literal
5583 ;; sequence, as above.
5584 (setq c (js2-get-char)
5585 escape-val (js2-x-digit-to-int c 0))
5586 (if (minusp escape-val)
5587 (progn
5588 (js2-add-to-string ?x)
5589 (throw 'continue nil))
5590 (setq c1 c
5591 c (js2-get-char)
5592 escape-val (js2-x-digit-to-int c escape-val))
5593 (if (minusp escape-val)
5594 (progn
5595 (js2-add-to-string ?x)
5596 (js2-add-to-string c1)
5597 (throw 'continue nil))
5598 ;; got 2 hex digits
5599 (setq c escape-val))))
5600 (?\n
5601 ;; Remove line terminator after escape to follow
5602 ;; SpiderMonkey and C/C++
5603 (setq c (js2-get-char))
5604 (throw 'continue nil))
5605 (t
5606 (when (and (<= ?0 c) (< c ?8))
5607 (setq val (- c ?0)
5608 c (js2-get-char))
5609 (when (and (<= ?0 c) (< c ?8))
5610 (setq val (- (+ (* 8 val) c) ?0)
5611 c (js2-get-char))
5612 (when (and (<= ?0 c)
5613 (< c ?8)
5614 (< val #o37))
5615 ;; c is 3rd char of octal sequence only
5616 ;; if the resulting val <= 0377
5617 (setq val (- (+ (* 8 val) c) ?0)
5618 c (js2-get-char))))
5619 (js2-unget-char)
5620 (setq c val)))))
5621 (js2-add-to-string c)
5622 (setq c (js2-get-char)))))
5623 (setq js2-ts-string (js2-get-string-from-buffer))
5624 (throw 'return js2-STRING))
5625 (case c
5626 (?\;
5627 (throw 'return js2-SEMI))
5628 (?\[
5629 (throw 'return js2-LB))
5630 (?\]
5631 (throw 'return js2-RB))
5632 (?{
5633 (throw 'return js2-LC))
5634 (?}
5635 (throw 'return js2-RC))
5636 (?\(
5637 (throw 'return js2-LP))
5638 (?\)
5639 (throw 'return js2-RP))
5640 (?,
5641 (throw 'return js2-COMMA))
5642 (??
5643 (throw 'return js2-HOOK))
5644 (?:
5645 (if (js2-match-char ?:)
5646 (js2-ts-return js2-COLONCOLON)
5647 (throw 'return js2-COLON)))
5648 (?.
5649 (if (js2-match-char ?.)
5650 (js2-ts-return js2-DOTDOT)
5651 (if (js2-match-char ?\()
5652 (js2-ts-return js2-DOTQUERY)
5653 (throw 'return js2-DOT))))
5654 (?|
5655 (if (js2-match-char ?|)
5656 (throw 'return js2-OR)
5657 (if (js2-match-char ?=)
5658 (js2-ts-return js2-ASSIGN_BITOR)
5659 (throw 'return js2-BITOR))))
5660 (?^
5661 (if (js2-match-char ?=)
5662 (js2-ts-return js2-ASSIGN_BITOR)
5663 (throw 'return js2-BITXOR)))
5664 (?&
5665 (if (js2-match-char ?&)
5666 (throw 'return js2-AND)
5667 (if (js2-match-char ?=)
5668 (js2-ts-return js2-ASSIGN_BITAND)
5669 (throw 'return js2-BITAND))))
5670 (?=
5671 (if (js2-match-char ?=)
5672 (if (js2-match-char ?=)
5673 (js2-ts-return js2-SHEQ)
5674 (throw 'return js2-EQ))
5675 (throw 'return js2-ASSIGN)))
5676 (?!
5677 (if (js2-match-char ?=)
5678 (if (js2-match-char ?=)
5679 (js2-ts-return js2-SHNE)
5680 (js2-ts-return js2-NE))
5681 (throw 'return js2-NOT)))
5682 (?<
5683 ;; NB:treat HTML begin-comment as comment-till-eol
5684 (when (js2-match-char ?!)
5685 (when (js2-match-char ?-)
5686 (when (js2-match-char ?-)
5687 (js2-skip-line)
5688 (setq js2-ts-comment-type 'html)
5689 (throw 'return js2-COMMENT)))
5690 (js2-unget-char))
5691 (if (js2-match-char ?<)
5692 (if (js2-match-char ?=)
5693 (js2-ts-return js2-ASSIGN_LSH)
5694 (js2-ts-return js2-LSH))
5695 (if (js2-match-char ?=)
5696 (js2-ts-return js2-LE)
5697 (throw 'return js2-LT))))
5698 (?>
5699 (if (js2-match-char ?>)
5700 (if (js2-match-char ?>)
5701 (if (js2-match-char ?=)
5702 (js2-ts-return js2-ASSIGN_URSH)
5703 (js2-ts-return js2-URSH))
5704 (if (js2-match-char ?=)
5705 (js2-ts-return js2-ASSIGN_RSH)
5706 (js2-ts-return js2-RSH)))
5707 (if (js2-match-char ?=)
5708 (js2-ts-return js2-GE)
5709 (throw 'return js2-GT))))
5710 (?*
5711 (if (js2-match-char ?=)
5712 (js2-ts-return js2-ASSIGN_MUL)
5713 (throw 'return js2-MUL)))
5714 (?/
5715 ;; is it a // comment?
5716 (when (js2-match-char ?/)
5717 (setq js2-token-beg (- js2-ts-cursor 2))
5718 (js2-skip-line)
5719 (setq js2-ts-comment-type 'line)
5720 ;; include newline so highlighting goes to end of window
5721 (incf js2-token-end)
5722 (throw 'return js2-COMMENT))
5723 ;; is it a /* comment?
5724 (when (js2-match-char ?*)
5725 (setq look-for-slash nil
5726 js2-token-beg (- js2-ts-cursor 2)
5727 js2-ts-comment-type
5728 (if (js2-match-char ?*)
5729 (progn
5730 (setq look-for-slash t)
5731 'jsdoc)
5732 'block))
5733 (while t
5734 (setq c (js2-get-char))
5735 (cond
5736 ((eq c js2-EOF_CHAR)
5737 (setq js2-token-end (1- js2-ts-cursor))
5738 (js2-report-error "msg.unterminated.comment")
5739 (throw 'return js2-COMMENT))
5740 ((eq c ?*)
5741 (setq look-for-slash t))
5742 ((eq c ?/)
5743 (if look-for-slash
5744 (js2-ts-return js2-COMMENT)))
5745 (t
5746 (setq look-for-slash nil
5747 js2-token-end js2-ts-cursor)))))
5748 (if (js2-match-char ?=)
5749 (js2-ts-return js2-ASSIGN_DIV)
5750 (throw 'return js2-DIV)))
5751 (?#
5752 (when js2-skip-preprocessor-directives
5753 (js2-skip-line)
5754 (setq js2-ts-comment-type 'preprocessor
5755 js2-token-end js2-ts-cursor)
5756 (throw 'return js2-COMMENT))
5757 (throw 'return js2-ERROR))
5758 (?%
5759 (if (js2-match-char ?=)
5760 (js2-ts-return js2-ASSIGN_MOD)
5761 (throw 'return js2-MOD)))
5762 (?~
5763 (throw 'return js2-BITNOT))
5764 (?+
5765 (if (js2-match-char ?=)
5766 (js2-ts-return js2-ASSIGN_ADD)
5767 (if (js2-match-char ?+)
5768 (js2-ts-return js2-INC)
5769 (throw 'return js2-ADD))))
5770 (?-
5771 (cond
5772 ((js2-match-char ?=)
5773 (setq c js2-ASSIGN_SUB))
5774 ((js2-match-char ?-)
5775 (unless js2-ts-dirty-line
5776 ;; treat HTML end-comment after possible whitespace
5777 ;; after line start as comment-until-eol
5778 (when (js2-match-char ?>)
5779 (js2-skip-line)
5780 (setq js2-ts-comment-type 'html)
5781 (throw 'return js2-COMMENT)))
5782 (setq c js2-DEC))
5783 (t
5784 (setq c js2-SUB)))
5785 (setq js2-ts-dirty-line t)
5786 (js2-ts-return c))
5787 (otherwise
5788 (js2-report-scan-error "msg.illegal.character")))))))
5789
5790 (defun js2-read-regexp (start-token)
5791 "Called by parser when it gets / or /= in literal context."
5792 (let (c err
5793 in-class ; inside a '[' .. ']' character-class
5794 flags
5795 (continue t))
5796 (setq js2-token-beg js2-ts-cursor
5797 js2-ts-string-buffer nil
5798 js2-ts-regexp-flags nil)
5799 (if (eq start-token js2-ASSIGN_DIV)
5800 ;; mis-scanned /=
5801 (js2-add-to-string ?=)
5802 (if (not (eq start-token js2-DIV))
5803 (error "failed assertion")))
5804 (while (and (not err)
5805 (or (/= (setq c (js2-get-char)) ?/)
5806 in-class))
5807 (cond
5808 ((or (= c ?\n)
5809 (= c js2-EOF_CHAR))
5810 (setq js2-token-end (1- js2-ts-cursor)
5811 err t
5812 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5813 (js2-report-error "msg.unterminated.re.lit"))
5814 (t (cond
5815 ((= c ?\\)
5816 (js2-add-to-string c)
5817 (setq c (js2-get-char)))
5818 ((= c ?\[)
5819 (setq in-class t))
5820 ((= c ?\])
5821 (setq in-class nil)))
5822 (js2-add-to-string c))))
5823 (unless err
5824 (while continue
5825 (cond
5826 ((js2-match-char ?g)
5827 (push ?g flags))
5828 ((js2-match-char ?i)
5829 (push ?i flags))
5830 ((js2-match-char ?m)
5831 (push ?m flags))
5832 (t
5833 (setq continue nil))))
5834 (if (js2-alpha-p (js2-peek-char))
5835 (js2-report-scan-error "msg.invalid.re.flag" t
5836 js2-ts-cursor 1))
5837 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5838 js2-ts-regexp-flags (js2-collect-string flags)
5839 js2-token-end js2-ts-cursor)
5840 ;; tell `parse-partial-sexp' to ignore this range of chars
5841 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5842
5843 (defun js2-get-first-xml-token ()
5844 (setq js2-ts-xml-open-tags-count 0
5845 js2-ts-is-xml-attribute nil
5846 js2-ts-xml-is-tag-content nil)
5847 (js2-unget-char)
5848 (js2-get-next-xml-token))
5849
5850 (defun js2-xml-discard-string ()
5851 "Throw away the string in progress and flag an XML parse error."
5852 (setq js2-ts-string-buffer nil
5853 js2-ts-string nil)
5854 (js2-report-scan-error "msg.XML.bad.form" t))
5855
5856 (defun js2-get-next-xml-token ()
5857 (setq js2-ts-string-buffer nil ; for recording the XML
5858 js2-token-beg js2-ts-cursor)
5859 (let (c result)
5860 (setq result
5861 (catch 'return
5862 (while t
5863 (setq c (js2-get-char))
5864 (cond
5865 ((= c js2-EOF_CHAR)
5866 (throw 'return js2-ERROR))
5867 (js2-ts-xml-is-tag-content
5868 (case c
5869 (?>
5870 (js2-add-to-string c)
5871 (setq js2-ts-xml-is-tag-content nil
5872 js2-ts-is-xml-attribute nil))
5873 (?/
5874 (js2-add-to-string c)
5875 (when (eq ?> (js2-peek-char))
5876 (setq c (js2-get-char))
5877 (js2-add-to-string c)
5878 (setq js2-ts-xml-is-tag-content nil)
5879 (decf js2-ts-xml-open-tags-count)))
5880 (?{
5881 (js2-unget-char)
5882 (setq js2-ts-string (js2-get-string-from-buffer))
5883 (throw 'return js2-XML))
5884 ((?\' ?\")
5885 (js2-add-to-string c)
5886 (unless (js2-read-quoted-string c)
5887 (throw 'return js2-ERROR)))
5888 (?=
5889 (js2-add-to-string c)
5890 (setq js2-ts-is-xml-attribute t))
5891 ((? ?\t ?\r ?\n)
5892 (js2-add-to-string c))
5893 (t
5894 (js2-add-to-string c)
5895 (setq js2-ts-is-xml-attribute nil)))
5896 (when (and (not js2-ts-xml-is-tag-content)
5897 (zerop js2-ts-xml-open-tags-count))
5898 (setq js2-ts-string (js2-get-string-from-buffer))
5899 (throw 'return js2-XMLEND)))
5900 (t
5901 ;; else not tag content
5902 (case c
5903 (?<
5904 (js2-add-to-string c)
5905 (setq c (js2-peek-char))
5906 (case c
5907 (?!
5908 (setq c (js2-get-char)) ;; skip !
5909 (js2-add-to-string c)
5910 (setq c (js2-peek-char))
5911 (case c
5912 (?-
5913 (setq c (js2-get-char)) ;; skip -
5914 (js2-add-to-string c)
5915 (if (eq c ?-)
5916 (progn
5917 (js2-add-to-string c)
5918 (unless (js2-read-xml-comment)
5919 (throw 'return js2-ERROR)))
5920 (js2-xml-discard-string)
5921 (throw 'return js2-ERROR)))
5922 (?\[
5923 (setq c (js2-get-char)) ;; skip [
5924 (js2-add-to-string c)
5925 (if (and (= (js2-get-char) ?C)
5926 (= (js2-get-char) ?D)
5927 (= (js2-get-char) ?A)
5928 (= (js2-get-char) ?T)
5929 (= (js2-get-char) ?A)
5930 (= (js2-get-char) ?\[))
5931 (progn
5932 (js2-add-to-string ?C)
5933 (js2-add-to-string ?D)
5934 (js2-add-to-string ?A)
5935 (js2-add-to-string ?T)
5936 (js2-add-to-string ?A)
5937 (js2-add-to-string ?\[)
5938 (unless (js2-read-cdata)
5939 (throw 'return js2-ERROR)))
5940 (js2-xml-discard-string)
5941 (throw 'return js2-ERROR)))
5942 (t
5943 (unless (js2-read-entity)
5944 (throw 'return js2-ERROR))))
5945 ;; Allow bare CDATA section, e.g.:
5946 ;; let xml = <![CDATA[ foo bar baz ]]>;
5947 (when (zerop js2-ts-xml-open-tags-count)
5948 (throw 'return js2-XMLEND)))
5949 (??
5950 (setq c (js2-get-char)) ;; skip ?
5951 (js2-add-to-string c)
5952 (unless (js2-read-PI)
5953 (throw 'return js2-ERROR)))
5954 (?/
5955 ;; end tag
5956 (setq c (js2-get-char)) ;; skip /
5957 (js2-add-to-string c)
5958 (when (zerop js2-ts-xml-open-tags-count)
5959 (js2-xml-discard-string)
5960 (throw 'return js2-ERROR))
5961 (setq js2-ts-xml-is-tag-content t)
5962 (decf js2-ts-xml-open-tags-count))
5963 (t
5964 ;; start tag
5965 (setq js2-ts-xml-is-tag-content t)
5966 (incf js2-ts-xml-open-tags-count))))
5967 (?{
5968 (js2-unget-char)
5969 (setq js2-ts-string (js2-get-string-from-buffer))
5970 (throw 'return js2-XML))
5971 (t
5972 (js2-add-to-string c))))))))
5973 (setq js2-token-end js2-ts-cursor)
5974 result))
5975
5976 (defun js2-read-quoted-string (quote)
5977 (let (c)
5978 (catch 'return
5979 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5980 (js2-add-to-string c)
5981 (if (eq c quote)
5982 (throw 'return t)))
5983 (js2-xml-discard-string) ;; throw away string in progress
5984 nil)))
5985
5986 (defun js2-read-xml-comment ()
5987 (let ((c (js2-get-char)))
5988 (catch 'return
5989 (while (/= c js2-EOF_CHAR)
5990 (catch 'continue
5991 (js2-add-to-string c)
5992 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5993 (setq c (js2-get-char))
5994 (js2-add-to-string c)
5995 (if (eq (js2-peek-char) ?>)
5996 (progn
5997 (setq c (js2-get-char)) ;; skip >
5998 (js2-add-to-string c)
5999 (throw 'return t))
6000 (throw 'continue nil)))
6001 (setq c (js2-get-char))))
6002 (js2-xml-discard-string)
6003 nil)))
6004
6005 (defun js2-read-cdata ()
6006 (let ((c (js2-get-char)))
6007 (catch 'return
6008 (while (/= c js2-EOF_CHAR)
6009 (catch 'continue
6010 (js2-add-to-string c)
6011 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6012 (setq c (js2-get-char))
6013 (js2-add-to-string c)
6014 (if (eq (js2-peek-char) ?>)
6015 (progn
6016 (setq c (js2-get-char)) ;; Skip >
6017 (js2-add-to-string c)
6018 (throw 'return t))
6019 (throw 'continue nil)))
6020 (setq c (js2-get-char))))
6021 (js2-xml-discard-string)
6022 nil)))
6023
6024 (defun js2-read-entity ()
6025 (let ((decl-tags 1)
6026 c)
6027 (catch 'return
6028 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6029 (js2-add-to-string c)
6030 (case c
6031 (?<
6032 (incf decl-tags))
6033 (?>
6034 (decf decl-tags)
6035 (if (zerop decl-tags)
6036 (throw 'return t)))))
6037 (js2-xml-discard-string)
6038 nil)))
6039
6040 (defun js2-read-PI ()
6041 "Scan an XML processing instruction."
6042 (let (c)
6043 (catch 'return
6044 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6045 (js2-add-to-string c)
6046 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6047 (setq c (js2-get-char)) ;; Skip >
6048 (js2-add-to-string c)
6049 (throw 'return t)))
6050 (js2-xml-discard-string)
6051 nil)))
6052
6053 (defun js2-scanner-get-line ()
6054 "Return the text of the current scan line."
6055 (buffer-substring (point-at-bol) (point-at-eol)))
6056
6057 ;;; Highlighting
6058
6059 (defun js2-set-face (beg end face &optional record)
6060 "Fontify a region. If RECORD is non-nil, record for later."
6061 (when (plusp js2-highlight-level)
6062 (setq beg (min (point-max) beg)
6063 beg (max (point-min) beg)
6064 end (min (point-max) end)
6065 end (max (point-min) end))
6066 (if record
6067 (push (list beg end face) js2-mode-fontifications)
6068 (put-text-property beg end 'font-lock-face face))))
6069
6070 (defun js2-set-kid-face (pos kid len face)
6071 "Set-face on a child node.
6072 POS is absolute buffer position of parent.
6073 KID is the child node.
6074 LEN is the length to fontify.
6075 FACE is the face to fontify with."
6076 (js2-set-face (+ pos (js2-node-pos kid))
6077 (+ pos (js2-node-pos kid) (js2-node-len kid))
6078 face))
6079
6080 (defsubst js2-fontify-kwd (start length)
6081 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6082
6083 (defsubst js2-clear-face (beg end)
6084 (remove-text-properties beg end '(font-lock-face nil
6085 help-echo nil
6086 point-entered nil
6087 c-in-sws nil)))
6088
6089 (defconst js2-ecma-global-props
6090 (concat "^"
6091 (regexp-opt
6092 '("Infinity" "NaN" "undefined" "arguments") t)
6093 "$")
6094 "Value properties of the Ecma-262 Global Object.
6095 Shown at or above `js2-highlight-level' 2.")
6096
6097 ;; might want to add the name "arguments" to this list?
6098 (defconst js2-ecma-object-props
6099 (concat "^"
6100 (regexp-opt
6101 '("prototype" "__proto__" "__parent__") t)
6102 "$")
6103 "Value properties of the Ecma-262 Object constructor.
6104 Shown at or above `js2-highlight-level' 2.")
6105
6106 (defconst js2-ecma-global-funcs
6107 (concat
6108 "^"
6109 (regexp-opt
6110 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6111 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6112 "$")
6113 "Function properties of the Ecma-262 Global object.
6114 Shown at or above `js2-highlight-level' 2.")
6115
6116 (defconst js2-ecma-number-props
6117 (concat "^"
6118 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6119 "NEGATIVE_INFINITY"
6120 "POSITIVE_INFINITY") t)
6121 "$")
6122 "Properties of the Ecma-262 Number constructor.
6123 Shown at or above `js2-highlight-level' 2.")
6124
6125 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6126 "Properties of the Ecma-262 Date constructor.
6127 Shown at or above `js2-highlight-level' 2.")
6128
6129 (defconst js2-ecma-math-props
6130 (concat "^"
6131 (regexp-opt
6132 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6133 t)
6134 "$")
6135 "Properties of the Ecma-262 Math object.
6136 Shown at or above `js2-highlight-level' 2.")
6137
6138 (defconst js2-ecma-math-funcs
6139 (concat "^"
6140 (regexp-opt
6141 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6142 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6143 "$")
6144 "Function properties of the Ecma-262 Math object.
6145 Shown at or above `js2-highlight-level' 2.")
6146
6147 (defconst js2-ecma-function-props
6148 (concat
6149 "^"
6150 (regexp-opt
6151 '(;; properties of the Object prototype object
6152 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6153 "toLocaleString" "toString" "valueOf"
6154 ;; properties of the Function prototype object
6155 "apply" "call"
6156 ;; properties of the Array prototype object
6157 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6158 "splice" "unshift"
6159 ;; properties of the String prototype object
6160 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6161 "localeCompare" "match" "replace" "search" "split" "substring"
6162 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6163 "toUpperCase"
6164 ;; properties of the Number prototype object
6165 "toExponential" "toFixed" "toPrecision"
6166 ;; properties of the Date prototype object
6167 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6168 "getMinutes" "getMonth" "getSeconds" "getTime"
6169 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6170 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6171 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6172 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6173 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6174 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6175 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6176 "toTimeString" "toUTCString"
6177 ;; properties of the RegExp prototype object
6178 "exec" "test"
6179 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6180 "toSource" "__defineGetter__" "__defineSetter__"
6181 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6182 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6183 t)
6184 "$")
6185 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6186 Shown at or above `js2-highlight-level' 3.")
6187
6188 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6189 (let ((target-name (and target
6190 (js2-name-node-p target)
6191 (js2-name-node-name target)))
6192 (prop-name (if prop (js2-name-node-name prop)))
6193 (level1 (>= js2-highlight-level 1))
6194 (level2 (>= js2-highlight-level 2))
6195 (level3 (>= js2-highlight-level 3))
6196 pos face)
6197 (when level2
6198 (if call-p
6199 (cond
6200 ((and target prop)
6201 (cond
6202 ((and level3 (string-match js2-ecma-function-props prop-name))
6203 (setq face 'font-lock-builtin-face))
6204 ((and target-name prop)
6205 (cond
6206 ((string= target-name "Date")
6207 (if (string-match js2-ecma-date-props prop-name)
6208 (setq face 'font-lock-builtin-face)))
6209 ((string= target-name "Math")
6210 (if (string-match js2-ecma-math-funcs prop-name)
6211 (setq face 'font-lock-builtin-face)))))))
6212 (prop
6213 (if (string-match js2-ecma-global-funcs prop-name)
6214 (setq face 'font-lock-builtin-face))))
6215 (cond
6216 ((and target prop)
6217 (cond
6218 ((string= target-name "Number")
6219 (if (string-match js2-ecma-number-props prop-name)
6220 (setq face 'font-lock-constant-face)))
6221 ((string= target-name "Math")
6222 (if (string-match js2-ecma-math-props prop-name)
6223 (setq face 'font-lock-constant-face)))))
6224 (prop
6225 (if (string-match js2-ecma-object-props prop-name)
6226 (setq face 'font-lock-constant-face)))))
6227 (when face
6228 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6229 (js2-node-pos prop))) ; relative
6230 (+ pos (js2-node-len prop))
6231 face)))))
6232
6233 (defun js2-parse-highlight-member-expr-node (node)
6234 "Perform syntax highlighting of EcmaScript built-in properties.
6235 The variable `js2-highlight-level' governs this highighting."
6236 (let (face target prop name pos end parent call-p callee)
6237 (cond
6238 ;; case 1: simple name, e.g. foo
6239 ((js2-name-node-p node)
6240 (setq name (js2-name-node-name node))
6241 ;; possible for name to be nil in rare cases - saw it when
6242 ;; running js2-mode on an elisp buffer. Might as well try to
6243 ;; make it so js2-mode never barfs.
6244 (when name
6245 (setq face (if (string-match js2-ecma-global-props name)
6246 'font-lock-constant-face))
6247 (when face
6248 (setq pos (js2-node-pos node)
6249 end (+ pos (js2-node-len node)))
6250 (js2-set-face pos end face))))
6251 ;; case 2: property access or function call
6252 ((or (js2-prop-get-node-p node)
6253 ;; highlight function call if expr is a prop-get node
6254 ;; or a plain name (i.e. unqualified function call)
6255 (and (setq call-p (js2-call-node-p node))
6256 (setq callee (js2-call-node-target node)) ; separate setq!
6257 (or (js2-prop-get-node-p callee)
6258 (js2-name-node-p callee))))
6259 (setq parent node
6260 node (if call-p callee node))
6261 (if (and call-p (js2-name-node-p callee))
6262 (setq prop callee)
6263 (setq target (js2-prop-get-node-left node)
6264 prop (js2-prop-get-node-right node)))
6265 (cond
6266 ((js2-name-node-p target)
6267 (if (js2-name-node-p prop)
6268 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6269 (js2-parse-highlight-prop-get parent target prop call-p)
6270 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6271 (js2-parse-highlight-prop-get parent target nil call-p)))
6272 ((js2-name-node-p prop)
6273 ;; case 2c: complex target, simple name, e.g. x[y].bar
6274 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6275
6276 (defun js2-parse-highlight-member-expr-fn-name (expr)
6277 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6278 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6279 We currently only handle the case where the last component is a prop-get
6280 of a simple name. Called before EXPR has a parent node."
6281 (let (pos
6282 (name (and (js2-prop-get-node-p expr)
6283 (js2-prop-get-node-right expr))))
6284 (when (js2-name-node-p name)
6285 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6286 (js2-node-pos name)))
6287 (+ pos (js2-node-len name))
6288 'font-lock-function-name-face
6289 'record))))
6290
6291 ;; source: http://jsdoc.sourceforge.net/
6292 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6293 ;; allows type specifications, and needs work before entering the wild.
6294
6295 (defconst js2-jsdoc-param-tag-regexp
6296 (concat "^\\s-*\\*+\\s-*\\(@"
6297 "\\(?:param\\|argument\\)"
6298 "\\)"
6299 "\\s-*\\({[^}]+}\\)?" ; optional type
6300 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6301 "\\>")
6302 "Matches jsdoc tags with optional type and optional param name.")
6303
6304 (defconst js2-jsdoc-typed-tag-regexp
6305 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6306 (regexp-opt
6307 '("enum"
6308 "extends"
6309 "field"
6310 "id"
6311 "implements"
6312 "lends"
6313 "mods"
6314 "requires"
6315 "return"
6316 "returns"
6317 "throw"
6318 "throws"))
6319 "\\)\\)\\s-*\\({[^}]+}\\)?")
6320 "Matches jsdoc tags with optional type.")
6321
6322 (defconst js2-jsdoc-arg-tag-regexp
6323 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6324 (regexp-opt
6325 '("alias"
6326 "augments"
6327 "borrows"
6328 "bug"
6329 "base"
6330 "config"
6331 "default"
6332 "define"
6333 "exception"
6334 "function"
6335 "member"
6336 "memberOf"
6337 "name"
6338 "namespace"
6339 "property"
6340 "since"
6341 "suppress"
6342 "this"
6343 "throws"
6344 "type"
6345 "version"))
6346 "\\)\\)\\s-+\\([^ \t]+\\)")
6347 "Matches jsdoc tags with a single argument.")
6348
6349 (defconst js2-jsdoc-empty-tag-regexp
6350 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6351 (regexp-opt
6352 '("addon"
6353 "author"
6354 "class"
6355 "const"
6356 "constant"
6357 "constructor"
6358 "constructs"
6359 "deprecated"
6360 "desc"
6361 "description"
6362 "event"
6363 "example"
6364 "exec"
6365 "export"
6366 "fileoverview"
6367 "final"
6368 "function"
6369 "hidden"
6370 "ignore"
6371 "implicitCast"
6372 "inheritDoc"
6373 "inner"
6374 "interface"
6375 "license"
6376 "noalias"
6377 "noshadow"
6378 "notypecheck"
6379 "override"
6380 "owner"
6381 "preserve"
6382 "preserveTry"
6383 "private"
6384 "protected"
6385 "public"
6386 "static"
6387 "supported"
6388 ))
6389 "\\)\\)\\s-*")
6390 "Matches empty jsdoc tags.")
6391
6392 (defconst js2-jsdoc-link-tag-regexp
6393 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6394 "Matches a jsdoc link or code tag.")
6395
6396 (defconst js2-jsdoc-see-tag-regexp
6397 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6398 "Matches a jsdoc @see tag.")
6399
6400 (defconst js2-jsdoc-html-tag-regexp
6401 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6402 "Matches a simple (no attributes) html start- or end-tag.")
6403
6404 (defun js2-jsdoc-highlight-helper ()
6405 (js2-set-face (match-beginning 1)
6406 (match-end 1)
6407 'js2-jsdoc-tag-face)
6408 (if (match-beginning 2)
6409 (if (save-excursion
6410 (goto-char (match-beginning 2))
6411 (= (char-after) ?{))
6412 (js2-set-face (1+ (match-beginning 2))
6413 (1- (match-end 2))
6414 'js2-jsdoc-type-face)
6415 (js2-set-face (match-beginning 2)
6416 (match-end 2)
6417 'js2-jsdoc-value-face)))
6418 (if (match-beginning 3)
6419 (js2-set-face (match-beginning 3)
6420 (match-end 3)
6421 'js2-jsdoc-value-face)))
6422
6423 (defun js2-highlight-jsdoc (ast)
6424 "Highlight doc comment tags."
6425 (let ((comments (js2-ast-root-comments ast))
6426 beg end)
6427 (save-excursion
6428 (dolist (node comments)
6429 (when (eq (js2-comment-node-format node) 'jsdoc)
6430 (setq beg (js2-node-abs-pos node)
6431 end (+ beg (js2-node-len node)))
6432 (save-restriction
6433 (narrow-to-region beg end)
6434 (dolist (re (list js2-jsdoc-param-tag-regexp
6435 js2-jsdoc-typed-tag-regexp
6436 js2-jsdoc-arg-tag-regexp
6437 js2-jsdoc-link-tag-regexp
6438 js2-jsdoc-see-tag-regexp
6439 js2-jsdoc-empty-tag-regexp))
6440 (goto-char beg)
6441 (while (re-search-forward re nil t)
6442 (js2-jsdoc-highlight-helper)))
6443 ;; simple highlighting for html tags
6444 (goto-char beg)
6445 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6446 (js2-set-face (match-beginning 1)
6447 (match-end 1)
6448 'js2-jsdoc-html-tag-delimiter-face)
6449 (js2-set-face (match-beginning 2)
6450 (match-end 2)
6451 'js2-jsdoc-html-tag-name-face)
6452 (js2-set-face (match-beginning 3)
6453 (match-end 3)
6454 'js2-jsdoc-html-tag-delimiter-face))))))))
6455
6456 (defun js2-highlight-assign-targets (node left right)
6457 "Highlight function properties and external variables."
6458 (let (leftpos end name)
6459 ;; highlight vars and props assigned function values
6460 (when (js2-function-node-p right)
6461 (cond
6462 ;; var foo = function() {...}
6463 ((js2-name-node-p left)
6464 (setq name left))
6465 ;; foo.bar.baz = function() {...}
6466 ((and (js2-prop-get-node-p left)
6467 (js2-name-node-p (js2-prop-get-node-right left)))
6468 (setq name (js2-prop-get-node-right left))))
6469 (when name
6470 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6471 (+ leftpos (js2-node-len name))
6472 'font-lock-function-name-face
6473 'record)))))
6474
6475 (defun js2-record-name-node (node)
6476 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6477 later. NODE must be a name node."
6478 (let (leftpos end)
6479 (push (list node js2-current-scope
6480 (setq leftpos (js2-node-abs-pos node))
6481 (setq end (+ leftpos (js2-node-len node))))
6482 js2-recorded-identifiers)))
6483
6484 (defun js2-highlight-undeclared-vars ()
6485 "After entire parse is finished, look for undeclared variable references.
6486 We have to wait until entire buffer is parsed, since JavaScript permits var
6487 decls to occur after they're used.
6488
6489 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6490 it is considered declared."
6491 (let (name)
6492 (dolist (entry js2-recorded-identifiers)
6493 (destructuring-bind (name-node scope pos end) entry
6494 (setq name (js2-name-node-name name-node))
6495 (unless (or (member name js2-global-externs)
6496 (member name js2-default-externs)
6497 (member name js2-additional-externs)
6498 (js2-get-defining-scope scope name))
6499 (js2-set-face pos end 'js2-external-variable-face 'record)
6500 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6501 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6502 (setq js2-recorded-identifiers nil)))
6503
6504 ;;; IMenu support
6505
6506 ;; We currently only support imenu, but eventually should support speedbar and
6507 ;; possibly other browsing mechanisms.
6508
6509 ;; The basic strategy is to identify function assignment targets of the form
6510 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6511 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6512 ;; for imenu after parsing is finished.
6513
6514 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6515 ;; JavaScript, and the general problem is undecidable. However, several forms
6516 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6517 ;; include:
6518
6519 ;; function foo() -- function declaration
6520 ;; foo = function() -- function expression assigned to variable
6521 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6522 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6523 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6524 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6525 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6526 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6527 ;; function foo() {function bar() {...}} -- nested function
6528 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6529
6530 ;; This list boils down to a few forms that can be combined recursively.
6531 ;; Top-level named function declarations include both the left-hand (name)
6532 ;; and the right-hand (function value) expressions needed to produce an imenu
6533 ;; entry. The other "right-hand" forms we need to look for are:
6534 ;; - functions declared as props/getters/setters in object literals
6535 ;; - nested named function declarations
6536 ;; The "left-hand" expressions that functions can be assigned to include:
6537 ;; - local/global variables
6538 ;; - nested property-get expressions like a.b.c.d
6539 ;; - element gets like foo[10] or foo['bar'] where the index
6540 ;; expression can be trivially converted to a property name. They
6541 ;; effectively then become property gets.
6542
6543 ;; All the different definition types are canonicalized into the form
6544 ;; foo.bar.baz = position-of-function-keyword
6545
6546 ;; We need to build a trie-like structure for imenu. As an example,
6547 ;; consider the following JavaScript code:
6548
6549 ;; a = function() {...} // function at position 5
6550 ;; b = function() {...} // function at position 25
6551 ;; foo = function() {...} // function at position 100
6552 ;; foo.bar = function() {...} // function at position 200
6553 ;; foo.bar.baz = function() {...} // function at position 300
6554 ;; foo.bar.zab = function() {...} // function at position 400
6555
6556 ;; During parsing we accumulate an entry for each definition in
6557 ;; the variable `js2-imenu-recorder', like so:
6558
6559 ;; '((fn a 5)
6560 ;; (fn b 25)
6561 ;; (fn foo 100)
6562 ;; (fn foo bar 200)
6563 ;; (fn foo bar baz 300)
6564 ;; (fn foo bar zab 400))
6565
6566 ;; Where 'fn' is the respective function node.
6567 ;; After parsing these entries are merged into this alist-trie:
6568
6569 ;; '((a . 1)
6570 ;; (b . 2)
6571 ;; (foo (<definition> . 3)
6572 ;; (bar (<definition> . 6)
6573 ;; (baz . 100)
6574 ;; (zab . 200))))
6575
6576 ;; Note the wacky need for a <definition> name. The token can be anything
6577 ;; that isn't a valid JavaScript identifier, because you might make foo
6578 ;; a function and then start setting properties on it that are also functions.
6579
6580 (defun js2-prop-node-name (node)
6581 "Return the name of a node that may be a property-get/property-name.
6582 If NODE is not a valid name-node, string-node or integral number-node,
6583 returns nil. Otherwise returns the string name/value of the node."
6584 (cond
6585 ((js2-name-node-p node)
6586 (js2-name-node-name node))
6587 ((js2-string-node-p node)
6588 (js2-string-node-value node))
6589 ((and (js2-number-node-p node)
6590 (string-match "^[0-9]+$" (js2-number-node-value node)))
6591 (js2-number-node-value node))
6592 ((js2-this-node-p node)
6593 "this")))
6594
6595 (defun js2-node-qname-component (node)
6596 "Return the name of this node, if it contributes to a qname.
6597 Returns nil if the node doesn't contribute."
6598 (copy-sequence
6599 (or (js2-prop-node-name node)
6600 (if (and (js2-function-node-p node)
6601 (js2-function-node-name node))
6602 (js2-name-node-name (js2-function-node-name node))))))
6603
6604 (defun js2-record-imenu-entry (fn-node qname pos)
6605 "Add an entry to `js2-imenu-recorder'.
6606 FN-NODE should be the current item's function node.
6607
6608 Associate FN-NODE with its QNAME for later lookup.
6609 This is used in postprocessing the chain list. For each chain, we find
6610 the parent function, look up its qname, then prepend a copy of it to the chain."
6611 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6612 (unless js2-imenu-function-map
6613 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6614 (puthash fn-node qname js2-imenu-function-map))
6615
6616 (defun js2-record-imenu-functions (node &optional var)
6617 "Record function definitions for imenu.
6618 NODE is a function node or an object literal.
6619 VAR, if non-nil, is the expression that NODE is being assigned to."
6620 (when js2-parse-ide-mode
6621 (let ((fun-p (js2-function-node-p node))
6622 qname left fname-node pos)
6623 (cond
6624 ;; non-anonymous function declaration?
6625 ((and fun-p
6626 (not var)
6627 (setq fname-node (js2-function-node-name node)))
6628 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6629 ;; for remaining forms, compute left-side tree branch first
6630 ((and var (setq qname (js2-compute-nested-prop-get var)))
6631 (cond
6632 ;; foo.bar.baz = function
6633 (fun-p
6634 (js2-record-imenu-entry node qname (js2-node-pos node)))
6635 ;; foo.bar.baz = object-literal
6636 ;; look for nested functions: {a: {b: function() {...} }}
6637 ((js2-object-node-p node)
6638 ;; Node position here is still absolute, since the parser
6639 ;; passes the assignment target and value expressions
6640 ;; to us before they are added as children of the assignment node.
6641 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6642
6643 (defun js2-compute-nested-prop-get (node)
6644 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6645 component nodes as a list. Otherwise return nil. Element-gets are treated
6646 as property-gets if the index expression is a string, or a positive integer."
6647 (let (left right head)
6648 (cond
6649 ((or (js2-name-node-p node)
6650 (js2-this-node-p node))
6651 (list node))
6652 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6653 ((js2-prop-get-node-p node) ; foo.bar
6654 (setq left (js2-prop-get-node-left node)
6655 right (js2-prop-get-node-right node))
6656 (if (setq head (js2-compute-nested-prop-get left))
6657 (nconc head (list right))))
6658 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6659 (setq left (js2-elem-get-node-target node)
6660 right (js2-elem-get-node-element node))
6661 (if (or (js2-string-node-p right) ; ['bar']
6662 (and (js2-number-node-p right) ; [10]
6663 (string-match "^[0-9]+$"
6664 (js2-number-node-value right))))
6665 (if (setq head (js2-compute-nested-prop-get left))
6666 (nconc head (list right))))))))
6667
6668 (defun js2-record-object-literal (node qname pos)
6669 "Recursively process an object literal looking for functions.
6670 NODE is an object literal that is the right-hand child of an assignment
6671 expression. QNAME is a list of nodes representing the assignment target,
6672 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6673 POS is the absolute position of the node.
6674 We do a depth-first traversal of NODE. For any functions we find,
6675 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6676 (let (left right prop-qname)
6677 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6678 (let ((left (js2-infix-node-left e))
6679 ;; Element positions are relative to the parent position.
6680 (pos (+ pos (js2-node-pos e))))
6681 (cond
6682 ;; foo: function() {...}
6683 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6684 (when (js2-prop-node-name left)
6685 ;; As a policy decision, we record the position of the property,
6686 ;; not the position of the `function' keyword, since the property
6687 ;; is effectively the name of the function.
6688 (js2-record-imenu-entry right (append qname (list left)) pos)))
6689 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6690 ((js2-object-node-p right)
6691 (js2-record-object-literal right
6692 (append qname (list (js2-infix-node-left e)))
6693 (+ pos (js2-node-pos right)))))))))
6694
6695 (defun js2-node-top-level-decl-p (node)
6696 "Return t if NODE's name is defined in the top-level scope.
6697 Also returns t if NODE's name is not defined in any scope, since it implies
6698 that it's an external variable, which must also be in the top-level scope."
6699 (let* ((name (js2-prop-node-name node))
6700 (this-scope (js2-node-get-enclosing-scope node))
6701 defining-scope)
6702 (cond
6703 ((js2-this-node-p node)
6704 nil)
6705 ((null this-scope)
6706 t)
6707 ((setq defining-scope (js2-get-defining-scope this-scope name))
6708 (js2-ast-root-p defining-scope))
6709 (t t))))
6710
6711 (defun js2-wrapper-function-p (node)
6712 "Returns t if NODE is a function expression that's immediately invoked.
6713 NODE must be `js2-function-node'."
6714 (let ((parent (js2-node-parent node)))
6715 (or
6716 ;; function(){...}();
6717 (js2-call-node-p parent)
6718 (and (js2-paren-node-p parent)
6719 ;; (function(){...})();
6720 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6721 ;; (function(){...}).call(this);
6722 (and (js2-prop-get-node-p parent)
6723 (member (js2-name-node-name (js2-prop-get-node-right parent))
6724 '("call" "apply"))
6725 (js2-call-node-p (js2-node-parent parent))))))))
6726
6727 (defun js2-browse-postprocess-chains (entries)
6728 "Modify function-declaration name chains after parsing finishes.
6729 Some of the information is only available after the parse tree is complete.
6730 For instance, processing a nested scope requires a parent function node."
6731 (let (result head fn current-fn parent-qname qname p elem)
6732 (dolist (entry entries)
6733 ;; function node goes first
6734 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6735 ;; examine its defining scope;
6736 ;; if top-level/external, keep as-is
6737 (if (js2-node-top-level-decl-p head)
6738 (push chain result)
6739 (when (js2-this-node-p head)
6740 (setq chain (cdr chain))) ; discard this-node
6741 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6742 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6743 (when (eq parent-qname 'not-found)
6744 ;; anonymous function expressions are not recorded
6745 ;; during the parse, so we need to handle this case here
6746 (setq parent-qname
6747 (if (js2-wrapper-function-p fn)
6748 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6749 (if (js2-ast-root-p grandparent)
6750 nil
6751 (gethash grandparent js2-imenu-function-map 'skip)))
6752 'skip))
6753 (puthash fn parent-qname js2-imenu-function-map))
6754 (unless (eq parent-qname 'skip)
6755 ;; prefix parent fn qname to this chain.
6756 (let ((qname (append parent-qname chain)))
6757 (puthash current-fn (butlast qname) js2-imenu-function-map)
6758 (push qname result)))))))
6759 ;; finally replace each node in each chain with its name.
6760 (dolist (chain result)
6761 (setq p chain)
6762 (while p
6763 (if (js2-node-p (setq elem (car p)))
6764 (setcar p (js2-node-qname-component elem)))
6765 (setq p (cdr p))))
6766 result))
6767
6768 ;; Merge name chains into a trie-like tree structure of nested lists.
6769 ;; To simplify construction of the trie, we first build it out using the rule
6770 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6771 ;; [key, num-or-list]. The second element can be a number; if so, this key
6772 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6773 ;; associated with the key at this level.) Otherwise the second element is
6774 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6775 ;; a simple recursive formulation.
6776 ;;
6777 ;; js2-mode is building the data structure for imenu. The imenu documentation
6778 ;; claims that it's the structure above, but in practice it wants the children
6779 ;; at the same list level as the key for that level, which is how I've drawn
6780 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6781 ;; list wrapper around the children at each level.
6782 ;;
6783 ;; A completed nested imenu-alist entry looks like this:
6784 ;; '(("foo"
6785 ;; ("<definition>" . 7)
6786 ;; ("bar"
6787 ;; ("a" . 40)
6788 ;; ("b" . 60))))
6789 ;;
6790 ;; In particular, the documentation for `imenu--index-alist' says that
6791 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6792 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6793
6794 (defun js2-treeify (lst)
6795 "Convert (a b c d) to (a ((b ((c d)))))."
6796 (if (null (cddr lst)) ; list length <= 2
6797 lst
6798 (list (car lst) (list (js2-treeify (cdr lst))))))
6799
6800 (defun js2-build-alist-trie (chains trie)
6801 "Merge declaration name chains into a trie-like alist structure for imenu.
6802 CHAINS is the qname chain list produced during parsing. TRIE is a
6803 list of elements built up so far."
6804 (let (head tail pos branch kids)
6805 (dolist (chain chains)
6806 (setq head (car chain)
6807 tail (cdr chain)
6808 pos (if (numberp (car tail)) (car tail))
6809 branch (js2-find-if (lambda (n)
6810 (string= (car n) head))
6811 trie)
6812 kids (second branch))
6813 (cond
6814 ;; case 1: this key isn't in the trie yet
6815 ((null branch)
6816 (if trie
6817 (setcdr (last trie) (list (js2-treeify chain)))
6818 (setq trie (list (js2-treeify chain)))))
6819 ;; case 2: key is present with a single number entry: replace w/ list
6820 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6821 ;; ("<definition>" 20)))
6822 ((numberp kids)
6823 (setcar (cdr branch)
6824 (list (list "<definition-1>" kids)
6825 (if pos
6826 (list "<definition-2>" pos)
6827 (js2-treeify tail)))))
6828 ;; case 3: key is there (with kids), and we're a number entry
6829 (pos
6830 (setcdr (last kids)
6831 (list
6832 (list (format "<definition-%d>"
6833 (1+ (loop for kid in kids
6834 count (eq ?< (aref (car kid) 0)))))
6835 pos))))
6836 ;; case 4: key is there with kids, need to merge in our chain
6837 (t
6838 (js2-build-alist-trie (list tail) kids))))
6839 trie))
6840
6841 (defun js2-flatten-trie (trie)
6842 "Convert TRIE to imenu-format.
6843 Recurses through nodes, and for each one whose second element is a list,
6844 appends the list's flattened elements to the current element. Also
6845 changes the tails into conses. For instance, this pre-flattened trie
6846
6847 '(a ((b 20)
6848 (c ((d 30)
6849 (e 40)))))
6850
6851 becomes
6852
6853 '(a (b . 20)
6854 (c (d . 30)
6855 (e . 40)))
6856
6857 Note that the root of the trie has no key, just a list of chains.
6858 This is also true for the value of any key with multiple children,
6859 e.g. key 'c' in the example above."
6860 (cond
6861 ((listp (car trie))
6862 (mapcar #'js2-flatten-trie trie))
6863 (t
6864 (if (numberp (second trie))
6865 (cons (car trie) (second trie))
6866 ;; else pop list and append its kids
6867 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6868
6869 (defun js2-build-imenu-index ()
6870 "Turn `js2-imenu-recorder' into an imenu data structure."
6871 (unless (eq js2-imenu-recorder 'empty)
6872 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6873 (result (js2-build-alist-trie chains nil)))
6874 (js2-flatten-trie result))))
6875
6876 (defun js2-test-print-chains (chains)
6877 "Print a list of qname chains.
6878 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6879 i.e. one or more nodes, and an integer position as the list tail."
6880 (mapconcat (lambda (chain)
6881 (concat "("
6882 (mapconcat (lambda (elem)
6883 (if (js2-node-p elem)
6884 (or (js2-node-qname-component elem)
6885 "nil")
6886 (number-to-string elem)))
6887 chain
6888 " ")
6889 ")"))
6890 chains
6891 "\n"))
6892
6893 ;;; Parser
6894
6895 (defconst js2-version "1.8.0"
6896 "Version of JavaScript supported, plus minor js2 version.")
6897
6898 (defmacro js2-record-face (face)
6899 "Record a style run of FACE for the current token."
6900 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6901
6902 (defsubst js2-node-end (n)
6903 "Computes the absolute end of node N.
6904 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6905 is only true until the node is added to its parent; i.e., while parsing."
6906 (+ (js2-node-pos n)
6907 (js2-node-len n)))
6908
6909 (defun js2-record-comment ()
6910 "Record a comment in `js2-scanned-comments'."
6911 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6912 :format js2-ts-comment-type)
6913 js2-scanned-comments)
6914 (when js2-parse-ide-mode
6915 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6916 'font-lock-doc-face
6917 'font-lock-comment-face))
6918 (when (memq js2-ts-comment-type '(html preprocessor))
6919 ;; Tell cc-engine the bounds of the comment.
6920 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6921
6922 ;; This function is called depressingly often, so it should be fast.
6923 ;; Most of the time it's looking at the same token it peeked before.
6924 (defun js2-peek-token ()
6925 "Return the next token without consuming it.
6926 If previous token was consumed, calls scanner to get new token.
6927 If previous token was -not- consumed, returns it (idempotent).
6928
6929 This function will not return a newline (js2-EOL) - instead, it
6930 gobbles newlines until it finds a non-newline token, and flags
6931 that token as appearing just after a newline.
6932
6933 This function will also not return a js2-COMMENT. Instead, it
6934 records comments found in `js2-scanned-comments'. If the token
6935 returned by this function immediately follows a jsdoc comment,
6936 the token is flagged as such.
6937
6938 Note that this function always returned the un-flagged token!
6939 The flags, if any, are saved in `js2-current-flagged-token'."
6940 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6941 js2-current-token ; most common case - return already-peeked token
6942 (let ((tt (js2-get-token)) ; call scanner
6943 saw-eol
6944 face)
6945 ;; process comments and whitespace
6946 (while (or (= tt js2-EOL)
6947 (= tt js2-COMMENT))
6948 (if (= tt js2-EOL)
6949 (setq saw-eol t)
6950 (setq saw-eol nil)
6951 (if js2-record-comments
6952 (js2-record-comment)))
6953 (setq tt (js2-get-token))) ; call scanner
6954 (setq js2-current-token tt
6955 js2-current-flagged-token (if saw-eol
6956 (logior tt js2-ti-after-eol)
6957 tt))
6958 ;; perform lexical fontification as soon as token is scanned
6959 (when js2-parse-ide-mode
6960 (cond
6961 ((minusp tt)
6962 (js2-record-face 'js2-error-face))
6963 ((setq face (aref js2-kwd-tokens tt))
6964 (js2-record-face face))
6965 ((and (= tt js2-NAME)
6966 (equal js2-ts-string "undefined"))
6967 (js2-record-face 'font-lock-constant-face))))
6968 tt))) ; return unflagged token
6969
6970 (defun js2-peek-flagged-token ()
6971 "Returns the current token along with any flags set for it."
6972 (js2-peek-token)
6973 js2-current-flagged-token)
6974
6975 (defsubst js2-consume-token ()
6976 (setq js2-current-flagged-token js2-EOF))
6977
6978 (defun js2-next-token ()
6979 (prog1
6980 (js2-peek-token)
6981 (js2-consume-token)))
6982
6983 (defun js2-next-flagged-token ()
6984 (js2-peek-token)
6985 (prog1 js2-current-flagged-token
6986 (js2-consume-token)))
6987
6988 (defun js2-match-token (match)
6989 "Consume and return t if next token matches MATCH, a bytecode.
6990 Returns nil and consumes nothing if MATCH is not the next token."
6991 (if (/= (js2-peek-token) match)
6992 nil
6993 (js2-consume-token)
6994 t))
6995
6996 (defun js2-valid-prop-name-token (tt)
6997 (or (= tt js2-NAME)
6998 (and js2-allow-keywords-as-property-names
6999 (plusp tt)
7000 (aref js2-kwd-tokens tt))))
7001
7002 (defun js2-match-prop-name ()
7003 "Consume token and return t if next token is a valid property name.
7004 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7005 is non-nil and it's a keyword token."
7006 (if (js2-valid-prop-name-token (js2-peek-token))
7007 (progn
7008 (js2-consume-token)
7009 t)
7010 nil))
7011
7012 (defun js2-must-match-prop-name (msg-id &optional pos len)
7013 (if (js2-match-prop-name)
7014 t
7015 (js2-report-error msg-id nil pos len)
7016 nil))
7017
7018 (defun js2-peek-token-or-eol ()
7019 "Return js2-EOL if the current token immediately follows a newline.
7020 Else returns the current token. Used in situations where we don't
7021 consider certain token types valid if they are preceded by a newline.
7022 One example is the postfix ++ or -- operator, which has to be on the
7023 same line as its operand."
7024 (let ((tt (js2-peek-token)))
7025 ;; Check for last peeked token flags
7026 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7027 js2-EOL
7028 tt)))
7029
7030 (defun js2-set-check-for-label ()
7031 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7032 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7033
7034 (defun js2-must-match (token msg-id &optional pos len)
7035 "Match next token to token code TOKEN, or record a syntax error.
7036 MSG-ID is the error message to report if the match fails.
7037 Returns t on match, nil if no match."
7038 (if (js2-match-token token)
7039 t
7040 (js2-report-error msg-id nil pos len)
7041 nil))
7042
7043 (defsubst js2-inside-function ()
7044 (plusp js2-nesting-of-function))
7045
7046 (defun js2-set-requires-activation ()
7047 (if (js2-function-node-p js2-current-script-or-fn)
7048 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7049
7050 (defun js2-check-activation-name (name token)
7051 (when (js2-inside-function)
7052 ;; skip language-version 1.2 check from Rhino
7053 (if (or (string= "arguments" name)
7054 (and js2-compiler-activation-names ; only used in codegen
7055 (gethash name js2-compiler-activation-names)))
7056 (js2-set-requires-activation))))
7057
7058 (defun js2-set-is-generator ()
7059 (if (js2-function-node-p js2-current-script-or-fn)
7060 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7061
7062 (defun js2-must-have-xml ()
7063 (unless js2-compiler-xml-available
7064 (js2-report-error "msg.XML.not.available")))
7065
7066 (defun js2-push-scope (scope)
7067 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7068 (assert (js2-scope-p scope))
7069 (assert (null (js2-scope-parent-scope scope)))
7070 (assert (not (eq js2-current-scope scope)))
7071 (setf (js2-scope-parent-scope scope) js2-current-scope
7072 js2-current-scope scope))
7073
7074 (defsubst js2-pop-scope ()
7075 (setq js2-current-scope
7076 (js2-scope-parent-scope js2-current-scope)))
7077
7078 (defun js2-enter-loop (loop-node)
7079 (push loop-node js2-loop-set)
7080 (push loop-node js2-loop-and-switch-set)
7081 (js2-push-scope loop-node)
7082 ;; Tell the current labeled statement (if any) its statement,
7083 ;; and set the jump target of the first label to the loop.
7084 ;; These are used in `js2-parse-continue' to verify that the
7085 ;; continue target is an actual labeled loop. (And for codegen.)
7086 (when js2-labeled-stmt
7087 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7088 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7089 js2-labeled-stmt))) loop-node)))
7090
7091 (defun js2-exit-loop ()
7092 (pop js2-loop-set)
7093 (pop js2-loop-and-switch-set)
7094 (js2-pop-scope))
7095
7096 (defsubst js2-enter-switch (switch-node)
7097 (push switch-node js2-loop-and-switch-set))
7098
7099 (defsubst js2-exit-switch ()
7100 (pop js2-loop-and-switch-set))
7101
7102 (defun js2-parse (&optional buf cb)
7103 "Tell the js2 parser to parse a region of JavaScript.
7104
7105 BUF is a buffer or buffer name containing the code to parse.
7106 Call `narrow-to-region' first to parse only part of the buffer.
7107
7108 The returned AST root node is given some additional properties:
7109 `node-count' - total number of nodes in the AST
7110 `buffer' - BUF. The buffer it refers to may change or be killed,
7111 so the value is not necessarily reliable.
7112
7113 An optional callback CB can be specified to report parsing
7114 progress. If `(functionp CB)' returns t, it will be called with
7115 the current line number once before parsing begins, then again
7116 each time the lexer reaches a new line number.
7117
7118 CB can also be a list of the form `(symbol cb ...)' to specify
7119 multiple callbacks with different criteria. Each symbol is a
7120 criterion keyword, and the following element is the callback to
7121 call
7122
7123 :line - called whenever the line number changes
7124 :token - called for each new token consumed
7125
7126 The list of criteria could be extended to include entering or
7127 leaving a statement, an expression, or a function definition."
7128 (if (and cb (not (functionp cb)))
7129 (error "criteria callbacks not yet implemented"))
7130 (let ((inhibit-point-motion-hooks t)
7131 (js2-compiler-xml-available (>= js2-language-version 160))
7132 ;; This is a recursive-descent parser, so give it a big stack.
7133 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7134 (max-specpdl-size (max max-specpdl-size 3000))
7135 (case-fold-search nil)
7136 ast)
7137 (message nil) ; clear any error message from previous parse
7138 (with-current-buffer (or buf (current-buffer))
7139 (setq js2-scanned-comments nil
7140 js2-parsed-errors nil
7141 js2-parsed-warnings nil
7142 js2-imenu-recorder nil
7143 js2-imenu-function-map nil
7144 js2-label-set nil)
7145 (js2-init-scanner)
7146 (setq ast (with-silent-modifications
7147 (js2-do-parse)))
7148 (unless js2-ts-hit-eof
7149 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7150 (setf (js2-ast-root-errors ast) js2-parsed-errors
7151 (js2-ast-root-warnings ast) js2-parsed-warnings)
7152 ;; if we didn't find any declarations, put a dummy in this list so we
7153 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7154 (unless js2-imenu-recorder
7155 (setq js2-imenu-recorder 'empty))
7156 (run-hooks 'js2-parse-finished-hook)
7157 ast)))
7158
7159 ;; Corresponds to Rhino's Parser.parse() method.
7160 (defun js2-do-parse ()
7161 "Parse current buffer starting from current point.
7162 Scanner should be initialized."
7163 (let ((pos js2-ts-cursor)
7164 (end js2-ts-cursor) ; in case file is empty
7165 root n tt)
7166 ;; initialize buffer-local parsing vars
7167 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7168 js2-current-script-or-fn root
7169 js2-current-scope root
7170 js2-current-flagged-token js2-EOF
7171 js2-nesting-of-function 0
7172 js2-labeled-stmt nil
7173 js2-recorded-identifiers nil) ; for js2-highlight
7174 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7175 (if (= tt js2-FUNCTION)
7176 (progn
7177 (js2-consume-token)
7178 (setq n (js2-parse-function (if js2-called-by-compile-function
7179 'FUNCTION_EXPRESSION
7180 'FUNCTION_STATEMENT))))
7181 ;; not a function - parse a statement
7182 (setq n (js2-parse-statement)))
7183 ;; add function or statement to script
7184 (setq end (js2-node-end n))
7185 (js2-block-node-push root n))
7186 ;; add comments to root in lexical order
7187 (when js2-scanned-comments
7188 ;; if we find a comment beyond end of normal kids, use its end
7189 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7190 (dolist (comment js2-scanned-comments)
7191 (push comment (js2-ast-root-comments root))
7192 (js2-node-add-children root comment)))
7193 (setf (js2-node-len root) (- end pos))
7194 ;; Give extensions a chance to muck with things before highlighting starts.
7195 (let ((js2-additional-externs js2-additional-externs))
7196 (dolist (callback js2-post-parse-callbacks)
7197 (funcall callback))
7198 (js2-highlight-undeclared-vars))
7199 root))
7200
7201 (defun js2-function-parser ()
7202 (js2-consume-token)
7203 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7204
7205 (defun js2-parse-function-closure-body (fn-node)
7206 "Parse a JavaScript 1.8 function closure body."
7207 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7208 (if js2-ts-hit-eof
7209 (js2-report-error "msg.no.brace.body" nil
7210 (js2-node-pos fn-node)
7211 (- js2-ts-cursor (js2-node-pos fn-node)))
7212 (js2-node-add-children fn-node
7213 (setf (js2-function-node-body fn-node)
7214 (js2-parse-expr t))))))
7215
7216 (defun js2-parse-function-body (fn-node)
7217 (js2-must-match js2-LC "msg.no.brace.body"
7218 (js2-node-pos fn-node)
7219 (- js2-ts-cursor (js2-node-pos fn-node)))
7220 (let ((pos js2-token-beg) ; LC position
7221 (pn (make-js2-block-node)) ; starts at LC position
7222 tt
7223 end)
7224 (incf js2-nesting-of-function)
7225 (unwind-protect
7226 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7227 (= tt js2-EOF)
7228 (= tt js2-RC)))
7229 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7230 (js2-parse-statement)
7231 (js2-consume-token)
7232 (js2-parse-function 'FUNCTION_STATEMENT))))
7233 (decf js2-nesting-of-function))
7234 (setq end js2-token-end) ; assume no curly and leave at current token
7235 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7236 (setq end js2-token-end))
7237 (setf (js2-node-pos pn) pos
7238 (js2-node-len pn) (- end pos))
7239 (setf (js2-function-node-body fn-node) pn)
7240 (js2-node-add-children fn-node pn)
7241 pn))
7242
7243 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7244 "Declare and fontify destructuring parameters inside NODE.
7245 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7246 (cond
7247 ((js2-name-node-p node)
7248 (let (leftpos)
7249 (js2-define-symbol decl-type (js2-name-node-name node)
7250 node ignore-not-in-block)
7251 (when face
7252 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7253 (+ leftpos (js2-node-len node))
7254 face 'record))))
7255 ((js2-object-node-p node)
7256 (dolist (elem (js2-object-node-elems node))
7257 (js2-define-destruct-symbols
7258 (if (js2-object-prop-node-p elem)
7259 (js2-object-prop-node-right elem)
7260 ;; abbreviated destructuring {a, b}
7261 elem)
7262 decl-type face ignore-not-in-block)))
7263 ((js2-array-node-p node)
7264 (dolist (elem (js2-array-node-elems node))
7265 (when elem
7266 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7267 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7268 (js2-node-len node)))))
7269
7270 (defun js2-parse-function-params (fn-node pos)
7271 (if (js2-match-token js2-RP)
7272 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7273 (let (params len param)
7274 (loop for tt = (js2-peek-token)
7275 do
7276 (cond
7277 ;; destructuring param
7278 ((or (= tt js2-LB) (= tt js2-LC))
7279 (setq param (js2-parse-primary-expr-lhs))
7280 (js2-define-destruct-symbols param
7281 js2-LP
7282 'js2-function-param-face)
7283 (push param params))
7284 ;; simple name
7285 (t
7286 (js2-must-match js2-NAME "msg.no.parm")
7287 (js2-record-face 'js2-function-param-face)
7288 (setq param (js2-create-name-node))
7289 (js2-define-symbol js2-LP js2-ts-string param)
7290 (push param params)))
7291 while
7292 (js2-match-token js2-COMMA))
7293 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7294 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7295 (dolist (p params)
7296 (js2-node-add-children fn-node p)
7297 (push p (js2-function-node-params fn-node))))))
7298
7299 (defun js2-check-inconsistent-return-warning (fn-node name)
7300 "Possibly show inconsistent-return warning.
7301 Last token scanned is the close-curly for the function body."
7302 (when (and js2-mode-show-strict-warnings
7303 js2-strict-inconsistent-return-warning
7304 (not (js2-has-consistent-return-usage
7305 (js2-function-node-body fn-node))))
7306 ;; Have it extend from close-curly to bol or beginning of block.
7307 (let ((pos (save-excursion
7308 (goto-char js2-token-end)
7309 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7310 (point-at-bol))))
7311 (end js2-token-end))
7312 (if (plusp (js2-name-node-length name))
7313 (js2-add-strict-warning "msg.no.return.value"
7314 (js2-name-node-name name) pos end)
7315 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7316
7317 (defun js2-parse-function (function-type)
7318 "Function parser. FUNCTION-TYPE is a symbol."
7319 (let ((pos js2-token-beg) ; start of 'function' keyword
7320 name name-beg name-end fn-node lp
7321 (synthetic-type function-type)
7322 member-expr-node)
7323 ;; parse function name, expression, or non-name (anonymous)
7324 (cond
7325 ;; function foo(...)
7326 ((js2-match-token js2-NAME)
7327 (setq name (js2-create-name-node t)
7328 name-beg js2-token-beg
7329 name-end js2-token-end)
7330 (unless (js2-match-token js2-LP)
7331 (when js2-allow-member-expr-as-function-name
7332 ;; function foo.bar(...)
7333 (setq member-expr-node name
7334 name nil
7335 member-expr-node (js2-parse-member-expr-tail
7336 nil member-expr-node)))
7337 (js2-must-match js2-LP "msg.no.paren.parms")))
7338 ((js2-match-token js2-LP)
7339 nil) ; anonymous function: leave name as null
7340 (t
7341 ;; function random-member-expr(...)
7342 (when js2-allow-member-expr-as-function-name
7343 ;; Note that memberExpr can not start with '(' like
7344 ;; in function (1+2).toString(), because 'function (' already
7345 ;; processed as anonymous function
7346 (setq member-expr-node (js2-parse-member-expr)))
7347 (js2-must-match js2-LP "msg.no.paren.parms")))
7348 (if (= js2-current-token js2-LP) ; eventually matched LP?
7349 (setq lp js2-token-beg))
7350 (if member-expr-node
7351 (progn
7352 (setq synthetic-type 'FUNCTION_EXPRESSION)
7353 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7354 (if name
7355 (js2-set-face name-beg name-end
7356 'font-lock-function-name-face 'record)))
7357 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7358 (plusp (js2-name-node-length name)))
7359 ;; Function statements define a symbol in the enclosing scope
7360 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7361 (setf fn-node (make-js2-function-node :pos pos
7362 :name name
7363 :form function-type
7364 :lp (if lp (- lp pos))))
7365 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7366 ;; 1. Nested functions are not affected by the dynamic scope flag
7367 ;; as dynamic scope is already a parent of their scope.
7368 ;; 2. Functions defined under the with statement also immune to
7369 ;; this setup, in which case dynamic scope is ignored in favor
7370 ;; of the with object.
7371 (setf (js2-function-node-ignore-dynamic fn-node) t))
7372 ;; dynamically bind all the per-function variables
7373 (let ((js2-current-script-or-fn fn-node)
7374 (js2-current-scope fn-node)
7375 (js2-nesting-of-with 0)
7376 (js2-end-flags 0)
7377 js2-label-set
7378 js2-loop-set
7379 js2-loop-and-switch-set)
7380 (js2-parse-function-params fn-node pos)
7381 (if (and (>= js2-language-version 180)
7382 (/= (js2-peek-token) js2-LC))
7383 (js2-parse-function-closure-body fn-node)
7384 (js2-parse-function-body fn-node))
7385 (if name
7386 (js2-node-add-children fn-node name))
7387 (js2-check-inconsistent-return-warning fn-node name)
7388 ;; Function expressions define a name only in the body of the
7389 ;; function, and only if not hidden by a parameter name
7390 (if (and name
7391 (eq synthetic-type 'FUNCTION_EXPRESSION)
7392 (null (js2-scope-get-symbol js2-current-scope
7393 (js2-name-node-name name))))
7394 (js2-define-symbol js2-FUNCTION
7395 (js2-name-node-name name)
7396 fn-node))
7397 (if (and name
7398 (not (eq function-type 'FUNCTION_EXPRESSION)))
7399 (js2-record-imenu-functions fn-node)))
7400 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7401 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7402 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7403 ;; We wait until after parsing the function to set its parent scope,
7404 ;; since `js2-define-symbol' needs the defining-scope check to stop
7405 ;; at the function boundary when checking for redeclarations.
7406 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7407 fn-node))
7408
7409 (defun js2-parse-statements (&optional parent)
7410 "Parse a statement list. Last token consumed must be js2-LC.
7411
7412 PARENT can be a `js2-block-node', in which case the statements are
7413 appended to PARENT. Otherwise a new `js2-block-node' is created
7414 and returned.
7415
7416 This function does not match the closing js2-RC: the caller
7417 matches the RC so it can provide a suitable error message if not
7418 matched. This means it's up to the caller to set the length of
7419 the node to include the closing RC. The node start pos is set to
7420 the absolute buffer start position, and the caller should fix it
7421 up to be relative to the parent node. All children of this block
7422 node are given relative start positions and correct lengths."
7423 (let ((pn (or parent (make-js2-block-node)))
7424 tt)
7425 (setf (js2-node-pos pn) js2-token-beg)
7426 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7427 (/= tt js2-RC))
7428 (js2-block-node-push pn (js2-parse-statement)))
7429 pn))
7430
7431 (defun js2-parse-statement ()
7432 (let (tt pn beg end)
7433 ;; coarse-grained user-interrupt check - needs work
7434 (and js2-parse-interruptable-p
7435 (zerop (% (incf js2-parse-stmt-count)
7436 js2-statements-per-pause))
7437 (input-pending-p)
7438 (throw 'interrupted t))
7439 (setq pn (js2-statement-helper))
7440 ;; no-side-effects warning check
7441 (unless (js2-node-has-side-effects pn)
7442 (setq end (js2-node-end pn))
7443 (save-excursion
7444 (goto-char end)
7445 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7446 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7447 pn))
7448
7449 ;; These correspond to the switch cases in Parser.statementHelper
7450 (defconst js2-parsers
7451 (let ((parsers (make-vector js2-num-tokens
7452 #'js2-parse-expr-stmt)))
7453 (aset parsers js2-BREAK #'js2-parse-break)
7454 (aset parsers js2-CONST #'js2-parse-const-var)
7455 (aset parsers js2-CONTINUE #'js2-parse-continue)
7456 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7457 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7458 (aset parsers js2-DO #'js2-parse-do)
7459 (aset parsers js2-FOR #'js2-parse-for)
7460 (aset parsers js2-FUNCTION #'js2-function-parser)
7461 (aset parsers js2-IF #'js2-parse-if)
7462 (aset parsers js2-LC #'js2-parse-block)
7463 (aset parsers js2-LET #'js2-parse-let-stmt)
7464 (aset parsers js2-NAME #'js2-parse-name-or-label)
7465 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7466 (aset parsers js2-SEMI #'js2-parse-semi)
7467 (aset parsers js2-SWITCH #'js2-parse-switch)
7468 (aset parsers js2-THROW #'js2-parse-throw)
7469 (aset parsers js2-TRY #'js2-parse-try)
7470 (aset parsers js2-VAR #'js2-parse-const-var)
7471 (aset parsers js2-WHILE #'js2-parse-while)
7472 (aset parsers js2-WITH #'js2-parse-with)
7473 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7474 parsers)
7475 "A vector mapping token types to parser functions.")
7476
7477 (defun js2-parse-warn-missing-semi (beg end)
7478 (and js2-mode-show-strict-warnings
7479 js2-strict-missing-semi-warning
7480 (js2-add-strict-warning
7481 "msg.missing.semi" nil
7482 ;; back up to beginning of statement or line
7483 (max beg (save-excursion
7484 (goto-char end)
7485 (point-at-bol)))
7486 end)))
7487
7488 (defconst js2-no-semi-insertion
7489 (list js2-IF
7490 js2-SWITCH
7491 js2-WHILE
7492 js2-DO
7493 js2-FOR
7494 js2-TRY
7495 js2-WITH
7496 js2-LC
7497 js2-ERROR
7498 js2-SEMI
7499 js2-FUNCTION)
7500 "List of tokens that don't do automatic semicolon insertion.")
7501
7502 (defconst js2-autoinsert-semi-and-warn
7503 (list js2-ERROR js2-EOF js2-RC))
7504
7505 (defun js2-statement-helper ()
7506 (let* ((tt (js2-peek-token))
7507 (first-tt tt)
7508 (beg js2-token-beg)
7509 (parser (if (= tt js2-ERROR)
7510 #'js2-parse-semi
7511 (aref js2-parsers tt)))
7512 pn
7513 tt-flagged)
7514 ;; If the statement is set, then it's been told its label by now.
7515 (and js2-labeled-stmt
7516 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7517 (setq js2-labeled-stmt nil))
7518 (setq pn (funcall parser))
7519 ;; Don't do auto semi insertion for certain statement types.
7520 (unless (or (memq first-tt js2-no-semi-insertion)
7521 (js2-labeled-stmt-node-p pn))
7522 (js2-auto-insert-semicolon pn))
7523 pn))
7524
7525 (defun js2-auto-insert-semicolon (pn)
7526 (let* ((tt-flagged (js2-peek-flagged-token))
7527 (tt (logand tt-flagged js2-clear-ti-mask))
7528 (pos (js2-node-pos pn)))
7529 (cond
7530 ((= tt js2-SEMI)
7531 ;; Consume ';' as a part of expression
7532 (js2-consume-token)
7533 ;; extend the node bounds to include the semicolon.
7534 (setf (js2-node-len pn) (- js2-token-end pos)))
7535 ((memq tt js2-autoinsert-semi-and-warn)
7536 ;; Autoinsert ;
7537 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7538 (t
7539 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7540 ;; Report error if no EOL or autoinsert ';' otherwise
7541 (js2-report-error "msg.no.semi.stmt")
7542 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7543
7544 (defun js2-parse-condition ()
7545 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7546 The parens are discarded and the expression node is returned.
7547 The `pos' field of the return value is set to an absolute position
7548 that must be fixed up by the caller.
7549 Return value is a list (EXPR LP RP), with absolute paren positions."
7550 (let (pn lp rp)
7551 (if (js2-must-match js2-LP "msg.no.paren.cond")
7552 (setq lp js2-token-beg))
7553 (setq pn (js2-parse-expr))
7554 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7555 (setq rp js2-token-beg))
7556 ;; Report strict warning on code like "if (a = 7) ..."
7557 (if (and js2-strict-cond-assign-warning
7558 (js2-assign-node-p pn))
7559 (js2-add-strict-warning "msg.equal.as.assign" nil
7560 (js2-node-pos pn)
7561 (+ (js2-node-pos pn)
7562 (js2-node-len pn))))
7563 (list pn lp rp)))
7564
7565 (defun js2-parse-if ()
7566 "Parser for if-statement. Last matched token must be js2-IF."
7567 (let ((pos js2-token-beg)
7568 cond if-true if-false else-pos end pn)
7569 (js2-consume-token)
7570 (setq cond (js2-parse-condition)
7571 if-true (js2-parse-statement)
7572 if-false (if (js2-match-token js2-ELSE)
7573 (progn
7574 (setq else-pos (- js2-token-beg pos))
7575 (js2-parse-statement)))
7576 end (js2-node-end (or if-false if-true))
7577 pn (make-js2-if-node :pos pos
7578 :len (- end pos)
7579 :condition (car cond)
7580 :then-part if-true
7581 :else-part if-false
7582 :else-pos else-pos
7583 :lp (js2-relpos (second cond) pos)
7584 :rp (js2-relpos (third cond) pos)))
7585 (js2-node-add-children pn (car cond) if-true if-false)
7586 pn))
7587
7588 (defun js2-parse-switch ()
7589 "Parser for if-statement. Last matched token must be js2-SWITCH."
7590 (let ((pos js2-token-beg)
7591 tt pn discriminant has-default case-expr case-node
7592 case-pos cases stmt lp rp)
7593 (js2-consume-token)
7594 (if (js2-must-match js2-LP "msg.no.paren.switch")
7595 (setq lp js2-token-beg))
7596 (setq discriminant (js2-parse-expr)
7597 pn (make-js2-switch-node :discriminant discriminant
7598 :pos pos
7599 :lp (js2-relpos lp pos)))
7600 (js2-node-add-children pn discriminant)
7601 (js2-enter-switch pn)
7602 (unwind-protect
7603 (progn
7604 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7605 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7606 (js2-must-match js2-LC "msg.no.brace.switch")
7607 (catch 'break
7608 (while t
7609 (setq tt (js2-next-token)
7610 case-pos js2-token-beg)
7611 (cond
7612 ((= tt js2-RC)
7613 (setf (js2-node-len pn) (- js2-token-end pos))
7614 (throw 'break nil)) ; done
7615 ((= tt js2-CASE)
7616 (setq case-expr (js2-parse-expr))
7617 (js2-must-match js2-COLON "msg.no.colon.case"))
7618 ((= tt js2-DEFAULT)
7619 (if has-default
7620 (js2-report-error "msg.double.switch.default"))
7621 (setq has-default t
7622 case-expr nil)
7623 (js2-must-match js2-COLON "msg.no.colon.case"))
7624 (t
7625 (js2-report-error "msg.bad.switch")
7626 (throw 'break nil)))
7627 (setq case-node (make-js2-case-node :pos case-pos
7628 :len (- js2-token-end case-pos)
7629 :expr case-expr))
7630 (js2-node-add-children case-node case-expr)
7631 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7632 (/= tt js2-CASE)
7633 (/= tt js2-DEFAULT)
7634 (/= tt js2-EOF))
7635 (setf stmt (js2-parse-statement)
7636 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7637 (js2-block-node-push case-node stmt))
7638 (push case-node cases)))
7639 ;; add cases last, as pushing reverses the order to be correct
7640 (dolist (kid cases)
7641 (js2-node-add-children pn kid)
7642 (push kid (js2-switch-node-cases pn)))
7643 pn) ; return value
7644 (js2-exit-switch))))
7645
7646 (defun js2-parse-while ()
7647 "Parser for while-statement. Last matched token must be js2-WHILE."
7648 (let ((pos js2-token-beg)
7649 (pn (make-js2-while-node))
7650 cond body)
7651 (js2-consume-token)
7652 (js2-enter-loop pn)
7653 (unwind-protect
7654 (progn
7655 (setf cond (js2-parse-condition)
7656 (js2-while-node-condition pn) (car cond)
7657 body (js2-parse-statement)
7658 (js2-while-node-body pn) body
7659 (js2-node-len pn) (- (js2-node-end body) pos)
7660 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7661 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7662 (js2-node-add-children pn body (car cond)))
7663 (js2-exit-loop))
7664 pn))
7665
7666 (defun js2-parse-do ()
7667 "Parser for do-statement. Last matched token must be js2-DO."
7668 (let ((pos js2-token-beg)
7669 (pn (make-js2-do-node))
7670 cond body end)
7671 (js2-consume-token)
7672 (js2-enter-loop pn)
7673 (unwind-protect
7674 (progn
7675 (setq body (js2-parse-statement))
7676 (js2-must-match js2-WHILE "msg.no.while.do")
7677 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7678 cond (js2-parse-condition)
7679 (js2-do-node-condition pn) (car cond)
7680 (js2-do-node-body pn) body
7681 end js2-ts-cursor
7682 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7683 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7684 (js2-node-add-children pn (car cond) body))
7685 (js2-exit-loop))
7686 ;; Always auto-insert semicolon to follow SpiderMonkey:
7687 ;; It is required by ECMAScript but is ignored by the rest of
7688 ;; world; see bug 238945
7689 (if (js2-match-token js2-SEMI)
7690 (setq end js2-ts-cursor))
7691 (setf (js2-node-len pn) (- end pos))
7692 pn))
7693
7694 (defun js2-parse-for ()
7695 "Parser for for-statement. Last matched token must be js2-FOR.
7696 Parses for, for-in, and for each-in statements."
7697 (let ((for-pos js2-token-beg)
7698 pn is-for-each is-for-in in-pos each-pos tmp-pos
7699 init ; Node init is also foo in 'foo in object'
7700 cond ; Node cond is also object in 'foo in object'
7701 incr ; 3rd section of for-loop initializer
7702 body tt lp rp)
7703 (js2-consume-token)
7704 ;; See if this is a for each () instead of just a for ()
7705 (when (js2-match-token js2-NAME)
7706 (if (string= "each" js2-ts-string)
7707 (progn
7708 (setq is-for-each t
7709 each-pos (- js2-token-beg for-pos)) ; relative
7710 (js2-record-face 'font-lock-keyword-face))
7711 (js2-report-error "msg.no.paren.for")))
7712 (if (js2-must-match js2-LP "msg.no.paren.for")
7713 (setq lp (- js2-token-beg for-pos)))
7714 (setq tt (js2-peek-token))
7715 ;; 'for' makes local scope
7716 (js2-push-scope (make-js2-scope))
7717 (unwind-protect
7718 ;; parse init clause
7719 (let ((js2-in-for-init t)) ; set as dynamic variable
7720 (cond
7721 ((= tt js2-SEMI)
7722 (setq init (make-js2-empty-expr-node)))
7723 ((or (= tt js2-VAR) (= tt js2-LET))
7724 (js2-consume-token)
7725 (setq init (js2-parse-variables tt js2-token-beg)))
7726 (t
7727 (setq init (js2-parse-expr)))))
7728 (if (js2-match-token js2-IN)
7729 (setq is-for-in t
7730 in-pos (- js2-token-beg for-pos)
7731 ;; scope of iteration target object is not the scope we've created above.
7732 ;; stash current scope temporary.
7733 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7734 (js2-parse-expr))) ; object over which we're iterating
7735 ;; else ordinary for loop - parse cond and incr
7736 (js2-must-match js2-SEMI "msg.no.semi.for")
7737 (setq cond (if (= (js2-peek-token) js2-SEMI)
7738 (make-js2-empty-expr-node) ; no loop condition
7739 (js2-parse-expr)))
7740 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7741 (setq tmp-pos js2-token-end
7742 incr (if (= (js2-peek-token) js2-RP)
7743 (make-js2-empty-expr-node :pos tmp-pos)
7744 (js2-parse-expr))))
7745 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7746 (setq rp (- js2-token-beg for-pos)))
7747 (if (not is-for-in)
7748 (setq pn (make-js2-for-node :init init
7749 :condition cond
7750 :update incr
7751 :lp lp
7752 :rp rp))
7753 ;; cond could be null if 'in obj' got eaten by the init node.
7754 (if (js2-infix-node-p init)
7755 ;; it was (foo in bar) instead of (var foo in bar)
7756 (setq cond (js2-infix-node-right init)
7757 init (js2-infix-node-left init))
7758 (if (and (js2-var-decl-node-p init)
7759 (> (length (js2-var-decl-node-kids init)) 1))
7760 (js2-report-error "msg.mult.index")))
7761 (setq pn (make-js2-for-in-node :iterator init
7762 :object cond
7763 :in-pos in-pos
7764 :foreach-p is-for-each
7765 :each-pos each-pos
7766 :lp lp
7767 :rp rp)))
7768 (unwind-protect
7769 (progn
7770 (js2-enter-loop pn)
7771 ;; We have to parse the body -after- creating the loop node,
7772 ;; so that the loop node appears in the js2-loop-set, allowing
7773 ;; break/continue statements to find the enclosing loop.
7774 (setf body (js2-parse-statement)
7775 (js2-loop-node-body pn) body
7776 (js2-node-pos pn) for-pos
7777 (js2-node-len pn) (- (js2-node-end body) for-pos))
7778 (js2-node-add-children pn init cond incr body))
7779 ;; finally
7780 (js2-exit-loop))
7781 (js2-pop-scope))
7782 pn))
7783
7784 (defun js2-parse-try ()
7785 "Parser for try-statement. Last matched token must be js2-TRY."
7786 (let ((try-pos js2-token-beg)
7787 try-end
7788 try-block
7789 catch-blocks
7790 finally-block
7791 saw-default-catch
7792 peek
7793 param
7794 catch-cond
7795 catch-node
7796 guard-kwd
7797 catch-pos
7798 finally-pos
7799 pn
7800 block
7801 lp
7802 rp)
7803 (js2-consume-token)
7804 (if (/= (js2-peek-token) js2-LC)
7805 (js2-report-error "msg.no.brace.try"))
7806 (setq try-block (js2-parse-statement)
7807 try-end (js2-node-end try-block)
7808 peek (js2-peek-token))
7809 (cond
7810 ((= peek js2-CATCH)
7811 (while (js2-match-token js2-CATCH)
7812 (setq catch-pos js2-token-beg
7813 guard-kwd nil
7814 catch-cond nil
7815 lp nil
7816 rp nil)
7817 (if saw-default-catch
7818 (js2-report-error "msg.catch.unreachable"))
7819 (if (js2-must-match js2-LP "msg.no.paren.catch")
7820 (setq lp (- js2-token-beg catch-pos)))
7821 (js2-push-scope (make-js2-scope))
7822 (let ((tt (js2-peek-token)))
7823 (cond
7824 ;; destructuring pattern
7825 ;; catch ({ message, file }) { ... }
7826 ((or (= tt js2-LB) (= tt js2-LC))
7827 (setq param
7828 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
7829 js2-LET nil)))
7830 ;; simple name
7831 (t
7832 (js2-must-match js2-NAME "msg.bad.catchcond")
7833 (setq param (js2-create-name-node))
7834 (js2-define-symbol js2-LET js2-ts-string param))))
7835 ;; pattern guard
7836 (if (js2-match-token js2-IF)
7837 (setq guard-kwd (- js2-token-beg catch-pos)
7838 catch-cond (js2-parse-expr))
7839 (setq saw-default-catch t))
7840 (if (js2-must-match js2-RP "msg.bad.catchcond")
7841 (setq rp (- js2-token-beg catch-pos)))
7842 (js2-must-match js2-LC "msg.no.brace.catchblock")
7843 (setq block (js2-parse-statements)
7844 try-end (js2-node-end block)
7845 catch-node (make-js2-catch-node :pos catch-pos
7846 :param param
7847 :guard-expr catch-cond
7848 :guard-kwd guard-kwd
7849 :block block
7850 :lp lp
7851 :rp rp))
7852 (js2-pop-scope)
7853 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7854 (setq try-end js2-token-beg))
7855 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7856 (js2-node-len catch-node) (- try-end catch-pos))
7857 (js2-node-add-children catch-node param catch-cond block)
7858 (push catch-node catch-blocks)))
7859 ((/= peek js2-FINALLY)
7860 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7861 (js2-node-pos try-block)
7862 (- (setq try-end (js2-node-end try-block))
7863 (js2-node-pos try-block)))))
7864 (when (js2-match-token js2-FINALLY)
7865 (setq finally-pos js2-token-beg
7866 block (js2-parse-statement)
7867 try-end (js2-node-end block)
7868 finally-block (make-js2-finally-node :pos finally-pos
7869 :len (- try-end finally-pos)
7870 :body block))
7871 (js2-node-add-children finally-block block))
7872 (setq pn (make-js2-try-node :pos try-pos
7873 :len (- try-end try-pos)
7874 :try-block try-block
7875 :finally-block finally-block))
7876 (js2-node-add-children pn try-block finally-block)
7877 ;; push them onto the try-node, which reverses and corrects their order
7878 (dolist (cb catch-blocks)
7879 (js2-node-add-children pn cb)
7880 (push cb (js2-try-node-catch-clauses pn)))
7881 pn))
7882
7883 (defun js2-parse-throw ()
7884 "Parser for throw-statement. Last matched token must be js2-THROW."
7885 (let ((pos js2-token-beg)
7886 expr pn)
7887 (js2-consume-token)
7888 (if (= (js2-peek-token-or-eol) js2-EOL)
7889 ;; ECMAScript does not allow new lines before throw expression,
7890 ;; see bug 256617
7891 (js2-report-error "msg.bad.throw.eol"))
7892 (setq expr (js2-parse-expr)
7893 pn (make-js2-throw-node :pos pos
7894 :len (- (js2-node-end expr) pos)
7895 :expr expr))
7896 (js2-node-add-children pn expr)
7897 pn))
7898
7899 (defun js2-match-jump-label-name (label-name)
7900 "If break/continue specified a label, return that label's labeled stmt.
7901 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7902 does not match an existing label, reports an error and returns nil."
7903 (let ((bundle (cdr (assoc label-name js2-label-set))))
7904 (if (null bundle)
7905 (js2-report-error "msg.undef.label"))
7906 bundle))
7907
7908 (defun js2-parse-break ()
7909 "Parser for break-statement. Last matched token must be js2-BREAK."
7910 (let ((pos js2-token-beg)
7911 (end js2-token-end)
7912 break-target ; statement to break from
7913 break-label ; in "break foo", name-node representing the foo
7914 labels ; matching labeled statement to break to
7915 pn)
7916 (js2-consume-token) ; `break'
7917 (when (eq (js2-peek-token-or-eol) js2-NAME)
7918 (js2-consume-token)
7919 (setq break-label (js2-create-name-node)
7920 end (js2-node-end break-label)
7921 ;; matchJumpLabelName only matches if there is one
7922 labels (js2-match-jump-label-name js2-ts-string)
7923 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7924 (unless (or break-target break-label)
7925 ;; no break target specified - try for innermost enclosing loop/switch
7926 (if (null js2-loop-and-switch-set)
7927 (unless break-label
7928 (js2-report-error "msg.bad.break" nil pos (length "break")))
7929 (setq break-target (car js2-loop-and-switch-set))))
7930 (setq pn (make-js2-break-node :pos pos
7931 :len (- end pos)
7932 :label break-label
7933 :target break-target))
7934 (js2-node-add-children pn break-label) ; but not break-target
7935 pn))
7936
7937 (defun js2-parse-continue ()
7938 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7939 (let ((pos js2-token-beg)
7940 (end js2-token-end)
7941 label ; optional user-specified label, a `js2-name-node'
7942 labels ; current matching labeled stmt, if any
7943 target ; the `js2-loop-node' target of this continue stmt
7944 pn)
7945 (js2-consume-token) ; `continue'
7946 (when (= (js2-peek-token-or-eol) js2-NAME)
7947 (js2-consume-token)
7948 (setq label (js2-create-name-node)
7949 end (js2-node-end label)
7950 ;; matchJumpLabelName only matches if there is one
7951 labels (js2-match-jump-label-name js2-ts-string)))
7952 (cond
7953 ((null labels) ; no current label to go to
7954 (if (null js2-loop-set) ; no loop to continue to
7955 (js2-report-error "msg.continue.outside" nil pos
7956 (length "continue"))
7957 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7958 (t
7959 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7960 (setq target (js2-labeled-stmt-node-stmt labels))
7961 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7962 (setq pn (make-js2-continue-node :pos pos
7963 :len (- end pos)
7964 :label label
7965 :target target))
7966 (js2-node-add-children pn label) ; but not target - it's not our child
7967 pn))
7968
7969 (defun js2-parse-with ()
7970 "Parser for with-statement. Last matched token must be js2-WITH."
7971 (js2-consume-token)
7972 (let ((pos js2-token-beg)
7973 obj body pn lp rp)
7974 (if (js2-must-match js2-LP "msg.no.paren.with")
7975 (setq lp js2-token-beg))
7976 (setq obj (js2-parse-expr))
7977 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7978 (setq rp js2-token-beg))
7979 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7980 (setq body (js2-parse-statement)))
7981 (setq pn (make-js2-with-node :pos pos
7982 :len (- (js2-node-end body) pos)
7983 :object obj
7984 :body body
7985 :lp (js2-relpos lp pos)
7986 :rp (js2-relpos rp pos)))
7987 (js2-node-add-children pn obj body)
7988 pn))
7989
7990 (defun js2-parse-const-var ()
7991 "Parser for var- or const-statement.
7992 Last matched token must be js2-CONST or js2-VAR."
7993 (let ((tt (js2-peek-token))
7994 (pos js2-token-beg)
7995 expr pn)
7996 (js2-consume-token)
7997 (setq expr (js2-parse-variables tt js2-token-beg)
7998 pn (make-js2-expr-stmt-node :pos pos
7999 :len (- (js2-node-end expr) pos)
8000 :expr expr))
8001 (js2-node-add-children pn expr)
8002 pn))
8003
8004 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8005 (let ((pn (make-js2-expr-stmt-node :pos pos
8006 :len (js2-node-len expr)
8007 :type (if (js2-inside-function)
8008 js2-EXPR_VOID
8009 js2-EXPR_RESULT)
8010 :expr expr)))
8011 (if add-child
8012 (js2-node-add-children pn expr))
8013 pn))
8014
8015 (defun js2-parse-let-stmt ()
8016 "Parser for let-statement. Last matched token must be js2-LET."
8017 (js2-consume-token)
8018 (let ((pos js2-token-beg)
8019 expr pn)
8020 (if (= (js2-peek-token) js2-LP)
8021 ;; let expression in statement context
8022 (setq expr (js2-parse-let pos 'statement)
8023 pn (js2-wrap-with-expr-stmt pos expr t))
8024 ;; else we're looking at a statement like let x=6, y=7;
8025 (setf expr (js2-parse-variables js2-LET pos)
8026 pn (js2-wrap-with-expr-stmt pos expr t)
8027 (js2-node-type pn) js2-EXPR_RESULT))
8028 pn))
8029
8030 (defun js2-parse-ret-yield ()
8031 (js2-parse-return-or-yield (js2-peek-token) nil))
8032
8033 (defconst js2-parse-return-stmt-enders
8034 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8035
8036 (defsubst js2-now-all-set (before after mask)
8037 "Return whether or not the bits in the mask have changed to all set.
8038 BEFORE is bits before change, AFTER is bits after change, and MASK is
8039 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8040 but not BEFORE."
8041 (and (/= (logand before mask) mask)
8042 (= (logand after mask) mask)))
8043
8044 (defun js2-parse-return-or-yield (tt expr-context)
8045 (let ((pos js2-token-beg)
8046 (end js2-token-end)
8047 (before js2-end-flags)
8048 (inside-function (js2-inside-function))
8049 e ret name)
8050 (unless inside-function
8051 (js2-report-error (if (eq tt js2-RETURN)
8052 "msg.bad.return"
8053 "msg.bad.yield")))
8054 (js2-consume-token)
8055 ;; This is ugly, but we don't want to require a semicolon.
8056 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8057 (setq e (js2-parse-expr)
8058 end (js2-node-end e)))
8059 (cond
8060 ((eq tt js2-RETURN)
8061 (js2-set-flag js2-end-flags (if (null e)
8062 js2-end-returns
8063 js2-end-returns-value))
8064 (setq ret (make-js2-return-node :pos pos
8065 :len (- end pos)
8066 :retval e))
8067 (js2-node-add-children ret e)
8068 ;; See if we need a strict mode warning.
8069 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8070 ;; more thorough and accurate than this before/after flag check.
8071 ;; E.g. if there's a finally-block that always returns, we shouldn't
8072 ;; show a warning generated by inconsistent returns in the catch blocks.
8073 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8074 ;; so we know which returns/yields to highlight, and we should get rid of
8075 ;; all the checking in `js2-parse-return-or-yield'.
8076 (if (and js2-strict-inconsistent-return-warning
8077 (js2-now-all-set before js2-end-flags
8078 (logior js2-end-returns js2-end-returns-value)))
8079 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8080 (t
8081 (unless (js2-inside-function)
8082 (js2-report-error "msg.bad.yield"))
8083 (js2-set-flag js2-end-flags js2-end-yields)
8084 (setq ret (make-js2-yield-node :pos pos
8085 :len (- end pos)
8086 :value e))
8087 (js2-node-add-children ret e)
8088 (unless expr-context
8089 (setq e ret
8090 ret (js2-wrap-with-expr-stmt pos e t))
8091 (js2-set-requires-activation)
8092 (js2-set-is-generator))))
8093 ;; see if we are mixing yields and value returns.
8094 (when (and inside-function
8095 (js2-now-all-set before js2-end-flags
8096 (logior js2-end-yields js2-end-returns-value)))
8097 (setq name (js2-function-name js2-current-script-or-fn))
8098 (if (zerop (length name))
8099 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8100 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8101 ret))
8102
8103 (defun js2-parse-debugger ()
8104 (js2-consume-token)
8105 (make-js2-keyword-node :type js2-DEBUGGER))
8106
8107 (defun js2-parse-block ()
8108 "Parser for a curly-delimited statement block.
8109 Last token matched must be `js2-LC'."
8110 (let ((pos js2-token-beg)
8111 (pn (make-js2-scope)))
8112 (js2-consume-token)
8113 (js2-push-scope pn)
8114 (unwind-protect
8115 (progn
8116 (js2-parse-statements pn)
8117 (js2-must-match js2-RC "msg.no.brace.block")
8118 (setf (js2-node-len pn) (- js2-token-end pos)))
8119 (js2-pop-scope))
8120 pn))
8121
8122 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8123 (defun js2-parse-semi ()
8124 "Parse a statement or handle an error.
8125 Last matched token is `js2-SEMI' or `js2-ERROR'."
8126 (let ((tt (js2-peek-token)) pos len)
8127 (js2-consume-token)
8128 (if (eq tt js2-SEMI)
8129 (make-js2-empty-expr-node :len 1)
8130 (setq pos js2-token-beg
8131 len (- js2-token-beg pos))
8132 (js2-report-error "msg.syntax" nil pos len)
8133 (make-js2-error-node :pos pos :len len))))
8134
8135 (defun js2-parse-default-xml-namespace ()
8136 "Parse a `default xml namespace = <expr>' e4x statement."
8137 (let ((pos js2-token-beg)
8138 end len expr unary es)
8139 (js2-consume-token)
8140 (js2-must-have-xml)
8141 (js2-set-requires-activation)
8142 (setq len (- js2-ts-cursor pos))
8143 (unless (and (js2-match-token js2-NAME)
8144 (string= js2-ts-string "xml"))
8145 (js2-report-error "msg.bad.namespace" nil pos len))
8146 (unless (and (js2-match-token js2-NAME)
8147 (string= js2-ts-string "namespace"))
8148 (js2-report-error "msg.bad.namespace" nil pos len))
8149 (unless (js2-match-token js2-ASSIGN)
8150 (js2-report-error "msg.bad.namespace" nil pos len))
8151 (setq expr (js2-parse-expr)
8152 end (js2-node-end expr)
8153 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8154 :pos pos
8155 :len (- end pos)
8156 :operand expr))
8157 (js2-node-add-children unary expr)
8158 (make-js2-expr-stmt-node :pos pos
8159 :len (- end pos)
8160 :expr unary)))
8161
8162 (defun js2-record-label (label bundle)
8163 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8164 (js2-consume-token)
8165 (let ((name (js2-label-node-name label))
8166 labeled-stmt
8167 dup)
8168 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8169 ;; flag both labels if possible when used in editing mode
8170 (if (and js2-parse-ide-mode
8171 (setq dup (js2-get-label-by-name labeled-stmt name)))
8172 (js2-report-error "msg.dup.label" nil
8173 (js2-node-abs-pos dup) (js2-node-len dup)))
8174 (js2-report-error "msg.dup.label" nil
8175 (js2-node-pos label) (js2-node-len label)))
8176 (js2-labeled-stmt-node-add-label bundle label)
8177 (js2-node-add-children bundle label)
8178 ;; Add one reference to the bundle per label in `js2-label-set'
8179 (push (cons name bundle) js2-label-set)))
8180
8181 (defun js2-parse-name-or-label ()
8182 "Parser for identifier or label. Last token matched must be js2-NAME.
8183 Called when we found a name in a statement context. If it's a label, we gather
8184 up any following labels and the next non-label statement into a
8185 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8186 expression and return it wrapped in a `js2-expr-stmt-node'."
8187 (let ((pos js2-token-beg)
8188 (end js2-token-end)
8189 expr stmt pn bundle
8190 (continue t))
8191 ;; set check for label and call down to `js2-parse-primary-expr'
8192 (js2-set-check-for-label)
8193 (setq expr (js2-parse-expr))
8194 (if (/= (js2-node-type expr) js2-LABEL)
8195 ;; Parsed non-label expression - wrap with expression stmt.
8196 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8197 ;; else parsed a label
8198 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8199 (js2-record-label expr bundle)
8200 ;; look for more labels
8201 (while (and continue (= (js2-peek-token) js2-NAME))
8202 (js2-set-check-for-label)
8203 (setq expr (js2-parse-expr))
8204 (if (/= (js2-node-type expr) js2-LABEL)
8205 (progn
8206 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8207 continue nil)
8208 (js2-auto-insert-semicolon stmt))
8209 (js2-record-label expr bundle)))
8210 ;; no more labels; now parse the labeled statement
8211 (unwind-protect
8212 (unless stmt
8213 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8214 (setq stmt (js2-statement-helper))))
8215 ;; remove the labels for this statement from the global set
8216 (dolist (label (js2-labeled-stmt-node-labels bundle))
8217 (setq js2-label-set (remove label js2-label-set))))
8218 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8219 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8220 (js2-node-add-children bundle stmt)
8221 bundle)))
8222
8223 (defun js2-parse-expr-stmt ()
8224 "Default parser in statement context, if no recognized statement found."
8225 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8226
8227 (defun js2-parse-variables (decl-type pos)
8228 "Parse a comma-separated list of variable declarations.
8229 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8230
8231 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8232 For 'var' or 'const', the keyword should be the token last scanned.
8233
8234 POS is the position where the node should start. It's sometimes the
8235 var/const/let keyword, and other times the beginning of the first token
8236 in the first variable declaration.
8237
8238 Returns the parsed `js2-var-decl-node' expression node."
8239 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8240 :pos pos))
8241 destructuring kid-pos tt init name end nbeg nend vi
8242 (continue t))
8243 ;; Example:
8244 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8245 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8246 ;; var {a, b} = baz;
8247 (while continue
8248 (setq destructuring nil
8249 name nil
8250 tt (js2-peek-token)
8251 kid-pos js2-token-beg
8252 end js2-token-end
8253 init nil)
8254 (if (or (= tt js2-LB) (= tt js2-LC))
8255 ;; Destructuring assignment, e.g., var [a, b] = ...
8256 (setq destructuring (js2-parse-primary-expr-lhs)
8257 end (js2-node-end destructuring))
8258 ;; Simple variable name
8259 (when (js2-must-match js2-NAME "msg.bad.var")
8260 (setq name (js2-create-name-node)
8261 nbeg js2-token-beg
8262 nend js2-token-end
8263 end nend)
8264 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8265 (when (js2-match-token js2-ASSIGN)
8266 (setq init (js2-parse-assign-expr)
8267 end (js2-node-end init))
8268 (if (and js2-parse-ide-mode
8269 (or (js2-object-node-p init)
8270 (js2-function-node-p init)))
8271 (js2-record-imenu-functions init name)))
8272 (when name
8273 (js2-set-face nbeg nend (if (js2-function-node-p init)
8274 'font-lock-function-name-face
8275 'font-lock-variable-name-face)
8276 'record))
8277 (setq vi (make-js2-var-init-node :pos kid-pos
8278 :len (- end kid-pos)
8279 :type decl-type))
8280 (if destructuring
8281 (progn
8282 (if (and (null init) (not js2-in-for-init))
8283 (js2-report-error "msg.destruct.assign.no.init"))
8284 (js2-define-destruct-symbols destructuring
8285 decl-type
8286 'font-lock-variable-name-face)
8287 (setf (js2-var-init-node-target vi) destructuring))
8288 (setf (js2-var-init-node-target vi) name))
8289 (setf (js2-var-init-node-initializer vi) init)
8290 (js2-node-add-children vi name destructuring init)
8291 (js2-block-node-push result vi)
8292 (unless (js2-match-token js2-COMMA)
8293 (setq continue nil)))
8294 (setf (js2-node-len result) (- end pos))
8295 result))
8296
8297 (defun js2-parse-let (pos &optional stmt-p)
8298 "Parse a let expression or statement.
8299 A let-expression is of the form `let (vars) expr'.
8300 A let-statment is of the form `let (vars) {statements}'.
8301 The third form of let is a variable declaration list, handled
8302 by `js2-parse-variables'."
8303 (let ((pn (make-js2-let-node :pos pos))
8304 beg vars body)
8305 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8306 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8307 (js2-push-scope pn)
8308 (unwind-protect
8309 (progn
8310 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8311 (if (js2-must-match js2-RP "msg.no.paren.let")
8312 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8313 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8314 ;; let statement
8315 (progn
8316 (js2-consume-token)
8317 (setf beg js2-token-beg ; position stmt at LC
8318 body (js2-parse-statements))
8319 (js2-must-match js2-RC "msg.no.curly.let")
8320 (setf (js2-node-len body) (- js2-token-end beg)
8321 (js2-node-len pn) (- js2-token-end pos)
8322 (js2-let-node-body pn) body
8323 (js2-node-type pn) js2-LET))
8324 ;; let expression
8325 (setf body (js2-parse-expr)
8326 (js2-node-len pn) (- (js2-node-end body) pos)
8327 (js2-let-node-body pn) body))
8328 (js2-node-add-children pn vars body))
8329 (js2-pop-scope))
8330 pn))
8331
8332 (defun js2-define-new-symbol (decl-type name node &optional scope)
8333 (js2-scope-put-symbol (or scope js2-current-scope)
8334 name
8335 (make-js2-symbol decl-type name node)))
8336
8337 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8338 "Define a symbol in the current scope.
8339 If NODE is non-nil, it is the AST node associated with the symbol."
8340 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8341 (symbol (if defining-scope
8342 (js2-scope-get-symbol defining-scope name)))
8343 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8344 (cond
8345 ((and symbol ; already defined
8346 (or (= sdt js2-CONST) ; old version is const
8347 (= decl-type js2-CONST) ; new version is const
8348 ;; two let-bound vars in this block have same name
8349 (and (= sdt js2-LET)
8350 (eq defining-scope js2-current-scope))))
8351 (js2-report-error
8352 (cond
8353 ((= sdt js2-CONST) "msg.const.redecl")
8354 ((= sdt js2-LET) "msg.let.redecl")
8355 ((= sdt js2-VAR) "msg.var.redecl")
8356 ((= sdt js2-FUNCTION) "msg.function.redecl")
8357 (t "msg.parm.redecl"))
8358 name))
8359 ((= decl-type js2-LET)
8360 (if (and (not ignore-not-in-block)
8361 (or (= (js2-node-type js2-current-scope) js2-IF)
8362 (js2-loop-node-p js2-current-scope)))
8363 (js2-report-error "msg.let.decl.not.in.block")
8364 (js2-define-new-symbol decl-type name node)))
8365 ((or (= decl-type js2-VAR)
8366 (= decl-type js2-CONST)
8367 (= decl-type js2-FUNCTION))
8368 (if symbol
8369 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8370 (js2-add-strict-warning "msg.var.redecl" name)
8371 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8372 (js2-add-strict-warning "msg.var.hides.arg" name)))
8373 (js2-define-new-symbol decl-type name node
8374 js2-current-script-or-fn)))
8375 ((= decl-type js2-LP)
8376 (if symbol
8377 ;; must be duplicate parameter. Second parameter hides the
8378 ;; first, so go ahead and add the second pararameter
8379 (js2-report-warning "msg.dup.parms" name))
8380 (js2-define-new-symbol decl-type name node))
8381 (t (js2-code-bug)))))
8382
8383 (defun js2-parse-expr (&optional oneshot)
8384 (let* ((pn (js2-parse-assign-expr))
8385 (pos (js2-node-pos pn))
8386 left
8387 right
8388 op-pos)
8389 (while (and (not oneshot)
8390 (js2-match-token js2-COMMA))
8391 (setq op-pos (- js2-token-beg pos)) ; relative
8392 (if (= (js2-peek-token) js2-YIELD)
8393 (js2-report-error "msg.yield.parenthesized"))
8394 (setq right (js2-parse-assign-expr)
8395 left pn
8396 pn (make-js2-infix-node :type js2-COMMA
8397 :pos pos
8398 :len (- js2-ts-cursor pos)
8399 :op-pos op-pos
8400 :left left
8401 :right right))
8402 (js2-node-add-children pn left right))
8403 pn))
8404
8405 (defun js2-parse-assign-expr ()
8406 (let ((tt (js2-peek-token))
8407 (pos js2-token-beg)
8408 pn left right op-pos)
8409 (if (= tt js2-YIELD)
8410 (js2-parse-return-or-yield tt t)
8411 ;; not yield - parse assignment expression
8412 (setq pn (js2-parse-cond-expr)
8413 tt (js2-peek-token))
8414 (when (and (<= js2-first-assign tt)
8415 (<= tt js2-last-assign))
8416 ;; tt express assignment (=, |=, ^=, ..., %=)
8417 (js2-consume-token)
8418 (setq op-pos (- js2-token-beg pos) ; relative
8419 left pn
8420 right (js2-parse-assign-expr)
8421 pn (make-js2-assign-node :type tt
8422 :pos pos
8423 :len (- (js2-node-end right) pos)
8424 :op-pos op-pos
8425 :left left
8426 :right right))
8427 (when js2-parse-ide-mode
8428 (js2-highlight-assign-targets pn left right)
8429 (if (or (js2-function-node-p right)
8430 (js2-object-node-p right))
8431 (js2-record-imenu-functions right left)))
8432 ;; do this last so ide checks above can use absolute positions
8433 (js2-node-add-children pn left right))
8434 pn)))
8435
8436 (defun js2-parse-cond-expr ()
8437 (let ((pos js2-token-beg)
8438 (pn (js2-parse-or-expr))
8439 test-expr
8440 if-true
8441 if-false
8442 q-pos
8443 c-pos)
8444 (when (js2-match-token js2-HOOK)
8445 (setq q-pos (- js2-token-beg pos)
8446 if-true (js2-parse-assign-expr))
8447 (js2-must-match js2-COLON "msg.no.colon.cond")
8448 (setq c-pos (- js2-token-beg pos)
8449 if-false (js2-parse-assign-expr)
8450 test-expr pn
8451 pn (make-js2-cond-node :pos pos
8452 :len (- (js2-node-end if-false) pos)
8453 :test-expr test-expr
8454 :true-expr if-true
8455 :false-expr if-false
8456 :q-pos q-pos
8457 :c-pos c-pos))
8458 (js2-node-add-children pn test-expr if-true if-false))
8459 pn))
8460
8461 (defun js2-make-binary (type left parser)
8462 "Helper for constructing a binary-operator AST node.
8463 LEFT is the left-side-expression, already parsed, and the
8464 binary operator should have just been matched.
8465 PARSER is a function to call to parse the right operand,
8466 or a `js2-node' struct if it has already been parsed."
8467 (let* ((pos (js2-node-pos left))
8468 (op-pos (- js2-token-beg pos))
8469 (right (if (js2-node-p parser)
8470 parser
8471 (funcall parser)))
8472 (pn (make-js2-infix-node :type type
8473 :pos pos
8474 :len (- (js2-node-end right) pos)
8475 :op-pos op-pos
8476 :left left
8477 :right right)))
8478 (js2-node-add-children pn left right)
8479 pn))
8480
8481 (defun js2-parse-or-expr ()
8482 (let ((pn (js2-parse-and-expr)))
8483 (when (js2-match-token js2-OR)
8484 (setq pn (js2-make-binary js2-OR
8485 pn
8486 'js2-parse-or-expr)))
8487 pn))
8488
8489 (defun js2-parse-and-expr ()
8490 (let ((pn (js2-parse-bit-or-expr)))
8491 (when (js2-match-token js2-AND)
8492 (setq pn (js2-make-binary js2-AND
8493 pn
8494 'js2-parse-and-expr)))
8495 pn))
8496
8497 (defun js2-parse-bit-or-expr ()
8498 (let ((pn (js2-parse-bit-xor-expr)))
8499 (while (js2-match-token js2-BITOR)
8500 (setq pn (js2-make-binary js2-BITOR
8501 pn
8502 'js2-parse-bit-xor-expr)))
8503 pn))
8504
8505 (defun js2-parse-bit-xor-expr ()
8506 (let ((pn (js2-parse-bit-and-expr)))
8507 (while (js2-match-token js2-BITXOR)
8508 (setq pn (js2-make-binary js2-BITXOR
8509 pn
8510 'js2-parse-bit-and-expr)))
8511 pn))
8512
8513 (defun js2-parse-bit-and-expr ()
8514 (let ((pn (js2-parse-eq-expr)))
8515 (while (js2-match-token js2-BITAND)
8516 (setq pn (js2-make-binary js2-BITAND
8517 pn
8518 'js2-parse-eq-expr)))
8519 pn))
8520
8521 (defconst js2-parse-eq-ops
8522 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8523
8524 (defun js2-parse-eq-expr ()
8525 (let ((pn (js2-parse-rel-expr))
8526 tt)
8527 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8528 (js2-consume-token)
8529 (setq pn (js2-make-binary tt
8530 pn
8531 'js2-parse-rel-expr)))
8532 pn))
8533
8534 (defconst js2-parse-rel-ops
8535 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8536
8537 (defun js2-parse-rel-expr ()
8538 (let ((pn (js2-parse-shift-expr))
8539 (continue t)
8540 tt)
8541 (while continue
8542 (setq tt (js2-peek-token))
8543 (cond
8544 ((and js2-in-for-init (= tt js2-IN))
8545 (setq continue nil))
8546 ((memq tt js2-parse-rel-ops)
8547 (js2-consume-token)
8548 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8549 (t
8550 (setq continue nil))))
8551 pn))
8552
8553 (defconst js2-parse-shift-ops
8554 (list js2-LSH js2-URSH js2-RSH))
8555
8556 (defun js2-parse-shift-expr ()
8557 (let ((pn (js2-parse-add-expr))
8558 tt
8559 (continue t))
8560 (while continue
8561 (setq tt (js2-peek-token))
8562 (if (memq tt js2-parse-shift-ops)
8563 (progn
8564 (js2-consume-token)
8565 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8566 (setq continue nil)))
8567 pn))
8568
8569 (defun js2-parse-add-expr ()
8570 (let ((pn (js2-parse-mul-expr))
8571 tt
8572 (continue t))
8573 (while continue
8574 (setq tt (js2-peek-token))
8575 (if (or (= tt js2-ADD) (= tt js2-SUB))
8576 (progn
8577 (js2-consume-token)
8578 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8579 (setq continue nil)))
8580 pn))
8581
8582 (defconst js2-parse-mul-ops
8583 (list js2-MUL js2-DIV js2-MOD))
8584
8585 (defun js2-parse-mul-expr ()
8586 (let ((pn (js2-parse-unary-expr))
8587 tt
8588 (continue t))
8589 (while continue
8590 (setq tt (js2-peek-token))
8591 (if (memq tt js2-parse-mul-ops)
8592 (progn
8593 (js2-consume-token)
8594 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8595 (setq continue nil)))
8596 pn))
8597
8598 (defun js2-make-unary (type parser &rest args)
8599 "Make a unary node of type TYPE.
8600 PARSER is either a node (for postfix operators) or a function to call
8601 to parse the operand (for prefix operators)."
8602 (let* ((pos js2-token-beg)
8603 (postfix (js2-node-p parser))
8604 (expr (if postfix
8605 parser
8606 (apply parser args)))
8607 end
8608 pn)
8609 (if postfix ; e.g. i++
8610 (setq pos (js2-node-pos expr)
8611 end js2-token-end)
8612 (setq end (js2-node-end expr)))
8613 (setq pn (make-js2-unary-node :type type
8614 :pos pos
8615 :len (- end pos)
8616 :operand expr))
8617 (js2-node-add-children pn expr)
8618 pn))
8619
8620 (defconst js2-incrementable-node-types
8621 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8622 "Node types that can be the operand of a ++ or -- operator.")
8623
8624 (defun js2-check-bad-inc-dec (tt beg end unary)
8625 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8626 js2-incrementable-node-types)
8627 (js2-report-error (if (= tt js2-INC)
8628 "msg.bad.incr"
8629 "msg.bad.decr")
8630 nil beg (- end beg))))
8631
8632 (defun js2-parse-unary-expr ()
8633 (let ((tt (js2-peek-token))
8634 pn expr beg end)
8635 (cond
8636 ((or (= tt js2-VOID)
8637 (= tt js2-NOT)
8638 (= tt js2-BITNOT)
8639 (= tt js2-TYPEOF))
8640 (js2-consume-token)
8641 (js2-make-unary tt 'js2-parse-unary-expr))
8642 ((= tt js2-ADD)
8643 (js2-consume-token)
8644 ;; Convert to special POS token in decompiler and parse tree
8645 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8646 ((= tt js2-SUB)
8647 (js2-consume-token)
8648 ;; Convert to special NEG token in decompiler and parse tree
8649 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8650 ((or (= tt js2-INC)
8651 (= tt js2-DEC))
8652 (js2-consume-token)
8653 (prog1
8654 (setq beg js2-token-beg
8655 end js2-token-end
8656 expr (js2-make-unary tt 'js2-parse-member-expr t))
8657 (js2-check-bad-inc-dec tt beg end expr)))
8658 ((= tt js2-DELPROP)
8659 (js2-consume-token)
8660 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8661 ((= tt js2-ERROR)
8662 (js2-consume-token)
8663 (make-js2-error-node)) ; try to continue
8664 ((and (= tt js2-LT)
8665 js2-compiler-xml-available)
8666 ;; XML stream encountered in expression.
8667 (js2-consume-token)
8668 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8669 (t
8670 (setq pn (js2-parse-member-expr t)
8671 ;; Don't look across a newline boundary for a postfix incop.
8672 tt (js2-peek-token-or-eol))
8673 (when (or (= tt js2-INC) (= tt js2-DEC))
8674 (js2-consume-token)
8675 (setf expr pn
8676 pn (js2-make-unary tt expr))
8677 (js2-node-set-prop pn 'postfix t)
8678 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8679 pn))))
8680
8681 (defun js2-parse-xml-initializer ()
8682 "Parse an E4X XML initializer.
8683 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8684 Then I'll postprocess the result, depending on whether we're in IDE
8685 mode or codegen mode, and generate the appropriate rewritten AST.
8686 IDE mode uses a rich AST that models the XML structure. Codegen mode
8687 just concatenates everything and makes a new XML or XMLList out of it."
8688 (let ((tt (js2-get-first-xml-token))
8689 pn-xml pn expr kids expr-pos
8690 (continue t)
8691 (first-token t))
8692 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8693 (js2-report-error "msg.syntax"))
8694 (setq pn-xml (make-js2-xml-node))
8695 (while continue
8696 (if first-token
8697 (setq first-token nil)
8698 (setq tt (js2-get-next-xml-token)))
8699 (cond
8700 ;; js2-XML means we found a {expr} in the XML stream.
8701 ;; The js2-ts-string is the XML up to the left-curly.
8702 ((= tt js2-XML)
8703 (push (make-js2-string-node :pos js2-token-beg
8704 :len (- js2-ts-cursor js2-token-beg))
8705 kids)
8706 (js2-must-match js2-LC "msg.syntax")
8707 (setq expr-pos js2-ts-cursor
8708 expr (if (eq (js2-peek-token) js2-RC)
8709 (make-js2-empty-expr-node :pos expr-pos)
8710 (js2-parse-expr)))
8711 (js2-must-match js2-RC "msg.syntax")
8712 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8713 :len (js2-node-len expr)
8714 :expr expr))
8715 (js2-node-add-children pn expr)
8716 (push pn kids))
8717 ;; a js2-XMLEND token means we hit the final close-tag.
8718 ((= tt js2-XMLEND)
8719 (push (make-js2-string-node :pos js2-token-beg
8720 :len (- js2-ts-cursor js2-token-beg))
8721 kids)
8722 (dolist (kid (nreverse kids))
8723 (js2-block-node-push pn-xml kid))
8724 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8725 (js2-node-pos pn-xml))
8726 continue nil))
8727 (t
8728 (js2-report-error "msg.syntax")
8729 (setq continue nil))))
8730 pn-xml))
8731
8732
8733 (defun js2-parse-argument-list ()
8734 "Parse an argument list and return it as a Lisp list of nodes.
8735 Returns the list in reverse order. Consumes the right-paren token."
8736 (let (result)
8737 (unless (js2-match-token js2-RP)
8738 (loop do
8739 (if (= (js2-peek-token) js2-YIELD)
8740 (js2-report-error "msg.yield.parenthesized"))
8741 (push (js2-parse-assign-expr) result)
8742 while
8743 (js2-match-token js2-COMMA))
8744 (js2-must-match js2-RP "msg.no.paren.arg")
8745 result)))
8746
8747 (defun js2-parse-member-expr (&optional allow-call-syntax)
8748 (let ((tt (js2-peek-token))
8749 pn pos target args beg end init tail)
8750 (if (/= tt js2-NEW)
8751 (setq pn (js2-parse-primary-expr))
8752 ;; parse a 'new' expression
8753 (js2-consume-token)
8754 (setq pos js2-token-beg
8755 beg pos
8756 target (js2-parse-member-expr)
8757 end (js2-node-end target)
8758 pn (make-js2-new-node :pos pos
8759 :target target
8760 :len (- end pos)))
8761 (js2-node-add-children pn target)
8762 (when (js2-match-token js2-LP)
8763 ;; Add the arguments to pn, if any are supplied.
8764 (setf beg pos ; start of "new" keyword
8765 pos js2-token-beg
8766 args (nreverse (js2-parse-argument-list))
8767 (js2-new-node-args pn) args
8768 end js2-token-end
8769 (js2-new-node-lp pn) (- pos beg)
8770 (js2-new-node-rp pn) (- end 1 beg))
8771 (apply #'js2-node-add-children pn args))
8772 (when (and js2-allow-rhino-new-expr-initializer
8773 (js2-match-token js2-LC))
8774 (setf init (js2-parse-object-literal)
8775 end (js2-node-end init)
8776 (js2-new-node-initializer pn) init)
8777 (js2-node-add-children pn init))
8778 (setf (js2-node-len pn) (- end beg))) ; end outer if
8779 (js2-parse-member-expr-tail allow-call-syntax pn)))
8780
8781 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8782 "Parse a chain of property/array accesses or function calls.
8783 Includes parsing for E4X operators like `..' and `.@'.
8784 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8785 Returns an expression tree that includes PN, the parent node."
8786 (let ((beg (js2-node-pos pn))
8787 tt
8788 (continue t))
8789 (while continue
8790 (setq tt (js2-peek-token))
8791 (cond
8792 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8793 (setq pn (js2-parse-property-access tt pn)))
8794 ((= tt js2-DOTQUERY)
8795 (setq pn (js2-parse-dot-query pn)))
8796 ((= tt js2-LB)
8797 (setq pn (js2-parse-element-get pn)))
8798 ((= tt js2-LP)
8799 (if allow-call-syntax
8800 (setq pn (js2-parse-function-call pn))
8801 (setq continue nil)))
8802 (t
8803 (setq continue nil))))
8804 (if (>= js2-highlight-level 2)
8805 (js2-parse-highlight-member-expr-node pn))
8806 pn))
8807
8808 (defun js2-parse-dot-query (pn)
8809 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8810 Last token parsed must be `js2-DOTQUERY'."
8811 (let ((pos (js2-node-pos pn))
8812 op-pos expr end)
8813 (js2-consume-token)
8814 (js2-must-have-xml)
8815 (js2-set-requires-activation)
8816 (setq op-pos js2-token-beg
8817 expr (js2-parse-expr)
8818 end (js2-node-end expr)
8819 pn (make-js2-xml-dot-query-node :left pn
8820 :pos pos
8821 :op-pos op-pos
8822 :right expr))
8823 (js2-node-add-children pn
8824 (js2-xml-dot-query-node-left pn)
8825 (js2-xml-dot-query-node-right pn))
8826 (if (js2-must-match js2-RP "msg.no.paren")
8827 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8828 end js2-token-end))
8829 (setf (js2-node-len pn) (- end pos))
8830 pn))
8831
8832 (defun js2-parse-element-get (pn)
8833 "Parse an element-get expression, e.g. foo[bar].
8834 Last token parsed must be `js2-RB'."
8835 (let ((lb js2-token-beg)
8836 (pos (js2-node-pos pn))
8837 rb expr)
8838 (js2-consume-token)
8839 (setq expr (js2-parse-expr))
8840 (if (js2-must-match js2-RB "msg.no.bracket.index")
8841 (setq rb js2-token-beg))
8842 (setq pn (make-js2-elem-get-node :target pn
8843 :pos pos
8844 :element expr
8845 :lb (js2-relpos lb pos)
8846 :rb (js2-relpos rb pos)
8847 :len (- js2-token-end pos)))
8848 (js2-node-add-children pn
8849 (js2-elem-get-node-target pn)
8850 (js2-elem-get-node-element pn))
8851 pn))
8852
8853 (defun js2-parse-function-call (pn)
8854 (let (args
8855 (pos (js2-node-pos pn)))
8856 (js2-consume-token)
8857 (setq pn (make-js2-call-node :pos pos
8858 :target pn
8859 :lp (- js2-token-beg pos)))
8860 (js2-node-add-children pn (js2-call-node-target pn))
8861 ;; Add the arguments to pn, if any are supplied.
8862 (setf args (nreverse (js2-parse-argument-list))
8863 (js2-call-node-rp pn) (- js2-token-beg pos)
8864 (js2-call-node-args pn) args)
8865 (apply #'js2-node-add-children pn args)
8866 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8867 pn))
8868
8869 (defun js2-parse-property-access (tt pn)
8870 "Parse a property access, XML descendants access, or XML attr access."
8871 (let ((member-type-flags 0)
8872 (dot-pos js2-token-beg)
8873 (dot-len (if (= tt js2-DOTDOT) 2 1))
8874 name
8875 ref ; right side of . or .. operator
8876 result)
8877 (js2-consume-token)
8878 (when (= tt js2-DOTDOT)
8879 (js2-must-have-xml)
8880 (setq member-type-flags js2-descendants-flag))
8881 (if (not js2-compiler-xml-available)
8882 (progn
8883 (js2-must-match-prop-name "msg.no.name.after.dot")
8884 (setq name (js2-create-name-node t js2-GETPROP)
8885 result (make-js2-prop-get-node :left pn
8886 :pos js2-token-beg
8887 :right name
8888 :len (- js2-token-end
8889 js2-token-beg)))
8890 (js2-node-add-children result pn name)
8891 result)
8892 ;; otherwise look for XML operators
8893 (setf result (if (= tt js2-DOT)
8894 (make-js2-prop-get-node)
8895 (make-js2-infix-node :type js2-DOTDOT))
8896 (js2-node-pos result) (js2-node-pos pn)
8897 (js2-infix-node-op-pos result) dot-pos
8898 (js2-infix-node-left result) pn ; do this after setting position
8899 tt (js2-next-token))
8900 (cond
8901 ;; needed for generator.throw()
8902 ((= tt js2-THROW)
8903 (js2-save-name-token-data js2-token-beg "throw")
8904 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8905 ;; handles: name, ns::name, ns::*, ns::[expr]
8906 ((js2-valid-prop-name-token tt)
8907 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8908 ;; handles: *, *::name, *::*, *::[expr]
8909 ((= tt js2-MUL)
8910 (js2-save-name-token-data js2-token-beg "*")
8911 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8912 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8913 ((= tt js2-XMLATTR)
8914 (setq result (js2-parse-attribute-access)))
8915 (t
8916 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8917 (if ref
8918 (setf (js2-node-len result) (- (js2-node-end ref)
8919 (js2-node-pos result))
8920 (js2-infix-node-right result) ref))
8921 (if (js2-infix-node-p result)
8922 (js2-node-add-children result
8923 (js2-infix-node-left result)
8924 (js2-infix-node-right result)))
8925 result)))
8926
8927 (defun js2-parse-attribute-access ()
8928 "Parse an E4X XML attribute expression.
8929 This includes expressions of the forms:
8930
8931 @attr @ns::attr @ns::*
8932 @* @*::attr @*::*
8933 @[expr] @*::[expr] @ns::[expr]
8934
8935 Called if we peeked an '@' token."
8936 (let ((tt (js2-next-token))
8937 (at-pos js2-token-beg))
8938 (cond
8939 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8940 ((js2-valid-prop-name-token tt)
8941 (js2-parse-property-name at-pos js2-ts-string 0))
8942 ;; handles: @*, @*::name, @*::*, @*::[expr]
8943 ((= tt js2-MUL)
8944 (js2-save-name-token-data js2-token-beg "*")
8945 (js2-parse-property-name js2-token-beg "*" 0))
8946 ;; handles @[expr]
8947 ((= tt js2-LB)
8948 (js2-parse-xml-elem-ref at-pos))
8949 (t
8950 (js2-report-error "msg.no.name.after.xmlAttr")
8951 ;; Avoid cascaded errors that happen if we make an error node here.
8952 (js2-save-name-token-data js2-token-beg "")
8953 (js2-parse-property-name js2-token-beg "" 0)))))
8954
8955 (defun js2-parse-property-name (at-pos s member-type-flags)
8956 "Check if :: follows name in which case it becomes qualified name.
8957
8958 AT-POS is a natural number if we just read an '@' token, else nil.
8959 S is the name or string that was matched: an identifier, 'throw' or '*'.
8960 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8961
8962 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8963 operator, or the name is followed by ::. For a plain name, returns a
8964 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8965 (let ((pos (or at-pos js2-token-beg))
8966 colon-pos
8967 (name (js2-create-name-node t js2-current-token))
8968 ns tt ref pn)
8969 (catch 'return
8970 (when (js2-match-token js2-COLONCOLON)
8971 (setq ns name
8972 colon-pos js2-token-beg
8973 tt (js2-next-token))
8974 (cond
8975 ;; handles name::name
8976 ((js2-valid-prop-name-token tt)
8977 (setq name (js2-create-name-node)))
8978 ;; handles name::*
8979 ((= tt js2-MUL)
8980 (js2-save-name-token-data js2-token-beg "*")
8981 (setq name (js2-create-name-node)))
8982 ;; handles name::[expr]
8983 ((= tt js2-LB)
8984 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8985 (t
8986 (js2-report-error "msg.no.name.after.coloncolon"))))
8987 (if (and (null ns) (zerop member-type-flags))
8988 name
8989 (prog1
8990 (setq pn
8991 (make-js2-xml-prop-ref-node :pos pos
8992 :len (- (js2-node-end name) pos)
8993 :at-pos at-pos
8994 :colon-pos colon-pos
8995 :propname name))
8996 (js2-node-add-children pn name))))))
8997
8998 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
8999 "Parse the [expr] portion of an xml element reference.
9000 For instance, @[expr], @*::[expr], or ns::[expr]."
9001 (let* ((lb js2-token-beg)
9002 (pos (or at-pos lb))
9003 rb
9004 (expr (js2-parse-expr))
9005 (end (js2-node-end expr))
9006 pn)
9007 (if (js2-must-match js2-RB "msg.no.bracket.index")
9008 (setq rb js2-token-beg
9009 end js2-token-end))
9010 (prog1
9011 (setq pn
9012 (make-js2-xml-elem-ref-node :pos pos
9013 :len (- end pos)
9014 :namespace namespace
9015 :colon-pos colon-pos
9016 :at-pos at-pos
9017 :expr expr
9018 :lb (js2-relpos lb pos)
9019 :rb (js2-relpos rb pos)))
9020 (js2-node-add-children pn namespace expr))))
9021
9022 (defun js2-parse-primary-expr-lhs ()
9023 (let ((js2-is-in-lhs t))
9024 (js2-parse-primary-expr)))
9025
9026 (defun js2-parse-primary-expr ()
9027 "Parse a literal (leaf) expression of some sort.
9028 Includes complex literals such as functions, object-literals,
9029 array-literals, array comprehensions and regular expressions."
9030 (let ((tt-flagged (js2-next-flagged-token))
9031 pn ; parent node (usually return value)
9032 tt
9033 px-pos ; paren-expr pos
9034 len
9035 flags ; regexp flags
9036 expr)
9037 (setq tt js2-current-token)
9038 (cond
9039 ((= tt js2-FUNCTION)
9040 (js2-parse-function 'FUNCTION_EXPRESSION))
9041 ((= tt js2-LB)
9042 (js2-parse-array-literal))
9043 ((= tt js2-LC)
9044 (js2-parse-object-literal))
9045 ((= tt js2-LET)
9046 (js2-parse-let js2-token-beg))
9047 ((= tt js2-LP)
9048 (setq px-pos js2-token-beg
9049 expr (js2-parse-expr))
9050 (js2-must-match js2-RP "msg.no.paren")
9051 (setq pn (make-js2-paren-node :pos px-pos
9052 :expr expr
9053 :len (- js2-token-end px-pos)))
9054 (js2-node-add-children pn (js2-paren-node-expr pn))
9055 pn)
9056 ((= tt js2-XMLATTR)
9057 (js2-must-have-xml)
9058 (js2-parse-attribute-access))
9059 ((= tt js2-NAME)
9060 (js2-parse-name tt-flagged tt))
9061 ((= tt js2-NUMBER)
9062 (make-js2-number-node))
9063 ((= tt js2-STRING)
9064 (prog1
9065 (make-js2-string-node)
9066 (js2-record-face 'font-lock-string-face)))
9067 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9068 ;; Got / or /= which in this context means a regexp literal
9069 (setq px-pos js2-token-beg)
9070 (js2-read-regexp tt)
9071 (setq flags js2-ts-regexp-flags
9072 js2-ts-regexp-flags nil)
9073 (prog1
9074 (make-js2-regexp-node :pos px-pos
9075 :len (- js2-ts-cursor px-pos)
9076 :value js2-ts-string
9077 :flags flags)
9078 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9079 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9080 ((or (= tt js2-NULL)
9081 (= tt js2-THIS)
9082 (= tt js2-FALSE)
9083 (= tt js2-TRUE))
9084 (make-js2-keyword-node :type tt))
9085 ((= tt js2-RESERVED)
9086 (js2-report-error "msg.reserved.id")
9087 (make-js2-name-node))
9088 ((= tt js2-ERROR)
9089 ;; the scanner or one of its subroutines reported the error.
9090 (make-js2-error-node))
9091 ((= tt js2-EOF)
9092 (setq px-pos (point-at-bol)
9093 len (- js2-ts-cursor px-pos))
9094 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9095 (make-js2-error-node :pos px-pos :len len))
9096 (t
9097 (js2-report-error "msg.syntax")
9098 (make-js2-error-node)))))
9099
9100 (defun js2-parse-name (tt-flagged tt)
9101 (let ((name js2-ts-string)
9102 (name-pos js2-token-beg)
9103 node)
9104 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9105 (= (js2-peek-token) js2-COLON))
9106 (prog1
9107 ;; Do not consume colon, it is used as unwind indicator
9108 ;; to return to statementHelper.
9109 (make-js2-label-node :pos name-pos
9110 :len (- js2-token-end name-pos)
9111 :name name)
9112 (js2-set-face name-pos
9113 js2-token-end
9114 'font-lock-variable-name-face 'record))
9115 ;; Otherwise not a label, just a name. Unfortunately peeking
9116 ;; the next token to check for a colon has biffed js2-token-beg
9117 ;; and js2-token-end. We store the name's bounds in buffer vars
9118 ;; and `js2-create-name-node' uses them.
9119 (js2-save-name-token-data name-pos name)
9120 (setq node (if js2-compiler-xml-available
9121 (js2-parse-property-name nil name 0)
9122 (js2-create-name-node 'check-activation)))
9123 (if js2-highlight-external-variables
9124 (js2-record-name-node node))
9125 node)))
9126
9127 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9128 (js2-add-strict-warning
9129 msg nil
9130 ;; back up from comma to beginning of line or array/objlit
9131 (max (if elems
9132 (js2-node-pos (car elems))
9133 pos)
9134 (save-excursion
9135 (goto-char comma-pos)
9136 (back-to-indentation)
9137 (point)))
9138 comma-pos))
9139
9140 (defun js2-parse-array-literal ()
9141 (let ((pos js2-token-beg)
9142 (end js2-token-end)
9143 (after-lb-or-comma t)
9144 after-comma tt elems pn
9145 (continue t))
9146 (unless js2-is-in-lhs
9147 (js2-push-scope (make-js2-scope))) ; for array comp
9148 (while continue
9149 (setq tt (js2-peek-token))
9150 (cond
9151 ;; comma
9152 ((= tt js2-COMMA)
9153 (js2-consume-token)
9154 (setq after-comma js2-token-end)
9155 (if (not after-lb-or-comma)
9156 (setq after-lb-or-comma t)
9157 (push nil elems)))
9158 ;; end of array
9159 ((or (= tt js2-RB)
9160 (= tt js2-EOF)) ; prevent infinite loop
9161 (if (= tt js2-EOF)
9162 (js2-report-error "msg.no.bracket.arg" nil pos)
9163 (js2-consume-token))
9164 (setq continue nil
9165 end js2-token-end
9166 pn (make-js2-array-node :pos pos
9167 :len (- js2-ts-cursor pos)
9168 :elems (nreverse elems)))
9169 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9170 (when (and after-comma (not js2-is-in-lhs))
9171 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9172 pos elems after-comma)))
9173 ;; destructuring binding
9174 (js2-is-in-lhs
9175 (push (if (or (= tt js2-LC)
9176 (= tt js2-LB)
9177 (= tt js2-NAME))
9178 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9179 (js2-parse-primary-expr-lhs)
9180 ;; invalid pattern
9181 (js2-consume-token)
9182 (js2-report-error "msg.bad.var")
9183 (make-js2-error-node))
9184 elems)
9185 (setq after-lb-or-comma nil
9186 after-comma nil))
9187 ;; array comp
9188 ((and (>= js2-language-version 170)
9189 (= tt js2-FOR) ; check for array comprehension
9190 (not after-lb-or-comma) ; "for" can't follow a comma
9191 elems ; must have at least 1 element
9192 (not (cdr elems))) ; but no 2nd element
9193 (setf continue nil
9194 pn (js2-parse-array-comprehension (car elems) pos)))
9195
9196 ;; another element
9197 (t
9198 (unless after-lb-or-comma
9199 (js2-report-error "msg.no.bracket.arg"))
9200 (push (js2-parse-assign-expr) elems)
9201 (setq after-lb-or-comma nil
9202 after-comma nil))))
9203 (unless js2-is-in-lhs
9204 (js2-pop-scope))
9205 pn))
9206
9207 (defun js2-parse-array-comprehension (expr pos)
9208 "Parse a JavaScript 1.7 Array Comprehension.
9209 EXPR is the first expression after the opening left-bracket.
9210 POS is the beginning of the LB token preceding EXPR.
9211 We should have just parsed the 'for' keyword before calling this function."
9212 (let (loops loop first prev filter if-pos result)
9213 (while (= (js2-peek-token) js2-FOR)
9214 (let ((prev (car loops))) ; rearrange scope chain
9215 (push (setq loop (js2-parse-array-comp-loop)) loops)
9216 (if prev ; each loop is parent scope to the next one
9217 (setf (js2-scope-parent-scope loop) prev)
9218 ; first loop takes expr scope's parent
9219 (setf (js2-scope-parent-scope (setq first loop))
9220 (js2-scope-parent-scope js2-current-scope)))))
9221 ;; set expr scope's parent to the last loop
9222 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9223 (when (= (js2-peek-token) js2-IF)
9224 (js2-consume-token)
9225 (setq if-pos (- js2-token-beg pos) ; relative
9226 filter (js2-parse-condition)))
9227 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9228 (setq result (make-js2-array-comp-node :pos pos
9229 :len (- js2-ts-cursor pos)
9230 :result expr
9231 :loops (nreverse loops)
9232 :filter (car filter)
9233 :lp (js2-relpos (second filter) pos)
9234 :rp (js2-relpos (third filter) pos)
9235 :if-pos if-pos))
9236 (apply #'js2-node-add-children result expr (car filter)
9237 (js2-array-comp-node-loops result))
9238 (setq js2-current-scope first) ; pop to the first loop
9239 result))
9240
9241 (defun js2-parse-array-comp-loop ()
9242 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9243 Last token peeked should be the initial FOR."
9244 (let ((pos js2-token-beg)
9245 (pn (make-js2-array-comp-loop-node))
9246 tt iter obj foreach-p in-pos each-pos lp rp)
9247 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9248 (js2-push-scope pn)
9249 (unwind-protect
9250 (progn
9251 (when (js2-match-token js2-NAME)
9252 (if (string= js2-ts-string "each")
9253 (progn
9254 (setq foreach-p t
9255 each-pos (- js2-token-beg pos)) ; relative
9256 (js2-record-face 'font-lock-keyword-face))
9257 (js2-report-error "msg.no.paren.for")))
9258 (if (js2-must-match js2-LP "msg.no.paren.for")
9259 (setq lp (- js2-token-beg pos)))
9260 (setq tt (js2-peek-token))
9261 (cond
9262 ((or (= tt js2-LB)
9263 (= tt js2-LC))
9264 ;; handle destructuring assignment
9265 (setq iter (js2-parse-primary-expr-lhs))
9266 (js2-define-destruct-symbols iter js2-LET
9267 'font-lock-variable-name-face t))
9268 ((js2-valid-prop-name-token tt)
9269 (js2-consume-token)
9270 (setq iter (js2-create-name-node)))
9271 (t
9272 (js2-report-error "msg.bad.var")))
9273 ;; Define as a let since we want the scope of the variable to
9274 ;; be restricted to the array comprehension
9275 (if (js2-name-node-p iter)
9276 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9277 (if (js2-must-match js2-IN "msg.in.after.for.name")
9278 (setq in-pos (- js2-token-beg pos)))
9279 (setq obj (js2-parse-expr))
9280 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9281 (setq rp (- js2-token-beg pos)))
9282 (setf (js2-node-pos pn) pos
9283 (js2-node-len pn) (- js2-ts-cursor pos)
9284 (js2-array-comp-loop-node-iterator pn) iter
9285 (js2-array-comp-loop-node-object pn) obj
9286 (js2-array-comp-loop-node-in-pos pn) in-pos
9287 (js2-array-comp-loop-node-each-pos pn) each-pos
9288 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9289 (js2-array-comp-loop-node-lp pn) lp
9290 (js2-array-comp-loop-node-rp pn) rp)
9291 (js2-node-add-children pn iter obj))
9292 (js2-pop-scope))
9293 pn))
9294
9295 (defun js2-parse-object-literal ()
9296 (let ((pos js2-token-beg)
9297 tt elems result after-comma
9298 (continue t))
9299 (while continue
9300 (setq tt (js2-peek-token))
9301 (cond
9302 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9303 ;; {get foo() {...}}, or {set foo(x) {...}}
9304 ((or (js2-valid-prop-name-token tt)
9305 (= tt js2-STRING))
9306 (setq after-comma nil
9307 result (js2-parse-named-prop tt))
9308 (if (and (null result)
9309 (not js2-recover-from-parse-errors))
9310 (setq continue nil)
9311 (push result elems)))
9312 ;; {12: x} or {10.7: x}
9313 ((= tt js2-NUMBER)
9314 (js2-consume-token)
9315 (setq after-comma nil)
9316 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9317 ;; trailing comma
9318 ((= tt js2-RC)
9319 (setq continue nil)
9320 (if after-comma
9321 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9322 pos elems after-comma)))
9323 (t
9324 (js2-report-error "msg.bad.prop")
9325 (unless js2-recover-from-parse-errors
9326 (setq continue nil)))) ; end switch
9327 (if (js2-match-token js2-COMMA)
9328 (setq after-comma js2-token-end)
9329 (setq continue nil))) ; end loop
9330 (js2-must-match js2-RC "msg.no.brace.prop")
9331 (setq result (make-js2-object-node :pos pos
9332 :len (- js2-ts-cursor pos)
9333 :elems (nreverse elems)))
9334 (apply #'js2-node-add-children result (js2-object-node-elems result))
9335 result))
9336
9337 (defun js2-parse-named-prop (tt)
9338 "Parse a name, string, or getter/setter object property.
9339 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9340 (js2-consume-token)
9341 (let ((string-prop (and (= tt js2-STRING)
9342 (make-js2-string-node)))
9343 expr
9344 (ppos js2-token-beg)
9345 (pend js2-token-end)
9346 (name (js2-create-name-node))
9347 (prop js2-ts-string))
9348 (cond
9349 ;; getter/setter prop
9350 ((and (= tt js2-NAME)
9351 (= (js2-peek-token) js2-NAME)
9352 (or (string= prop "get")
9353 (string= prop "set")))
9354 (js2-consume-token)
9355 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9356 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9357 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9358 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9359 ;; abbreviated destructuring bind e.g., {a, b} = c;
9360 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9361 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9362 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9363 ;; assignment but it's difficult because it requires looking ahead of expression.
9364 ((and js2-is-in-lhs
9365 (= tt js2-NAME)
9366 (let ((ctk (js2-peek-token)))
9367 (or (= ctk js2-COMMA)
9368 (= ctk js2-RC)
9369 (js2-valid-prop-name-token ctk))))
9370 name)
9371 ;; regular prop
9372 (t
9373 (prog1
9374 (setq expr (js2-parse-plain-property (or string-prop name)))
9375 (js2-set-face ppos pend
9376 (if (js2-function-node-p
9377 (js2-object-prop-node-right expr))
9378 'font-lock-function-name-face
9379 'font-lock-variable-name-face)
9380 'record))))))
9381
9382 (defun js2-parse-plain-property (prop)
9383 "Parse a non-getter/setter property in an object literal.
9384 PROP is the node representing the property: a number, name or string."
9385 (js2-must-match js2-COLON "msg.no.colon.prop")
9386 (let* ((pos (js2-node-pos prop))
9387 (colon (- js2-token-beg pos))
9388 (expr (js2-parse-assign-expr))
9389 (result (make-js2-object-prop-node
9390 :pos pos
9391 ;; don't include last consumed token in length
9392 :len (- (+ (js2-node-pos expr)
9393 (js2-node-len expr))
9394 pos)
9395 :left prop
9396 :right expr
9397 :op-pos colon)))
9398 (js2-node-add-children result prop expr)
9399 result))
9400
9401 (defun js2-parse-getter-setter-prop (pos prop get-p)
9402 "Parse getter or setter property in an object literal.
9403 JavaScript syntax is:
9404
9405 { get foo() {...}, set foo(x) {...} }
9406
9407 and expression closure style is also supported
9408
9409 { get foo() x, set foo(x) _x = x }
9410
9411 POS is the start position of the `get' or `set' keyword.
9412 PROP is the `js2-name-node' representing the property name.
9413 GET-P is non-nil if the keyword was `get'."
9414 (let ((type (if get-p js2-GET js2-SET))
9415 result end
9416 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9417 ;; it has to be an anonymous function, as we already parsed the name
9418 (if (/= (js2-node-type fn) js2-FUNCTION)
9419 (js2-report-error "msg.bad.prop")
9420 (if (plusp (length (js2-function-name fn)))
9421 (js2-report-error "msg.bad.prop")))
9422 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9423 (setq end (js2-node-end fn)
9424 result (make-js2-getter-setter-node :type type
9425 :pos pos
9426 :len (- end pos)
9427 :left prop
9428 :right fn))
9429 (js2-node-add-children result prop fn)
9430 result))
9431
9432 (defun js2-create-name-node (&optional check-activation-p token)
9433 "Create a name node using the token info from last scanned name.
9434 In some cases we need to either synthesize a name node, or we lost
9435 the name token information by peeking. If the TOKEN parameter is
9436 not `js2-NAME', then we use the token info saved in instance vars."
9437 (let ((beg js2-token-beg)
9438 (s js2-ts-string)
9439 name)
9440 (when (/= js2-current-token js2-NAME)
9441 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9442 s js2-prev-name-token-string
9443 js2-prev-name-token-start nil
9444 js2-prev-name-token-string nil))
9445 (setq name (make-js2-name-node :pos beg
9446 :name s
9447 :len (length s)))
9448 (if check-activation-p
9449 (js2-check-activation-name s (or token js2-NAME)))
9450 name))
9451
9452 ;;; Indentation support
9453
9454 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9455 ;; Karl cleverly deduces that the desired indentation level is often a
9456 ;; function of paren/bracket/brace nesting depth, which can be determined
9457 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9458 ;; then does some equally clever checks to see if we're in the context of a
9459 ;; substatement of a possibly braceless statement keyword such as if, while,
9460 ;; or finally. This approach yields pretty good results.
9461
9462 ;; The indenter is often "wrong", however, and needs to be overridden.
9463 ;; The right long-term solution is probably to emulate (or integrate
9464 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9465 ;; parse tree from `js2-parse' is present, which is not true at the
9466 ;; moment the user is typing, computing indentation is still thousands
9467 ;; of lines of code to handle every possible syntactic edge case.
9468
9469 ;; In the meantime, the compromise solution is that we offer a "bounce
9470 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9471 ;; current line indent among various likely guess points. This approach
9472 ;; is far from perfect, but should at least make it slightly easier to
9473 ;; move the line towards its desired indentation when manually
9474 ;; overriding Karl's heuristic nesting guesser.
9475
9476 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9477 ;; extensions such as `let' and Array comprehensions. Major kudos to
9478 ;; Karl for coming up with the initial approach, which packs a lot of
9479 ;; punch for so little code.
9480
9481 (defconst js2-possibly-braceless-keywords-re
9482 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9483 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9484 "try" "while" "with" "let")))
9485 "Regular expression matching keywords that are optionally
9486 followed by an opening brace.")
9487
9488 (defconst js2-indent-operator-re
9489 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9490 (regexp-opt '("in" "instanceof") 'words))
9491 "Regular expression matching operators that affect indentation
9492 of continued expressions.")
9493
9494 (defconst js2-declaration-keyword-re
9495 (regexp-opt '("var" "let" "const") 'words)
9496 "Regular expression matching variable declaration keywords.")
9497
9498 ;; This function has horrible results if you're typing an array
9499 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9500 ;; in conjunction with electric-indent, so just disabling it.
9501 (defsubst js2-code-at-bol-p ()
9502 "Return t if the first character on line is non-whitespace."
9503 nil)
9504
9505 (defun js2-insert-and-indent (key)
9506 "Run command bound to KEY and indent current line.
9507 Runs the command bound to KEY in the global keymap and indents
9508 the current line."
9509 (interactive (list (this-command-keys)))
9510 (let ((cmd (lookup-key (current-global-map) key)))
9511 (if (commandp cmd)
9512 (call-interactively cmd)))
9513 ;; don't do the electric keys inside comments or strings,
9514 ;; and don't do bounce-indent with them.
9515 (let ((parse-state (syntax-ppss (point)))
9516 (js2-bounce-indent-p (js2-code-at-bol-p)))
9517 (unless (or (nth 3 parse-state)
9518 (nth 4 parse-state))
9519 (indent-according-to-mode))))
9520
9521 (defun js2-re-search-forward-inner (regexp &optional bound count)
9522 "Auxiliary function for `js2-re-search-forward'."
9523 (let (parse saved-point)
9524 (while (> count 0)
9525 (re-search-forward regexp bound)
9526 (setq parse (if saved-point
9527 (parse-partial-sexp saved-point (point))
9528 (syntax-ppss (point))))
9529 (cond ((nth 3 parse)
9530 (re-search-forward
9531 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9532 (save-excursion (end-of-line) (point)) t))
9533 ((nth 7 parse)
9534 (forward-line))
9535 ((or (nth 4 parse)
9536 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9537 (re-search-forward "\\*/"))
9538 (t
9539 (setq count (1- count))))
9540 (setq saved-point (point))))
9541 (point))
9542
9543 (defun js2-re-search-forward (regexp &optional bound noerror count)
9544 "Search forward but ignore strings and comments.
9545 Invokes `re-search-forward' but treats the buffer as if strings
9546 and comments have been removed."
9547 (let ((saved-point (point))
9548 (search-expr
9549 (cond ((null count)
9550 '(js2-re-search-forward-inner regexp bound 1))
9551 ((< count 0)
9552 '(js2-re-search-backward-inner regexp bound (- count)))
9553 ((> count 0)
9554 '(js2-re-search-forward-inner regexp bound count)))))
9555 (condition-case err
9556 (eval search-expr)
9557 (search-failed
9558 (goto-char saved-point)
9559 (unless noerror
9560 (error (error-message-string err)))))))
9561
9562 (defun js2-re-search-backward-inner (regexp &optional bound count)
9563 "Auxiliary function for `js2-re-search-backward'."
9564 (let (parse)
9565 (while (> count 0)
9566 (re-search-backward regexp bound)
9567 (setq parse (syntax-ppss (point)))
9568 (cond ((nth 3 parse)
9569 (re-search-backward
9570 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9571 (line-beginning-position) t))
9572 ((nth 7 parse)
9573 (goto-char (nth 8 parse)))
9574 ((or (nth 4 parse)
9575 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9576 (re-search-backward "/\\*"))
9577 (t
9578 (setq count (1- count))))))
9579 (point))
9580
9581 (defun js2-re-search-backward (regexp &optional bound noerror count)
9582 "Search backward but ignore strings and comments.
9583 Invokes `re-search-backward' but treats the buffer as if strings
9584 and comments have been removed."
9585 (let ((saved-point (point))
9586 (search-expr
9587 (cond ((null count)
9588 '(js2-re-search-backward-inner regexp bound 1))
9589 ((< count 0)
9590 '(js2-re-search-forward-inner regexp bound (- count)))
9591 ((> count 0)
9592 '(js2-re-search-backward-inner regexp bound count)))))
9593 (condition-case err
9594 (eval search-expr)
9595 (search-failed
9596 (goto-char saved-point)
9597 (unless noerror
9598 (error (error-message-string err)))))))
9599
9600 (defun js2-looking-at-operator-p ()
9601 "Return non-nil if text after point is a non-comma operator."
9602 (and (looking-at js2-indent-operator-re)
9603 (or (not (looking-at ":"))
9604 (save-excursion
9605 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9606 (looking-at "?"))))))
9607
9608 (defun js2-continued-expression-p ()
9609 "Return non-nil if the current line continues an expression."
9610 (save-excursion
9611 (back-to-indentation)
9612 (or (js2-looking-at-operator-p)
9613 (when (js2-re-search-backward "\n" nil t) ;; comment
9614 (skip-chars-backward " \t")
9615 (backward-char)
9616 (when (js2-looking-at-operator-p)
9617 (backward-char)
9618 (not (looking-at "\\*\\|++\\|--\\|/[/*]")))))))
9619
9620 (defun js2-end-of-do-while-loop-p ()
9621 "Return non-nil if word after point is `while' of a do-while
9622 statement, else returns nil. A braceless do-while statement
9623 spanning several lines requires that the start of the loop is
9624 indented to the same column as the current line."
9625 (interactive)
9626 (save-excursion
9627 (when (looking-at "\\s-*\\<while\\>")
9628 (if (save-excursion
9629 (skip-chars-backward "[ \t\n]*}")
9630 (looking-at "[ \t\n]*}"))
9631 (save-excursion
9632 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9633 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9634 (or (looking-at "\\<do\\>")
9635 (let ((saved-indent (current-indentation)))
9636 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9637 (/= (current-indentation) saved-indent)))
9638 (and (looking-at "[ \t]*\\<do\\>")
9639 (not (js2-re-search-forward
9640 "\\<while\\>" (point-at-eol) t))
9641 (= (current-indentation) saved-indent))))))))
9642
9643 (defun js2-multiline-decl-indentation ()
9644 "Returns the declaration indentation column if the current line belongs
9645 to a multiline declaration statement. All declarations are lined up vertically:
9646
9647 var a = 10,
9648 b = 20,
9649 c = 30;
9650
9651 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9652 assigned expression is a function or array/object literal, it will be indented
9653 differently:
9654
9655 var o = { var bar = 2,
9656 foo: 3 o = {
9657 }, foo: 3
9658 bar = 2; };
9659 "
9660 (let (forward-sexp-function ; use Lisp version
9661 at-opening-bracket)
9662 (save-excursion
9663 (back-to-indentation)
9664 (when (not (looking-at js2-declaration-keyword-re))
9665 (when (looking-at js2-indent-operator-re)
9666 (goto-char (match-end 0))) ; continued expressions are ok
9667 (while (and (not at-opening-bracket)
9668 (not (bobp))
9669 (let ((pos (point)))
9670 (save-excursion
9671 (js2-backward-sws)
9672 (or (eq (char-before) ?,)
9673 (and (not (eq (char-before) ?\;))
9674 (and
9675 (prog2 (skip-chars-backward "[[:punct:]]")
9676 (looking-at js2-indent-operator-re)
9677 (js2-backward-sws))
9678 (not (eq (char-before) ?\;))))
9679 (js2-same-line pos)))))
9680 (condition-case err
9681 (backward-sexp)
9682 (scan-error (setq at-opening-bracket t))))
9683 (when (looking-at js2-declaration-keyword-re)
9684 (- (1+ (match-end 0)) (point-at-bol)))))))
9685
9686 (defun js2-ctrl-statement-indentation ()
9687 "Return the proper indentation of current line if it is a control statement.
9688 Returns an indentation if this line starts the body of a control
9689 statement without braces, else returns nil."
9690 (let (forward-sexp-function)
9691 (save-excursion
9692 (back-to-indentation)
9693 (when (and (not (js2-same-line (point-min)))
9694 (not (looking-at "{"))
9695 (js2-re-search-backward "[[:graph:]]" nil t)
9696 (not (looking-at "[{([]"))
9697 (progn
9698 (forward-char)
9699 (when (= (char-before) ?\))
9700 ;; scan-sexps sometimes throws an error
9701 (ignore-errors (backward-sexp))
9702 (skip-chars-backward " \t" (point-at-bol)))
9703 (let ((pt (point)))
9704 (back-to-indentation)
9705 (and (looking-at js2-possibly-braceless-keywords-re)
9706 (= (match-end 0) pt)
9707 (not (js2-end-of-do-while-loop-p))))))
9708 (+ (current-indentation) js2-basic-offset)))))
9709
9710 (defun js2-indent-in-array-comp (parse-status)
9711 "Return non-nil if we think we're in an array comprehension.
9712 In particular, return the buffer position of the first `for' kwd."
9713 (let ((bracket (nth 1 parse-status))
9714 (end (point)))
9715 (when bracket
9716 (save-excursion
9717 (goto-char bracket)
9718 (when (looking-at "\\[")
9719 (forward-char 1)
9720 (js2-forward-sws)
9721 (if (looking-at "[[{]")
9722 (let (forward-sexp-function) ; use Lisp version
9723 (forward-sexp) ; skip destructuring form
9724 (js2-forward-sws)
9725 (if (and (/= (char-after) ?,) ; regular array
9726 (looking-at "for"))
9727 (match-beginning 0)))
9728 ;; to skip arbitrary expressions we need the parser,
9729 ;; so we'll just guess at it.
9730 (if (and (> end (point)) ; not empty literal
9731 (re-search-forward "[^,]]* \\(for\\) " end t)
9732 ;; not inside a string literal
9733 (not (nth 3 (parse-partial-sexp bracket (point)))))
9734 (match-beginning 1))))))))
9735
9736 (defun js2-array-comp-indentation (parse-status for-kwd)
9737 (if (js2-same-line for-kwd)
9738 ;; first continuation line
9739 (save-excursion
9740 (goto-char (nth 1 parse-status))
9741 (forward-char 1)
9742 (skip-chars-forward " \t")
9743 (current-column))
9744 (save-excursion
9745 (goto-char for-kwd)
9746 (current-column))))
9747
9748 (defun js2-proper-indentation (parse-status)
9749 "Return the proper indentation for the current line."
9750 (save-excursion
9751 (back-to-indentation)
9752 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9753 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9754 (continued-expr-p (js2-continued-expression-p))
9755 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
9756 (js2-multiline-decl-indentation)))
9757 (bracket (nth 1 parse-status))
9758 beg)
9759 (cond
9760 ;; indent array comprehension continuation lines specially
9761 ((and bracket
9762 (not (js2-same-line bracket))
9763 (setq beg (js2-indent-in-array-comp parse-status))
9764 (>= (point) (save-excursion
9765 (goto-char beg)
9766 (point-at-bol)))) ; at or after first loop?
9767 (js2-array-comp-indentation parse-status beg))
9768
9769 (ctrl-stmt-indent)
9770
9771 ((and declaration-indent continued-expr-p)
9772 (+ declaration-indent js2-basic-offset))
9773
9774 (declaration-indent)
9775
9776 (bracket
9777 (goto-char bracket)
9778 (cond
9779 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9780 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9781 (when (save-excursion (skip-chars-backward " \t)")
9782 (looking-at ")"))
9783 (backward-list))
9784 (if (and (nth 1 p)
9785 (not js2-consistent-level-indent-inner-bracket-p))
9786 (progn (goto-char (1+ (nth 1 p)))
9787 (skip-chars-forward " \t"))
9788 (back-to-indentation)
9789 (when (and js2-pretty-multiline-decl-indentation-p
9790 js2-always-indent-assigned-expr-in-decls-p
9791 (looking-at js2-declaration-keyword-re))
9792 (goto-char (1+ (match-end 0)))))
9793 (cond (same-indent-p
9794 (current-column))
9795 (continued-expr-p
9796 (+ (current-column) (* 2 js2-basic-offset)))
9797 (t
9798 (+ (current-column) js2-basic-offset)))))
9799 (t
9800 (unless same-indent-p
9801 (forward-char)
9802 (skip-chars-forward " \t"))
9803 (current-column))))
9804
9805 (continued-expr-p js2-basic-offset)
9806
9807 (t 0)))))
9808
9809 (defun js2-lineup-comment (parse-status)
9810 "Indent a multi-line block comment continuation line."
9811 (let* ((beg (nth 8 parse-status))
9812 (first-line (js2-same-line beg))
9813 (offset (save-excursion
9814 (goto-char beg)
9815 (if (looking-at "/\\*")
9816 (+ 1 (current-column))
9817 0))))
9818 (unless first-line
9819 (indent-line-to offset))))
9820
9821 (defun js2-backward-sws ()
9822 "Move backward through whitespace and comments."
9823 (interactive)
9824 (while (forward-comment -1)))
9825
9826 (defun js2-forward-sws ()
9827 "Move forward through whitespace and comments."
9828 (interactive)
9829 (while (forward-comment 1)))
9830
9831 (defun js2-current-indent (&optional pos)
9832 "Return column of indentation on current line.
9833 If POS is non-nil, go to that point and return indentation for that line."
9834 (save-excursion
9835 (if pos
9836 (goto-char pos))
9837 (back-to-indentation)
9838 (current-column)))
9839
9840 (defun js2-arglist-close ()
9841 "Return non-nil if we're on a line beginning with a close-paren/brace."
9842 (save-excursion
9843 (goto-char (point-at-bol))
9844 (js2-forward-sws)
9845 (looking-at "[])}]")))
9846
9847 (defun js2-indent-looks-like-label-p ()
9848 (goto-char (point-at-bol))
9849 (js2-forward-sws)
9850 (looking-at (concat js2-mode-identifier-re ":")))
9851
9852 (defun js2-indent-in-objlit-p (parse-status)
9853 "Return non-nil if this looks like an object-literal entry."
9854 (let ((start (nth 1 parse-status)))
9855 (and
9856 start
9857 (save-excursion
9858 (and (zerop (forward-line -1))
9859 (not (< (point) start)) ; crossed a {} boundary
9860 (js2-indent-looks-like-label-p)))
9861 (save-excursion
9862 (js2-indent-looks-like-label-p)))))
9863
9864 ;; If prev line looks like foobar({ then we're passing an object
9865 ;; literal to a function call, and people pretty much always want to
9866 ;; de-dent back to the previous line, so move the 'basic-offset'
9867 ;; position to the front.
9868 (defun js2-indent-objlit-arg-p (parse-status)
9869 (save-excursion
9870 (back-to-indentation)
9871 (js2-backward-sws)
9872 (and (eq (1- (point)) (nth 1 parse-status))
9873 (eq (char-before) ?{)
9874 (progn
9875 (forward-char -1)
9876 (skip-chars-backward " \t")
9877 (eq (char-before) ?\()))))
9878
9879 (defun js2-indent-case-block-p ()
9880 (save-excursion
9881 (back-to-indentation)
9882 (js2-backward-sws)
9883 (goto-char (point-at-bol))
9884 (skip-chars-forward " \t")
9885 (looking-at "case\\s-.+:")))
9886
9887 (defun js2-syntax-bol ()
9888 "Return the point at the first non-whitespace char on the line.
9889 Returns `point-at-bol' if the line is empty."
9890 (save-excursion
9891 (beginning-of-line)
9892 (skip-chars-forward " \t")
9893 (point)))
9894
9895 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9896 "Cycle among alternate computed indentation positions.
9897 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9898 of the buffer to the current point. NORMAL-COL is the indentation
9899 column computed by the heuristic guesser based on current paren,
9900 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9901 in reverse."
9902 (let ((cur-indent (js2-current-indent))
9903 (old-buffer-undo-list buffer-undo-list)
9904 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9905 (current-line (save-excursion
9906 (forward-line 0) ; move to bol
9907 (1+ (count-lines (point-min) (point)))))
9908 positions pos main-pos anchor arglist-cont same-indent
9909 prev-line-col basic-offset computed-pos)
9910 ;; temporarily don't record undo info, if user requested this
9911 (when js2-mode-indent-inhibit-undo
9912 (setq buffer-undo-list t))
9913 (unwind-protect
9914 (progn
9915 ;; First likely point: indent from beginning of previous code line
9916 (push (setq basic-offset
9917 (+ (save-excursion
9918 (back-to-indentation)
9919 (js2-backward-sws)
9920 (back-to-indentation)
9921 (setq prev-line-col (current-column)))
9922 js2-basic-offset))
9923 positions)
9924
9925 ;; (First + epsilon) likely point: indent 2x from beginning of
9926 ;; previous code line. Google does it this way.
9927 (push (setq basic-offset
9928 (+ (save-excursion
9929 (back-to-indentation)
9930 (js2-backward-sws)
9931 (back-to-indentation)
9932 (setq prev-line-col (current-column)))
9933 (* 2 js2-basic-offset)))
9934 positions)
9935
9936 ;; Second likely point: indent from assign-expr RHS. This
9937 ;; is just a crude guess based on finding " = " on the previous
9938 ;; line containing actual code.
9939 (setq pos (save-excursion
9940 (forward-line -1)
9941 (goto-char (point-at-bol))
9942 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9943 (point-at-eol) t)
9944 (goto-char (match-end 1))
9945 (skip-chars-forward " \t\r\n")
9946 (current-column))))
9947 (when pos
9948 (incf pos js2-basic-offset)
9949 (push pos positions))
9950
9951 ;; Third likely point: same indent as previous line of code.
9952 ;; Make it the first likely point if we're not on an
9953 ;; arglist-close line and previous line ends in a comma, or
9954 ;; both this line and prev line look like object-literal
9955 ;; elements.
9956 (setq pos (save-excursion
9957 (goto-char (point-at-bol))
9958 (js2-backward-sws)
9959 (back-to-indentation)
9960 (prog1
9961 (current-column)
9962 ;; while we're here, look for trailing comma
9963 (if (save-excursion
9964 (goto-char (point-at-eol))
9965 (js2-backward-sws)
9966 (eq (char-before) ?,))
9967 (setq arglist-cont (1- (point)))))))
9968 (when pos
9969 (if (and (or arglist-cont
9970 (js2-indent-in-objlit-p parse-status))
9971 (not (js2-arglist-close)))
9972 (setq same-indent pos))
9973 (push pos positions))
9974
9975 ;; Fourth likely point: first preceding code with less indentation.
9976 ;; than the immediately preceding code line.
9977 (setq pos (save-excursion
9978 (back-to-indentation)
9979 (js2-backward-sws)
9980 (back-to-indentation)
9981 (setq anchor (current-column))
9982 (while (and (zerop (forward-line -1))
9983 (>= (progn
9984 (back-to-indentation)
9985 (current-column))
9986 anchor)))
9987 (setq pos (current-column))))
9988 (push pos positions)
9989
9990 ;; nesting-heuristic position, main by default
9991 (push (setq main-pos normal-col) positions)
9992
9993 ;; delete duplicates and sort positions list
9994 (setq positions (sort (delete-dups positions) '<))
9995
9996 ;; comma-list continuation lines: prev line indent takes precedence
9997 (if same-indent
9998 (setq main-pos same-indent))
9999
10000 ;; common special cases where we want to indent in from previous line
10001 (if (or (js2-indent-case-block-p)
10002 (js2-indent-objlit-arg-p parse-status))
10003 (setq main-pos basic-offset))
10004
10005 ;; if bouncing backwards, reverse positions list
10006 (if backwards
10007 (setq positions (reverse positions)))
10008
10009 ;; record whether we're already sitting on one of the alternatives
10010 (setq pos (member cur-indent positions))
10011
10012 (cond
10013 ;; case 0: we're one one of the alternatives and this is the
10014 ;; first time they've pressed TAB on this line (best-guess).
10015 ((and js2-mode-indent-ignore-first-tab
10016 pos
10017 ;; first time pressing TAB on this line?
10018 (not (eq js2-mode-last-indented-line current-line)))
10019 ;; do nothing
10020 (setq computed-pos nil))
10021 ;; case 1: only one computed position => use it
10022 ((null (cdr positions))
10023 (setq computed-pos 0))
10024 ;; case 2: not on any of the computed spots => use main spot
10025 ((not pos)
10026 (setq computed-pos (js2-position main-pos positions)))
10027 ;; case 3: on last position: cycle to first position
10028 ((null (cdr pos))
10029 (setq computed-pos 0))
10030 ;; case 4: on intermediate position: cycle to next position
10031 (t
10032 (setq computed-pos (js2-position (second pos) positions))))
10033
10034 ;; see if any hooks want to indent; otherwise we do it
10035 (loop with result = nil
10036 for hook in js2-indent-hook
10037 while (null result)
10038 do
10039 (setq result (funcall hook positions computed-pos))
10040 finally do
10041 (unless (or result (null computed-pos))
10042 (indent-line-to (nth computed-pos positions)))))
10043
10044 ;; finally
10045 (if js2-mode-indent-inhibit-undo
10046 (setq buffer-undo-list old-buffer-undo-list))
10047 ;; see commentary for `js2-mode-last-indented-line'
10048 (setq js2-mode-last-indented-line current-line))))
10049
10050 (defun js2-indent-bounce-backwards ()
10051 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10052 cycles between the computed indentation positions in reverse order."
10053 (interactive)
10054 (js2-indent-line t))
10055
10056 (defun js2-1-line-comment-continuation-p ()
10057 "Return t if we're in a 1-line comment continuation.
10058 If so, we don't ever want to use bounce-indent."
10059 (save-excursion
10060 (and (progn
10061 (forward-line 0)
10062 (looking-at "\\s-*//"))
10063 (progn
10064 (forward-line -1)
10065 (forward-line 0)
10066 (when (looking-at "\\s-*$")
10067 (js2-backward-sws)
10068 (forward-line 0))
10069 (looking-at "\\s-*//")))))
10070
10071 (defun js2-indent-line (&optional bounce-backwards)
10072 "Indent the current line as JavaScript source text."
10073 (interactive)
10074 (let (parse-status current-indent offset indent-col moved
10075 ;; Don't whine about errors/warnings when we're indenting.
10076 ;; This has to be set before calling parse-partial-sexp below.
10077 (inhibit-point-motion-hooks t))
10078 (setq parse-status (save-excursion
10079 (syntax-ppss (point-at-bol)))
10080 offset (- (point) (save-excursion
10081 (back-to-indentation)
10082 (point))))
10083 (js2-with-underscore-as-word-syntax
10084 (if (nth 4 parse-status)
10085 (js2-lineup-comment parse-status)
10086 (setq indent-col (js2-proper-indentation parse-status))
10087 ;; See comments below about `js2-mode-last-indented-line'.
10088 (cond
10089 ;; bounce-indenting is disabled during electric-key indent.
10090 ;; It doesn't work well on first line of buffer.
10091 ((and js2-bounce-indent-p
10092 (not (js2-same-line (point-min)))
10093 (not (js2-1-line-comment-continuation-p)))
10094 (js2-bounce-indent indent-col parse-status bounce-backwards))
10095 ;; just indent to the guesser's likely spot
10096 (t (indent-line-to indent-col)))
10097 (when (plusp offset)
10098 (forward-char offset))))))
10099
10100 (defun js2-indent-region (start end)
10101 "Indent the region, but don't use bounce indenting."
10102 (let ((js2-bounce-indent-p nil)
10103 (indent-region-function nil)
10104 (after-change-functions (remq 'js2-mode-edit
10105 after-change-functions)))
10106 (indent-region start end nil) ; nil for byte-compiler
10107 (js2-mode-edit start end (- end start))))
10108
10109 (defvar js2-minor-mode-map
10110 (let ((map (make-sparse-keymap)))
10111 (define-key map (kbd "C-c C-`") #'js2-next-error)
10112 (define-key map [mouse-1] #'js2-mode-show-node)
10113 map)
10114 "Keymap used when `js2-minor-mode' is active.")
10115
10116 (define-minor-mode js2-minor-mode
10117 "Minor mode for running js2 as a background linter.
10118 This allows you to use a different major mode for JavaScript editing,
10119 such as `espresso-mode', while retaining the asynchronous error/warning
10120 highlighting features of `js2-mode'."
10121 :group 'js2-mode
10122 :lighter " js-lint"
10123 (if js2-minor-mode
10124 (js2-minor-mode-enter)
10125 (js2-minor-mode-exit)))
10126
10127 (defun js2-minor-mode-enter ()
10128 "Initialization for `js2-minor-mode'."
10129 (set (make-local-variable 'max-lisp-eval-depth)
10130 (max max-lisp-eval-depth 3000))
10131 (setq next-error-function #'js2-next-error)
10132 (setq js2-default-externs
10133 (append js2-ecma-262-externs
10134 (if js2-include-browser-externs js2-browser-externs)
10135 (if js2-include-gears-externs js2-gears-externs)
10136 (if js2-include-rhino-externs js2-rhino-externs)))
10137 ;; Experiment: make reparse-delay longer for longer files.
10138 (if (plusp js2-dynamic-idle-timer-adjust)
10139 (setq js2-idle-timer-delay
10140 (* js2-idle-timer-delay
10141 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10142 (setq js2-mode-buffer-dirty-p t
10143 js2-mode-parsing nil
10144 js2-highlight-level 0) ; no syntax highlighting
10145 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10146 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10147 (js2-reparse))
10148
10149 (defun js2-minor-mode-exit ()
10150 "Turn off `js2-minor-mode'."
10151 (setq next-error-function nil)
10152 (remove-hook 'after-change-functions #'js2-mode-edit t)
10153 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10154 (when js2-mode-node-overlay
10155 (delete-overlay js2-mode-node-overlay)
10156 (setq js2-mode-node-overlay nil))
10157 (js2-remove-overlays)
10158 (setq js2-mode-ast nil))
10159
10160 (defun js2-display-error-list ()
10161 "Display a navigable buffer listing parse errors/warnings."
10162 (interactive)
10163 (if (not (js2-have-errors-p))
10164 (message "No errors")
10165 (let ((srcbuf (current-buffer))
10166 (errbuf (get-buffer-create "*js-lint*"))
10167 (errs (js2-errors-and-warnings)))
10168 (setq errs (sort errs (lambda (e1 e2)
10169 (funcall '< (second e1) (second e2)))))
10170 (with-current-buffer errbuf
10171 (let ((inhibit-read-only t))
10172 (erase-buffer)
10173 (dolist (err errs)
10174 (insert (format "%s\n" err)))
10175 (pop-to-buffer errbuf))))))
10176
10177 ;;;###autoload
10178 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10179 ;; FIXME: Should derive from js-mode.
10180 "Major mode for editing JavaScript code."
10181 (setq comment-start "//" ; used by comment-region; don't change it
10182 comment-end "")
10183 (set (make-local-variable 'max-lisp-eval-depth)
10184 (max max-lisp-eval-depth 3000))
10185 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10186 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10187 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10188 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10189 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10190 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10191 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10192 ;; for characters inside regexp literals.
10193 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10194 ;; this is necessary to make `show-paren-function' work properly
10195 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10196 ;; needed for M-x rgrep, among other things
10197 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10198
10199 (set (make-local-variable 'electric-indent-chars)
10200 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10201 electric-indent-chars))
10202 (set (make-local-variable 'electric-layout-rules)
10203 '((?\; . after) (?\{ . after) (?\} . before)))
10204
10205 ;; some variables needed by cc-engine for paragraph-fill, etc.
10206 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10207 c-comment-start-regexp "/[*/]\\|\\s|"
10208 c-line-comment-starter "//"
10209 c-paragraph-start js2-paragraph-start
10210 c-paragraph-separate "$"
10211 comment-start-skip js2-comment-start-skip
10212 c-syntactic-ws-start js2-syntactic-ws-start
10213 c-syntactic-ws-end js2-syntactic-ws-end
10214 c-syntactic-eol js2-syntactic-eol)
10215
10216 (let ((c-buffer-is-cc-mode t))
10217 ;; Copied from `js-mode'. Also see Bug#6071.
10218 (make-local-variable 'paragraph-start)
10219 (make-local-variable 'paragraph-separate)
10220 (make-local-variable 'paragraph-ignore-fill-prefix)
10221 (make-local-variable 'adaptive-fill-mode)
10222 (make-local-variable 'adaptive-fill-regexp)
10223 (c-setup-paragraph-variables))
10224
10225 (setq js2-default-externs
10226 (append js2-ecma-262-externs
10227 (if js2-include-browser-externs js2-browser-externs)
10228 (if js2-include-gears-externs js2-gears-externs)
10229 (if js2-include-rhino-externs js2-rhino-externs)))
10230
10231 (setq font-lock-defaults '(nil t))
10232
10233 ;; Experiment: make reparse-delay longer for longer files.
10234 (when (plusp js2-dynamic-idle-timer-adjust)
10235 (setq js2-idle-timer-delay
10236 (* js2-idle-timer-delay
10237 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10238
10239 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10240 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10241 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10242 (imenu-add-to-menubar (concat "IM-" mode-name))
10243 (add-to-invisibility-spec '(js2-outline . t))
10244 (set (make-local-variable 'line-move-ignore-invisible) t)
10245 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10246
10247 (if (fboundp 'run-mode-hooks)
10248 (run-mode-hooks 'js2-mode-hook)
10249 (run-hooks 'js2-mode-hook))
10250
10251 (setq js2-mode-functions-hidden nil
10252 js2-mode-comments-hidden nil
10253 js2-mode-buffer-dirty-p t
10254 js2-mode-parsing nil)
10255 (js2-reparse))
10256
10257 (defun js2-mode-exit ()
10258 "Exit `js2-mode' and clean up."
10259 (interactive)
10260 (when js2-mode-node-overlay
10261 (delete-overlay js2-mode-node-overlay)
10262 (setq js2-mode-node-overlay nil))
10263 (js2-remove-overlays)
10264 (setq js2-mode-ast nil)
10265 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10266 (remove-from-invisibility-spec '(js2-outline . t))
10267 (js2-mode-show-all)
10268 (with-silent-modifications
10269 (js2-clear-face (point-min) (point-max))))
10270
10271 (defun js2-mode-reset-timer ()
10272 "Cancel any existing parse timer and schedule a new one."
10273 (if js2-mode-parse-timer
10274 (cancel-timer js2-mode-parse-timer))
10275 (setq js2-mode-parsing nil)
10276 (setq js2-mode-parse-timer
10277 (run-with-idle-timer js2-idle-timer-delay nil
10278 #'js2-mode-idle-reparse (current-buffer))))
10279
10280 (defun js2-mode-idle-reparse (buffer)
10281 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10282 it to be reparsed when the buffer is selected."
10283 (if (eq buffer (current-buffer))
10284 (js2-reparse)
10285 ;; reparse when the buffer is selected again
10286 (with-current-buffer buffer
10287 (add-hook 'window-configuration-change-hook
10288 #'js2-mode-idle-reparse-inner
10289 nil t))))
10290
10291 (defun js2-mode-idle-reparse-inner ()
10292 (remove-hook 'window-configuration-change-hook
10293 #'js2-mode-idle-reparse-inner
10294 t)
10295 (js2-reparse))
10296
10297 (defun js2-mode-edit (beg end len)
10298 "Schedule a new parse after buffer is edited.
10299 Buffer edit spans from BEG to END and is of length LEN."
10300 (setq js2-mode-buffer-dirty-p t)
10301 (js2-mode-hide-overlay)
10302 (js2-mode-reset-timer))
10303
10304 (defun js2-minor-mode-edit (beg end len)
10305 "Callback for buffer edits in `js2-mode'.
10306 Schedules a new parse after buffer is edited.
10307 Buffer edit spans from BEG to END and is of length LEN."
10308 (setq js2-mode-buffer-dirty-p t)
10309 (js2-mode-hide-overlay)
10310 (js2-mode-reset-timer))
10311
10312 (defun js2-reparse (&optional force)
10313 "Re-parse current buffer after user finishes some data entry.
10314 If we get any user input while parsing, including cursor motion,
10315 we discard the parse and reschedule it. If FORCE is nil, then the
10316 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10317 (let (time
10318 interrupted-p
10319 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10320 (unless js2-mode-parsing
10321 (setq js2-mode-parsing t)
10322 (unwind-protect
10323 (when (or js2-mode-buffer-dirty-p force)
10324 (js2-remove-overlays)
10325 (with-silent-modifications
10326 (setq js2-mode-buffer-dirty-p nil
10327 js2-mode-fontifications nil
10328 js2-mode-deferred-properties nil)
10329 (if js2-mode-verbose-parse-p
10330 (message "parsing..."))
10331 (setq time
10332 (js2-time
10333 (setq interrupted-p
10334 (catch 'interrupted
10335 (setq js2-mode-ast (js2-parse))
10336 ;; if parsing is interrupted, comments and regex
10337 ;; literals stay ignored by `parse-partial-sexp'
10338 (remove-text-properties (point-min) (point-max)
10339 '(syntax-table))
10340 (js2-mode-apply-deferred-properties)
10341 (js2-mode-remove-suppressed-warnings)
10342 (js2-mode-show-warnings)
10343 (js2-mode-show-errors)
10344 (if (>= js2-highlight-level 1)
10345 (js2-highlight-jsdoc js2-mode-ast))
10346 nil))))
10347 (if interrupted-p
10348 (progn
10349 ;; unfinished parse => try again
10350 (setq js2-mode-buffer-dirty-p t)
10351 (js2-mode-reset-timer))
10352 (if js2-mode-verbose-parse-p
10353 (message "Parse time: %s" time)))))
10354 (setq js2-mode-parsing nil)
10355 (unless interrupted-p
10356 (setq js2-mode-parse-timer nil))))))
10357
10358 (defun js2-mode-show-node ()
10359 "Debugging aid: highlight selected AST node on mouse click."
10360 (interactive)
10361 (let ((node (js2-node-at-point))
10362 beg end)
10363 (when js2-mode-show-overlay
10364 (if (null node)
10365 (message "No node found at location %s" (point))
10366 (setq beg (js2-node-abs-pos node)
10367 end (+ beg (js2-node-len node)))
10368 (if js2-mode-node-overlay
10369 (move-overlay js2-mode-node-overlay beg end)
10370 (setq js2-mode-node-overlay (make-overlay beg end))
10371 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10372 (with-silent-modifications
10373 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10374 (message "%s, parent: %s"
10375 (js2-node-short-name node)
10376 (if (js2-node-parent node)
10377 (js2-node-short-name (js2-node-parent node))
10378 "nil"))))))
10379
10380 (defun js2-mode-hide-overlay (&optional p1 p2)
10381 "Remove the debugging overlay when the point moves.
10382 P1 and P2 are the old and new values of point, respectively."
10383 (when js2-mode-node-overlay
10384 (let ((beg (overlay-start js2-mode-node-overlay))
10385 (end (overlay-end js2-mode-node-overlay)))
10386 ;; Sometimes we're called spuriously.
10387 (unless (and p2
10388 (>= p2 beg)
10389 (<= p2 end))
10390 (with-silent-modifications
10391 (remove-text-properties beg end '(point-left nil)))
10392 (delete-overlay js2-mode-node-overlay)
10393 (setq js2-mode-node-overlay nil)))))
10394
10395 (defun js2-mode-reset ()
10396 "Debugging helper: reset everything."
10397 (interactive)
10398 (js2-mode-exit)
10399 (js2-mode))
10400
10401 (defun js2-mode-show-warn-or-err (e face)
10402 "Highlight a warning or error E with FACE.
10403 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10404 (let* ((key (first e))
10405 (beg (second e))
10406 (end (+ beg (third e)))
10407 ;; Don't inadvertently go out of bounds.
10408 (beg (max (point-min) (min beg (point-max))))
10409 (end (max (point-min) (min end (point-max))))
10410 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10411 (ovl (make-overlay beg end)))
10412 (overlay-put ovl 'font-lock-face face)
10413 (overlay-put ovl 'js2-error t)
10414 (put-text-property beg end 'help-echo (js2-get-msg key))
10415 (put-text-property beg end 'point-entered #'js2-echo-error)))
10416
10417 (defun js2-remove-overlays ()
10418 "Remove overlays from buffer that have a `js2-error' property."
10419 (let ((beg (point-min))
10420 (end (point-max)))
10421 (save-excursion
10422 (dolist (o (overlays-in beg end))
10423 (when (overlay-get o 'js2-error)
10424 (delete-overlay o))))))
10425
10426 (defun js2-error-at-point (&optional pos)
10427 "Return non-nil if there's an error overlay at POS.
10428 Defaults to point."
10429 (loop with pos = (or pos (point))
10430 for o in (overlays-at pos)
10431 thereis (overlay-get o 'js2-error)))
10432
10433 (defun js2-mode-apply-deferred-properties ()
10434 "Apply fontifications and other text properties recorded during parsing."
10435 (when (plusp js2-highlight-level)
10436 ;; We defer clearing faces as long as possible to eliminate flashing.
10437 (js2-clear-face (point-min) (point-max))
10438 ;; Have to reverse the recorded fontifications list so that errors
10439 ;; and warnings overwrite the normal fontifications.
10440 (dolist (f (nreverse js2-mode-fontifications))
10441 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10442 (setq js2-mode-fontifications nil))
10443 (dolist (p js2-mode-deferred-properties)
10444 (apply #'put-text-property p))
10445 (setq js2-mode-deferred-properties nil))
10446
10447 (defun js2-mode-show-errors ()
10448 "Highlight syntax errors."
10449 (when js2-mode-show-parse-errors
10450 (dolist (e (js2-ast-root-errors js2-mode-ast))
10451 (js2-mode-show-warn-or-err e 'js2-error-face))))
10452
10453 (defun js2-mode-remove-suppressed-warnings ()
10454 "Take suppressed warnings out of the AST warnings list.
10455 This ensures that the counts and `next-error' are correct."
10456 (setf (js2-ast-root-warnings js2-mode-ast)
10457 (js2-delete-if
10458 (lambda (e)
10459 (let ((key (caar e)))
10460 (or
10461 (and (not js2-strict-trailing-comma-warning)
10462 (string-match "trailing\\.comma" key))
10463 (and (not js2-strict-cond-assign-warning)
10464 (string= key "msg.equal.as.assign"))
10465 (and js2-missing-semi-one-line-override
10466 (string= key "msg.missing.semi")
10467 (let* ((beg (second e))
10468 (node (js2-node-at-point beg))
10469 (fn (js2-mode-find-parent-fn node))
10470 (body (and fn (js2-function-node-body fn)))
10471 (lc (and body (js2-node-abs-pos body)))
10472 (rc (and lc (+ lc (js2-node-len body)))))
10473 (and fn
10474 (or (null body)
10475 (save-excursion
10476 (goto-char beg)
10477 (and (js2-same-line lc)
10478 (js2-same-line rc))))))))))
10479 (js2-ast-root-warnings js2-mode-ast))))
10480
10481 (defun js2-mode-show-warnings ()
10482 "Highlight strict-mode warnings."
10483 (when js2-mode-show-strict-warnings
10484 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10485 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10486
10487 (defun js2-echo-error (old-point new-point)
10488 "Called by point-motion hooks."
10489 (let ((msg (get-text-property new-point 'help-echo)))
10490 (if (and msg (or (not (current-message))
10491 (string= (current-message) "Quit")))
10492 (message msg))))
10493
10494 (defalias #'js2-echo-help #'js2-echo-error)
10495
10496 (defun js2-line-break (&optional soft)
10497 "Break line at point."
10498 (let ((parse-status (syntax-ppss)))
10499 (cond
10500 ;; Check if we're inside a string.
10501 ((nth 3 parse-status)
10502 (js2-mode-split-string parse-status))
10503 ;; Check if inside a block comment.
10504 ((nth 4 parse-status)
10505 (js2-mode-extend-comment))
10506 (t
10507 (newline)))))
10508
10509 (defun js2-mode-split-string (parse-status)
10510 "Turn a newline in mid-string into a string concatenation.
10511 PARSE-STATUS is as documented in `parse-partial-sexp'."
10512 (let* ((col (current-column))
10513 (quote-char (nth 3 parse-status))
10514 (quote-string (string quote-char))
10515 (string-beg (nth 8 parse-status))
10516 (indent (or
10517 (save-excursion
10518 (back-to-indentation)
10519 (if (looking-at "\\+")
10520 (current-column)))
10521 (save-excursion
10522 (goto-char string-beg)
10523 (if (looking-back "\\+\\s-+")
10524 (goto-char (match-beginning 0)))
10525 (current-column)))))
10526 (insert quote-char "\n")
10527 (indent-to indent)
10528 (insert "+ " quote-string)
10529 (when (eolp)
10530 (insert quote-string)
10531 (backward-char 1))))
10532
10533 (defun js2-mode-extend-comment ()
10534 "Indent the line and, when inside a comment block, add comment prefix."
10535 (let (star single col first-line needs-close)
10536 (save-excursion
10537 (back-to-indentation)
10538 (cond
10539 ((looking-at "\\*[^/]")
10540 (setq star t
10541 col (current-column)))
10542 ((looking-at "/\\*")
10543 (setq star t
10544 first-line t
10545 col (1+ (current-column))))
10546 ((looking-at "//")
10547 (setq single t
10548 col (current-column)))))
10549 ;; Heuristic for whether we need to close the comment:
10550 ;; if we've got a parse error here, assume it's an unterminated
10551 ;; comment.
10552 (setq needs-close
10553 (or
10554 (eq (get-text-property (1- (point)) 'point-entered)
10555 'js2-echo-error)
10556 ;; The heuristic above doesn't work well when we're
10557 ;; creating a comment and there's another one downstream,
10558 ;; as our parser thinks this one ends at the end of the
10559 ;; next one. (You can have a /* inside a js block comment.)
10560 ;; So just close it if the next non-ws char isn't a *.
10561 (and first-line
10562 (eolp)
10563 (save-excursion
10564 (skip-chars-forward " \t\r\n")
10565 (not (eq (char-after) ?*))))))
10566 (insert "\n")
10567 (cond
10568 (star
10569 (indent-to col)
10570 (insert "* ")
10571 (if (and first-line needs-close)
10572 (save-excursion
10573 (insert "\n")
10574 (indent-to col)
10575 (insert "*/"))))
10576 ((and single
10577 (save-excursion
10578 (and (zerop (forward-line 1))
10579 (looking-at "\\s-*//"))))
10580 (indent-to col)
10581 (insert "// "))
10582 ;; don't need to extend the comment after all
10583 (js2-enter-indents-newline
10584 (js2-indent-line)))))
10585
10586 (defun js2-beginning-of-line ()
10587 "Toggles point between bol and first non-whitespace char in line.
10588 Also moves past comment delimiters when inside comments."
10589 (interactive)
10590 (let (node beg)
10591 (cond
10592 ((bolp)
10593 (back-to-indentation))
10594 ((looking-at "//")
10595 (skip-chars-forward "/ \t"))
10596 ((and (eq (char-after) ?*)
10597 (setq node (js2-comment-at-point))
10598 (memq (js2-comment-node-format node) '(jsdoc block))
10599 (save-excursion
10600 (skip-chars-backward " \t")
10601 (bolp)))
10602 (skip-chars-forward "\* \t"))
10603 (t
10604 (goto-char (point-at-bol))))))
10605
10606 (defun js2-end-of-line ()
10607 "Toggles point between eol and last non-whitespace char in line."
10608 (interactive)
10609 (if (eolp)
10610 (skip-chars-backward " \t")
10611 (goto-char (point-at-eol))))
10612
10613 (defsubst js2-mode-inside-string ()
10614 "Return non-nil if inside a string.
10615 Actually returns the quote character that begins the string."
10616 (nth 3 (syntax-ppss)))
10617
10618 (defun js2-mode-inside-comment-or-string ()
10619 "Return non-nil if inside a comment or string."
10620 (or
10621 (let ((comment-start
10622 (save-excursion
10623 (goto-char (point-at-bol))
10624 (if (re-search-forward "//" (point-at-eol) t)
10625 (match-beginning 0)))))
10626 (and comment-start
10627 (<= comment-start (point))))
10628 (let ((parse-state (syntax-ppss)))
10629 (or (nth 3 parse-state)
10630 (nth 4 parse-state)))))
10631
10632
10633 (defun js2-insert-catch-skel (try-pos)
10634 "Complete a try/catch block after inserting a { following a try keyword.
10635 Rationale is that a try always needs a catch or a finally, and the catch is
10636 the more likely of the two.
10637
10638 TRY-POS is the buffer position of the try keyword. The open-curly should
10639 already have been inserted."
10640 (insert "{")
10641 (let ((try-col (save-excursion
10642 (goto-char try-pos)
10643 (current-column))))
10644 (insert "\n")
10645 (undo-boundary)
10646 (js2-indent-line) ;; indent the blank line where cursor will end up
10647 (save-excursion
10648 (insert "\n")
10649 (indent-to try-col)
10650 (insert "} catch (x) {\n\n")
10651 (indent-to try-col)
10652 (insert "}"))))
10653
10654
10655 (defun js2-mode-wait-for-parse (callback)
10656 "Invoke CALLBACK when parsing is finished.
10657 If parsing is already finished, calls CALLBACK immediately."
10658 (if (not js2-mode-buffer-dirty-p)
10659 (funcall callback)
10660 (push callback js2-mode-pending-parse-callbacks)
10661 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10662
10663 (defun js2-mode-parse-finished ()
10664 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10665 ;; We can't let errors propagate up, since it prevents the
10666 ;; `js2-parse' method from completing normally and returning
10667 ;; the ast, which makes things mysteriously not work right.
10668 (unwind-protect
10669 (dolist (cb js2-mode-pending-parse-callbacks)
10670 (condition-case err
10671 (funcall cb)
10672 (error (message "%s" err))))
10673 (setq js2-mode-pending-parse-callbacks nil)))
10674
10675 (defun js2-mode-flag-region (from to flag)
10676 "Hide or show text from FROM to TO, according to FLAG.
10677 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10678 Returns the created overlay if FLAG is non-nil."
10679 (remove-overlays from to 'invisible 'js2-outline)
10680 (when flag
10681 (let ((o (make-overlay from to)))
10682 (overlay-put o 'invisible 'js2-outline)
10683 (overlay-put o 'isearch-open-invisible
10684 'js2-isearch-open-invisible)
10685 o)))
10686
10687 ;; Function to be set as an outline-isearch-open-invisible' property
10688 ;; to the overlay that makes the outline invisible (see
10689 ;; `js2-mode-flag-region').
10690 (defun js2-isearch-open-invisible (overlay)
10691 ;; We rely on the fact that isearch places point on the matched text.
10692 (js2-mode-show-element))
10693
10694 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10695 "Return cons cell of bounds of folding overlay at POS.
10696 Returns nil if not found."
10697 (let ((overlays (overlays-at (or pos (point))))
10698 o)
10699 (while (and overlays
10700 (not o))
10701 (if (overlay-get (car overlays) 'invisible)
10702 (setq o (car overlays))
10703 (setq overlays (cdr overlays))))
10704 (if o
10705 (cons (overlay-start o) (overlay-end o)))))
10706
10707 (defun js2-mode-function-at-point (&optional pos)
10708 "Return the innermost function node enclosing current point.
10709 Returns nil if point is not in a function."
10710 (let ((node (js2-node-at-point pos)))
10711 (while (and node (not (js2-function-node-p node)))
10712 (setq node (js2-node-parent node)))
10713 (if (js2-function-node-p node)
10714 node)))
10715
10716 (defun js2-mode-toggle-element ()
10717 "Hide or show the foldable element at the point."
10718 (interactive)
10719 (let (comment fn pos)
10720 (save-excursion
10721 (cond
10722 ;; /* ... */ comment?
10723 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10724 (if (js2-mode-invisible-overlay-bounds
10725 (setq pos (+ 3 (js2-node-abs-pos comment))))
10726 (progn
10727 (goto-char pos)
10728 (js2-mode-show-element))
10729 (js2-mode-hide-element)))
10730 ;; //-comment?
10731 ((save-excursion
10732 (back-to-indentation)
10733 (looking-at js2-mode-//-comment-re))
10734 (js2-mode-toggle-//-comment))
10735 ;; function?
10736 ((setq fn (js2-mode-function-at-point))
10737 (setq pos (and (js2-function-node-body fn)
10738 (js2-node-abs-pos (js2-function-node-body fn))))
10739 (goto-char (1+ pos))
10740 (if (js2-mode-invisible-overlay-bounds)
10741 (js2-mode-show-element)
10742 (js2-mode-hide-element)))
10743 (t
10744 (message "Nothing at point to hide or show"))))))
10745
10746 (defun js2-mode-hide-element ()
10747 "Fold/hide contents of a block, showing ellipses.
10748 Show the hidden text with \\[js2-mode-show-element]."
10749 (interactive)
10750 (if js2-mode-buffer-dirty-p
10751 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10752 (let (node body beg end)
10753 (cond
10754 ((js2-mode-invisible-overlay-bounds)
10755 (message "already hidden"))
10756 (t
10757 (setq node (js2-node-at-point))
10758 (cond
10759 ((js2-block-comment-p node)
10760 (js2-mode-hide-comment node))
10761 (t
10762 (while (and node (not (js2-function-node-p node)))
10763 (setq node (js2-node-parent node)))
10764 (if (and node
10765 (setq body (js2-function-node-body node)))
10766 (progn
10767 (setq beg (js2-node-abs-pos body)
10768 end (+ beg (js2-node-len body)))
10769 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10770 (message "No collapsable element found at point"))))))))
10771
10772 (defun js2-mode-show-element ()
10773 "Show the hidden element at current point."
10774 (interactive)
10775 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10776 (if bounds
10777 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10778 (message "Nothing to un-hide"))))
10779
10780 (defun js2-mode-show-all ()
10781 "Show all of the text in the buffer."
10782 (interactive)
10783 (js2-mode-flag-region (point-min) (point-max) nil))
10784
10785 (defun js2-mode-toggle-hide-functions ()
10786 (interactive)
10787 (if js2-mode-functions-hidden
10788 (js2-mode-show-functions)
10789 (js2-mode-hide-functions)))
10790
10791 (defun js2-mode-hide-functions ()
10792 "Hides all non-nested function bodies in the buffer.
10793 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10794 to open an individual entry."
10795 (interactive)
10796 (if js2-mode-buffer-dirty-p
10797 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10798 (if (null js2-mode-ast)
10799 (message "Oops - parsing failed")
10800 (setq js2-mode-functions-hidden t)
10801 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10802
10803 (defun js2-mode-function-hider (n endp)
10804 (when (not endp)
10805 (let ((tt (js2-node-type n))
10806 body beg end)
10807 (cond
10808 ((and (= tt js2-FUNCTION)
10809 (setq body (js2-function-node-body n)))
10810 (setq beg (js2-node-abs-pos body)
10811 end (+ beg (js2-node-len body)))
10812 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10813 nil) ; don't process children of function
10814 (t
10815 t))))) ; keep processing other AST nodes
10816
10817 (defun js2-mode-show-functions ()
10818 "Un-hide any folded function bodies in the buffer."
10819 (interactive)
10820 (setq js2-mode-functions-hidden nil)
10821 (save-excursion
10822 (goto-char (point-min))
10823 (while (/= (goto-char (next-overlay-change (point)))
10824 (point-max))
10825 (dolist (o (overlays-at (point)))
10826 (when (and (overlay-get o 'invisible)
10827 (not (overlay-get o 'comment)))
10828 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10829
10830 (defun js2-mode-hide-comment (n)
10831 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10832 3 ; /**
10833 2)) ; /*
10834 (beg (+ (js2-node-abs-pos n) head))
10835 (end (- (+ beg (js2-node-len n)) head 2))
10836 (o (js2-mode-flag-region beg end 'hide)))
10837 (overlay-put o 'comment t)))
10838
10839 (defun js2-mode-toggle-hide-comments ()
10840 "Folds all block comments in the buffer.
10841 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10842 to open an individual entry."
10843 (interactive)
10844 (if js2-mode-comments-hidden
10845 (js2-mode-show-comments)
10846 (js2-mode-hide-comments)))
10847
10848 (defun js2-mode-hide-comments ()
10849 (interactive)
10850 (if js2-mode-buffer-dirty-p
10851 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10852 (if (null js2-mode-ast)
10853 (message "Oops - parsing failed")
10854 (setq js2-mode-comments-hidden t)
10855 (dolist (n (js2-ast-root-comments js2-mode-ast))
10856 (let ((format (js2-comment-node-format n)))
10857 (when (js2-block-comment-p n)
10858 (js2-mode-hide-comment n))))
10859 (js2-mode-hide-//-comments)))
10860
10861 (defun js2-mode-extend-//-comment (direction)
10862 "Find start or end of a block of similar //-comment lines.
10863 DIRECTION is -1 to look back, 1 to look forward.
10864 INDENT is the indentation level to match.
10865 Returns the end-of-line position of the furthest adjacent
10866 //-comment line with the same indentation as the current line.
10867 If there is no such matching line, returns current end of line."
10868 (let ((pos (point-at-eol))
10869 (indent (current-indentation)))
10870 (save-excursion
10871 (while (and (zerop (forward-line direction))
10872 (looking-at js2-mode-//-comment-re)
10873 (eq indent (length (match-string 1))))
10874 (setq pos (point-at-eol))
10875 pos))))
10876
10877 (defun js2-mode-hide-//-comments ()
10878 "Fold adjacent 1-line comments, showing only snippet of first one."
10879 (let (beg end)
10880 (save-excursion
10881 (goto-char (point-min))
10882 (while (re-search-forward js2-mode-//-comment-re nil t)
10883 (setq beg (point)
10884 end (js2-mode-extend-//-comment 1))
10885 (unless (eq beg end)
10886 (overlay-put (js2-mode-flag-region beg end 'hide)
10887 'comment t))
10888 (goto-char end)
10889 (forward-char 1)))))
10890
10891 (defun js2-mode-toggle-//-comment ()
10892 "Fold or un-fold any multi-line //-comment at point.
10893 Caller should have determined that this line starts with a //-comment."
10894 (let* ((beg (point-at-eol))
10895 (end beg))
10896 (save-excursion
10897 (goto-char end)
10898 (if (js2-mode-invisible-overlay-bounds)
10899 (js2-mode-show-element)
10900 ;; else hide the comment
10901 (setq beg (js2-mode-extend-//-comment -1)
10902 end (js2-mode-extend-//-comment 1))
10903 (unless (eq beg end)
10904 (overlay-put (js2-mode-flag-region beg end 'hide)
10905 'comment t))))))
10906
10907 (defun js2-mode-show-comments ()
10908 "Un-hide any hidden comments, leaving other hidden elements alone."
10909 (interactive)
10910 (setq js2-mode-comments-hidden nil)
10911 (save-excursion
10912 (goto-char (point-min))
10913 (while (/= (goto-char (next-overlay-change (point)))
10914 (point-max))
10915 (dolist (o (overlays-at (point)))
10916 (when (overlay-get o 'comment)
10917 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10918
10919 (defun js2-mode-display-warnings-and-errors ()
10920 "Turn on display of warnings and errors."
10921 (interactive)
10922 (setq js2-mode-show-parse-errors t
10923 js2-mode-show-strict-warnings t)
10924 (js2-reparse 'force))
10925
10926 (defun js2-mode-hide-warnings-and-errors ()
10927 "Turn off display of warnings and errors."
10928 (interactive)
10929 (setq js2-mode-show-parse-errors nil
10930 js2-mode-show-strict-warnings nil)
10931 (js2-reparse 'force))
10932
10933 (defun js2-mode-toggle-warnings-and-errors ()
10934 "Toggle the display of warnings and errors.
10935 Some users don't like having warnings/errors reported while they type."
10936 (interactive)
10937 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10938 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10939 (if (called-interactively-p 'any)
10940 (message "warnings and errors %s"
10941 (if js2-mode-show-parse-errors
10942 "enabled"
10943 "disabled")))
10944 (js2-reparse 'force))
10945
10946 (defun js2-mode-customize ()
10947 (interactive)
10948 (customize-group 'js2-mode))
10949
10950 (defun js2-mode-forward-sexp (&optional arg)
10951 "Move forward across one statement or balanced expression.
10952 With ARG, do it that many times. Negative arg -N means
10953 move backward across N balanced expressions."
10954 (interactive "p")
10955 (setq arg (or arg 1))
10956 (let (node end (start (point)))
10957 (cond
10958 ;; backward-sexp
10959 ;; could probably make this better for some cases:
10960 ;; - if in statement block (e.g. function body), go to parent
10961 ;; - infix exprs like (foo in bar) - maybe go to beginning
10962 ;; of infix expr if in the right-side expression?
10963 ((and arg (minusp arg))
10964 (dotimes (i (- arg))
10965 (js2-backward-sws)
10966 (forward-char -1) ; enter the node we backed up to
10967 (setq node (js2-node-at-point (point) t))
10968 (goto-char (if node
10969 (js2-node-abs-pos node)
10970 (point-min)))))
10971 (t
10972 ;; forward-sexp
10973 (js2-forward-sws)
10974 (dotimes (i arg)
10975 (js2-forward-sws)
10976 (setq node (js2-node-at-point (point) t)
10977 end (if node (+ (js2-node-abs-pos node)
10978 (js2-node-len node))))
10979 (goto-char (or end (point-max))))))))
10980
10981 (defun js2-errors ()
10982 "Return a list of errors found."
10983 (and js2-mode-ast
10984 (js2-ast-root-errors js2-mode-ast)))
10985
10986 (defun js2-warnings ()
10987 "Return a list of warnings found."
10988 (and js2-mode-ast
10989 (js2-ast-root-warnings js2-mode-ast)))
10990
10991 (defun js2-have-errors-p ()
10992 "Return non-nil if any parse errors or warnings were found."
10993 (or (js2-errors) (js2-warnings)))
10994
10995 (defun js2-errors-and-warnings ()
10996 "Return a copy of the concatenated errors and warnings lists."
10997 (and js2-mode-ast
10998 (append (js2-ast-root-errors js2-mode-ast)
10999 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
11000
11001 (defun js2-next-error (&optional arg reset)
11002 "Move to next parse error.
11003 Typically invoked via \\[next-error].
11004 ARG is the number of errors, forward or backward, to move.
11005 RESET means start over from the beginning."
11006 (interactive "p")
11007 (if (not (or (js2-errors) (js2-warnings)))
11008 (message "No errors")
11009 (when reset
11010 (goto-char (point-min)))
11011 (let* ((errs (js2-errors-and-warnings))
11012 (continue t)
11013 (start (point))
11014 (count (or arg 1))
11015 (backward (minusp count))
11016 (sorter (if backward '> '<))
11017 (stopper (if backward '< '>))
11018 (count (abs count))
11019 all-errs err)
11020 ;; Sort by start position.
11021 (setq errs (sort errs (lambda (e1 e2)
11022 (funcall sorter (second e1) (second e2))))
11023 all-errs errs)
11024 ;; Find nth error with pos > start.
11025 (while (and errs continue)
11026 (when (funcall stopper (cadar errs) start)
11027 (setq err (car errs))
11028 (if (zerop (decf count))
11029 (setq continue nil)))
11030 (setq errs (cdr errs)))
11031 (if err
11032 (goto-char (second err))
11033 ;; Wrap around to first error.
11034 (goto-char (second (car all-errs)))
11035 ;; If we were already on it, echo msg again.
11036 (if (= (point) start)
11037 (js2-echo-error (point) (point)))))))
11038
11039 (defun js2-down-mouse-3 ()
11040 "Make right-click move the point to the click location.
11041 This makes right-click context menu operations a bit more intuitive.
11042 The point will not move if the region is active, however, to avoid
11043 destroying the region selection."
11044 (interactive)
11045 (when (and js2-move-point-on-right-click
11046 (not mark-active))
11047 (let ((e last-input-event))
11048 (ignore-errors
11049 (goto-char (cadadr e))))))
11050
11051 (defun js2-mode-create-imenu-index ()
11052 "Return an alist for `imenu--index-alist'."
11053 ;; This is built up in `js2-parse-record-imenu' during parsing.
11054 (when js2-mode-ast
11055 ;; if we have an ast but no recorder, they're requesting a rescan
11056 (unless js2-imenu-recorder
11057 (js2-reparse 'force))
11058 (prog1
11059 (js2-build-imenu-index)
11060 (setq js2-imenu-recorder nil
11061 js2-imenu-function-map nil))))
11062
11063 (defun js2-mode-find-tag ()
11064 "Replacement for `find-tag-default'.
11065 `find-tag-default' returns a ridiculous answer inside comments."
11066 (let (beg end)
11067 (js2-with-underscore-as-word-syntax
11068 (save-excursion
11069 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11070 (looking-back "[A-Za-z0-9_$]"))
11071 (setq beg (progn (forward-word -1) (point))
11072 end (progn (forward-word 1) (point)))
11073 (setq beg (progn (forward-word 1) (point))
11074 end (progn (forward-word -1) (point))))
11075 (replace-regexp-in-string
11076 "[\"']" ""
11077 (buffer-substring-no-properties beg end))))))
11078
11079 (defun js2-mode-forward-sibling ()
11080 "Move to the end of the sibling following point in parent.
11081 Returns non-nil if successful, or nil if there was no following sibling."
11082 (let* ((node (js2-node-at-point))
11083 (parent (js2-mode-find-enclosing-fn node))
11084 sib)
11085 (when (setq sib (js2-node-find-child-after (point) parent))
11086 (goto-char (+ (js2-node-abs-pos sib)
11087 (js2-node-len sib))))))
11088
11089 (defun js2-mode-backward-sibling ()
11090 "Move to the beginning of the sibling node preceding point in parent.
11091 Parent is defined as the enclosing script or function."
11092 (let* ((node (js2-node-at-point))
11093 (parent (js2-mode-find-enclosing-fn node))
11094 sib)
11095 (when (setq sib (js2-node-find-child-before (point) parent))
11096 (goto-char (js2-node-abs-pos sib)))))
11097
11098 (defun js2-beginning-of-defun (&optional arg)
11099 "Go to line on which current function starts, and return t on success.
11100 If we're not in a function or already at the beginning of one, go
11101 to beginning of previous script-level element.
11102 With ARG N, do that N times. If N is negative, move forward."
11103 (setq arg (or arg 1))
11104 (if (plusp arg)
11105 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11106 (when (cond
11107 ((js2-function-node-p parent)
11108 (goto-char (js2-node-abs-pos parent)))
11109 (t
11110 (js2-mode-backward-sibling)))
11111 (if (> arg 1)
11112 (js2-beginning-of-defun (1- arg))
11113 t)))
11114 (when (js2-end-of-defun)
11115 (if (>= arg -1)
11116 (js2-beginning-of-defun 1)
11117 (js2-beginning-of-defun (1+ arg))))))
11118
11119 (defun js2-end-of-defun ()
11120 "Go to the char after the last position of the current function
11121 or script-level element."
11122 (let* ((node (js2-node-at-point))
11123 (parent (or (and (js2-function-node-p node) node)
11124 (js2-node-parent-script-or-fn node)))
11125 script)
11126 (unless (js2-function-node-p parent)
11127 ;; Use current script-level node, or, if none, the next one.
11128 (setq script (or parent node)
11129 parent (js2-node-find-child-before (point) script))
11130 (when (or (null parent)
11131 (>= (point) (+ (js2-node-abs-pos parent)
11132 (js2-node-len parent))))
11133 (setq parent (js2-node-find-child-after (point) script))))
11134 (when parent
11135 (goto-char (+ (js2-node-abs-pos parent)
11136 (js2-node-len parent))))))
11137
11138 (defun js2-mark-defun (&optional allow-extend)
11139 "Put mark at end of this function, point at beginning.
11140 The function marked is the one that contains point.
11141
11142 Interactively, if this command is repeated,
11143 or (in Transient Mark mode) if the mark is active,
11144 it marks the next defun after the ones already marked."
11145 (interactive "p")
11146 (let (extended)
11147 (when (and allow-extend
11148 (or (and (eq last-command this-command) (mark t))
11149 (and transient-mark-mode mark-active)))
11150 (let ((sib (save-excursion
11151 (goto-char (mark))
11152 (if (js2-mode-forward-sibling)
11153 (point))))
11154 node)
11155 (if sib
11156 (progn
11157 (set-mark sib)
11158 (setq extended t))
11159 ;; no more siblings - try extending to enclosing node
11160 (goto-char (mark t)))))
11161 (when (not extended)
11162 (let ((node (js2-node-at-point (point) t)) ; skip comments
11163 ast fn stmt parent beg end)
11164 (when (js2-ast-root-p node)
11165 (setq ast node
11166 node (or (js2-node-find-child-after (point) node)
11167 (js2-node-find-child-before (point) node))))
11168 ;; only mark whole buffer if we can't find any children
11169 (if (null node)
11170 (setq node ast))
11171 (if (js2-function-node-p node)
11172 (setq parent node)
11173 (setq fn (js2-mode-find-enclosing-fn node)
11174 stmt (if (or (null fn)
11175 (js2-ast-root-p fn))
11176 (js2-mode-find-first-stmt node))
11177 parent (or stmt fn)))
11178 (setq beg (js2-node-abs-pos parent)
11179 end (+ beg (js2-node-len parent)))
11180 (push-mark beg)
11181 (goto-char end)
11182 (exchange-point-and-mark)))))
11183
11184 (defun js2-narrow-to-defun ()
11185 "Narrow to the function enclosing point."
11186 (interactive)
11187 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11188 (fn (if (js2-script-node-p node)
11189 node
11190 (js2-mode-find-enclosing-fn node)))
11191 (beg (js2-node-abs-pos fn)))
11192 (unless (js2-ast-root-p fn)
11193 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11194
11195 (provide 'js2-mode)
11196
11197 ;;; js2-mode.el ends here