]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Add autoload cookie for js2-minor-mode
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- 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 none.
197 1 adds basic syntax highlighting.
198 2 adds highlighting of some Ecma built-in properties.
199 3 adds highlighting of many Ecma built-in functions."
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
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
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
1054 '((t :foreground "SlateGray"))
1055 "Face used to highlight @whatever tags in jsdoc comments."
1056 :group 'js2-mode)
1057
1058 (defface js2-jsdoc-type
1059 '((t :foreground "SteelBlue"))
1060 "Face used to highlight {FooBar} types in jsdoc comments."
1061 :group 'js2-mode)
1062
1063 (defface js2-jsdoc-value
1064 '((t :foreground "PeachPuff3"))
1065 "Face used to highlight tag values in jsdoc comments."
1066 :group 'js2-mode)
1067
1068 (defface js2-function-param
1069 '((t :foreground "SeaGreen"))
1070 "Face used to highlight function parameters in javascript."
1071 :group 'js2-mode)
1072
1073 (defface js2-instance-member
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
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
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
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
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
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) "let ")
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 (insert "]")))
3654
3655 (defstruct (js2-array-comp-loop-node
3656 (:include js2-for-in-node)
3657 (:constructor nil)
3658 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3659 (pos js2-ts-cursor)
3660 len iterator
3661 object in-pos
3662 foreach-p
3663 each-pos
3664 lp rp)))
3665 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3666
3667 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3668 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3669
3670 (defun js2-visit-array-comp-loop (n v)
3671 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3672 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3673
3674 (defun js2-print-array-comp-loop (n i)
3675 (insert "for ")
3676 (when (js2-array-comp-loop-node-foreach-p n) (insert "each "))
3677 (insert "(")
3678 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3679 (insert " in ")
3680 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3681 (insert ")"))
3682
3683 (defstruct (js2-empty-expr-node
3684 (:include js2-node)
3685 (:constructor nil)
3686 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3687 (pos js2-token-beg)
3688 len)))
3689 "AST node for an empty expression.")
3690
3691 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3692 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3693
3694 (defstruct (js2-xml-node
3695 (:include js2-block-node)
3696 (:constructor nil)
3697 (:constructor make-js2-xml-node (&key (type js2-XML)
3698 (pos js2-token-beg)
3699 len kids)))
3700 "AST node for initial parse of E4X literals.
3701 The kids field is a list of XML fragments, each a `js2-string-node' or
3702 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3703
3704 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3705 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3706
3707 (defun js2-print-xml-node (n i)
3708 (dolist (kid (js2-xml-node-kids n))
3709 (js2-print-ast kid i)))
3710
3711 (defstruct (js2-xml-js-expr-node
3712 (:include js2-xml-node)
3713 (:constructor nil)
3714 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3715 (pos js2-ts-cursor)
3716 len expr)))
3717 "AST node for an embedded JavaScript {expression} in an E4X literal.
3718 The start and end fields correspond to the curly-braces."
3719 expr) ; a `js2-expr-node' of some sort
3720
3721 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3722 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3723
3724 (defun js2-visit-xml-js-expr (n v)
3725 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3726
3727 (defun js2-print-xml-js-expr (n i)
3728 (insert (js2-make-pad i))
3729 (insert "{")
3730 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3731 (insert "}"))
3732
3733 (defstruct (js2-xml-dot-query-node
3734 (:include js2-infix-node)
3735 (:constructor nil)
3736 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3737 (pos js2-ts-cursor)
3738 op-pos len left
3739 right rp)))
3740 "AST node for an E4X foo.(bar) filter expression.
3741 Note that the left-paren is automatically the character immediately
3742 following the dot (.) in the operator. No whitespace is permitted
3743 between the dot and the lp by the scanner."
3744 rp)
3745
3746 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3747 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3748
3749 (defun js2-print-xml-dot-query (n i)
3750 (insert (js2-make-pad i))
3751 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3752 (insert ".(")
3753 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3754 (insert ")"))
3755
3756 (defstruct (js2-xml-ref-node
3757 (:include js2-node)
3758 (:constructor nil)) ; abstract
3759 "Base type for E4X XML attribute-access or property-get expressions.
3760 Such expressions can take a variety of forms. The general syntax has
3761 three parts:
3762
3763 - (optional) an @ (specifying an attribute access)
3764 - (optional) a namespace (a `js2-name-node') and double-colon
3765 - (required) either a `js2-name-node' or a bracketed [expression]
3766
3767 The property-name expressions (examples: ns::name, @name) are
3768 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3769 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3770
3771 This node type (or more specifically, its subclasses) will sometimes
3772 be the right-hand child of a `js2-prop-get-node' or a
3773 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3774 The `js2-xml-ref-node' may also be a standalone primary expression with
3775 no explicit target, which is valid in certain expression contexts such as
3776
3777 company..employee.(@id < 100)
3778
3779 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3780 expression whose parent is a `js2-xml-dot-query-node'."
3781 namespace
3782 at-pos
3783 colon-pos)
3784
3785 (defsubst js2-xml-ref-node-attr-access-p (node)
3786 "Return non-nil if this expression began with an @-token."
3787 (and (numberp (js2-xml-ref-node-at-pos node))
3788 (plusp (js2-xml-ref-node-at-pos node))))
3789
3790 (defstruct (js2-xml-prop-ref-node
3791 (:include js2-xml-ref-node)
3792 (:constructor nil)
3793 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3794 (pos js2-token-beg)
3795 len propname
3796 namespace at-pos
3797 colon-pos)))
3798 "AST node for an E4X XML [expr] property-ref expression.
3799 The JavaScript syntax is an optional @, an optional ns::, and a name.
3800
3801 [ '@' ] [ name '::' ] name
3802
3803 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3804 @ns::*, @*::attr, @*::*, and @*.
3805
3806 The node starts at the @ token, if present. Otherwise it starts at the
3807 namespace name. The node bounds extend through the closing right-bracket,
3808 or if it is missing due to a syntax error, through the end of the index
3809 expression."
3810 propname)
3811
3812 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3813 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3814
3815 (defun js2-visit-xml-prop-ref-node (n v)
3816 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v)
3817 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v))
3818
3819 (defun js2-print-xml-prop-ref-node (n i)
3820 (insert (js2-make-pad i))
3821 (if (js2-xml-ref-node-attr-access-p n)
3822 (insert "@"))
3823 (when (js2-xml-prop-ref-node-namespace n)
3824 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3825 (insert "::"))
3826 (if (js2-xml-prop-ref-node-propname n)
3827 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3828
3829 (defstruct (js2-xml-elem-ref-node
3830 (:include js2-xml-ref-node)
3831 (:constructor nil)
3832 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3833 (pos js2-token-beg)
3834 len expr lb rb
3835 namespace at-pos
3836 colon-pos)))
3837 "AST node for an E4X XML [expr] member-ref expression.
3838 Syntax:
3839
3840 [ '@' ] [ name '::' ] '[' expr ']'
3841
3842 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3843
3844 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3845 is not a legal E4X XML element-ref expression, since it's already used
3846 for standard JavaScript element-get array indexing. Hence, a
3847 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3848 non-nil namespace node, or both.
3849
3850 The node starts at the @ token, if present. Otherwise it starts
3851 at the namespace name. The node bounds extend through the closing
3852 right-bracket, or if it is missing due to a syntax error, through the
3853 end of the index expression."
3854 expr ; the bracketed index expression
3855 lb
3856 rb)
3857
3858 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3859 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3860
3861 (defun js2-visit-xml-elem-ref-node (n v)
3862 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v)
3863 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v))
3864
3865 (defun js2-print-xml-elem-ref-node (n i)
3866 (insert (js2-make-pad i))
3867 (if (js2-xml-ref-node-attr-access-p n)
3868 (insert "@"))
3869 (when (js2-xml-elem-ref-node-namespace n)
3870 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3871 (insert "::"))
3872 (insert "[")
3873 (if (js2-xml-elem-ref-node-expr n)
3874 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3875 (insert "]"))
3876
3877 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
3878
3879 (defstruct (js2-xml-start-tag-node
3880 (:include js2-xml-node)
3881 (:constructor nil)
3882 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
3883 (pos js2-ts-cursor)
3884 len name attrs kids
3885 empty-p)))
3886 "AST node for an XML start-tag. Not currently used.
3887 The `kids' field is a Lisp list of child content nodes."
3888 name ; a `js2-xml-name-node'
3889 attrs ; a Lisp list of `js2-xml-attr-node'
3890 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
3891
3892 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
3893 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
3894
3895 (defun js2-visit-xml-start-tag (n v)
3896 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
3897 (dolist (attr (js2-xml-start-tag-node-attrs n))
3898 (js2-visit-ast attr v))
3899 (js2-visit-block n v))
3900
3901 (defun js2-print-xml-start-tag (n i)
3902 (insert (js2-make-pad i) "<")
3903 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
3904 (when (js2-xml-start-tag-node-attrs n)
3905 (insert " ")
3906 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
3907 (insert ">"))
3908
3909 ;; I -think- I'm going to make the parent node the corresponding start-tag,
3910 ;; and add the end-tag to the kids list of the parent as well.
3911 (defstruct (js2-xml-end-tag-node
3912 (:include js2-xml-node)
3913 (:constructor nil)
3914 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
3915 (pos js2-ts-cursor)
3916 len name)))
3917 "AST node for an XML end-tag. Not currently used."
3918 name) ; a `js2-xml-name-node'
3919
3920 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
3921 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
3922
3923 (defun js2-visit-xml-end-tag (n v)
3924 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
3925
3926 (defun js2-print-xml-end-tag (n i)
3927 (insert (js2-make-pad i))
3928 (insert "</")
3929 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
3930 (insert ">"))
3931
3932 (defstruct (js2-xml-name-node
3933 (:include js2-xml-node)
3934 (:constructor nil)
3935 (:constructor make-js2-xml-name-node (&key (type js2-XML)
3936 (pos js2-ts-cursor)
3937 len namespace kids)))
3938 "AST node for an E4X XML name. Not currently used.
3939 Any XML name can be qualified with a namespace, hence the namespace field.
3940 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
3941 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
3942 For a simple name, the kids list has exactly one node, a `js2-name-node'."
3943 namespace) ; a `js2-string-node'
3944
3945 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
3946 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
3947
3948 (defun js2-visit-xml-name-node (n v)
3949 (js2-visit-ast (js2-xml-name-node-namespace n) v))
3950
3951 (defun js2-print-xml-name-node (n i)
3952 (insert (js2-make-pad i))
3953 (when (js2-xml-name-node-namespace n)
3954 (js2-print-ast (js2-xml-name-node-namespace n) 0)
3955 (insert "::"))
3956 (dolist (kid (js2-xml-name-node-kids n))
3957 (js2-print-ast kid 0)))
3958
3959 (defstruct (js2-xml-pi-node
3960 (:include js2-xml-node)
3961 (:constructor nil)
3962 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
3963 (pos js2-ts-cursor)
3964 len name attrs)))
3965 "AST node for an E4X XML processing instruction. Not currently used."
3966 name ; a `js2-xml-name-node'
3967 attrs) ; a list of `js2-xml-attr-node'
3968
3969 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
3970 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
3971
3972 (defun js2-visit-xml-pi-node (n v)
3973 (js2-visit-ast (js2-xml-pi-node-name n) v)
3974 (dolist (attr (js2-xml-pi-node-attrs n))
3975 (js2-visit-ast attr v)))
3976
3977 (defun js2-print-xml-pi-node (n i)
3978 (insert (js2-make-pad i) "<?")
3979 (js2-print-ast (js2-xml-pi-node-name n))
3980 (when (js2-xml-pi-node-attrs n)
3981 (insert " ")
3982 (js2-print-list (js2-xml-pi-node-attrs n)))
3983 (insert "?>"))
3984
3985 (defstruct (js2-xml-cdata-node
3986 (:include js2-xml-node)
3987 (:constructor nil)
3988 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
3989 (pos js2-ts-cursor)
3990 len content)))
3991 "AST node for a CDATA escape section. Not currently used."
3992 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
3993
3994 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
3995 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
3996
3997 (defun js2-visit-xml-cdata-node (n v)
3998 (js2-visit-ast (js2-xml-cdata-node-content n) v))
3999
4000 (defun js2-print-xml-cdata-node (n i)
4001 (insert (js2-make-pad i))
4002 (js2-print-ast (js2-xml-cdata-node-content n)))
4003
4004 (defstruct (js2-xml-attr-node
4005 (:include js2-xml-node)
4006 (:constructor nil)
4007 (:constructor make-js2-attr-node (&key (type js2-XML)
4008 (pos js2-ts-cursor)
4009 len name value
4010 eq-pos quote-type)))
4011 "AST node representing a foo='bar' XML attribute value. Not yet used."
4012 name ; a `js2-xml-name-node'
4013 value ; a `js2-xml-name-node'
4014 eq-pos ; buffer position of "=" sign
4015 quote-type) ; 'single or 'double
4016
4017 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4018 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4019
4020 (defun js2-visit-xml-attr-node (n v)
4021 (js2-visit-ast (js2-xml-attr-node-name n) v)
4022 (js2-visit-ast (js2-xml-attr-node-value n) v))
4023
4024 (defun js2-print-xml-attr-node (n i)
4025 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4026 "'"
4027 "\"")))
4028 (insert (js2-make-pad i))
4029 (js2-print-ast (js2-xml-attr-node-name n) 0)
4030 (insert "=" quote)
4031 (js2-print-ast (js2-xml-attr-node-value n) 0)
4032 (insert quote)))
4033
4034 (defstruct (js2-xml-text-node
4035 (:include js2-xml-node)
4036 (:constructor nil)
4037 (:constructor make-js2-text-node (&key (type js2-XML)
4038 (pos js2-ts-cursor)
4039 len content)))
4040 "AST node for an E4X XML text node. Not currently used."
4041 content) ; a Lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4042
4043 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4044 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4045
4046 (defun js2-visit-xml-text-node (n v)
4047 (js2-visit-ast (js2-xml-text-node-content n) v))
4048
4049 (defun js2-print-xml-text-node (n i)
4050 (insert (js2-make-pad i))
4051 (dolist (kid (js2-xml-text-node-content n))
4052 (js2-print-ast kid)))
4053
4054 (defstruct (js2-xml-comment-node
4055 (:include js2-xml-node)
4056 (:constructor nil)
4057 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4058 (pos js2-ts-cursor)
4059 len)))
4060 "AST node for E4X XML comment. Not currently used.")
4061
4062 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4063 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4064
4065 (defun js2-print-xml-comment (n i)
4066 (insert (js2-make-pad i)
4067 (js2-node-string n)))
4068
4069 ;;; Node utilities
4070
4071 (defsubst js2-node-line (n)
4072 "Fetch the source line number at the start of node N.
4073 This is O(n) in the length of the source buffer; use prudently."
4074 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4075
4076 (defsubst js2-block-node-kid (n i)
4077 "Return child I of node N, or nil if there aren't that many."
4078 (nth i (js2-block-node-kids n)))
4079
4080 (defsubst js2-block-node-first (n)
4081 "Return first child of block node N, or nil if there is none."
4082 (first (js2-block-node-kids n)))
4083
4084 (defun js2-node-root (n)
4085 "Return the root of the AST containing N.
4086 If N has no parent pointer, returns N."
4087 (let ((parent (js2-node-parent n)))
4088 (if parent
4089 (js2-node-root parent)
4090 n)))
4091
4092 (defun js2-node-position-in-parent (node &optional parent)
4093 "Return the position of NODE in parent's block-kids list.
4094 PARENT can be supplied if known. Positioned returned is zero-indexed.
4095 Returns 0 if NODE is not a child of a block statement, or if NODE
4096 is not a statement node."
4097 (let ((p (or parent (js2-node-parent node)))
4098 (i 0))
4099 (if (not (js2-block-node-p p))
4100 i
4101 (or (js2-position node (js2-block-node-kids p))
4102 0))))
4103
4104 (defsubst js2-node-short-name (n)
4105 "Return the short name of node N as a string, e.g. `js2-if-node'."
4106 (substring (symbol-name (aref n 0))
4107 (length "cl-struct-")))
4108
4109 (defun js2-node-child-list (node)
4110 "Return the child list for NODE, a Lisp list of nodes.
4111 Works for block nodes, array nodes, obj literals, funarg lists,
4112 var decls and try nodes (for catch clauses). Note that you should call
4113 `js2-block-node-kids' on the function body for the body statements.
4114 Returns nil for zero-length child lists or unsupported nodes."
4115 (cond
4116 ((js2-function-node-p node)
4117 (js2-function-node-params node))
4118 ((js2-block-node-p node)
4119 (js2-block-node-kids node))
4120 ((js2-try-node-p node)
4121 (js2-try-node-catch-clauses node))
4122 ((js2-array-node-p node)
4123 (js2-array-node-elems node))
4124 ((js2-object-node-p node)
4125 (js2-object-node-elems node))
4126 ((js2-call-node-p node)
4127 (js2-call-node-args node))
4128 ((js2-new-node-p node)
4129 (js2-new-node-args node))
4130 ((js2-var-decl-node-p node)
4131 (js2-var-decl-node-kids node))
4132 (t
4133 nil)))
4134
4135 (defun js2-node-set-child-list (node kids)
4136 "Set the child list for NODE to KIDS."
4137 (cond
4138 ((js2-function-node-p node)
4139 (setf (js2-function-node-params node) kids))
4140 ((js2-block-node-p node)
4141 (setf (js2-block-node-kids node) kids))
4142 ((js2-try-node-p node)
4143 (setf (js2-try-node-catch-clauses node) kids))
4144 ((js2-array-node-p node)
4145 (setf (js2-array-node-elems node) kids))
4146 ((js2-object-node-p node)
4147 (setf (js2-object-node-elems node) kids))
4148 ((js2-call-node-p node)
4149 (setf (js2-call-node-args node) kids))
4150 ((js2-new-node-p node)
4151 (setf (js2-new-node-args node) kids))
4152 ((js2-var-decl-node-p node)
4153 (setf (js2-var-decl-node-kids node) kids))
4154 (t
4155 (error "Unsupported node type: %s" (js2-node-short-name node))))
4156 kids)
4157
4158 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4159 (defconst js2-paren-expr-nodes
4160 '(cl-struct-js2-array-comp-loop-node
4161 cl-struct-js2-array-comp-node
4162 cl-struct-js2-call-node
4163 cl-struct-js2-catch-node
4164 cl-struct-js2-do-node
4165 cl-struct-js2-elem-get-node
4166 cl-struct-js2-for-in-node
4167 cl-struct-js2-for-node
4168 cl-struct-js2-function-node
4169 cl-struct-js2-if-node
4170 cl-struct-js2-let-node
4171 cl-struct-js2-new-node
4172 cl-struct-js2-paren-node
4173 cl-struct-js2-switch-node
4174 cl-struct-js2-while-node
4175 cl-struct-js2-with-node
4176 cl-struct-js2-xml-dot-query-node)
4177 "Node types that can have a parenthesized child expression.
4178 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4179
4180 (defsubst js2-paren-expr-node-p (node)
4181 "Return t for nodes that typically have a parenthesized child expression.
4182 Useful for computing the indentation anchors for arg-lists and conditions.
4183 Note that it may return a false positive, for instance when NODE is
4184 a `js2-new-node' and there are no arguments or parentheses."
4185 (memq (aref node 0) js2-paren-expr-nodes))
4186
4187 ;; Fake polymorphism... yech.
4188 (defun js2-node-lp (node)
4189 "Return relative left-paren position for NODE, if applicable.
4190 For `js2-elem-get-node' structs, returns left-bracket position.
4191 Note that the position may be nil in the case of a parse error."
4192 (cond
4193 ((js2-elem-get-node-p node)
4194 (js2-elem-get-node-lb node))
4195 ((js2-loop-node-p node)
4196 (js2-loop-node-lp node))
4197 ((js2-function-node-p node)
4198 (js2-function-node-lp node))
4199 ((js2-if-node-p node)
4200 (js2-if-node-lp node))
4201 ((js2-new-node-p node)
4202 (js2-new-node-lp node))
4203 ((js2-call-node-p node)
4204 (js2-call-node-lp node))
4205 ((js2-paren-node-p node)
4206 (js2-node-pos node))
4207 ((js2-switch-node-p node)
4208 (js2-switch-node-lp node))
4209 ((js2-catch-node-p node)
4210 (js2-catch-node-lp node))
4211 ((js2-let-node-p node)
4212 (js2-let-node-lp node))
4213 ((js2-array-comp-node-p node)
4214 (js2-array-comp-node-lp node))
4215 ((js2-with-node-p node)
4216 (js2-with-node-lp node))
4217 ((js2-xml-dot-query-node-p node)
4218 (1+ (js2-infix-node-op-pos node)))
4219 (t
4220 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4221
4222 ;; Fake polymorphism... blech.
4223 (defun js2-node-rp (node)
4224 "Return relative right-paren position for NODE, if applicable.
4225 For `js2-elem-get-node' structs, returns right-bracket position.
4226 Note that the position may be nil in the case of a parse error."
4227 (cond
4228 ((js2-elem-get-node-p node)
4229 (js2-elem-get-node-lb node))
4230 ((js2-loop-node-p node)
4231 (js2-loop-node-rp node))
4232 ((js2-function-node-p node)
4233 (js2-function-node-rp node))
4234 ((js2-if-node-p node)
4235 (js2-if-node-rp node))
4236 ((js2-new-node-p node)
4237 (js2-new-node-rp node))
4238 ((js2-call-node-p node)
4239 (js2-call-node-rp node))
4240 ((js2-paren-node-p node)
4241 (+ (js2-node-pos node) (js2-node-len node)))
4242 ((js2-switch-node-p node)
4243 (js2-switch-node-rp node))
4244 ((js2-catch-node-p node)
4245 (js2-catch-node-rp node))
4246 ((js2-let-node-p node)
4247 (js2-let-node-rp node))
4248 ((js2-array-comp-node-p node)
4249 (js2-array-comp-node-rp node))
4250 ((js2-with-node-p node)
4251 (js2-with-node-rp node))
4252 ((js2-xml-dot-query-node-p node)
4253 (1+ (js2-xml-dot-query-node-rp node)))
4254 (t
4255 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4256
4257 (defsubst js2-node-first-child (node)
4258 "Return the first element of `js2-node-child-list' for NODE."
4259 (car (js2-node-child-list node)))
4260
4261 (defsubst js2-node-last-child (node)
4262 "Return the last element of `js2-node-last-child' for NODE."
4263 (car (last (js2-node-child-list node))))
4264
4265 (defun js2-node-prev-sibling (node)
4266 "Return the previous statement in parent.
4267 Works for parents supported by `js2-node-child-list'.
4268 Returns nil if NODE is not in the parent, or PARENT is
4269 not a supported node, or if NODE is the first child."
4270 (let* ((p (js2-node-parent node))
4271 (kids (js2-node-child-list p))
4272 (sib (car kids)))
4273 (while (and kids
4274 (not (eq node (cadr kids))))
4275 (setq kids (cdr kids)
4276 sib (car kids)))
4277 sib))
4278
4279 (defun js2-node-next-sibling (node)
4280 "Return the next statement in parent block.
4281 Returns nil if NODE is not in the block, or PARENT is not
4282 a block node, or if NODE is the last statement."
4283 (let* ((p (js2-node-parent node))
4284 (kids (js2-node-child-list p)))
4285 (while (and kids
4286 (not (eq node (car kids))))
4287 (setq kids (cdr kids)))
4288 (cadr kids)))
4289
4290 (defun js2-node-find-child-before (pos parent &optional after)
4291 "Find the last child that starts before POS in parent.
4292 If AFTER is non-nil, returns first child starting after POS.
4293 POS is an absolute buffer position. PARENT is any node
4294 supported by `js2-node-child-list'.
4295 Returns nil if no applicable child is found."
4296 (let ((kids (if (js2-function-node-p parent)
4297 (js2-block-node-kids (js2-function-node-body parent))
4298 (js2-node-child-list parent)))
4299 (beg (if (js2-function-node-p parent)
4300 (js2-node-abs-pos (js2-function-node-body parent))
4301 (js2-node-abs-pos parent)))
4302 kid result fn
4303 (continue t))
4304 (setq fn (if after '>= '<))
4305 (while (and kids continue)
4306 (setq kid (car kids))
4307 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4308 (setq result kid
4309 continue (if after nil t))
4310 (setq continue (if after t nil)))
4311 (setq kids (cdr kids)))
4312 result))
4313
4314 (defun js2-node-find-child-after (pos parent)
4315 "Find first child that starts after POS in parent.
4316 POS is an absolute buffer position. PARENT is any node
4317 supported by `js2-node-child-list'.
4318 Returns nil if no applicable child is found."
4319 (js2-node-find-child-before pos parent 'after))
4320
4321 (defun js2-node-replace-child (pos parent new-node)
4322 "Replace node at index POS in PARENT with NEW-NODE.
4323 Only works for parents supported by `js2-node-child-list'."
4324 (let ((kids (js2-node-child-list parent))
4325 (i 0))
4326 (while (< i pos)
4327 (setq kids (cdr kids)
4328 i (1+ i)))
4329 (setcar kids new-node)
4330 (js2-node-add-children parent new-node)))
4331
4332 (defun js2-node-buffer (n)
4333 "Return the buffer associated with AST N.
4334 Returns nil if the buffer is not set as a property on the root
4335 node, or if parent links were not recorded during parsing."
4336 (let ((root (js2-node-root n)))
4337 (and root
4338 (js2-ast-root-p root)
4339 (js2-ast-root-buffer root))))
4340
4341 (defun js2-block-node-push (n kid)
4342 "Push js2-node KID onto the end of js2-block-node N's child list.
4343 KID is always added to the -end- of the kids list.
4344 Function also calls `js2-node-add-children' to add the parent link."
4345 (let ((kids (js2-node-child-list n)))
4346 (if kids
4347 (setcdr kids (nconc (cdr kids) (list kid)))
4348 (js2-node-set-child-list n (list kid)))
4349 (js2-node-add-children n kid)))
4350
4351 (defun js2-node-string (node)
4352 (with-current-buffer (or (js2-node-buffer node)
4353 (error "No buffer available for node %s" node))
4354 (let ((pos (js2-node-abs-pos node)))
4355 (buffer-substring-no-properties pos (+ pos (js2-node-len node))))))
4356
4357 ;; Container for storing the node we're looking for in a traversal.
4358 (js2-deflocal js2-discovered-node nil)
4359
4360 ;; Keep track of absolute node position during traversals.
4361 (js2-deflocal js2-visitor-offset nil)
4362
4363 (js2-deflocal js2-node-search-point nil)
4364
4365 (when js2-mode-dev-mode-p
4366 (defun js2-find-node-at-point ()
4367 (interactive)
4368 (let ((node (js2-node-at-point)))
4369 (message "%s" (or node "No node found at point"))))
4370 (defun js2-node-name-at-point ()
4371 (interactive)
4372 (let ((node (js2-node-at-point)))
4373 (message "%s" (if node
4374 (js2-node-short-name node)
4375 "No node found at point.")))))
4376
4377 (defun js2-node-at-point (&optional pos skip-comments)
4378 "Return AST node at POS, a buffer position, defaulting to current point.
4379 The `js2-mode-ast' variable must be set to the current parse tree.
4380 Signals an error if the AST (`js2-mode-ast') is nil.
4381 Always returns a node - if it can't find one, it returns the root.
4382 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4383 (let ((ast js2-mode-ast)
4384 result)
4385 (unless ast
4386 (error "No JavaScript AST available"))
4387 ;; Look through comments first, since they may be inside nodes that
4388 ;; would otherwise report a match.
4389 (setq pos (or pos (point))
4390 result (if (> pos (js2-node-abs-end ast))
4391 ast
4392 (if (not skip-comments)
4393 (js2-comment-at-point pos))))
4394 (unless result
4395 (setq js2-discovered-node nil
4396 js2-visitor-offset 0
4397 js2-node-search-point pos)
4398 (unwind-protect
4399 (catch 'js2-visit-done
4400 (js2-visit-ast ast #'js2-node-at-point-visitor))
4401 (setq js2-visitor-offset nil
4402 js2-node-search-point nil))
4403 (setq result js2-discovered-node))
4404 ;; may have found a comment beyond end of last child node,
4405 ;; since visiting the ast-root looks at the comment-list last.
4406 (if (and skip-comments
4407 (js2-comment-node-p result))
4408 (setq result nil))
4409 (or result js2-mode-ast)))
4410
4411 (defun js2-node-at-point-visitor (node end-p)
4412 (let ((rel-pos (js2-node-pos node))
4413 abs-pos
4414 abs-end
4415 (point js2-node-search-point))
4416 (cond
4417 (end-p
4418 ;; this evaluates to a non-nil return value, even if it's zero
4419 (decf js2-visitor-offset rel-pos))
4420 ;; we already looked for comments before visiting, and don't want them now
4421 ((js2-comment-node-p node)
4422 nil)
4423 (t
4424 (setq abs-pos (incf js2-visitor-offset rel-pos)
4425 ;; we only want to use the node if the point is before
4426 ;; the last character position in the node, so we decrement
4427 ;; the absolute end by 1.
4428 abs-end (+ abs-pos (js2-node-len node) -1))
4429 (cond
4430 ;; If this node starts after search-point, stop the search.
4431 ((> abs-pos point)
4432 (throw 'js2-visit-done nil))
4433 ;; If this node ends before the search-point, don't check kids.
4434 ((> point abs-end)
4435 nil)
4436 (t
4437 ;; Otherwise point is within this node, possibly in a child.
4438 (setq js2-discovered-node node)
4439 t)))))) ; keep processing kids to look for more specific match
4440
4441 (defsubst js2-block-comment-p (node)
4442 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4443 (and (js2-comment-node-p node)
4444 (memq (js2-comment-node-format node) '(jsdoc block))))
4445
4446 ;; TODO: put the comments in a vector and binary-search them instead
4447 (defun js2-comment-at-point (&optional pos)
4448 "Look through scanned comment nodes for one containing POS.
4449 POS is a buffer position that defaults to current point.
4450 Function returns nil if POS was not in any comment node."
4451 (let ((ast js2-mode-ast)
4452 (x (or pos (point)))
4453 beg end)
4454 (unless ast
4455 (error "No JavaScript AST available"))
4456 (catch 'done
4457 ;; Comments are stored in lexical order.
4458 (dolist (comment (js2-ast-root-comments ast) nil)
4459 (setq beg (js2-node-abs-pos comment)
4460 end (+ beg (js2-node-len comment)))
4461 (if (and (>= x beg)
4462 (<= x end))
4463 (throw 'done comment))))))
4464
4465 (defun js2-mode-find-parent-fn (node)
4466 "Find function enclosing NODE.
4467 Returns nil if NODE is not inside a function."
4468 (setq node (js2-node-parent node))
4469 (while (and node (not (js2-function-node-p node)))
4470 (setq node (js2-node-parent node)))
4471 (and (js2-function-node-p node) node))
4472
4473 (defun js2-mode-find-enclosing-fn (node)
4474 "Find function or root enclosing NODE."
4475 (if (js2-ast-root-p node)
4476 node
4477 (setq node (js2-node-parent node))
4478 (while (not (or (js2-ast-root-p node)
4479 (js2-function-node-p node)))
4480 (setq node (js2-node-parent node)))
4481 node))
4482
4483 (defun js2-mode-find-enclosing-node (beg end)
4484 "Find script or function fully enclosing BEG and END."
4485 (let ((node (js2-node-at-point beg))
4486 pos
4487 (continue t))
4488 (while continue
4489 (if (or (js2-ast-root-p node)
4490 (and (js2-function-node-p node)
4491 (<= (setq pos (js2-node-abs-pos node)) beg)
4492 (>= (+ pos (js2-node-len node)) end)))
4493 (setq continue nil)
4494 (setq node (js2-node-parent node))))
4495 node))
4496
4497 (defun js2-node-parent-script-or-fn (node)
4498 "Find script or function immediately enclosing NODE.
4499 If NODE is the ast-root, returns nil."
4500 (if (js2-ast-root-p node)
4501 nil
4502 (setq node (js2-node-parent node))
4503 (while (and node (not (or (js2-function-node-p node)
4504 (js2-script-node-p node))))
4505 (setq node (js2-node-parent node)))
4506 node))
4507
4508 (defun js2-nested-function-p (node)
4509 "Return t if NODE is a nested function, or is inside a nested function."
4510 (unless (js2-ast-root-p node)
4511 (js2-function-node-p (if (js2-function-node-p node)
4512 (js2-node-parent-script-or-fn node)
4513 (js2-node-parent-script-or-fn
4514 (js2-node-parent-script-or-fn node))))))
4515
4516 (defun js2-mode-shift-kids (kids start offset)
4517 (dolist (kid kids)
4518 (if (> (js2-node-pos kid) start)
4519 (incf (js2-node-pos kid) offset))))
4520
4521 (defun js2-mode-shift-children (parent start offset)
4522 "Update start-positions of all children of PARENT beyond START."
4523 (let ((root (js2-node-root parent)))
4524 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4525 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4526
4527 (defun js2-node-is-descendant (node ancestor)
4528 "Return t if NODE is a descendant of ANCESTOR."
4529 (while (and node
4530 (not (eq node ancestor)))
4531 (setq node (js2-node-parent node)))
4532 node)
4533
4534 ;;; visitor infrastructure
4535
4536 (defun js2-visit-none (node callback)
4537 "Visitor for AST node that have no node children."
4538 nil)
4539
4540 (defun js2-print-none (node indent)
4541 "Visitor for AST node with no printed representation.")
4542
4543 (defun js2-print-body (node indent)
4544 "Print a statement, or a block without braces."
4545 (if (js2-block-node-p node)
4546 (dolist (kid (js2-block-node-kids node))
4547 (js2-print-ast kid indent))
4548 (js2-print-ast node indent)))
4549
4550 (defun js2-print-list (args &optional delimiter)
4551 (loop with len = (length args)
4552 for arg in args
4553 for count from 1
4554 do
4555 (when arg (js2-print-ast arg 0))
4556 (if (< count len)
4557 (insert (or delimiter ", ")))))
4558
4559 (defun js2-print-tree (ast)
4560 "Prints an AST to the current buffer.
4561 Makes `js2-ast-parent-nodes' available to the printer functions."
4562 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4563 (js2-print-ast ast)))
4564
4565 (defun js2-print-ast (node &optional indent)
4566 "Helper function for printing AST nodes.
4567 Requires `js2-ast-parent-nodes' to be non-nil.
4568 You should use `js2-print-tree' instead of this function."
4569 (let ((printer (get (aref node 0) 'js2-printer))
4570 (i (or indent 0))
4571 (pos (js2-node-abs-pos node)))
4572 ;; TODO: wedge comments in here somewhere
4573 (if printer
4574 (funcall printer node i))))
4575
4576 (defconst js2-side-effecting-tokens
4577 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4578 (dolist (tt (list js2-ASSIGN
4579 js2-ASSIGN_ADD
4580 js2-ASSIGN_BITAND
4581 js2-ASSIGN_BITOR
4582 js2-ASSIGN_BITXOR
4583 js2-ASSIGN_DIV
4584 js2-ASSIGN_LSH
4585 js2-ASSIGN_MOD
4586 js2-ASSIGN_MUL
4587 js2-ASSIGN_RSH
4588 js2-ASSIGN_SUB
4589 js2-ASSIGN_URSH
4590 js2-BLOCK
4591 js2-BREAK
4592 js2-CALL
4593 js2-CATCH
4594 js2-CATCH_SCOPE
4595 js2-CONST
4596 js2-CONTINUE
4597 js2-DEBUGGER
4598 js2-DEC
4599 js2-DELPROP
4600 js2-DEL_REF
4601 js2-DO
4602 js2-ELSE
4603 js2-EMPTY
4604 js2-ENTERWITH
4605 js2-EXPORT
4606 js2-EXPR_RESULT
4607 js2-FINALLY
4608 js2-FOR
4609 js2-FUNCTION
4610 js2-GOTO
4611 js2-IF
4612 js2-IFEQ
4613 js2-IFNE
4614 js2-IMPORT
4615 js2-INC
4616 js2-JSR
4617 js2-LABEL
4618 js2-LEAVEWITH
4619 js2-LET
4620 js2-LETEXPR
4621 js2-LOCAL_BLOCK
4622 js2-LOOP
4623 js2-NEW
4624 js2-REF_CALL
4625 js2-RETHROW
4626 js2-RETURN
4627 js2-RETURN_RESULT
4628 js2-SEMI
4629 js2-SETELEM
4630 js2-SETELEM_OP
4631 js2-SETNAME
4632 js2-SETPROP
4633 js2-SETPROP_OP
4634 js2-SETVAR
4635 js2-SET_REF
4636 js2-SET_REF_OP
4637 js2-SWITCH
4638 js2-TARGET
4639 js2-THROW
4640 js2-TRY
4641 js2-VAR
4642 js2-WHILE
4643 js2-WITH
4644 js2-WITHEXPR
4645 js2-YIELD))
4646 (aset tokens tt t))
4647 (if js2-instanceof-has-side-effects
4648 (aset tokens js2-INSTANCEOF t))
4649 tokens))
4650
4651 (defun js2-node-has-side-effects (node)
4652 "Return t if NODE has side effects."
4653 (when node ; makes it easier to handle malformed expressions
4654 (let ((tt (js2-node-type node)))
4655 (cond
4656 ;; This doubtless needs some work, since EXPR_VOID is used
4657 ;; in several ways in Rhino and I may not have caught them all.
4658 ;; I'll wait for people to notice incorrect warnings.
4659 ((and (= tt js2-EXPR_VOID)
4660 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4661 (let ((expr (js2-expr-stmt-node-expr node)))
4662 (or (js2-node-has-side-effects expr)
4663 (when (js2-string-node-p expr)
4664 (string= "use strict" (js2-string-node-value expr))))))
4665 ((= tt js2-COMMA)
4666 (js2-node-has-side-effects (js2-infix-node-right node)))
4667 ((or (= tt js2-AND)
4668 (= tt js2-OR))
4669 (or (js2-node-has-side-effects (js2-infix-node-right node))
4670 (js2-node-has-side-effects (js2-infix-node-left node))))
4671 ((= tt js2-HOOK)
4672 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4673 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4674 ((js2-paren-node-p node)
4675 (js2-node-has-side-effects (js2-paren-node-expr node)))
4676 ((= tt js2-ERROR) ; avoid cascaded error messages
4677 nil)
4678 (t
4679 (aref js2-side-effecting-tokens tt))))))
4680
4681 (defun js2-member-expr-leftmost-name (node)
4682 "For an expr such as foo.bar.baz, return leftmost node foo.
4683 NODE is any `js2-node' object. If it represents a member expression,
4684 which is any sequence of property gets, element-gets, function calls,
4685 or xml descendants/filter operators, then we look at the lexically
4686 leftmost (first) node in the chain. If it is a name-node we return it.
4687 Note that NODE can be a raw name-node and it will be returned as well.
4688 If NODE is not a name-node or member expression, or if it is a member
4689 expression whose leftmost target is not a name node, returns nil."
4690 (let ((continue t)
4691 result)
4692 (while (and continue (not result))
4693 (cond
4694 ((js2-name-node-p node)
4695 (setq result node))
4696 ((js2-prop-get-node-p node)
4697 (setq node (js2-prop-get-node-left node)))
4698 ;; TODO: handle call-nodes, xml-nodes, others?
4699 (t
4700 (setq continue nil))))
4701 result))
4702
4703 (defconst js2-stmt-node-types
4704 (list js2-BLOCK
4705 js2-BREAK
4706 js2-CONTINUE
4707 js2-DEFAULT ; e4x "default xml namespace" statement
4708 js2-DO
4709 js2-EXPR_RESULT
4710 js2-EXPR_VOID
4711 js2-FOR
4712 js2-IF
4713 js2-RETURN
4714 js2-SWITCH
4715 js2-THROW
4716 js2-TRY
4717 js2-WHILE
4718 js2-WITH)
4719 "Node types that only appear in statement contexts.
4720 The list does not include nodes that always appear as the child
4721 of another specific statement type, such as switch-cases,
4722 catch and finally blocks, and else-clauses. The list also excludes
4723 nodes like yield, let and var, which may appear in either expression
4724 or statement context, and in the latter context always have a
4725 `js2-expr-stmt-node' parent. Finally, the list does not include
4726 functions or scripts, which are treated separately from statements
4727 by the JavaScript parser and runtime.")
4728
4729 (defun js2-stmt-node-p (node)
4730 "Heuristic for figuring out if NODE is a statement.
4731 Some node types can appear in either an expression context or a
4732 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4733 For these node types in a statement context, the parent will be a
4734 `js2-expr-stmt-node'.
4735 Functions aren't included in the check."
4736 (memq (js2-node-type node) js2-stmt-node-types))
4737
4738 (defun js2-mode-find-first-stmt (node)
4739 "Search upward starting from NODE looking for a statement.
4740 For purposes of this function, a `js2-function-node' counts."
4741 (while (not (or (js2-stmt-node-p node)
4742 (js2-function-node-p node)))
4743 (setq node (js2-node-parent node)))
4744 node)
4745
4746 (defun js2-node-parent-stmt (node)
4747 "Return the node's first ancestor that is a statement.
4748 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4749 appearing in a statement context will have a parent that is a
4750 `js2-expr-stmt-node' that will be returned by this function."
4751 (let ((parent (js2-node-parent node)))
4752 (if (or (null parent)
4753 (js2-stmt-node-p parent)
4754 (and (js2-function-node-p parent)
4755 (not (eq (js2-function-node-form parent)
4756 'FUNCTION_EXPRESSION))))
4757 parent
4758 (js2-node-parent-stmt parent))))
4759
4760 ;; In the Mozilla Rhino sources, Roshan James writes:
4761 ;; Does consistent-return analysis on the function body when strict mode is
4762 ;; enabled.
4763 ;;
4764 ;; function (x) { return (x+1) }
4765 ;;
4766 ;; is ok, but
4767 ;;
4768 ;; function (x) { if (x < 0) return (x+1); }
4769 ;;
4770 ;; is not because the function can potentially return a value when the
4771 ;; condition is satisfied and if not, the function does not explicitly
4772 ;; return a value.
4773 ;;
4774 ;; This extends to checking mismatches such as "return" and "return <value>"
4775 ;; used in the same function. Warnings are not emitted if inconsistent
4776 ;; returns exist in code that can be statically shown to be unreachable.
4777 ;; Ex.
4778 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4779 ;;
4780 ;; emits no warning. However if the loop had a break statement, then a
4781 ;; warning would be emitted.
4782 ;;
4783 ;; The consistency analysis looks at control structures such as loops, ifs,
4784 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4785 ;; warns the user about an inconsistent set of termination possibilities.
4786 ;;
4787 ;; These flags enumerate the possible ways a statement/function can
4788 ;; terminate. These flags are used by endCheck() and by the Parser to
4789 ;; detect inconsistent return usage.
4790 ;;
4791 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4792 ;; able to execute (example: throw, continue)
4793 ;;
4794 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4795 ;; next one. Statement such as return dont. A compound statement may have
4796 ;; some branch that drops off control to the next statement.
4797 ;;
4798 ;; END_RETURNS indicates that the statement can return with no value.
4799 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4800 ;;
4801 ;; A compound statement such as
4802 ;; if (condition) {
4803 ;; return value;
4804 ;; }
4805 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4806
4807 (defconst js2-END_UNREACHED 0)
4808 (defconst js2-END_DROPS_OFF 1)
4809 (defconst js2-END_RETURNS 2)
4810 (defconst js2-END_RETURNS_VALUE 4)
4811 (defconst js2-END_YIELDS 8)
4812
4813 (defun js2-has-consistent-return-usage (node)
4814 "Check that every return usage in a function body is consistent.
4815 Returns t if the function satisfies strict mode requirement."
4816 (let ((n (js2-end-check node)))
4817 ;; either it doesn't return a value in any branch...
4818 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4819 ;; or it returns a value (or is unreached) at every branch
4820 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4821 js2-END_RETURNS
4822 js2-END_YIELDS)))))
4823
4824 (defun js2-end-check-if (node)
4825 "Ensure that return usage in then/else blocks is consistent.
4826 If there is no else block, then the return statement can fall through.
4827 Returns logical OR of END_* flags"
4828 (let ((th (js2-if-node-then-part node))
4829 (el (js2-if-node-else-part node)))
4830 (if (null th)
4831 js2-END_UNREACHED
4832 (logior (js2-end-check th) (if el
4833 (js2-end-check el)
4834 js2-END_DROPS_OFF)))))
4835
4836 (defun js2-end-check-switch (node)
4837 "Consistency of return statements is checked between the case statements.
4838 If there is no default, then the switch can fall through. If there is a
4839 default, we check to see if all code paths in the default return or if
4840 there is a code path that can fall through.
4841 Returns logical OR of END_* flags."
4842 (let ((rv js2-END_UNREACHED)
4843 default-case)
4844 ;; examine the cases
4845 (catch 'break
4846 (dolist (c (js2-switch-node-cases node))
4847 (if (js2-case-node-expr c)
4848 (js2-set-flag rv (js2-end-check-block c))
4849 (setq default-case c)
4850 (throw 'break nil))))
4851 ;; we don't care how the cases drop into each other
4852 (js2-clear-flag rv js2-END_DROPS_OFF)
4853 ;; examine the default
4854 (js2-set-flag rv (if default-case
4855 (js2-end-check default-case)
4856 js2-END_DROPS_OFF))
4857 rv))
4858
4859 (defun js2-end-check-try (node)
4860 "If the block has a finally, return consistency is checked in the
4861 finally block. If all code paths in the finally return, then the
4862 returns in the try-catch blocks don't matter. If there is a code path
4863 that does not return or if there is no finally block, the returns
4864 of the try and catch blocks are checked for mismatch.
4865 Returns logical OR of END_* flags."
4866 (let ((finally (js2-try-node-finally-block node))
4867 rv)
4868 ;; check the finally if it exists
4869 (setq rv (if finally
4870 (js2-end-check (js2-finally-node-body finally))
4871 js2-END_DROPS_OFF))
4872 ;; If the finally block always returns, then none of the returns
4873 ;; in the try or catch blocks matter.
4874 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
4875 (js2-clear-flag rv js2-END_DROPS_OFF)
4876 ;; examine the try block
4877 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
4878 ;; check each catch block
4879 (dolist (cb (js2-try-node-catch-clauses node))
4880 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
4881 rv))
4882
4883 (defun js2-end-check-loop (node)
4884 "Return statement in the loop body must be consistent.
4885 The default assumption for any kind of a loop is that it will eventually
4886 terminate. The only exception is a loop with a constant true condition.
4887 Code that follows such a loop is examined only if one can determine
4888 statically that there is a break out of the loop.
4889
4890 for(... ; ... ; ...) {}
4891 for(... in ... ) {}
4892 while(...) { }
4893 do { } while(...)
4894
4895 Returns logical OR of END_* flags."
4896 (let ((rv (js2-end-check (js2-loop-node-body node)))
4897 (condition (cond
4898 ((js2-while-node-p node)
4899 (js2-while-node-condition node))
4900 ((js2-do-node-p node)
4901 (js2-do-node-condition node))
4902 ((js2-for-node-p node)
4903 (js2-for-node-condition node)))))
4904
4905 ;; check to see if the loop condition is always true
4906 (if (and condition
4907 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
4908 (js2-clear-flag rv js2-END_DROPS_OFF))
4909
4910 ;; look for effect of breaks
4911 (js2-set-flag rv (js2-node-get-prop node
4912 'CONTROL_BLOCK_PROP
4913 js2-END_UNREACHED))
4914 rv))
4915
4916 (defun js2-end-check-block (node)
4917 "A general block of code is examined statement by statement.
4918 If any statement (even a compound one) returns in all branches, then
4919 subsequent statements are not examined.
4920 Returns logical OR of END_* flags."
4921 (let* ((rv js2-END_DROPS_OFF)
4922 (kids (js2-block-node-kids node))
4923 (n (car kids)))
4924 ;; Check each statment. If the statement can continue onto the next
4925 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
4926 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
4927 (js2-clear-flag rv js2-END_DROPS_OFF)
4928 (js2-set-flag rv (js2-end-check n))
4929 (setq kids (cdr kids)
4930 n (car kids)))
4931 rv))
4932
4933 (defun js2-end-check-label (node)
4934 "A labeled statement implies that there may be a break to the label.
4935 The function processes the labeled statement and then checks the
4936 CONTROL_BLOCK_PROP property to see if there is ever a break to the
4937 particular label.
4938 Returns logical OR of END_* flags."
4939 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
4940 (logior rv (js2-node-get-prop node
4941 'CONTROL_BLOCK_PROP
4942 js2-END_UNREACHED))))
4943
4944 (defun js2-end-check-break (node)
4945 "When a break is encountered annotate the statement being broken
4946 out of by setting its CONTROL_BLOCK_PROP property.
4947 Returns logical OR of END_* flags."
4948 (and (js2-break-node-target node)
4949 (js2-node-set-prop (js2-break-node-target node)
4950 'CONTROL_BLOCK_PROP
4951 js2-END_DROPS_OFF))
4952 js2-END_UNREACHED)
4953
4954 (defun js2-end-check (node)
4955 "Examine the body of a function, doing a basic reachability analysis.
4956 Returns a combination of flags END_* flags that indicate
4957 how the function execution can terminate. These constitute only the
4958 pessimistic set of termination conditions. It is possible that at
4959 runtime certain code paths will never be actually taken. Hence this
4960 analysis will flag errors in cases where there may not be errors.
4961 Returns logical OR of END_* flags"
4962 (let (kid)
4963 (cond
4964 ((js2-break-node-p node)
4965 (js2-end-check-break node))
4966 ((js2-expr-stmt-node-p node)
4967 (if (setq kid (js2-expr-stmt-node-expr node))
4968 (js2-end-check kid)
4969 js2-END_DROPS_OFF))
4970 ((or (js2-continue-node-p node)
4971 (js2-throw-node-p node))
4972 js2-END_UNREACHED)
4973 ((js2-return-node-p node)
4974 (if (setq kid (js2-return-node-retval node))
4975 js2-END_RETURNS_VALUE
4976 js2-END_RETURNS))
4977 ((js2-loop-node-p node)
4978 (js2-end-check-loop node))
4979 ((js2-switch-node-p node)
4980 (js2-end-check-switch node))
4981 ((js2-labeled-stmt-node-p node)
4982 (js2-end-check-label node))
4983 ((js2-if-node-p node)
4984 (js2-end-check-if node))
4985 ((js2-try-node-p node)
4986 (js2-end-check-try node))
4987 ((js2-block-node-p node)
4988 (if (null (js2-block-node-kids node))
4989 js2-END_DROPS_OFF
4990 (js2-end-check-block node)))
4991 ((js2-yield-node-p node)
4992 js2-END_YIELDS)
4993 (t
4994 js2-END_DROPS_OFF))))
4995
4996 (defun js2-always-defined-boolean-p (node)
4997 "Check if NODE always evaluates to true or false in boolean context.
4998 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
4999 nor always false."
5000 (let ((tt (js2-node-type node))
5001 num)
5002 (cond
5003 ((or (= tt js2-FALSE) (= tt js2-NULL))
5004 'ALWAYS_FALSE)
5005 ((= tt js2-TRUE)
5006 'ALWAYS_TRUE)
5007 ((= tt js2-NUMBER)
5008 (setq num (js2-number-node-num-value node))
5009 (if (and (not (eq num 0.0e+NaN))
5010 (not (zerop num)))
5011 'ALWAYS_TRUE
5012 'ALWAYS_FALSE))
5013 (t
5014 nil))))
5015
5016 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5017 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5018
5019 (defvar js2-tokens nil
5020 "List of all defined token names.") ; initialized in `js2-token-names'
5021
5022 (defconst js2-token-names
5023 (let* ((names (make-vector js2-num-tokens -1))
5024 (case-fold-search nil) ; only match js2-UPPER_CASE
5025 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5026 (loop for sym in syms
5027 for i from 0
5028 do
5029 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5030 (not (boundp sym)))
5031 (aset names (symbol-value sym) ; code, e.g. 152
5032 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5033 (push sym js2-tokens)))
5034 names)
5035 "Vector mapping int values to token string names, sans `js2-' prefix.")
5036
5037 (defun js2-token-name (tok)
5038 "Return a string name for TOK, a token symbol or code.
5039 Signals an error if it's not a recognized token."
5040 (let ((code tok))
5041 (if (symbolp tok)
5042 (setq code (symbol-value tok)))
5043 (if (eq code -1)
5044 "ERROR"
5045 (if (and (numberp code)
5046 (not (minusp code))
5047 (< code js2-num-tokens))
5048 (aref js2-token-names code)
5049 (error "Invalid token: %s" code)))))
5050
5051 (defsubst js2-token-sym (tok)
5052 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5053 (intern (js2-token-name tok)))
5054
5055 (defconst js2-token-codes
5056 (let ((table (make-hash-table :test 'eq :size 256)))
5057 (loop for name across js2-token-names
5058 for sym = (intern (concat "js2-" name))
5059 do
5060 (puthash sym (symbol-value sym) table))
5061 ;; clean up a few that are "wrong" in Rhino's token codes
5062 (puthash 'js2-DELETE js2-DELPROP table)
5063 table)
5064 "Hashtable mapping token symbols to their bytecodes.")
5065
5066 (defsubst js2-token-code (sym)
5067 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5068 (or (gethash sym js2-token-codes)
5069 (error "Invalid token symbol: %s " sym))) ; signal code bug
5070
5071 (defun js2-report-scan-error (msg &optional no-throw beg len)
5072 (setq js2-token-end js2-ts-cursor)
5073 (js2-report-error msg nil
5074 (or beg js2-token-beg)
5075 (or len (- js2-token-end js2-token-beg)))
5076 (unless no-throw
5077 (throw 'return js2-ERROR)))
5078
5079 (defun js2-get-string-from-buffer ()
5080 "Reverse the char accumulator and return it as a string."
5081 (setq js2-token-end js2-ts-cursor)
5082 (if js2-ts-string-buffer
5083 (apply #'string (nreverse js2-ts-string-buffer))
5084 ""))
5085
5086 ;; TODO: could potentially avoid a lot of consing by allocating a
5087 ;; char buffer the way Rhino does.
5088 (defsubst js2-add-to-string (c)
5089 (push c js2-ts-string-buffer))
5090
5091 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5092 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5093 ;; any other character: when it's not part of the current token, we
5094 ;; unget it, allowing it to be read again by the following call.
5095 (defsubst js2-unget-char ()
5096 (decf js2-ts-cursor))
5097
5098 ;; Rhino distinguishes \r and \n line endings. We don't need to
5099 ;; because we only scan from Emacs buffers, which always use \n.
5100 (defun js2-get-char ()
5101 "Read and return the next character from the input buffer.
5102 Increments `js2-ts-lineno' if the return value is a newline char.
5103 Updates `js2-ts-cursor' to the point after the returned char.
5104 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5105 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5106 (let (c)
5107 ;; check for end of buffer
5108 (if (>= js2-ts-cursor (point-max))
5109 (setq js2-ts-hit-eof t
5110 js2-ts-cursor (1+ js2-ts-cursor)
5111 c js2-EOF_CHAR) ; return value
5112 ;; otherwise read next char
5113 (setq c (char-before (incf js2-ts-cursor)))
5114 ;; if we read a newline, update counters
5115 (if (= c ?\n)
5116 (setq js2-ts-line-start js2-ts-cursor
5117 js2-ts-lineno (1+ js2-ts-lineno)))
5118 ;; TODO: skip over format characters
5119 c)))
5120
5121 (defun js2-read-unicode-escape ()
5122 "Read a \\uNNNN sequence from the input.
5123 Assumes the ?\ and ?u have already been read.
5124 Returns the unicode character, or nil if it wasn't a valid character.
5125 Doesn't change the values of any scanner variables."
5126 ;; I really wish I knew a better way to do this, but I can't
5127 ;; find the Emacs function that takes a 16-bit int and converts
5128 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5129 ;; Have to first check that it's 4 hex characters or it may stop
5130 ;; the read early.
5131 (ignore-errors
5132 (let ((s (buffer-substring-no-properties js2-ts-cursor
5133 (+ 4 js2-ts-cursor))))
5134 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5135 (read (concat "?\\u" s))))))
5136
5137 (defun js2-match-char (test)
5138 "Consume and return next character if it matches TEST, a character.
5139 Returns nil and consumes nothing if TEST is not the next character."
5140 (let ((c (js2-get-char)))
5141 (if (eq c test)
5142 t
5143 (js2-unget-char)
5144 nil)))
5145
5146 (defun js2-peek-char ()
5147 (prog1
5148 (js2-get-char)
5149 (js2-unget-char)))
5150
5151 (defun js2-java-identifier-start-p (c)
5152 (or
5153 (memq c '(?$ ?_))
5154 (js2-char-uppercase-p c)
5155 (js2-char-lowercase-p c)))
5156
5157 (defun js2-java-identifier-part-p (c)
5158 "Implementation of java.lang.Character.isJavaIdentifierPart()."
5159 ;; TODO: make me Unicode-friendly. See comments above.
5160 (or
5161 (memq c '(?$ ?_))
5162 (js2-char-uppercase-p c)
5163 (js2-char-lowercase-p c)
5164 (and (>= c ?0) (<= c ?9))))
5165
5166 (defun js2-alpha-p (c)
5167 (cond ((and (<= ?A c) (<= c ?Z)) t)
5168 ((and (<= ?a c) (<= c ?z)) t)
5169 (t nil)))
5170
5171 (defsubst js2-digit-p (c)
5172 (and (<= ?0 c) (<= c ?9)))
5173
5174 (defun js2-js-space-p (c)
5175 (if (<= c 127)
5176 (memq c '(#x20 #x9 #xB #xC #xD))
5177 (or
5178 (eq c #xA0)
5179 ;; TODO: change this nil to check for Unicode space character
5180 nil)))
5181
5182 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5183
5184 (defun js2-skip-line ()
5185 "Skip to end of line."
5186 (let (c)
5187 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5188 (js2-unget-char)
5189 (setq js2-token-end js2-ts-cursor)))
5190
5191 (defun js2-init-scanner (&optional buf line)
5192 "Create token stream for BUF starting on LINE.
5193 BUF defaults to `current-buffer' and LINE defaults to 1.
5194
5195 A buffer can only have one scanner active at a time, which yields
5196 dramatically simpler code than using a defstruct. If you need to
5197 have simultaneous scanners in a buffer, copy the regions to scan
5198 into temp buffers."
5199 (with-current-buffer (or buf (current-buffer))
5200 (setq js2-ts-dirty-line nil
5201 js2-ts-regexp-flags nil
5202 js2-ts-string ""
5203 js2-ts-number nil
5204 js2-ts-hit-eof nil
5205 js2-ts-line-start 0
5206 js2-ts-lineno (or line 1)
5207 js2-ts-line-end-char -1
5208 js2-ts-cursor (point-min)
5209 js2-ts-is-xml-attribute nil
5210 js2-ts-xml-is-tag-content nil
5211 js2-ts-xml-open-tags-count 0
5212 js2-ts-string-buffer nil)))
5213
5214 ;; This function uses the cached op, string and number fields in
5215 ;; TokenStream; if getToken has been called since the passed token
5216 ;; was scanned, the op or string printed may be incorrect.
5217 (defun js2-token-to-string (token)
5218 ;; Not sure where this function is used in Rhino. Not tested.
5219 (if (not js2-debug-print-trees)
5220 ""
5221 (let ((name (js2-token-name token)))
5222 (cond
5223 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5224 (concat name " `" js2-ts-string "'"))
5225 ((eq token js2-NUMBER)
5226 (format "NUMBER %g" js2-ts-number))
5227 (t
5228 name)))))
5229
5230 (defconst js2-keywords
5231 '(break
5232 case catch const continue
5233 debugger default delete do
5234 else enum
5235 false finally for function
5236 if in instanceof import
5237 let
5238 new null
5239 return
5240 switch
5241 this throw true try typeof
5242 var void
5243 while with
5244 yield))
5245
5246 ;; Token names aren't exactly the same as the keywords, unfortunately.
5247 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5248 (defconst js2-kwd-tokens
5249 (let ((table (make-vector js2-num-tokens nil))
5250 (tokens
5251 (list js2-BREAK
5252 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5253 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5254 js2-ELSE
5255 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5256 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5257 js2-LET
5258 js2-NEW js2-NULL
5259 js2-RETURN
5260 js2-SWITCH
5261 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5262 js2-VAR
5263 js2-WHILE js2-WITH
5264 js2-YIELD)))
5265 (dolist (i tokens)
5266 (aset table i 'font-lock-keyword-face))
5267 (aset table js2-STRING 'font-lock-string-face)
5268 (aset table js2-REGEXP 'font-lock-string-face)
5269 (aset table js2-COMMENT 'font-lock-comment-face)
5270 (aset table js2-THIS 'font-lock-builtin-face)
5271 (aset table js2-VOID 'font-lock-constant-face)
5272 (aset table js2-NULL 'font-lock-constant-face)
5273 (aset table js2-TRUE 'font-lock-constant-face)
5274 (aset table js2-FALSE 'font-lock-constant-face)
5275 table)
5276 "Vector whose values are non-nil for tokens that are keywords.
5277 The values are default faces to use for highlighting the keywords.")
5278
5279 (defconst js2-reserved-words
5280 '(abstract
5281 boolean byte
5282 char class
5283 double
5284 enum export extends
5285 final float
5286 goto
5287 implements import int interface
5288 long
5289 native
5290 package private protected public
5291 short static super synchronized
5292 throws transient
5293 volatile))
5294
5295 (defconst js2-keyword-names
5296 (let ((table (make-hash-table :test 'equal)))
5297 (loop for k in js2-keywords
5298 do (puthash
5299 (symbol-name k) ; instanceof
5300 (intern (concat "js2-"
5301 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5302 table))
5303 table)
5304 "JavaScript keywords by name, mapped to their symbols.")
5305
5306 (defconst js2-reserved-word-names
5307 (let ((table (make-hash-table :test 'equal)))
5308 (loop for k in js2-reserved-words
5309 do
5310 (puthash (symbol-name k) 'js2-RESERVED table))
5311 table)
5312 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5313
5314 (defun js2-collect-string (buf)
5315 "Convert BUF, a list of chars, to a string.
5316 Reverses BUF before converting."
5317 (cond
5318 ((stringp buf)
5319 buf)
5320 ((null buf) ; for emacs21 compat
5321 "")
5322 (t
5323 (if buf
5324 (apply #'string (nreverse buf))
5325 ""))))
5326
5327 (defun js2-string-to-keyword (s)
5328 "Return token for S, a string, if S is a keyword or reserved word.
5329 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5330 (or (gethash s js2-keyword-names)
5331 (gethash s js2-reserved-word-names)))
5332
5333 (defsubst js2-ts-set-char-token-bounds ()
5334 "Used when next token is one character."
5335 (setq js2-token-beg (1- js2-ts-cursor)
5336 js2-token-end js2-ts-cursor))
5337
5338 (defsubst js2-ts-return (token)
5339 "Return an N-character TOKEN from `js2-get-token'.
5340 Updates `js2-token-end' accordingly."
5341 (setq js2-token-end js2-ts-cursor)
5342 (throw 'return token))
5343
5344 (defun js2-x-digit-to-int (c accumulator)
5345 "Build up a hex number.
5346 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5347 corresponding number. Otherwise return -1."
5348 (catch 'return
5349 (catch 'check
5350 ;; Use 0..9 < A..Z < a..z
5351 (cond
5352 ((<= c ?9)
5353 (decf c ?0)
5354 (if (<= 0 c)
5355 (throw 'check nil)))
5356 ((<= c ?F)
5357 (when (<= ?A c)
5358 (decf c (- ?A 10))
5359 (throw 'check nil)))
5360 ((<= c ?f)
5361 (when (<= ?a c)
5362 (decf c (- ?a 10))
5363 (throw 'check nil))))
5364 (throw 'return -1))
5365 (logior c (lsh accumulator 4))))
5366
5367 (defun js2-get-token ()
5368 "Return next JavaScript token, an int such as js2-RETURN."
5369 (let (c c1 identifier-start is-unicode-escape-start
5370 contains-escape escape-val escape-start str result base
5371 is-integer quote-char val look-for-slash continue)
5372 (catch 'return
5373 (while t
5374 ;; Eat whitespace, possibly sensitive to newlines.
5375 (setq continue t)
5376 (while continue
5377 (setq c (js2-get-char))
5378 (cond
5379 ((eq c js2-EOF_CHAR)
5380 (js2-ts-set-char-token-bounds)
5381 (throw 'return js2-EOF))
5382 ((eq c ?\n)
5383 (js2-ts-set-char-token-bounds)
5384 (setq js2-ts-dirty-line nil)
5385 (throw 'return js2-EOL))
5386 ((not (js2-js-space-p c))
5387 (if (/= c ?-) ; in case end of HTML comment
5388 (setq js2-ts-dirty-line t))
5389 (setq continue nil))))
5390 ;; Assume the token will be 1 char - fixed up below.
5391 (js2-ts-set-char-token-bounds)
5392 (when (eq c ?@)
5393 (throw 'return js2-XMLATTR))
5394 ;; identifier/keyword/instanceof?
5395 ;; watch out for starting with a <backslash>
5396 (cond
5397 ((eq c ?\\)
5398 (setq c (js2-get-char))
5399 (if (eq c ?u)
5400 (setq identifier-start t
5401 is-unicode-escape-start t
5402 js2-ts-string-buffer nil)
5403 (setq identifier-start nil)
5404 (js2-unget-char)
5405 (setq c ?\\)))
5406 (t
5407 (when (setq identifier-start (js2-java-identifier-start-p c))
5408 (setq js2-ts-string-buffer nil)
5409 (js2-add-to-string c))))
5410 (when identifier-start
5411 (setq contains-escape is-unicode-escape-start)
5412 (catch 'break
5413 (while t
5414 (if is-unicode-escape-start
5415 ;; strictly speaking we should probably push-back
5416 ;; all the bad characters if the <backslash>uXXXX
5417 ;; sequence is malformed. But since there isn't a
5418 ;; correct context(is there?) for a bad Unicode
5419 ;; escape sequence in an identifier, we can report
5420 ;; an error here.
5421 (progn
5422 (setq escape-val 0)
5423 (dotimes (i 4)
5424 (setq c (js2-get-char)
5425 escape-val (js2-x-digit-to-int c escape-val))
5426 ;; Next check takes care of c < 0 and bad escape
5427 (if (minusp escape-val)
5428 (throw 'break nil)))
5429 (if (minusp escape-val)
5430 (js2-report-scan-error "msg.invalid.escape" t))
5431 (js2-add-to-string escape-val)
5432 (setq is-unicode-escape-start nil))
5433 (setq c (js2-get-char))
5434 (cond
5435 ((eq c ?\\)
5436 (setq c (js2-get-char))
5437 (if (eq c ?u)
5438 (setq is-unicode-escape-start t
5439 contains-escape t)
5440 (js2-report-scan-error "msg.illegal.character" t)))
5441 (t
5442 (if (or (eq c js2-EOF_CHAR)
5443 (not (js2-java-identifier-part-p c)))
5444 (throw 'break nil))
5445 (js2-add-to-string c))))))
5446 (js2-unget-char)
5447 (setq str (js2-get-string-from-buffer))
5448 (unless contains-escape
5449 ;; OPT we shouldn't have to make a string (object!) to
5450 ;; check if it's a keyword.
5451 ;; Return the corresponding token if it's a keyword
5452 (when (setq result (js2-string-to-keyword str))
5453 (if (and (< js2-language-version 170)
5454 (memq result '(js2-LET js2-YIELD)))
5455 ;; LET and YIELD are tokens only in 1.7 and later
5456 (setq result 'js2-NAME))
5457 (if (not (eq result 'js2-RESERVED))
5458 (throw 'return (js2-token-code result)))
5459 (js2-report-warning "msg.reserved.keyword" str)))
5460 ;; If we want to intern these as Rhino does, just use (intern str)
5461 (setq js2-ts-string str)
5462 (throw 'return js2-NAME)) ; end identifier/kwd check
5463 ;; is it a number?
5464 (when (or (js2-digit-p c)
5465 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5466 (setq js2-ts-string-buffer nil
5467 base 10)
5468 (when (eq c ?0)
5469 (setq c (js2-get-char))
5470 (cond
5471 ((or (eq c ?x) (eq c ?X))
5472 (setq base 16)
5473 (setq c (js2-get-char)))
5474 ((js2-digit-p c)
5475 (setq base 8))
5476 (t
5477 (js2-add-to-string ?0))))
5478 (if (eq base 16)
5479 (while (<= 0 (js2-x-digit-to-int c 0))
5480 (js2-add-to-string c)
5481 (setq c (js2-get-char)))
5482 (while (and (<= ?0 c) (<= c ?9))
5483 ;; We permit 08 and 09 as decimal numbers, which
5484 ;; makes our behavior a superset of the ECMA
5485 ;; numeric grammar. We might not always be so
5486 ;; permissive, so we warn about it.
5487 (when (and (eq base 8) (>= c ?8))
5488 (js2-report-warning "msg.bad.octal.literal"
5489 (if (eq c ?8) "8" "9"))
5490 (setq base 10))
5491 (js2-add-to-string c)
5492 (setq c (js2-get-char))))
5493 (setq is-integer t)
5494 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5495 (setq is-integer nil)
5496 (when (eq c ?.)
5497 (loop do
5498 (js2-add-to-string c)
5499 (setq c (js2-get-char))
5500 while (js2-digit-p c)))
5501 (when (memq c '(?e ?E))
5502 (js2-add-to-string c)
5503 (setq c (js2-get-char))
5504 (when (memq c '(?+ ?-))
5505 (js2-add-to-string c)
5506 (setq c (js2-get-char)))
5507 (unless (js2-digit-p c)
5508 (js2-report-scan-error "msg.missing.exponent" t))
5509 (loop do
5510 (js2-add-to-string c)
5511 (setq c (js2-get-char))
5512 while (js2-digit-p c))))
5513 (js2-unget-char)
5514 (setq js2-ts-string (js2-get-string-from-buffer)
5515 js2-ts-number
5516 (if (and (eq base 10) (not is-integer))
5517 (string-to-number js2-ts-string)
5518 ;; TODO: call runtime number-parser. Some of it is in
5519 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5520 (string-to-number js2-ts-string)))
5521 (throw 'return js2-NUMBER))
5522 ;; is it a string?
5523 (when (memq c '(?\" ?\'))
5524 ;; We attempt to accumulate a string the fast way, by
5525 ;; building it directly out of the reader. But if there
5526 ;; are any escaped characters in the string, we revert to
5527 ;; building it out of a string buffer.
5528 (setq quote-char c
5529 js2-ts-string-buffer nil
5530 c (js2-get-char))
5531 (catch 'break
5532 (while (/= c quote-char)
5533 (catch 'continue
5534 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5535 (js2-unget-char)
5536 (setq js2-token-end js2-ts-cursor)
5537 (js2-report-error "msg.unterminated.string.lit")
5538 (throw 'return js2-STRING))
5539 (when (eq c ?\\)
5540 ;; We've hit an escaped character
5541 (setq c (js2-get-char))
5542 (case c
5543 (?b (setq c ?\b))
5544 (?f (setq c ?\f))
5545 (?n (setq c ?\n))
5546 (?r (setq c ?\r))
5547 (?t (setq c ?\t))
5548 (?v (setq c ?\v))
5549 (?u
5550 (setq c1 (js2-read-unicode-escape))
5551 (if js2-parse-ide-mode
5552 (if c1
5553 (progn
5554 ;; just copy the string in IDE-mode
5555 (js2-add-to-string ?\\)
5556 (js2-add-to-string ?u)
5557 (dotimes (i 3)
5558 (js2-add-to-string (js2-get-char)))
5559 (setq c (js2-get-char))) ; added at end of loop
5560 ;; flag it as an invalid escape
5561 (js2-report-warning "msg.invalid.escape"
5562 nil (- js2-ts-cursor 2) 6))
5563 ;; Get 4 hex digits; if the u escape is not
5564 ;; followed by 4 hex digits, use 'u' + the
5565 ;; literal character sequence that follows.
5566 (js2-add-to-string ?u)
5567 (setq escape-val 0)
5568 (dotimes (i 4)
5569 (setq c (js2-get-char)
5570 escape-val (js2-x-digit-to-int c escape-val))
5571 (if (minusp escape-val)
5572 (throw 'continue nil))
5573 (js2-add-to-string c))
5574 ;; prepare for replace of stored 'u' sequence by escape value
5575 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5576 c escape-val)))
5577 (?x
5578 ;; Get 2 hex digits, defaulting to 'x'+literal
5579 ;; sequence, as above.
5580 (setq c (js2-get-char)
5581 escape-val (js2-x-digit-to-int c 0))
5582 (if (minusp escape-val)
5583 (progn
5584 (js2-add-to-string ?x)
5585 (throw 'continue nil))
5586 (setq c1 c
5587 c (js2-get-char)
5588 escape-val (js2-x-digit-to-int c escape-val))
5589 (if (minusp escape-val)
5590 (progn
5591 (js2-add-to-string ?x)
5592 (js2-add-to-string c1)
5593 (throw 'continue nil))
5594 ;; got 2 hex digits
5595 (setq c escape-val))))
5596 (?\n
5597 ;; Remove line terminator after escape to follow
5598 ;; SpiderMonkey and C/C++
5599 (setq c (js2-get-char))
5600 (throw 'continue nil))
5601 (t
5602 (when (and (<= ?0 c) (< c ?8))
5603 (setq val (- c ?0)
5604 c (js2-get-char))
5605 (when (and (<= ?0 c) (< c ?8))
5606 (setq val (- (+ (* 8 val) c) ?0)
5607 c (js2-get-char))
5608 (when (and (<= ?0 c)
5609 (< c ?8)
5610 (< val #o37))
5611 ;; c is 3rd char of octal sequence only
5612 ;; if the resulting val <= 0377
5613 (setq val (- (+ (* 8 val) c) ?0)
5614 c (js2-get-char))))
5615 (js2-unget-char)
5616 (setq c val)))))
5617 (js2-add-to-string c)
5618 (setq c (js2-get-char)))))
5619 (setq js2-ts-string (js2-get-string-from-buffer))
5620 (throw 'return js2-STRING))
5621 (case c
5622 (?\;
5623 (throw 'return js2-SEMI))
5624 (?\[
5625 (throw 'return js2-LB))
5626 (?\]
5627 (throw 'return js2-RB))
5628 (?{
5629 (throw 'return js2-LC))
5630 (?}
5631 (throw 'return js2-RC))
5632 (?\(
5633 (throw 'return js2-LP))
5634 (?\)
5635 (throw 'return js2-RP))
5636 (?,
5637 (throw 'return js2-COMMA))
5638 (??
5639 (throw 'return js2-HOOK))
5640 (?:
5641 (if (js2-match-char ?:)
5642 (js2-ts-return js2-COLONCOLON)
5643 (throw 'return js2-COLON)))
5644 (?.
5645 (if (js2-match-char ?.)
5646 (js2-ts-return js2-DOTDOT)
5647 (if (js2-match-char ?\()
5648 (js2-ts-return js2-DOTQUERY)
5649 (throw 'return js2-DOT))))
5650 (?|
5651 (if (js2-match-char ?|)
5652 (throw 'return js2-OR)
5653 (if (js2-match-char ?=)
5654 (js2-ts-return js2-ASSIGN_BITOR)
5655 (throw 'return js2-BITOR))))
5656 (?^
5657 (if (js2-match-char ?=)
5658 (js2-ts-return js2-ASSIGN_BITOR)
5659 (throw 'return js2-BITXOR)))
5660 (?&
5661 (if (js2-match-char ?&)
5662 (throw 'return js2-AND)
5663 (if (js2-match-char ?=)
5664 (js2-ts-return js2-ASSIGN_BITAND)
5665 (throw 'return js2-BITAND))))
5666 (?=
5667 (if (js2-match-char ?=)
5668 (if (js2-match-char ?=)
5669 (js2-ts-return js2-SHEQ)
5670 (throw 'return js2-EQ))
5671 (throw 'return js2-ASSIGN)))
5672 (?!
5673 (if (js2-match-char ?=)
5674 (if (js2-match-char ?=)
5675 (js2-ts-return js2-SHNE)
5676 (js2-ts-return js2-NE))
5677 (throw 'return js2-NOT)))
5678 (?<
5679 ;; NB:treat HTML begin-comment as comment-till-eol
5680 (when (js2-match-char ?!)
5681 (when (js2-match-char ?-)
5682 (when (js2-match-char ?-)
5683 (js2-skip-line)
5684 (setq js2-ts-comment-type 'html)
5685 (throw 'return js2-COMMENT)))
5686 (js2-unget-char))
5687 (if (js2-match-char ?<)
5688 (if (js2-match-char ?=)
5689 (js2-ts-return js2-ASSIGN_LSH)
5690 (js2-ts-return js2-LSH))
5691 (if (js2-match-char ?=)
5692 (js2-ts-return js2-LE)
5693 (throw 'return js2-LT))))
5694 (?>
5695 (if (js2-match-char ?>)
5696 (if (js2-match-char ?>)
5697 (if (js2-match-char ?=)
5698 (js2-ts-return js2-ASSIGN_URSH)
5699 (js2-ts-return js2-URSH))
5700 (if (js2-match-char ?=)
5701 (js2-ts-return js2-ASSIGN_RSH)
5702 (js2-ts-return js2-RSH)))
5703 (if (js2-match-char ?=)
5704 (js2-ts-return js2-GE)
5705 (throw 'return js2-GT))))
5706 (?*
5707 (if (js2-match-char ?=)
5708 (js2-ts-return js2-ASSIGN_MUL)
5709 (throw 'return js2-MUL)))
5710 (?/
5711 ;; is it a // comment?
5712 (when (js2-match-char ?/)
5713 (setq js2-token-beg (- js2-ts-cursor 2))
5714 (js2-skip-line)
5715 (setq js2-ts-comment-type 'line)
5716 ;; include newline so highlighting goes to end of window
5717 (incf js2-token-end)
5718 (throw 'return js2-COMMENT))
5719 ;; is it a /* comment?
5720 (when (js2-match-char ?*)
5721 (setq look-for-slash nil
5722 js2-token-beg (- js2-ts-cursor 2)
5723 js2-ts-comment-type
5724 (if (js2-match-char ?*)
5725 (progn
5726 (setq look-for-slash t)
5727 'jsdoc)
5728 'block))
5729 (while t
5730 (setq c (js2-get-char))
5731 (cond
5732 ((eq c js2-EOF_CHAR)
5733 (setq js2-token-end (1- js2-ts-cursor))
5734 (js2-report-error "msg.unterminated.comment")
5735 (throw 'return js2-COMMENT))
5736 ((eq c ?*)
5737 (setq look-for-slash t))
5738 ((eq c ?/)
5739 (if look-for-slash
5740 (js2-ts-return js2-COMMENT)))
5741 (t
5742 (setq look-for-slash nil
5743 js2-token-end js2-ts-cursor)))))
5744 (if (js2-match-char ?=)
5745 (js2-ts-return js2-ASSIGN_DIV)
5746 (throw 'return js2-DIV)))
5747 (?#
5748 (when js2-skip-preprocessor-directives
5749 (js2-skip-line)
5750 (setq js2-ts-comment-type 'preprocessor
5751 js2-token-end js2-ts-cursor)
5752 (throw 'return js2-COMMENT))
5753 (throw 'return js2-ERROR))
5754 (?%
5755 (if (js2-match-char ?=)
5756 (js2-ts-return js2-ASSIGN_MOD)
5757 (throw 'return js2-MOD)))
5758 (?~
5759 (throw 'return js2-BITNOT))
5760 (?+
5761 (if (js2-match-char ?=)
5762 (js2-ts-return js2-ASSIGN_ADD)
5763 (if (js2-match-char ?+)
5764 (js2-ts-return js2-INC)
5765 (throw 'return js2-ADD))))
5766 (?-
5767 (cond
5768 ((js2-match-char ?=)
5769 (setq c js2-ASSIGN_SUB))
5770 ((js2-match-char ?-)
5771 (unless js2-ts-dirty-line
5772 ;; treat HTML end-comment after possible whitespace
5773 ;; after line start as comment-until-eol
5774 (when (js2-match-char ?>)
5775 (js2-skip-line)
5776 (setq js2-ts-comment-type 'html)
5777 (throw 'return js2-COMMENT)))
5778 (setq c js2-DEC))
5779 (t
5780 (setq c js2-SUB)))
5781 (setq js2-ts-dirty-line t)
5782 (js2-ts-return c))
5783 (otherwise
5784 (js2-report-scan-error "msg.illegal.character")))))))
5785
5786 (defun js2-read-regexp (start-token)
5787 "Called by parser when it gets / or /= in literal context."
5788 (let (c err
5789 in-class ; inside a '[' .. ']' character-class
5790 flags
5791 (continue t))
5792 (setq js2-token-beg js2-ts-cursor
5793 js2-ts-string-buffer nil
5794 js2-ts-regexp-flags nil)
5795 (if (eq start-token js2-ASSIGN_DIV)
5796 ;; mis-scanned /=
5797 (js2-add-to-string ?=)
5798 (if (not (eq start-token js2-DIV))
5799 (error "failed assertion")))
5800 (while (and (not err)
5801 (or (/= (setq c (js2-get-char)) ?/)
5802 in-class))
5803 (cond
5804 ((or (= c ?\n)
5805 (= c js2-EOF_CHAR))
5806 (setq js2-token-end (1- js2-ts-cursor)
5807 err t
5808 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5809 (js2-report-error "msg.unterminated.re.lit"))
5810 (t (cond
5811 ((= c ?\\)
5812 (js2-add-to-string c)
5813 (setq c (js2-get-char)))
5814 ((= c ?\[)
5815 (setq in-class t))
5816 ((= c ?\])
5817 (setq in-class nil)))
5818 (js2-add-to-string c))))
5819 (unless err
5820 (while continue
5821 (cond
5822 ((js2-match-char ?g)
5823 (push ?g flags))
5824 ((js2-match-char ?i)
5825 (push ?i flags))
5826 ((js2-match-char ?m)
5827 (push ?m flags))
5828 (t
5829 (setq continue nil))))
5830 (if (js2-alpha-p (js2-peek-char))
5831 (js2-report-scan-error "msg.invalid.re.flag" t
5832 js2-ts-cursor 1))
5833 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5834 js2-ts-regexp-flags (js2-collect-string flags)
5835 js2-token-end js2-ts-cursor)
5836 ;; tell `parse-partial-sexp' to ignore this range of chars
5837 (js2-record-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
5838
5839 (defun js2-get-first-xml-token ()
5840 (setq js2-ts-xml-open-tags-count 0
5841 js2-ts-is-xml-attribute nil
5842 js2-ts-xml-is-tag-content nil)
5843 (js2-unget-char)
5844 (js2-get-next-xml-token))
5845
5846 (defun js2-xml-discard-string ()
5847 "Throw away the string in progress and flag an XML parse error."
5848 (setq js2-ts-string-buffer nil
5849 js2-ts-string nil)
5850 (js2-report-scan-error "msg.XML.bad.form" t))
5851
5852 (defun js2-get-next-xml-token ()
5853 (setq js2-ts-string-buffer nil ; for recording the XML
5854 js2-token-beg js2-ts-cursor)
5855 (let (c result)
5856 (setq result
5857 (catch 'return
5858 (while t
5859 (setq c (js2-get-char))
5860 (cond
5861 ((= c js2-EOF_CHAR)
5862 (throw 'return js2-ERROR))
5863 (js2-ts-xml-is-tag-content
5864 (case c
5865 (?>
5866 (js2-add-to-string c)
5867 (setq js2-ts-xml-is-tag-content nil
5868 js2-ts-is-xml-attribute nil))
5869 (?/
5870 (js2-add-to-string c)
5871 (when (eq ?> (js2-peek-char))
5872 (setq c (js2-get-char))
5873 (js2-add-to-string c)
5874 (setq js2-ts-xml-is-tag-content nil)
5875 (decf js2-ts-xml-open-tags-count)))
5876 (?{
5877 (js2-unget-char)
5878 (setq js2-ts-string (js2-get-string-from-buffer))
5879 (throw 'return js2-XML))
5880 ((?\' ?\")
5881 (js2-add-to-string c)
5882 (unless (js2-read-quoted-string c)
5883 (throw 'return js2-ERROR)))
5884 (?=
5885 (js2-add-to-string c)
5886 (setq js2-ts-is-xml-attribute t))
5887 ((? ?\t ?\r ?\n)
5888 (js2-add-to-string c))
5889 (t
5890 (js2-add-to-string c)
5891 (setq js2-ts-is-xml-attribute nil)))
5892 (when (and (not js2-ts-xml-is-tag-content)
5893 (zerop js2-ts-xml-open-tags-count))
5894 (setq js2-ts-string (js2-get-string-from-buffer))
5895 (throw 'return js2-XMLEND)))
5896 (t
5897 ;; else not tag content
5898 (case c
5899 (?<
5900 (js2-add-to-string c)
5901 (setq c (js2-peek-char))
5902 (case c
5903 (?!
5904 (setq c (js2-get-char)) ;; skip !
5905 (js2-add-to-string c)
5906 (setq c (js2-peek-char))
5907 (case c
5908 (?-
5909 (setq c (js2-get-char)) ;; skip -
5910 (js2-add-to-string c)
5911 (if (eq c ?-)
5912 (progn
5913 (js2-add-to-string c)
5914 (unless (js2-read-xml-comment)
5915 (throw 'return js2-ERROR)))
5916 (js2-xml-discard-string)
5917 (throw 'return js2-ERROR)))
5918 (?\[
5919 (setq c (js2-get-char)) ;; skip [
5920 (js2-add-to-string c)
5921 (if (and (= (js2-get-char) ?C)
5922 (= (js2-get-char) ?D)
5923 (= (js2-get-char) ?A)
5924 (= (js2-get-char) ?T)
5925 (= (js2-get-char) ?A)
5926 (= (js2-get-char) ?\[))
5927 (progn
5928 (js2-add-to-string ?C)
5929 (js2-add-to-string ?D)
5930 (js2-add-to-string ?A)
5931 (js2-add-to-string ?T)
5932 (js2-add-to-string ?A)
5933 (js2-add-to-string ?\[)
5934 (unless (js2-read-cdata)
5935 (throw 'return js2-ERROR)))
5936 (js2-xml-discard-string)
5937 (throw 'return js2-ERROR)))
5938 (t
5939 (unless (js2-read-entity)
5940 (throw 'return js2-ERROR))))
5941 ;; Allow bare CDATA section, e.g.:
5942 ;; let xml = <![CDATA[ foo bar baz ]]>;
5943 (when (zerop js2-ts-xml-open-tags-count)
5944 (throw 'return js2-XMLEND)))
5945 (??
5946 (setq c (js2-get-char)) ;; skip ?
5947 (js2-add-to-string c)
5948 (unless (js2-read-PI)
5949 (throw 'return js2-ERROR)))
5950 (?/
5951 ;; end tag
5952 (setq c (js2-get-char)) ;; skip /
5953 (js2-add-to-string c)
5954 (when (zerop js2-ts-xml-open-tags-count)
5955 (js2-xml-discard-string)
5956 (throw 'return js2-ERROR))
5957 (setq js2-ts-xml-is-tag-content t)
5958 (decf js2-ts-xml-open-tags-count))
5959 (t
5960 ;; start tag
5961 (setq js2-ts-xml-is-tag-content t)
5962 (incf js2-ts-xml-open-tags-count))))
5963 (?{
5964 (js2-unget-char)
5965 (setq js2-ts-string (js2-get-string-from-buffer))
5966 (throw 'return js2-XML))
5967 (t
5968 (js2-add-to-string c))))))))
5969 (setq js2-token-end js2-ts-cursor)
5970 result))
5971
5972 (defun js2-read-quoted-string (quote)
5973 (let (c)
5974 (catch 'return
5975 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
5976 (js2-add-to-string c)
5977 (if (eq c quote)
5978 (throw 'return t)))
5979 (js2-xml-discard-string) ;; throw away string in progress
5980 nil)))
5981
5982 (defun js2-read-xml-comment ()
5983 (let ((c (js2-get-char)))
5984 (catch 'return
5985 (while (/= c js2-EOF_CHAR)
5986 (catch 'continue
5987 (js2-add-to-string c)
5988 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
5989 (setq c (js2-get-char))
5990 (js2-add-to-string c)
5991 (if (eq (js2-peek-char) ?>)
5992 (progn
5993 (setq c (js2-get-char)) ;; skip >
5994 (js2-add-to-string c)
5995 (throw 'return t))
5996 (throw 'continue nil)))
5997 (setq c (js2-get-char))))
5998 (js2-xml-discard-string)
5999 nil)))
6000
6001 (defun js2-read-cdata ()
6002 (let ((c (js2-get-char)))
6003 (catch 'return
6004 (while (/= c js2-EOF_CHAR)
6005 (catch 'continue
6006 (js2-add-to-string c)
6007 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6008 (setq c (js2-get-char))
6009 (js2-add-to-string c)
6010 (if (eq (js2-peek-char) ?>)
6011 (progn
6012 (setq c (js2-get-char)) ;; Skip >
6013 (js2-add-to-string c)
6014 (throw 'return t))
6015 (throw 'continue nil)))
6016 (setq c (js2-get-char))))
6017 (js2-xml-discard-string)
6018 nil)))
6019
6020 (defun js2-read-entity ()
6021 (let ((decl-tags 1)
6022 c)
6023 (catch 'return
6024 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6025 (js2-add-to-string c)
6026 (case c
6027 (?<
6028 (incf decl-tags))
6029 (?>
6030 (decf decl-tags)
6031 (if (zerop decl-tags)
6032 (throw 'return t)))))
6033 (js2-xml-discard-string)
6034 nil)))
6035
6036 (defun js2-read-PI ()
6037 "Scan an XML processing instruction."
6038 (let (c)
6039 (catch 'return
6040 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6041 (js2-add-to-string c)
6042 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6043 (setq c (js2-get-char)) ;; Skip >
6044 (js2-add-to-string c)
6045 (throw 'return t)))
6046 (js2-xml-discard-string)
6047 nil)))
6048
6049 (defun js2-scanner-get-line ()
6050 "Return the text of the current scan line."
6051 (buffer-substring (point-at-bol) (point-at-eol)))
6052
6053 ;;; Highlighting
6054
6055 (defun js2-set-face (beg end face &optional record)
6056 "Fontify a region. If RECORD is non-nil, record for later."
6057 (when (plusp js2-highlight-level)
6058 (setq beg (min (point-max) beg)
6059 beg (max (point-min) beg)
6060 end (min (point-max) end)
6061 end (max (point-min) end))
6062 (if record
6063 (push (list beg end face) js2-mode-fontifications)
6064 (put-text-property beg end 'font-lock-face face))))
6065
6066 (defun js2-set-kid-face (pos kid len face)
6067 "Set-face on a child node.
6068 POS is absolute buffer position of parent.
6069 KID is the child node.
6070 LEN is the length to fontify.
6071 FACE is the face to fontify with."
6072 (js2-set-face (+ pos (js2-node-pos kid))
6073 (+ pos (js2-node-pos kid) (js2-node-len kid))
6074 face))
6075
6076 (defsubst js2-fontify-kwd (start length)
6077 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6078
6079 (defsubst js2-clear-face (beg end)
6080 (remove-text-properties beg end '(font-lock-face nil
6081 help-echo nil
6082 point-entered nil
6083 c-in-sws nil)))
6084
6085 (defconst js2-ecma-global-props
6086 (concat "^"
6087 (regexp-opt
6088 '("Infinity" "NaN" "undefined" "arguments") t)
6089 "$")
6090 "Value properties of the Ecma-262 Global Object.
6091 Shown at or above `js2-highlight-level' 2.")
6092
6093 ;; might want to add the name "arguments" to this list?
6094 (defconst js2-ecma-object-props
6095 (concat "^"
6096 (regexp-opt
6097 '("prototype" "__proto__" "__parent__") t)
6098 "$")
6099 "Value properties of the Ecma-262 Object constructor.
6100 Shown at or above `js2-highlight-level' 2.")
6101
6102 (defconst js2-ecma-global-funcs
6103 (concat
6104 "^"
6105 (regexp-opt
6106 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6107 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6108 "$")
6109 "Function properties of the Ecma-262 Global object.
6110 Shown at or above `js2-highlight-level' 2.")
6111
6112 (defconst js2-ecma-number-props
6113 (concat "^"
6114 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6115 "NEGATIVE_INFINITY"
6116 "POSITIVE_INFINITY") t)
6117 "$")
6118 "Properties of the Ecma-262 Number constructor.
6119 Shown at or above `js2-highlight-level' 2.")
6120
6121 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6122 "Properties of the Ecma-262 Date constructor.
6123 Shown at or above `js2-highlight-level' 2.")
6124
6125 (defconst js2-ecma-math-props
6126 (concat "^"
6127 (regexp-opt
6128 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6129 t)
6130 "$")
6131 "Properties of the Ecma-262 Math object.
6132 Shown at or above `js2-highlight-level' 2.")
6133
6134 (defconst js2-ecma-math-funcs
6135 (concat "^"
6136 (regexp-opt
6137 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6138 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6139 "$")
6140 "Function properties of the Ecma-262 Math object.
6141 Shown at or above `js2-highlight-level' 2.")
6142
6143 (defconst js2-ecma-function-props
6144 (concat
6145 "^"
6146 (regexp-opt
6147 '(;; properties of the Object prototype object
6148 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6149 "toLocaleString" "toString" "valueOf"
6150 ;; properties of the Function prototype object
6151 "apply" "call"
6152 ;; properties of the Array prototype object
6153 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6154 "splice" "unshift"
6155 ;; properties of the String prototype object
6156 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6157 "localeCompare" "match" "replace" "search" "split" "substring"
6158 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6159 "toUpperCase"
6160 ;; properties of the Number prototype object
6161 "toExponential" "toFixed" "toPrecision"
6162 ;; properties of the Date prototype object
6163 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6164 "getMinutes" "getMonth" "getSeconds" "getTime"
6165 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6166 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6167 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6168 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6169 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6170 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6171 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6172 "toTimeString" "toUTCString"
6173 ;; properties of the RegExp prototype object
6174 "exec" "test"
6175 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6176 "toSource" "__defineGetter__" "__defineSetter__"
6177 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6178 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6179 t)
6180 "$")
6181 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6182 Shown at or above `js2-highlight-level' 3.")
6183
6184 (defun js2-parse-highlight-prop-get (parent target prop call-p)
6185 (let ((target-name (and target
6186 (js2-name-node-p target)
6187 (js2-name-node-name target)))
6188 (prop-name (if prop (js2-name-node-name prop)))
6189 (level1 (>= js2-highlight-level 1))
6190 (level2 (>= js2-highlight-level 2))
6191 (level3 (>= js2-highlight-level 3))
6192 pos face)
6193 (when level2
6194 (if call-p
6195 (cond
6196 ((and target prop)
6197 (cond
6198 ((and level3 (string-match js2-ecma-function-props prop-name))
6199 (setq face 'font-lock-builtin-face))
6200 ((and target-name prop)
6201 (cond
6202 ((string= target-name "Date")
6203 (if (string-match js2-ecma-date-props prop-name)
6204 (setq face 'font-lock-builtin-face)))
6205 ((string= target-name "Math")
6206 (if (string-match js2-ecma-math-funcs prop-name)
6207 (setq face 'font-lock-builtin-face)))))))
6208 (prop
6209 (if (string-match js2-ecma-global-funcs prop-name)
6210 (setq face 'font-lock-builtin-face))))
6211 (cond
6212 ((and target prop)
6213 (cond
6214 ((string= target-name "Number")
6215 (if (string-match js2-ecma-number-props prop-name)
6216 (setq face 'font-lock-constant-face)))
6217 ((string= target-name "Math")
6218 (if (string-match js2-ecma-math-props prop-name)
6219 (setq face 'font-lock-constant-face)))))
6220 (prop
6221 (if (string-match js2-ecma-object-props prop-name)
6222 (setq face 'font-lock-constant-face)))))
6223 (when face
6224 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6225 (js2-node-pos prop))) ; relative
6226 (+ pos (js2-node-len prop))
6227 face)))))
6228
6229 (defun js2-parse-highlight-member-expr-node (node)
6230 "Perform syntax highlighting of EcmaScript built-in properties.
6231 The variable `js2-highlight-level' governs this highighting."
6232 (let (face target prop name pos end parent call-p callee)
6233 (cond
6234 ;; case 1: simple name, e.g. foo
6235 ((js2-name-node-p node)
6236 (setq name (js2-name-node-name node))
6237 ;; possible for name to be nil in rare cases - saw it when
6238 ;; running js2-mode on an elisp buffer. Might as well try to
6239 ;; make it so js2-mode never barfs.
6240 (when name
6241 (setq face (if (string-match js2-ecma-global-props name)
6242 'font-lock-constant-face))
6243 (when face
6244 (setq pos (js2-node-pos node)
6245 end (+ pos (js2-node-len node)))
6246 (js2-set-face pos end face))))
6247 ;; case 2: property access or function call
6248 ((or (js2-prop-get-node-p node)
6249 ;; highlight function call if expr is a prop-get node
6250 ;; or a plain name (i.e. unqualified function call)
6251 (and (setq call-p (js2-call-node-p node))
6252 (setq callee (js2-call-node-target node)) ; separate setq!
6253 (or (js2-prop-get-node-p callee)
6254 (js2-name-node-p callee))))
6255 (setq parent node
6256 node (if call-p callee node))
6257 (if (and call-p (js2-name-node-p callee))
6258 (setq prop callee)
6259 (setq target (js2-prop-get-node-left node)
6260 prop (js2-prop-get-node-right node)))
6261 (cond
6262 ((js2-name-node-p target)
6263 (if (js2-name-node-p prop)
6264 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6265 (js2-parse-highlight-prop-get parent target prop call-p)
6266 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6267 (js2-parse-highlight-prop-get parent target nil call-p)))
6268 ((js2-name-node-p prop)
6269 ;; case 2c: complex target, simple name, e.g. x[y].bar
6270 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6271
6272 (defun js2-parse-highlight-member-expr-fn-name (expr)
6273 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6274 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6275 We currently only handle the case where the last component is a prop-get
6276 of a simple name. Called before EXPR has a parent node."
6277 (let (pos
6278 (name (and (js2-prop-get-node-p expr)
6279 (js2-prop-get-node-right expr))))
6280 (when (js2-name-node-p name)
6281 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6282 (js2-node-pos name)))
6283 (+ pos (js2-node-len name))
6284 'font-lock-function-name-face
6285 'record))))
6286
6287 ;; source: http://jsdoc.sourceforge.net/
6288 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6289 ;; allows type specifications, and needs work before entering the wild.
6290
6291 (defconst js2-jsdoc-param-tag-regexp
6292 (concat "^\\s-*\\*+\\s-*\\(@"
6293 "\\(?:param\\|argument\\)"
6294 "\\)"
6295 "\\s-*\\({[^}]+}\\)?" ; optional type
6296 "\\s-*\\[?\\([a-zA-Z0-9_$\.]+\\)?\\]?" ; name
6297 "\\>")
6298 "Matches jsdoc tags with optional type and optional param name.")
6299
6300 (defconst js2-jsdoc-typed-tag-regexp
6301 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6302 (regexp-opt
6303 '("enum"
6304 "extends"
6305 "field"
6306 "id"
6307 "implements"
6308 "lends"
6309 "mods"
6310 "requires"
6311 "return"
6312 "returns"
6313 "throw"
6314 "throws"))
6315 "\\)\\)\\s-*\\({[^}]+}\\)?")
6316 "Matches jsdoc tags with optional type.")
6317
6318 (defconst js2-jsdoc-arg-tag-regexp
6319 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6320 (regexp-opt
6321 '("alias"
6322 "augments"
6323 "borrows"
6324 "bug"
6325 "base"
6326 "config"
6327 "default"
6328 "define"
6329 "exception"
6330 "function"
6331 "member"
6332 "memberOf"
6333 "name"
6334 "namespace"
6335 "property"
6336 "since"
6337 "suppress"
6338 "this"
6339 "throws"
6340 "type"
6341 "version"))
6342 "\\)\\)\\s-+\\([^ \t]+\\)")
6343 "Matches jsdoc tags with a single argument.")
6344
6345 (defconst js2-jsdoc-empty-tag-regexp
6346 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6347 (regexp-opt
6348 '("addon"
6349 "author"
6350 "class"
6351 "const"
6352 "constant"
6353 "constructor"
6354 "constructs"
6355 "deprecated"
6356 "desc"
6357 "description"
6358 "event"
6359 "example"
6360 "exec"
6361 "export"
6362 "fileoverview"
6363 "final"
6364 "function"
6365 "hidden"
6366 "ignore"
6367 "implicitCast"
6368 "inheritDoc"
6369 "inner"
6370 "interface"
6371 "license"
6372 "noalias"
6373 "noshadow"
6374 "notypecheck"
6375 "override"
6376 "owner"
6377 "preserve"
6378 "preserveTry"
6379 "private"
6380 "protected"
6381 "public"
6382 "static"
6383 "supported"
6384 ))
6385 "\\)\\)\\s-*")
6386 "Matches empty jsdoc tags.")
6387
6388 (defconst js2-jsdoc-link-tag-regexp
6389 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6390 "Matches a jsdoc link or code tag.")
6391
6392 (defconst js2-jsdoc-see-tag-regexp
6393 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6394 "Matches a jsdoc @see tag.")
6395
6396 (defconst js2-jsdoc-html-tag-regexp
6397 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6398 "Matches a simple (no attributes) html start- or end-tag.")
6399
6400 (defun js2-jsdoc-highlight-helper ()
6401 (js2-set-face (match-beginning 1)
6402 (match-end 1)
6403 'js2-jsdoc-tag)
6404 (if (match-beginning 2)
6405 (if (save-excursion
6406 (goto-char (match-beginning 2))
6407 (= (char-after) ?{))
6408 (js2-set-face (1+ (match-beginning 2))
6409 (1- (match-end 2))
6410 'js2-jsdoc-type)
6411 (js2-set-face (match-beginning 2)
6412 (match-end 2)
6413 'js2-jsdoc-value)))
6414 (if (match-beginning 3)
6415 (js2-set-face (match-beginning 3)
6416 (match-end 3)
6417 'js2-jsdoc-value)))
6418
6419 (defun js2-highlight-jsdoc (ast)
6420 "Highlight doc comment tags."
6421 (let ((comments (js2-ast-root-comments ast))
6422 beg end)
6423 (save-excursion
6424 (dolist (node comments)
6425 (when (eq (js2-comment-node-format node) 'jsdoc)
6426 (setq beg (js2-node-abs-pos node)
6427 end (+ beg (js2-node-len node)))
6428 (save-restriction
6429 (narrow-to-region beg end)
6430 (dolist (re (list js2-jsdoc-param-tag-regexp
6431 js2-jsdoc-typed-tag-regexp
6432 js2-jsdoc-arg-tag-regexp
6433 js2-jsdoc-link-tag-regexp
6434 js2-jsdoc-see-tag-regexp
6435 js2-jsdoc-empty-tag-regexp))
6436 (goto-char beg)
6437 (while (re-search-forward re nil t)
6438 (js2-jsdoc-highlight-helper)))
6439 ;; simple highlighting for html tags
6440 (goto-char beg)
6441 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6442 (js2-set-face (match-beginning 1)
6443 (match-end 1)
6444 'js2-jsdoc-html-tag-delimiter)
6445 (js2-set-face (match-beginning 2)
6446 (match-end 2)
6447 'js2-jsdoc-html-tag-name)
6448 (js2-set-face (match-beginning 3)
6449 (match-end 3)
6450 'js2-jsdoc-html-tag-delimiter))))))))
6451
6452 (defun js2-highlight-assign-targets (node left right)
6453 "Highlight function properties and external variables."
6454 (let (leftpos end name)
6455 ;; highlight vars and props assigned function values
6456 (when (js2-function-node-p right)
6457 (cond
6458 ;; var foo = function() {...}
6459 ((js2-name-node-p left)
6460 (setq name left))
6461 ;; foo.bar.baz = function() {...}
6462 ((and (js2-prop-get-node-p left)
6463 (js2-name-node-p (js2-prop-get-node-right left)))
6464 (setq name (js2-prop-get-node-right left))))
6465 (when name
6466 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6467 (+ leftpos (js2-node-len name))
6468 'font-lock-function-name-face
6469 'record)))))
6470
6471 (defun js2-record-name-node (node)
6472 "Saves NODE to `js2-recorded-identifiers' to check for undeclared variables
6473 later. NODE must be a name node."
6474 (let (leftpos end)
6475 (push (list node js2-current-scope
6476 (setq leftpos (js2-node-abs-pos node))
6477 (setq end (+ leftpos (js2-node-len node))))
6478 js2-recorded-identifiers)))
6479
6480 (defun js2-highlight-undeclared-vars ()
6481 "After entire parse is finished, look for undeclared variable references.
6482 We have to wait until entire buffer is parsed, since JavaScript permits var
6483 decls to occur after they're used.
6484
6485 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6486 it is considered declared."
6487 (let (name)
6488 (dolist (entry js2-recorded-identifiers)
6489 (destructuring-bind (name-node scope pos end) entry
6490 (setq name (js2-name-node-name name-node))
6491 (unless (or (member name js2-global-externs)
6492 (member name js2-default-externs)
6493 (member name js2-additional-externs)
6494 (js2-get-defining-scope scope name))
6495 (js2-set-face pos end 'js2-external-variable 'record)
6496 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6497 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6498 (setq js2-recorded-identifiers nil)))
6499
6500 ;;; IMenu support
6501
6502 ;; We currently only support imenu, but eventually should support speedbar and
6503 ;; possibly other browsing mechanisms.
6504
6505 ;; The basic strategy is to identify function assignment targets of the form
6506 ;; `foo.bar.baz', convert them to (list fn foo bar baz <position>), and push the
6507 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6508 ;; for imenu after parsing is finished.
6509
6510 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6511 ;; JavaScript, and the general problem is undecidable. However, several forms
6512 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6513 ;; include:
6514
6515 ;; function foo() -- function declaration
6516 ;; foo = function() -- function expression assigned to variable
6517 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6518 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6519 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6520 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6521 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6522 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6523 ;; function foo() {function bar() {...}} -- nested function
6524 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6525
6526 ;; This list boils down to a few forms that can be combined recursively.
6527 ;; Top-level named function declarations include both the left-hand (name)
6528 ;; and the right-hand (function value) expressions needed to produce an imenu
6529 ;; entry. The other "right-hand" forms we need to look for are:
6530 ;; - functions declared as props/getters/setters in object literals
6531 ;; - nested named function declarations
6532 ;; The "left-hand" expressions that functions can be assigned to include:
6533 ;; - local/global variables
6534 ;; - nested property-get expressions like a.b.c.d
6535 ;; - element gets like foo[10] or foo['bar'] where the index
6536 ;; expression can be trivially converted to a property name. They
6537 ;; effectively then become property gets.
6538
6539 ;; All the different definition types are canonicalized into the form
6540 ;; foo.bar.baz = position-of-function-keyword
6541
6542 ;; We need to build a trie-like structure for imenu. As an example,
6543 ;; consider the following JavaScript code:
6544
6545 ;; a = function() {...} // function at position 5
6546 ;; b = function() {...} // function at position 25
6547 ;; foo = function() {...} // function at position 100
6548 ;; foo.bar = function() {...} // function at position 200
6549 ;; foo.bar.baz = function() {...} // function at position 300
6550 ;; foo.bar.zab = function() {...} // function at position 400
6551
6552 ;; During parsing we accumulate an entry for each definition in
6553 ;; the variable `js2-imenu-recorder', like so:
6554
6555 ;; '((fn a 5)
6556 ;; (fn b 25)
6557 ;; (fn foo 100)
6558 ;; (fn foo bar 200)
6559 ;; (fn foo bar baz 300)
6560 ;; (fn foo bar zab 400))
6561
6562 ;; Where 'fn' is the respective function node.
6563 ;; After parsing these entries are merged into this alist-trie:
6564
6565 ;; '((a . 1)
6566 ;; (b . 2)
6567 ;; (foo (<definition> . 3)
6568 ;; (bar (<definition> . 6)
6569 ;; (baz . 100)
6570 ;; (zab . 200))))
6571
6572 ;; Note the wacky need for a <definition> name. The token can be anything
6573 ;; that isn't a valid JavaScript identifier, because you might make foo
6574 ;; a function and then start setting properties on it that are also functions.
6575
6576 (defun js2-prop-node-name (node)
6577 "Return the name of a node that may be a property-get/property-name.
6578 If NODE is not a valid name-node, string-node or integral number-node,
6579 returns nil. Otherwise returns the string name/value of the node."
6580 (cond
6581 ((js2-name-node-p node)
6582 (js2-name-node-name node))
6583 ((js2-string-node-p node)
6584 (js2-string-node-value node))
6585 ((and (js2-number-node-p node)
6586 (string-match "^[0-9]+$" (js2-number-node-value node)))
6587 (js2-number-node-value node))
6588 ((js2-this-node-p node)
6589 "this")))
6590
6591 (defun js2-node-qname-component (node)
6592 "Return the name of this node, if it contributes to a qname.
6593 Returns nil if the node doesn't contribute."
6594 (copy-sequence
6595 (or (js2-prop-node-name node)
6596 (if (and (js2-function-node-p node)
6597 (js2-function-node-name node))
6598 (js2-name-node-name (js2-function-node-name node))))))
6599
6600 (defun js2-record-imenu-entry (fn-node qname pos)
6601 "Add an entry to `js2-imenu-recorder'.
6602 FN-NODE should be the current item's function node.
6603
6604 Associate FN-NODE with its QNAME for later lookup.
6605 This is used in postprocessing the chain list. For each chain, we find
6606 the parent function, look up its qname, then prepend a copy of it to the chain."
6607 (push (cons fn-node (append qname (list pos))) js2-imenu-recorder)
6608 (unless js2-imenu-function-map
6609 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6610 (puthash fn-node qname js2-imenu-function-map))
6611
6612 (defun js2-record-imenu-functions (node &optional var)
6613 "Record function definitions for imenu.
6614 NODE is a function node or an object literal.
6615 VAR, if non-nil, is the expression that NODE is being assigned to."
6616 (when js2-parse-ide-mode
6617 (let ((fun-p (js2-function-node-p node))
6618 qname left fname-node pos)
6619 (cond
6620 ;; non-anonymous function declaration?
6621 ((and fun-p
6622 (not var)
6623 (setq fname-node (js2-function-node-name node)))
6624 (js2-record-imenu-entry node (list fname-node) (js2-node-pos node)))
6625 ;; for remaining forms, compute left-side tree branch first
6626 ((and var (setq qname (js2-compute-nested-prop-get var)))
6627 (cond
6628 ;; foo.bar.baz = function
6629 (fun-p
6630 (js2-record-imenu-entry node qname (js2-node-pos node)))
6631 ;; foo.bar.baz = object-literal
6632 ;; look for nested functions: {a: {b: function() {...} }}
6633 ((js2-object-node-p node)
6634 ;; Node position here is still absolute, since the parser
6635 ;; passes the assignment target and value expressions
6636 ;; to us before they are added as children of the assignment node.
6637 (js2-record-object-literal node qname (js2-node-pos node)))))))))
6638
6639 (defun js2-compute-nested-prop-get (node)
6640 "If NODE is of form foo.bar, foo['bar'], or any nested combination, return
6641 component nodes as a list. Otherwise return nil. Element-gets are treated
6642 as property-gets if the index expression is a string, or a positive integer."
6643 (let (left right head)
6644 (cond
6645 ((or (js2-name-node-p node)
6646 (js2-this-node-p node))
6647 (list node))
6648 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6649 ((js2-prop-get-node-p node) ; foo.bar
6650 (setq left (js2-prop-get-node-left node)
6651 right (js2-prop-get-node-right node))
6652 (if (setq head (js2-compute-nested-prop-get left))
6653 (nconc head (list right))))
6654 ((js2-elem-get-node-p node) ; foo['bar'] or foo[101]
6655 (setq left (js2-elem-get-node-target node)
6656 right (js2-elem-get-node-element node))
6657 (if (or (js2-string-node-p right) ; ['bar']
6658 (and (js2-number-node-p right) ; [10]
6659 (string-match "^[0-9]+$"
6660 (js2-number-node-value right))))
6661 (if (setq head (js2-compute-nested-prop-get left))
6662 (nconc head (list right))))))))
6663
6664 (defun js2-record-object-literal (node qname pos)
6665 "Recursively process an object literal looking for functions.
6666 NODE is an object literal that is the right-hand child of an assignment
6667 expression. QNAME is a list of nodes representing the assignment target,
6668 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6669 POS is the absolute position of the node.
6670 We do a depth-first traversal of NODE. For any functions we find,
6671 we append the property name to QNAME, then call `js2-record-imenu-entry'."
6672 (let (left right prop-qname)
6673 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6674 (let ((left (js2-infix-node-left e))
6675 ;; Element positions are relative to the parent position.
6676 (pos (+ pos (js2-node-pos e))))
6677 (cond
6678 ;; foo: function() {...}
6679 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6680 (when (js2-prop-node-name left)
6681 ;; As a policy decision, we record the position of the property,
6682 ;; not the position of the `function' keyword, since the property
6683 ;; is effectively the name of the function.
6684 (js2-record-imenu-entry right (append qname (list left)) pos)))
6685 ;; foo: {object-literal} -- add foo to qname, offset position, and recurse
6686 ((js2-object-node-p right)
6687 (js2-record-object-literal right
6688 (append qname (list (js2-infix-node-left e)))
6689 (+ pos (js2-node-pos right)))))))))
6690
6691 (defun js2-node-top-level-decl-p (node)
6692 "Return t if NODE's name is defined in the top-level scope.
6693 Also returns t if NODE's name is not defined in any scope, since it implies
6694 that it's an external variable, which must also be in the top-level scope."
6695 (let* ((name (js2-prop-node-name node))
6696 (this-scope (js2-node-get-enclosing-scope node))
6697 defining-scope)
6698 (cond
6699 ((js2-this-node-p node)
6700 nil)
6701 ((null this-scope)
6702 t)
6703 ((setq defining-scope (js2-get-defining-scope this-scope name))
6704 (js2-ast-root-p defining-scope))
6705 (t t))))
6706
6707 (defun js2-wrapper-function-p (node)
6708 "Returns t if NODE is a function expression that's immediately invoked.
6709 NODE must be `js2-function-node'."
6710 (let ((parent (js2-node-parent node)))
6711 (or
6712 ;; function(){...}();
6713 (js2-call-node-p parent)
6714 (and (js2-paren-node-p parent)
6715 ;; (function(){...})();
6716 (or (js2-call-node-p (setq parent (js2-node-parent parent)))
6717 ;; (function(){...}).call(this);
6718 (and (js2-prop-get-node-p parent)
6719 (member (js2-name-node-name (js2-prop-get-node-right parent))
6720 '("call" "apply"))
6721 (js2-call-node-p (js2-node-parent parent))))))))
6722
6723 (defun js2-browse-postprocess-chains (entries)
6724 "Modify function-declaration name chains after parsing finishes.
6725 Some of the information is only available after the parse tree is complete.
6726 For instance, processing a nested scope requires a parent function node."
6727 (let (result head fn current-fn parent-qname qname p elem)
6728 (dolist (entry entries)
6729 ;; function node goes first
6730 (destructuring-bind (current-fn &rest (&whole chain head &rest)) entry
6731 ;; examine its defining scope;
6732 ;; if top-level/external, keep as-is
6733 (if (js2-node-top-level-decl-p head)
6734 (push chain result)
6735 (when (js2-this-node-p head)
6736 (setq chain (cdr chain))) ; discard this-node
6737 (when (setq fn (js2-node-parent-script-or-fn current-fn))
6738 (setq parent-qname (gethash fn js2-imenu-function-map 'not-found))
6739 (when (eq parent-qname 'not-found)
6740 ;; anonymous function expressions are not recorded
6741 ;; during the parse, so we need to handle this case here
6742 (setq parent-qname
6743 (if (js2-wrapper-function-p fn)
6744 (let ((grandparent (js2-node-parent-script-or-fn fn)))
6745 (if (js2-ast-root-p grandparent)
6746 nil
6747 (gethash grandparent js2-imenu-function-map 'skip)))
6748 'skip))
6749 (puthash fn parent-qname js2-imenu-function-map))
6750 (unless (eq parent-qname 'skip)
6751 ;; prefix parent fn qname to this chain.
6752 (let ((qname (append parent-qname chain)))
6753 (puthash current-fn (butlast qname) js2-imenu-function-map)
6754 (push qname result)))))))
6755 ;; finally replace each node in each chain with its name.
6756 (dolist (chain result)
6757 (setq p chain)
6758 (while p
6759 (if (js2-node-p (setq elem (car p)))
6760 (setcar p (js2-node-qname-component elem)))
6761 (setq p (cdr p))))
6762 result))
6763
6764 ;; Merge name chains into a trie-like tree structure of nested lists.
6765 ;; To simplify construction of the trie, we first build it out using the rule
6766 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6767 ;; [key, num-or-list]. The second element can be a number; if so, this key
6768 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6769 ;; associated with the key at this level.) Otherwise the second element is
6770 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6771 ;; a simple recursive formulation.
6772 ;;
6773 ;; js2-mode is building the data structure for imenu. The imenu documentation
6774 ;; claims that it's the structure above, but in practice it wants the children
6775 ;; at the same list level as the key for that level, which is how I've drawn
6776 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6777 ;; list wrapper around the children at each level.
6778 ;;
6779 ;; A completed nested imenu-alist entry looks like this:
6780 ;; '(("foo"
6781 ;; ("<definition>" . 7)
6782 ;; ("bar"
6783 ;; ("a" . 40)
6784 ;; ("b" . 60))))
6785 ;;
6786 ;; In particular, the documentation for `imenu--index-alist' says that
6787 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6788 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6789
6790 (defun js2-treeify (lst)
6791 "Convert (a b c d) to (a ((b ((c d)))))."
6792 (if (null (cddr lst)) ; list length <= 2
6793 lst
6794 (list (car lst) (list (js2-treeify (cdr lst))))))
6795
6796 (defun js2-build-alist-trie (chains trie)
6797 "Merge declaration name chains into a trie-like alist structure for imenu.
6798 CHAINS is the qname chain list produced during parsing. TRIE is a
6799 list of elements built up so far."
6800 (let (head tail pos branch kids)
6801 (dolist (chain chains)
6802 (setq head (car chain)
6803 tail (cdr chain)
6804 pos (if (numberp (car tail)) (car tail))
6805 branch (js2-find-if (lambda (n)
6806 (string= (car n) head))
6807 trie)
6808 kids (second branch))
6809 (cond
6810 ;; case 1: this key isn't in the trie yet
6811 ((null branch)
6812 (if trie
6813 (setcdr (last trie) (list (js2-treeify chain)))
6814 (setq trie (list (js2-treeify chain)))))
6815 ;; case 2: key is present with a single number entry: replace w/ list
6816 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6817 ;; ("<definition>" 20)))
6818 ((numberp kids)
6819 (setcar (cdr branch)
6820 (list (list "<definition-1>" kids)
6821 (if pos
6822 (list "<definition-2>" pos)
6823 (js2-treeify tail)))))
6824 ;; case 3: key is there (with kids), and we're a number entry
6825 (pos
6826 (setcdr (last kids)
6827 (list
6828 (list (format "<definition-%d>"
6829 (1+ (loop for kid in kids
6830 count (eq ?< (aref (car kid) 0)))))
6831 pos))))
6832 ;; case 4: key is there with kids, need to merge in our chain
6833 (t
6834 (js2-build-alist-trie (list tail) kids))))
6835 trie))
6836
6837 (defun js2-flatten-trie (trie)
6838 "Convert TRIE to imenu-format.
6839 Recurses through nodes, and for each one whose second element is a list,
6840 appends the list's flattened elements to the current element. Also
6841 changes the tails into conses. For instance, this pre-flattened trie
6842
6843 '(a ((b 20)
6844 (c ((d 30)
6845 (e 40)))))
6846
6847 becomes
6848
6849 '(a (b . 20)
6850 (c (d . 30)
6851 (e . 40)))
6852
6853 Note that the root of the trie has no key, just a list of chains.
6854 This is also true for the value of any key with multiple children,
6855 e.g. key 'c' in the example above."
6856 (cond
6857 ((listp (car trie))
6858 (mapcar #'js2-flatten-trie trie))
6859 (t
6860 (if (numberp (second trie))
6861 (cons (car trie) (second trie))
6862 ;; else pop list and append its kids
6863 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
6864
6865 (defun js2-build-imenu-index ()
6866 "Turn `js2-imenu-recorder' into an imenu data structure."
6867 (unless (eq js2-imenu-recorder 'empty)
6868 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
6869 (result (js2-build-alist-trie chains nil)))
6870 (js2-flatten-trie result))))
6871
6872 (defun js2-test-print-chains (chains)
6873 "Print a list of qname chains.
6874 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
6875 i.e. one or more nodes, and an integer position as the list tail."
6876 (mapconcat (lambda (chain)
6877 (concat "("
6878 (mapconcat (lambda (elem)
6879 (if (js2-node-p elem)
6880 (or (js2-node-qname-component elem)
6881 "nil")
6882 (number-to-string elem)))
6883 chain
6884 " ")
6885 ")"))
6886 chains
6887 "\n"))
6888
6889 ;;; Parser
6890
6891 (defconst js2-version "1.8.0"
6892 "Version of JavaScript supported, plus minor js2 version.")
6893
6894 (defmacro js2-record-face (face)
6895 "Record a style run of FACE for the current token."
6896 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
6897
6898 (defsubst js2-node-end (n)
6899 "Computes the absolute end of node N.
6900 Use with caution! Assumes `js2-node-pos' is -absolute-, which
6901 is only true until the node is added to its parent; i.e., while parsing."
6902 (+ (js2-node-pos n)
6903 (js2-node-len n)))
6904
6905 (defun js2-record-comment ()
6906 "Record a comment in `js2-scanned-comments'."
6907 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
6908 :format js2-ts-comment-type)
6909 js2-scanned-comments)
6910 (when js2-parse-ide-mode
6911 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
6912 'font-lock-doc-face
6913 'font-lock-comment-face))
6914 (when (memq js2-ts-comment-type '(html preprocessor))
6915 ;; Tell cc-engine the bounds of the comment.
6916 (js2-record-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
6917
6918 ;; This function is called depressingly often, so it should be fast.
6919 ;; Most of the time it's looking at the same token it peeked before.
6920 (defun js2-peek-token ()
6921 "Return the next token without consuming it.
6922 If previous token was consumed, calls scanner to get new token.
6923 If previous token was -not- consumed, returns it (idempotent).
6924
6925 This function will not return a newline (js2-EOL) - instead, it
6926 gobbles newlines until it finds a non-newline token, and flags
6927 that token as appearing just after a newline.
6928
6929 This function will also not return a js2-COMMENT. Instead, it
6930 records comments found in `js2-scanned-comments'. If the token
6931 returned by this function immediately follows a jsdoc comment,
6932 the token is flagged as such.
6933
6934 Note that this function always returned the un-flagged token!
6935 The flags, if any, are saved in `js2-current-flagged-token'."
6936 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
6937 js2-current-token ; most common case - return already-peeked token
6938 (let ((tt (js2-get-token)) ; call scanner
6939 saw-eol
6940 face)
6941 ;; process comments and whitespace
6942 (while (or (= tt js2-EOL)
6943 (= tt js2-COMMENT))
6944 (if (= tt js2-EOL)
6945 (setq saw-eol t)
6946 (setq saw-eol nil)
6947 (if js2-record-comments
6948 (js2-record-comment)))
6949 (setq tt (js2-get-token))) ; call scanner
6950 (setq js2-current-token tt
6951 js2-current-flagged-token (if saw-eol
6952 (logior tt js2-ti-after-eol)
6953 tt))
6954 ;; perform lexical fontification as soon as token is scanned
6955 (when js2-parse-ide-mode
6956 (cond
6957 ((minusp tt)
6958 (js2-record-face 'js2-error))
6959 ((setq face (aref js2-kwd-tokens tt))
6960 (js2-record-face face))
6961 ((and (= tt js2-NAME)
6962 (equal js2-ts-string "undefined"))
6963 (js2-record-face 'font-lock-constant-face))))
6964 tt))) ; return unflagged token
6965
6966 (defun js2-peek-flagged-token ()
6967 "Returns the current token along with any flags set for it."
6968 (js2-peek-token)
6969 js2-current-flagged-token)
6970
6971 (defsubst js2-consume-token ()
6972 (setq js2-current-flagged-token js2-EOF))
6973
6974 (defun js2-next-token ()
6975 (prog1
6976 (js2-peek-token)
6977 (js2-consume-token)))
6978
6979 (defun js2-next-flagged-token ()
6980 (js2-peek-token)
6981 (prog1 js2-current-flagged-token
6982 (js2-consume-token)))
6983
6984 (defun js2-match-token (match)
6985 "Consume and return t if next token matches MATCH, a bytecode.
6986 Returns nil and consumes nothing if MATCH is not the next token."
6987 (if (/= (js2-peek-token) match)
6988 nil
6989 (js2-consume-token)
6990 t))
6991
6992 (defun js2-valid-prop-name-token (tt)
6993 (or (= tt js2-NAME)
6994 (and js2-allow-keywords-as-property-names
6995 (plusp tt)
6996 (aref js2-kwd-tokens tt))))
6997
6998 (defun js2-match-prop-name ()
6999 "Consume token and return t if next token is a valid property name.
7000 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7001 is non-nil and it's a keyword token."
7002 (if (js2-valid-prop-name-token (js2-peek-token))
7003 (progn
7004 (js2-consume-token)
7005 t)
7006 nil))
7007
7008 (defun js2-must-match-prop-name (msg-id &optional pos len)
7009 (if (js2-match-prop-name)
7010 t
7011 (js2-report-error msg-id nil pos len)
7012 nil))
7013
7014 (defun js2-peek-token-or-eol ()
7015 "Return js2-EOL if the current token immediately follows a newline.
7016 Else returns the current token. Used in situations where we don't
7017 consider certain token types valid if they are preceded by a newline.
7018 One example is the postfix ++ or -- operator, which has to be on the
7019 same line as its operand."
7020 (let ((tt (js2-peek-token)))
7021 ;; Check for last peeked token flags
7022 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7023 js2-EOL
7024 tt)))
7025
7026 (defun js2-set-check-for-label ()
7027 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7028 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7029
7030 (defun js2-must-match (token msg-id &optional pos len)
7031 "Match next token to token code TOKEN, or record a syntax error.
7032 MSG-ID is the error message to report if the match fails.
7033 Returns t on match, nil if no match."
7034 (if (js2-match-token token)
7035 t
7036 (js2-report-error msg-id nil pos len)
7037 nil))
7038
7039 (defsubst js2-inside-function ()
7040 (plusp js2-nesting-of-function))
7041
7042 (defun js2-set-requires-activation ()
7043 (if (js2-function-node-p js2-current-script-or-fn)
7044 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7045
7046 (defun js2-check-activation-name (name token)
7047 (when (js2-inside-function)
7048 ;; skip language-version 1.2 check from Rhino
7049 (if (or (string= "arguments" name)
7050 (and js2-compiler-activation-names ; only used in codegen
7051 (gethash name js2-compiler-activation-names)))
7052 (js2-set-requires-activation))))
7053
7054 (defun js2-set-is-generator ()
7055 (if (js2-function-node-p js2-current-script-or-fn)
7056 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7057
7058 (defun js2-must-have-xml ()
7059 (unless js2-compiler-xml-available
7060 (js2-report-error "msg.XML.not.available")))
7061
7062 (defun js2-push-scope (scope)
7063 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7064 (assert (js2-scope-p scope))
7065 (assert (null (js2-scope-parent-scope scope)))
7066 (assert (not (eq js2-current-scope scope)))
7067 (setf (js2-scope-parent-scope scope) js2-current-scope
7068 js2-current-scope scope))
7069
7070 (defsubst js2-pop-scope ()
7071 (setq js2-current-scope
7072 (js2-scope-parent-scope js2-current-scope)))
7073
7074 (defun js2-enter-loop (loop-node)
7075 (push loop-node js2-loop-set)
7076 (push loop-node js2-loop-and-switch-set)
7077 (js2-push-scope loop-node)
7078 ;; Tell the current labeled statement (if any) its statement,
7079 ;; and set the jump target of the first label to the loop.
7080 ;; These are used in `js2-parse-continue' to verify that the
7081 ;; continue target is an actual labeled loop. (And for codegen.)
7082 (when js2-labeled-stmt
7083 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7084 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7085 js2-labeled-stmt))) loop-node)))
7086
7087 (defun js2-exit-loop ()
7088 (pop js2-loop-set)
7089 (pop js2-loop-and-switch-set)
7090 (js2-pop-scope))
7091
7092 (defsubst js2-enter-switch (switch-node)
7093 (push switch-node js2-loop-and-switch-set))
7094
7095 (defsubst js2-exit-switch ()
7096 (pop js2-loop-and-switch-set))
7097
7098 (defun js2-parse (&optional buf cb)
7099 "Tell the js2 parser to parse a region of JavaScript.
7100
7101 BUF is a buffer or buffer name containing the code to parse.
7102 Call `narrow-to-region' first to parse only part of the buffer.
7103
7104 The returned AST root node is given some additional properties:
7105 `node-count' - total number of nodes in the AST
7106 `buffer' - BUF. The buffer it refers to may change or be killed,
7107 so the value is not necessarily reliable.
7108
7109 An optional callback CB can be specified to report parsing
7110 progress. If `(functionp CB)' returns t, it will be called with
7111 the current line number once before parsing begins, then again
7112 each time the lexer reaches a new line number.
7113
7114 CB can also be a list of the form `(symbol cb ...)' to specify
7115 multiple callbacks with different criteria. Each symbol is a
7116 criterion keyword, and the following element is the callback to
7117 call
7118
7119 :line - called whenever the line number changes
7120 :token - called for each new token consumed
7121
7122 The list of criteria could be extended to include entering or
7123 leaving a statement, an expression, or a function definition."
7124 (if (and cb (not (functionp cb)))
7125 (error "criteria callbacks not yet implemented"))
7126 (let ((inhibit-point-motion-hooks t)
7127 (js2-compiler-xml-available (>= js2-language-version 160))
7128 ;; This is a recursive-descent parser, so give it a big stack.
7129 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7130 (max-specpdl-size (max max-specpdl-size 3000))
7131 (case-fold-search nil)
7132 ast)
7133 (message nil) ; clear any error message from previous parse
7134 (with-current-buffer (or buf (current-buffer))
7135 (setq js2-scanned-comments nil
7136 js2-parsed-errors nil
7137 js2-parsed-warnings nil
7138 js2-imenu-recorder nil
7139 js2-imenu-function-map nil
7140 js2-label-set nil)
7141 (js2-init-scanner)
7142 (setq ast (with-silent-modifications
7143 (js2-do-parse)))
7144 (unless js2-ts-hit-eof
7145 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7146 (setf (js2-ast-root-errors ast) js2-parsed-errors
7147 (js2-ast-root-warnings ast) js2-parsed-warnings)
7148 ;; if we didn't find any declarations, put a dummy in this list so we
7149 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7150 (unless js2-imenu-recorder
7151 (setq js2-imenu-recorder 'empty))
7152 (run-hooks 'js2-parse-finished-hook)
7153 ast)))
7154
7155 ;; Corresponds to Rhino's Parser.parse() method.
7156 (defun js2-do-parse ()
7157 "Parse current buffer starting from current point.
7158 Scanner should be initialized."
7159 (let ((pos js2-ts-cursor)
7160 (end js2-ts-cursor) ; in case file is empty
7161 root n tt)
7162 ;; initialize buffer-local parsing vars
7163 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7164 js2-current-script-or-fn root
7165 js2-current-scope root
7166 js2-current-flagged-token js2-EOF
7167 js2-nesting-of-function 0
7168 js2-labeled-stmt nil
7169 js2-recorded-identifiers nil) ; for js2-highlight
7170 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7171 (if (= tt js2-FUNCTION)
7172 (progn
7173 (js2-consume-token)
7174 (setq n (js2-parse-function (if js2-called-by-compile-function
7175 'FUNCTION_EXPRESSION
7176 'FUNCTION_STATEMENT))))
7177 ;; not a function - parse a statement
7178 (setq n (js2-parse-statement)))
7179 ;; add function or statement to script
7180 (setq end (js2-node-end n))
7181 (js2-block-node-push root n))
7182 ;; add comments to root in lexical order
7183 (when js2-scanned-comments
7184 ;; if we find a comment beyond end of normal kids, use its end
7185 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7186 (dolist (comment js2-scanned-comments)
7187 (push comment (js2-ast-root-comments root))
7188 (js2-node-add-children root comment)))
7189 (setf (js2-node-len root) (- end pos))
7190 ;; Give extensions a chance to muck with things before highlighting starts.
7191 (let ((js2-additional-externs js2-additional-externs))
7192 (dolist (callback js2-post-parse-callbacks)
7193 (funcall callback))
7194 (js2-highlight-undeclared-vars))
7195 root))
7196
7197 (defun js2-function-parser ()
7198 (js2-consume-token)
7199 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7200
7201 (defun js2-parse-function-closure-body (fn-node)
7202 "Parse a JavaScript 1.8 function closure body."
7203 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7204 (if js2-ts-hit-eof
7205 (js2-report-error "msg.no.brace.body" nil
7206 (js2-node-pos fn-node)
7207 (- js2-ts-cursor (js2-node-pos fn-node)))
7208 (js2-node-add-children fn-node
7209 (setf (js2-function-node-body fn-node)
7210 (js2-parse-expr t))))))
7211
7212 (defun js2-parse-function-body (fn-node)
7213 (js2-must-match js2-LC "msg.no.brace.body"
7214 (js2-node-pos fn-node)
7215 (- js2-ts-cursor (js2-node-pos fn-node)))
7216 (let ((pos js2-token-beg) ; LC position
7217 (pn (make-js2-block-node)) ; starts at LC position
7218 tt
7219 end)
7220 (incf js2-nesting-of-function)
7221 (unwind-protect
7222 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7223 (= tt js2-EOF)
7224 (= tt js2-RC)))
7225 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7226 (js2-parse-statement)
7227 (js2-consume-token)
7228 (js2-parse-function 'FUNCTION_STATEMENT))))
7229 (decf js2-nesting-of-function))
7230 (setq end js2-token-end) ; assume no curly and leave at current token
7231 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7232 (setq end js2-token-end))
7233 (setf (js2-node-pos pn) pos
7234 (js2-node-len pn) (- end pos))
7235 (setf (js2-function-node-body fn-node) pn)
7236 (js2-node-add-children fn-node pn)
7237 pn))
7238
7239 (defun js2-define-destruct-symbols (node decl-type face &optional ignore-not-in-block)
7240 "Declare and fontify destructuring parameters inside NODE.
7241 NODE is either `js2-array-node', `js2-object-node', or `js2-name-node'."
7242 (cond
7243 ((js2-name-node-p node)
7244 (let (leftpos)
7245 (js2-define-symbol decl-type (js2-name-node-name node)
7246 node ignore-not-in-block)
7247 (when face
7248 (js2-set-face (setq leftpos (js2-node-abs-pos node))
7249 (+ leftpos (js2-node-len node))
7250 face 'record))))
7251 ((js2-object-node-p node)
7252 (dolist (elem (js2-object-node-elems node))
7253 (js2-define-destruct-symbols
7254 (if (js2-object-prop-node-p elem)
7255 (js2-object-prop-node-right elem)
7256 ;; abbreviated destructuring {a, b}
7257 elem)
7258 decl-type face ignore-not-in-block)))
7259 ((js2-array-node-p node)
7260 (dolist (elem (js2-array-node-elems node))
7261 (when elem
7262 (js2-define-destruct-symbols elem decl-type face ignore-not-in-block))))
7263 (t (js2-report-error "msg.no.parm" nil (js2-node-abs-pos node)
7264 (js2-node-len node)))))
7265
7266 (defun js2-parse-function-params (fn-node pos)
7267 (if (js2-match-token js2-RP)
7268 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7269 (let (params len param)
7270 (loop for tt = (js2-peek-token)
7271 do
7272 (cond
7273 ;; destructuring param
7274 ((or (= tt js2-LB) (= tt js2-LC))
7275 (setq param (js2-parse-primary-expr-lhs))
7276 (js2-define-destruct-symbols param
7277 js2-LP
7278 'js2-function-param)
7279 (push param params))
7280 ;; simple name
7281 (t
7282 (js2-must-match js2-NAME "msg.no.parm")
7283 (js2-record-face 'js2-function-param)
7284 (setq param (js2-create-name-node))
7285 (js2-define-symbol js2-LP js2-ts-string param)
7286 (push param params)))
7287 while
7288 (js2-match-token js2-COMMA))
7289 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7290 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7291 (dolist (p params)
7292 (js2-node-add-children fn-node p)
7293 (push p (js2-function-node-params fn-node))))))
7294
7295 (defun js2-check-inconsistent-return-warning (fn-node name)
7296 "Possibly show inconsistent-return warning.
7297 Last token scanned is the close-curly for the function body."
7298 (when (and js2-mode-show-strict-warnings
7299 js2-strict-inconsistent-return-warning
7300 (not (js2-has-consistent-return-usage
7301 (js2-function-node-body fn-node))))
7302 ;; Have it extend from close-curly to bol or beginning of block.
7303 (let ((pos (save-excursion
7304 (goto-char js2-token-end)
7305 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7306 (point-at-bol))))
7307 (end js2-token-end))
7308 (if (plusp (js2-name-node-length name))
7309 (js2-add-strict-warning "msg.no.return.value"
7310 (js2-name-node-name name) pos end)
7311 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7312
7313 (defun js2-parse-function (function-type)
7314 "Function parser. FUNCTION-TYPE is a symbol."
7315 (let ((pos js2-token-beg) ; start of 'function' keyword
7316 name name-beg name-end fn-node lp
7317 (synthetic-type function-type)
7318 member-expr-node)
7319 ;; parse function name, expression, or non-name (anonymous)
7320 (cond
7321 ;; function foo(...)
7322 ((js2-match-token js2-NAME)
7323 (setq name (js2-create-name-node t)
7324 name-beg js2-token-beg
7325 name-end js2-token-end)
7326 (unless (js2-match-token js2-LP)
7327 (when js2-allow-member-expr-as-function-name
7328 ;; function foo.bar(...)
7329 (setq member-expr-node name
7330 name nil
7331 member-expr-node (js2-parse-member-expr-tail
7332 nil member-expr-node)))
7333 (js2-must-match js2-LP "msg.no.paren.parms")))
7334 ((js2-match-token js2-LP)
7335 nil) ; anonymous function: leave name as null
7336 (t
7337 ;; function random-member-expr(...)
7338 (when js2-allow-member-expr-as-function-name
7339 ;; Note that memberExpr can not start with '(' like
7340 ;; in function (1+2).toString(), because 'function (' already
7341 ;; processed as anonymous function
7342 (setq member-expr-node (js2-parse-member-expr)))
7343 (js2-must-match js2-LP "msg.no.paren.parms")))
7344 (if (= js2-current-token js2-LP) ; eventually matched LP?
7345 (setq lp js2-token-beg))
7346 (if member-expr-node
7347 (progn
7348 (setq synthetic-type 'FUNCTION_EXPRESSION)
7349 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7350 (if name
7351 (js2-set-face name-beg name-end
7352 'font-lock-function-name-face 'record)))
7353 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7354 (plusp (js2-name-node-length name)))
7355 ;; Function statements define a symbol in the enclosing scope
7356 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7357 (setf fn-node (make-js2-function-node :pos pos
7358 :name name
7359 :form function-type
7360 :lp (if lp (- lp pos))))
7361 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7362 ;; 1. Nested functions are not affected by the dynamic scope flag
7363 ;; as dynamic scope is already a parent of their scope.
7364 ;; 2. Functions defined under the with statement also immune to
7365 ;; this setup, in which case dynamic scope is ignored in favor
7366 ;; of the with object.
7367 (setf (js2-function-node-ignore-dynamic fn-node) t))
7368 ;; dynamically bind all the per-function variables
7369 (let ((js2-current-script-or-fn fn-node)
7370 (js2-current-scope fn-node)
7371 (js2-nesting-of-with 0)
7372 (js2-end-flags 0)
7373 js2-label-set
7374 js2-loop-set
7375 js2-loop-and-switch-set)
7376 (js2-parse-function-params fn-node pos)
7377 (if (and (>= js2-language-version 180)
7378 (/= (js2-peek-token) js2-LC))
7379 (js2-parse-function-closure-body fn-node)
7380 (js2-parse-function-body fn-node))
7381 (if name
7382 (js2-node-add-children fn-node name))
7383 (js2-check-inconsistent-return-warning fn-node name)
7384 ;; Function expressions define a name only in the body of the
7385 ;; function, and only if not hidden by a parameter name
7386 (if (and name
7387 (eq synthetic-type 'FUNCTION_EXPRESSION)
7388 (null (js2-scope-get-symbol js2-current-scope
7389 (js2-name-node-name name))))
7390 (js2-define-symbol js2-FUNCTION
7391 (js2-name-node-name name)
7392 fn-node))
7393 (if (and name
7394 (not (eq function-type 'FUNCTION_EXPRESSION)))
7395 (js2-record-imenu-functions fn-node)))
7396 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7397 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7398 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7399 ;; We wait until after parsing the function to set its parent scope,
7400 ;; since `js2-define-symbol' needs the defining-scope check to stop
7401 ;; at the function boundary when checking for redeclarations.
7402 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7403 fn-node))
7404
7405 (defun js2-parse-statements (&optional parent)
7406 "Parse a statement list. Last token consumed must be js2-LC.
7407
7408 PARENT can be a `js2-block-node', in which case the statements are
7409 appended to PARENT. Otherwise a new `js2-block-node' is created
7410 and returned.
7411
7412 This function does not match the closing js2-RC: the caller
7413 matches the RC so it can provide a suitable error message if not
7414 matched. This means it's up to the caller to set the length of
7415 the node to include the closing RC. The node start pos is set to
7416 the absolute buffer start position, and the caller should fix it
7417 up to be relative to the parent node. All children of this block
7418 node are given relative start positions and correct lengths."
7419 (let ((pn (or parent (make-js2-block-node)))
7420 tt)
7421 (setf (js2-node-pos pn) js2-token-beg)
7422 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7423 (/= tt js2-RC))
7424 (js2-block-node-push pn (js2-parse-statement)))
7425 pn))
7426
7427 (defun js2-parse-statement ()
7428 (let (tt pn beg end)
7429 ;; coarse-grained user-interrupt check - needs work
7430 (and js2-parse-interruptable-p
7431 (zerop (% (incf js2-parse-stmt-count)
7432 js2-statements-per-pause))
7433 (input-pending-p)
7434 (throw 'interrupted t))
7435 (setq pn (js2-statement-helper))
7436 ;; no-side-effects warning check
7437 (unless (js2-node-has-side-effects pn)
7438 (setq end (js2-node-end pn))
7439 (save-excursion
7440 (goto-char end)
7441 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7442 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7443 pn))
7444
7445 ;; These correspond to the switch cases in Parser.statementHelper
7446 (defconst js2-parsers
7447 (let ((parsers (make-vector js2-num-tokens
7448 #'js2-parse-expr-stmt)))
7449 (aset parsers js2-BREAK #'js2-parse-break)
7450 (aset parsers js2-CONST #'js2-parse-const-var)
7451 (aset parsers js2-CONTINUE #'js2-parse-continue)
7452 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7453 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7454 (aset parsers js2-DO #'js2-parse-do)
7455 (aset parsers js2-FOR #'js2-parse-for)
7456 (aset parsers js2-FUNCTION #'js2-function-parser)
7457 (aset parsers js2-IF #'js2-parse-if)
7458 (aset parsers js2-LC #'js2-parse-block)
7459 (aset parsers js2-LET #'js2-parse-let-stmt)
7460 (aset parsers js2-NAME #'js2-parse-name-or-label)
7461 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7462 (aset parsers js2-SEMI #'js2-parse-semi)
7463 (aset parsers js2-SWITCH #'js2-parse-switch)
7464 (aset parsers js2-THROW #'js2-parse-throw)
7465 (aset parsers js2-TRY #'js2-parse-try)
7466 (aset parsers js2-VAR #'js2-parse-const-var)
7467 (aset parsers js2-WHILE #'js2-parse-while)
7468 (aset parsers js2-WITH #'js2-parse-with)
7469 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7470 parsers)
7471 "A vector mapping token types to parser functions.")
7472
7473 (defun js2-parse-warn-missing-semi (beg end)
7474 (and js2-mode-show-strict-warnings
7475 js2-strict-missing-semi-warning
7476 (js2-add-strict-warning
7477 "msg.missing.semi" nil
7478 ;; back up to beginning of statement or line
7479 (max beg (save-excursion
7480 (goto-char end)
7481 (point-at-bol)))
7482 end)))
7483
7484 (defconst js2-no-semi-insertion
7485 (list js2-IF
7486 js2-SWITCH
7487 js2-WHILE
7488 js2-DO
7489 js2-FOR
7490 js2-TRY
7491 js2-WITH
7492 js2-LC
7493 js2-ERROR
7494 js2-SEMI
7495 js2-FUNCTION)
7496 "List of tokens that don't do automatic semicolon insertion.")
7497
7498 (defconst js2-autoinsert-semi-and-warn
7499 (list js2-ERROR js2-EOF js2-RC))
7500
7501 (defun js2-statement-helper ()
7502 (let* ((tt (js2-peek-token))
7503 (first-tt tt)
7504 (beg js2-token-beg)
7505 (parser (if (= tt js2-ERROR)
7506 #'js2-parse-semi
7507 (aref js2-parsers tt)))
7508 pn
7509 tt-flagged)
7510 ;; If the statement is set, then it's been told its label by now.
7511 (and js2-labeled-stmt
7512 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7513 (setq js2-labeled-stmt nil))
7514 (setq pn (funcall parser))
7515 ;; Don't do auto semi insertion for certain statement types.
7516 (unless (or (memq first-tt js2-no-semi-insertion)
7517 (js2-labeled-stmt-node-p pn))
7518 (js2-auto-insert-semicolon pn))
7519 pn))
7520
7521 (defun js2-auto-insert-semicolon (pn)
7522 (let* ((tt-flagged (js2-peek-flagged-token))
7523 (tt (logand tt-flagged js2-clear-ti-mask))
7524 (pos (js2-node-pos pn)))
7525 (cond
7526 ((= tt js2-SEMI)
7527 ;; Consume ';' as a part of expression
7528 (js2-consume-token)
7529 ;; extend the node bounds to include the semicolon.
7530 (setf (js2-node-len pn) (- js2-token-end pos)))
7531 ((memq tt js2-autoinsert-semi-and-warn)
7532 ;; Autoinsert ;
7533 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7534 (t
7535 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7536 ;; Report error if no EOL or autoinsert ';' otherwise
7537 (js2-report-error "msg.no.semi.stmt")
7538 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7539
7540 (defun js2-parse-condition ()
7541 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7542 The parens are discarded and the expression node is returned.
7543 The `pos' field of the return value is set to an absolute position
7544 that must be fixed up by the caller.
7545 Return value is a list (EXPR LP RP), with absolute paren positions."
7546 (let (pn lp rp)
7547 (if (js2-must-match js2-LP "msg.no.paren.cond")
7548 (setq lp js2-token-beg))
7549 (setq pn (js2-parse-expr))
7550 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7551 (setq rp js2-token-beg))
7552 ;; Report strict warning on code like "if (a = 7) ..."
7553 (if (and js2-strict-cond-assign-warning
7554 (js2-assign-node-p pn))
7555 (js2-add-strict-warning "msg.equal.as.assign" nil
7556 (js2-node-pos pn)
7557 (+ (js2-node-pos pn)
7558 (js2-node-len pn))))
7559 (list pn lp rp)))
7560
7561 (defun js2-parse-if ()
7562 "Parser for if-statement. Last matched token must be js2-IF."
7563 (let ((pos js2-token-beg)
7564 cond if-true if-false else-pos end pn)
7565 (js2-consume-token)
7566 (setq cond (js2-parse-condition)
7567 if-true (js2-parse-statement)
7568 if-false (if (js2-match-token js2-ELSE)
7569 (progn
7570 (setq else-pos (- js2-token-beg pos))
7571 (js2-parse-statement)))
7572 end (js2-node-end (or if-false if-true))
7573 pn (make-js2-if-node :pos pos
7574 :len (- end pos)
7575 :condition (car cond)
7576 :then-part if-true
7577 :else-part if-false
7578 :else-pos else-pos
7579 :lp (js2-relpos (second cond) pos)
7580 :rp (js2-relpos (third cond) pos)))
7581 (js2-node-add-children pn (car cond) if-true if-false)
7582 pn))
7583
7584 (defun js2-parse-switch ()
7585 "Parser for if-statement. Last matched token must be js2-SWITCH."
7586 (let ((pos js2-token-beg)
7587 tt pn discriminant has-default case-expr case-node
7588 case-pos cases stmt lp rp)
7589 (js2-consume-token)
7590 (if (js2-must-match js2-LP "msg.no.paren.switch")
7591 (setq lp js2-token-beg))
7592 (setq discriminant (js2-parse-expr)
7593 pn (make-js2-switch-node :discriminant discriminant
7594 :pos pos
7595 :lp (js2-relpos lp pos)))
7596 (js2-node-add-children pn discriminant)
7597 (js2-enter-switch pn)
7598 (unwind-protect
7599 (progn
7600 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7601 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7602 (js2-must-match js2-LC "msg.no.brace.switch")
7603 (catch 'break
7604 (while t
7605 (setq tt (js2-next-token)
7606 case-pos js2-token-beg)
7607 (cond
7608 ((= tt js2-RC)
7609 (setf (js2-node-len pn) (- js2-token-end pos))
7610 (throw 'break nil)) ; done
7611 ((= tt js2-CASE)
7612 (setq case-expr (js2-parse-expr))
7613 (js2-must-match js2-COLON "msg.no.colon.case"))
7614 ((= tt js2-DEFAULT)
7615 (if has-default
7616 (js2-report-error "msg.double.switch.default"))
7617 (setq has-default t
7618 case-expr nil)
7619 (js2-must-match js2-COLON "msg.no.colon.case"))
7620 (t
7621 (js2-report-error "msg.bad.switch")
7622 (throw 'break nil)))
7623 (setq case-node (make-js2-case-node :pos case-pos
7624 :len (- js2-token-end case-pos)
7625 :expr case-expr))
7626 (js2-node-add-children case-node case-expr)
7627 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7628 (/= tt js2-CASE)
7629 (/= tt js2-DEFAULT)
7630 (/= tt js2-EOF))
7631 (setf stmt (js2-parse-statement)
7632 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7633 (js2-block-node-push case-node stmt))
7634 (push case-node cases)))
7635 ;; add cases last, as pushing reverses the order to be correct
7636 (dolist (kid cases)
7637 (js2-node-add-children pn kid)
7638 (push kid (js2-switch-node-cases pn)))
7639 pn) ; return value
7640 (js2-exit-switch))))
7641
7642 (defun js2-parse-while ()
7643 "Parser for while-statement. Last matched token must be js2-WHILE."
7644 (let ((pos js2-token-beg)
7645 (pn (make-js2-while-node))
7646 cond body)
7647 (js2-consume-token)
7648 (js2-enter-loop pn)
7649 (unwind-protect
7650 (progn
7651 (setf cond (js2-parse-condition)
7652 (js2-while-node-condition pn) (car cond)
7653 body (js2-parse-statement)
7654 (js2-while-node-body pn) body
7655 (js2-node-len pn) (- (js2-node-end body) pos)
7656 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7657 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7658 (js2-node-add-children pn body (car cond)))
7659 (js2-exit-loop))
7660 pn))
7661
7662 (defun js2-parse-do ()
7663 "Parser for do-statement. Last matched token must be js2-DO."
7664 (let ((pos js2-token-beg)
7665 (pn (make-js2-do-node))
7666 cond body end)
7667 (js2-consume-token)
7668 (js2-enter-loop pn)
7669 (unwind-protect
7670 (progn
7671 (setq body (js2-parse-statement))
7672 (js2-must-match js2-WHILE "msg.no.while.do")
7673 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7674 cond (js2-parse-condition)
7675 (js2-do-node-condition pn) (car cond)
7676 (js2-do-node-body pn) body
7677 end js2-ts-cursor
7678 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7679 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7680 (js2-node-add-children pn (car cond) body))
7681 (js2-exit-loop))
7682 ;; Always auto-insert semicolon to follow SpiderMonkey:
7683 ;; It is required by ECMAScript but is ignored by the rest of
7684 ;; world; see bug 238945
7685 (if (js2-match-token js2-SEMI)
7686 (setq end js2-ts-cursor))
7687 (setf (js2-node-len pn) (- end pos))
7688 pn))
7689
7690 (defun js2-parse-for ()
7691 "Parser for for-statement. Last matched token must be js2-FOR.
7692 Parses for, for-in, and for each-in statements."
7693 (let ((for-pos js2-token-beg)
7694 pn is-for-each is-for-in in-pos each-pos tmp-pos
7695 init ; Node init is also foo in 'foo in object'
7696 cond ; Node cond is also object in 'foo in object'
7697 incr ; 3rd section of for-loop initializer
7698 body tt lp rp)
7699 (js2-consume-token)
7700 ;; See if this is a for each () instead of just a for ()
7701 (when (js2-match-token js2-NAME)
7702 (if (string= "each" js2-ts-string)
7703 (progn
7704 (setq is-for-each t
7705 each-pos (- js2-token-beg for-pos)) ; relative
7706 (js2-record-face 'font-lock-keyword-face))
7707 (js2-report-error "msg.no.paren.for")))
7708 (if (js2-must-match js2-LP "msg.no.paren.for")
7709 (setq lp (- js2-token-beg for-pos)))
7710 (setq tt (js2-peek-token))
7711 ;; 'for' makes local scope
7712 (js2-push-scope (make-js2-scope))
7713 (unwind-protect
7714 ;; parse init clause
7715 (let ((js2-in-for-init t)) ; set as dynamic variable
7716 (cond
7717 ((= tt js2-SEMI)
7718 (setq init (make-js2-empty-expr-node)))
7719 ((or (= tt js2-VAR) (= tt js2-LET))
7720 (js2-consume-token)
7721 (setq init (js2-parse-variables tt js2-token-beg)))
7722 (t
7723 (setq init (js2-parse-expr)))))
7724 (if (js2-match-token js2-IN)
7725 (setq is-for-in t
7726 in-pos (- js2-token-beg for-pos)
7727 ;; scope of iteration target object is not the scope we've created above.
7728 ;; stash current scope temporary.
7729 cond (let ((js2-current-scope (js2-scope-parent-scope js2-current-scope)))
7730 (js2-parse-expr))) ; object over which we're iterating
7731 ;; else ordinary for loop - parse cond and incr
7732 (js2-must-match js2-SEMI "msg.no.semi.for")
7733 (setq cond (if (= (js2-peek-token) js2-SEMI)
7734 (make-js2-empty-expr-node) ; no loop condition
7735 (js2-parse-expr)))
7736 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7737 (setq tmp-pos js2-token-end
7738 incr (if (= (js2-peek-token) js2-RP)
7739 (make-js2-empty-expr-node :pos tmp-pos)
7740 (js2-parse-expr))))
7741 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7742 (setq rp (- js2-token-beg for-pos)))
7743 (if (not is-for-in)
7744 (setq pn (make-js2-for-node :init init
7745 :condition cond
7746 :update incr
7747 :lp lp
7748 :rp rp))
7749 ;; cond could be null if 'in obj' got eaten by the init node.
7750 (if (js2-infix-node-p init)
7751 ;; it was (foo in bar) instead of (var foo in bar)
7752 (setq cond (js2-infix-node-right init)
7753 init (js2-infix-node-left init))
7754 (if (and (js2-var-decl-node-p init)
7755 (> (length (js2-var-decl-node-kids init)) 1))
7756 (js2-report-error "msg.mult.index")))
7757 (setq pn (make-js2-for-in-node :iterator init
7758 :object cond
7759 :in-pos in-pos
7760 :foreach-p is-for-each
7761 :each-pos each-pos
7762 :lp lp
7763 :rp rp)))
7764 (unwind-protect
7765 (progn
7766 (js2-enter-loop pn)
7767 ;; We have to parse the body -after- creating the loop node,
7768 ;; so that the loop node appears in the js2-loop-set, allowing
7769 ;; break/continue statements to find the enclosing loop.
7770 (setf body (js2-parse-statement)
7771 (js2-loop-node-body pn) body
7772 (js2-node-pos pn) for-pos
7773 (js2-node-len pn) (- (js2-node-end body) for-pos))
7774 (js2-node-add-children pn init cond incr body))
7775 ;; finally
7776 (js2-exit-loop))
7777 (js2-pop-scope))
7778 pn))
7779
7780 (defun js2-parse-try ()
7781 "Parser for try-statement. Last matched token must be js2-TRY."
7782 (let ((try-pos js2-token-beg)
7783 try-end
7784 try-block
7785 catch-blocks
7786 finally-block
7787 saw-default-catch
7788 peek
7789 param
7790 catch-cond
7791 catch-node
7792 guard-kwd
7793 catch-pos
7794 finally-pos
7795 pn
7796 block
7797 lp
7798 rp)
7799 (js2-consume-token)
7800 (if (/= (js2-peek-token) js2-LC)
7801 (js2-report-error "msg.no.brace.try"))
7802 (setq try-block (js2-parse-statement)
7803 try-end (js2-node-end try-block)
7804 peek (js2-peek-token))
7805 (cond
7806 ((= peek js2-CATCH)
7807 (while (js2-match-token js2-CATCH)
7808 (setq catch-pos js2-token-beg
7809 guard-kwd nil
7810 catch-cond nil
7811 lp nil
7812 rp nil)
7813 (if saw-default-catch
7814 (js2-report-error "msg.catch.unreachable"))
7815 (if (js2-must-match js2-LP "msg.no.paren.catch")
7816 (setq lp (- js2-token-beg catch-pos)))
7817 (js2-push-scope (make-js2-scope))
7818 (let ((tt (js2-peek-token)))
7819 (cond
7820 ;; destructuring pattern
7821 ;; catch ({ message, file }) { ... }
7822 ((or (= tt js2-LB) (= tt js2-LC))
7823 (setq param
7824 (js2-define-destruct-symbols (js2-parse-primary-expr-lhs)
7825 js2-LET nil)))
7826 ;; simple name
7827 (t
7828 (js2-must-match js2-NAME "msg.bad.catchcond")
7829 (setq param (js2-create-name-node))
7830 (js2-define-symbol js2-LET js2-ts-string param))))
7831 ;; pattern guard
7832 (if (js2-match-token js2-IF)
7833 (setq guard-kwd (- js2-token-beg catch-pos)
7834 catch-cond (js2-parse-expr))
7835 (setq saw-default-catch t))
7836 (if (js2-must-match js2-RP "msg.bad.catchcond")
7837 (setq rp (- js2-token-beg catch-pos)))
7838 (js2-must-match js2-LC "msg.no.brace.catchblock")
7839 (setq block (js2-parse-statements)
7840 try-end (js2-node-end block)
7841 catch-node (make-js2-catch-node :pos catch-pos
7842 :param param
7843 :guard-expr catch-cond
7844 :guard-kwd guard-kwd
7845 :block block
7846 :lp lp
7847 :rp rp))
7848 (js2-pop-scope)
7849 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7850 (setq try-end js2-token-beg))
7851 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7852 (js2-node-len catch-node) (- try-end catch-pos))
7853 (js2-node-add-children catch-node param catch-cond block)
7854 (push catch-node catch-blocks)))
7855 ((/= peek js2-FINALLY)
7856 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7857 (js2-node-pos try-block)
7858 (- (setq try-end (js2-node-end try-block))
7859 (js2-node-pos try-block)))))
7860 (when (js2-match-token js2-FINALLY)
7861 (setq finally-pos js2-token-beg
7862 block (js2-parse-statement)
7863 try-end (js2-node-end block)
7864 finally-block (make-js2-finally-node :pos finally-pos
7865 :len (- try-end finally-pos)
7866 :body block))
7867 (js2-node-add-children finally-block block))
7868 (setq pn (make-js2-try-node :pos try-pos
7869 :len (- try-end try-pos)
7870 :try-block try-block
7871 :finally-block finally-block))
7872 (js2-node-add-children pn try-block finally-block)
7873 ;; push them onto the try-node, which reverses and corrects their order
7874 (dolist (cb catch-blocks)
7875 (js2-node-add-children pn cb)
7876 (push cb (js2-try-node-catch-clauses pn)))
7877 pn))
7878
7879 (defun js2-parse-throw ()
7880 "Parser for throw-statement. Last matched token must be js2-THROW."
7881 (let ((pos js2-token-beg)
7882 expr pn)
7883 (js2-consume-token)
7884 (if (= (js2-peek-token-or-eol) js2-EOL)
7885 ;; ECMAScript does not allow new lines before throw expression,
7886 ;; see bug 256617
7887 (js2-report-error "msg.bad.throw.eol"))
7888 (setq expr (js2-parse-expr)
7889 pn (make-js2-throw-node :pos pos
7890 :len (- (js2-node-end expr) pos)
7891 :expr expr))
7892 (js2-node-add-children pn expr)
7893 pn))
7894
7895 (defun js2-match-jump-label-name (label-name)
7896 "If break/continue specified a label, return that label's labeled stmt.
7897 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
7898 does not match an existing label, reports an error and returns nil."
7899 (let ((bundle (cdr (assoc label-name js2-label-set))))
7900 (if (null bundle)
7901 (js2-report-error "msg.undef.label"))
7902 bundle))
7903
7904 (defun js2-parse-break ()
7905 "Parser for break-statement. Last matched token must be js2-BREAK."
7906 (let ((pos js2-token-beg)
7907 (end js2-token-end)
7908 break-target ; statement to break from
7909 break-label ; in "break foo", name-node representing the foo
7910 labels ; matching labeled statement to break to
7911 pn)
7912 (js2-consume-token) ; `break'
7913 (when (eq (js2-peek-token-or-eol) js2-NAME)
7914 (js2-consume-token)
7915 (setq break-label (js2-create-name-node)
7916 end (js2-node-end break-label)
7917 ;; matchJumpLabelName only matches if there is one
7918 labels (js2-match-jump-label-name js2-ts-string)
7919 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
7920 (unless (or break-target break-label)
7921 ;; no break target specified - try for innermost enclosing loop/switch
7922 (if (null js2-loop-and-switch-set)
7923 (unless break-label
7924 (js2-report-error "msg.bad.break" nil pos (length "break")))
7925 (setq break-target (car js2-loop-and-switch-set))))
7926 (setq pn (make-js2-break-node :pos pos
7927 :len (- end pos)
7928 :label break-label
7929 :target break-target))
7930 (js2-node-add-children pn break-label) ; but not break-target
7931 pn))
7932
7933 (defun js2-parse-continue ()
7934 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
7935 (let ((pos js2-token-beg)
7936 (end js2-token-end)
7937 label ; optional user-specified label, a `js2-name-node'
7938 labels ; current matching labeled stmt, if any
7939 target ; the `js2-loop-node' target of this continue stmt
7940 pn)
7941 (js2-consume-token) ; `continue'
7942 (when (= (js2-peek-token-or-eol) js2-NAME)
7943 (js2-consume-token)
7944 (setq label (js2-create-name-node)
7945 end (js2-node-end label)
7946 ;; matchJumpLabelName only matches if there is one
7947 labels (js2-match-jump-label-name js2-ts-string)))
7948 (cond
7949 ((null labels) ; no current label to go to
7950 (if (null js2-loop-set) ; no loop to continue to
7951 (js2-report-error "msg.continue.outside" nil pos
7952 (length "continue"))
7953 (setq target (car js2-loop-set)))) ; innermost enclosing loop
7954 (t
7955 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
7956 (setq target (js2-labeled-stmt-node-stmt labels))
7957 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
7958 (setq pn (make-js2-continue-node :pos pos
7959 :len (- end pos)
7960 :label label
7961 :target target))
7962 (js2-node-add-children pn label) ; but not target - it's not our child
7963 pn))
7964
7965 (defun js2-parse-with ()
7966 "Parser for with-statement. Last matched token must be js2-WITH."
7967 (js2-consume-token)
7968 (let ((pos js2-token-beg)
7969 obj body pn lp rp)
7970 (if (js2-must-match js2-LP "msg.no.paren.with")
7971 (setq lp js2-token-beg))
7972 (setq obj (js2-parse-expr))
7973 (if (js2-must-match js2-RP "msg.no.paren.after.with")
7974 (setq rp js2-token-beg))
7975 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
7976 (setq body (js2-parse-statement)))
7977 (setq pn (make-js2-with-node :pos pos
7978 :len (- (js2-node-end body) pos)
7979 :object obj
7980 :body body
7981 :lp (js2-relpos lp pos)
7982 :rp (js2-relpos rp pos)))
7983 (js2-node-add-children pn obj body)
7984 pn))
7985
7986 (defun js2-parse-const-var ()
7987 "Parser for var- or const-statement.
7988 Last matched token must be js2-CONST or js2-VAR."
7989 (let ((tt (js2-peek-token))
7990 (pos js2-token-beg)
7991 expr pn)
7992 (js2-consume-token)
7993 (setq expr (js2-parse-variables tt js2-token-beg)
7994 pn (make-js2-expr-stmt-node :pos pos
7995 :len (- (js2-node-end expr) pos)
7996 :expr expr))
7997 (js2-node-add-children pn expr)
7998 pn))
7999
8000 (defun js2-wrap-with-expr-stmt (pos expr &optional add-child)
8001 (let ((pn (make-js2-expr-stmt-node :pos pos
8002 :len (js2-node-len expr)
8003 :type (if (js2-inside-function)
8004 js2-EXPR_VOID
8005 js2-EXPR_RESULT)
8006 :expr expr)))
8007 (if add-child
8008 (js2-node-add-children pn expr))
8009 pn))
8010
8011 (defun js2-parse-let-stmt ()
8012 "Parser for let-statement. Last matched token must be js2-LET."
8013 (js2-consume-token)
8014 (let ((pos js2-token-beg)
8015 expr pn)
8016 (if (= (js2-peek-token) js2-LP)
8017 ;; let expression in statement context
8018 (setq expr (js2-parse-let pos 'statement)
8019 pn (js2-wrap-with-expr-stmt pos expr t))
8020 ;; else we're looking at a statement like let x=6, y=7;
8021 (setf expr (js2-parse-variables js2-LET pos)
8022 pn (js2-wrap-with-expr-stmt pos expr t)
8023 (js2-node-type pn) js2-EXPR_RESULT))
8024 pn))
8025
8026 (defun js2-parse-ret-yield ()
8027 (js2-parse-return-or-yield (js2-peek-token) nil))
8028
8029 (defconst js2-parse-return-stmt-enders
8030 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8031
8032 (defsubst js2-now-all-set (before after mask)
8033 "Return whether or not the bits in the mask have changed to all set.
8034 BEFORE is bits before change, AFTER is bits after change, and MASK is
8035 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8036 but not BEFORE."
8037 (and (/= (logand before mask) mask)
8038 (= (logand after mask) mask)))
8039
8040 (defun js2-parse-return-or-yield (tt expr-context)
8041 (let ((pos js2-token-beg)
8042 (end js2-token-end)
8043 (before js2-end-flags)
8044 (inside-function (js2-inside-function))
8045 e ret name)
8046 (unless inside-function
8047 (js2-report-error (if (eq tt js2-RETURN)
8048 "msg.bad.return"
8049 "msg.bad.yield")))
8050 (js2-consume-token)
8051 ;; This is ugly, but we don't want to require a semicolon.
8052 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8053 (setq e (js2-parse-expr)
8054 end (js2-node-end e)))
8055 (cond
8056 ((eq tt js2-RETURN)
8057 (js2-set-flag js2-end-flags (if (null e)
8058 js2-end-returns
8059 js2-end-returns-value))
8060 (setq ret (make-js2-return-node :pos pos
8061 :len (- end pos)
8062 :retval e))
8063 (js2-node-add-children ret e)
8064 ;; See if we need a strict mode warning.
8065 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8066 ;; more thorough and accurate than this before/after flag check.
8067 ;; E.g. if there's a finally-block that always returns, we shouldn't
8068 ;; show a warning generated by inconsistent returns in the catch blocks.
8069 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8070 ;; so we know which returns/yields to highlight, and we should get rid of
8071 ;; all the checking in `js2-parse-return-or-yield'.
8072 (if (and js2-strict-inconsistent-return-warning
8073 (js2-now-all-set before js2-end-flags
8074 (logior js2-end-returns js2-end-returns-value)))
8075 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8076 (t
8077 (unless (js2-inside-function)
8078 (js2-report-error "msg.bad.yield"))
8079 (js2-set-flag js2-end-flags js2-end-yields)
8080 (setq ret (make-js2-yield-node :pos pos
8081 :len (- end pos)
8082 :value e))
8083 (js2-node-add-children ret e)
8084 (unless expr-context
8085 (setq e ret
8086 ret (js2-wrap-with-expr-stmt pos e t))
8087 (js2-set-requires-activation)
8088 (js2-set-is-generator))))
8089 ;; see if we are mixing yields and value returns.
8090 (when (and inside-function
8091 (js2-now-all-set before js2-end-flags
8092 (logior js2-end-yields js2-end-returns-value)))
8093 (setq name (js2-function-name js2-current-script-or-fn))
8094 (if (zerop (length name))
8095 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8096 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8097 ret))
8098
8099 (defun js2-parse-debugger ()
8100 (js2-consume-token)
8101 (make-js2-keyword-node :type js2-DEBUGGER))
8102
8103 (defun js2-parse-block ()
8104 "Parser for a curly-delimited statement block.
8105 Last token matched must be `js2-LC'."
8106 (let ((pos js2-token-beg)
8107 (pn (make-js2-scope)))
8108 (js2-consume-token)
8109 (js2-push-scope pn)
8110 (unwind-protect
8111 (progn
8112 (js2-parse-statements pn)
8113 (js2-must-match js2-RC "msg.no.brace.block")
8114 (setf (js2-node-len pn) (- js2-token-end pos)))
8115 (js2-pop-scope))
8116 pn))
8117
8118 ;; For `js2-ERROR' too, to have a node for error recovery to work on.
8119 (defun js2-parse-semi ()
8120 "Parse a statement or handle an error.
8121 Last matched token is `js2-SEMI' or `js2-ERROR'."
8122 (let ((tt (js2-peek-token)) pos len)
8123 (js2-consume-token)
8124 (if (eq tt js2-SEMI)
8125 (make-js2-empty-expr-node :len 1)
8126 (setq pos js2-token-beg
8127 len (- js2-token-beg pos))
8128 (js2-report-error "msg.syntax" nil pos len)
8129 (make-js2-error-node :pos pos :len len))))
8130
8131 (defun js2-parse-default-xml-namespace ()
8132 "Parse a `default xml namespace = <expr>' e4x statement."
8133 (let ((pos js2-token-beg)
8134 end len expr unary es)
8135 (js2-consume-token)
8136 (js2-must-have-xml)
8137 (js2-set-requires-activation)
8138 (setq len (- js2-ts-cursor pos))
8139 (unless (and (js2-match-token js2-NAME)
8140 (string= js2-ts-string "xml"))
8141 (js2-report-error "msg.bad.namespace" nil pos len))
8142 (unless (and (js2-match-token js2-NAME)
8143 (string= js2-ts-string "namespace"))
8144 (js2-report-error "msg.bad.namespace" nil pos len))
8145 (unless (js2-match-token js2-ASSIGN)
8146 (js2-report-error "msg.bad.namespace" nil pos len))
8147 (setq expr (js2-parse-expr)
8148 end (js2-node-end expr)
8149 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8150 :pos pos
8151 :len (- end pos)
8152 :operand expr))
8153 (js2-node-add-children unary expr)
8154 (make-js2-expr-stmt-node :pos pos
8155 :len (- end pos)
8156 :expr unary)))
8157
8158 (defun js2-record-label (label bundle)
8159 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8160 (js2-consume-token)
8161 (let ((name (js2-label-node-name label))
8162 labeled-stmt
8163 dup)
8164 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8165 ;; flag both labels if possible when used in editing mode
8166 (if (and js2-parse-ide-mode
8167 (setq dup (js2-get-label-by-name labeled-stmt name)))
8168 (js2-report-error "msg.dup.label" nil
8169 (js2-node-abs-pos dup) (js2-node-len dup)))
8170 (js2-report-error "msg.dup.label" nil
8171 (js2-node-pos label) (js2-node-len label)))
8172 (js2-labeled-stmt-node-add-label bundle label)
8173 (js2-node-add-children bundle label)
8174 ;; Add one reference to the bundle per label in `js2-label-set'
8175 (push (cons name bundle) js2-label-set)))
8176
8177 (defun js2-parse-name-or-label ()
8178 "Parser for identifier or label. Last token matched must be js2-NAME.
8179 Called when we found a name in a statement context. If it's a label, we gather
8180 up any following labels and the next non-label statement into a
8181 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8182 expression and return it wrapped in a `js2-expr-stmt-node'."
8183 (let ((pos js2-token-beg)
8184 (end js2-token-end)
8185 expr stmt pn bundle
8186 (continue t))
8187 ;; set check for label and call down to `js2-parse-primary-expr'
8188 (js2-set-check-for-label)
8189 (setq expr (js2-parse-expr))
8190 (if (/= (js2-node-type expr) js2-LABEL)
8191 ;; Parsed non-label expression - wrap with expression stmt.
8192 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8193 ;; else parsed a label
8194 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8195 (js2-record-label expr bundle)
8196 ;; look for more labels
8197 (while (and continue (= (js2-peek-token) js2-NAME))
8198 (js2-set-check-for-label)
8199 (setq expr (js2-parse-expr))
8200 (if (/= (js2-node-type expr) js2-LABEL)
8201 (progn
8202 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8203 continue nil)
8204 (js2-auto-insert-semicolon stmt))
8205 (js2-record-label expr bundle)))
8206 ;; no more labels; now parse the labeled statement
8207 (unwind-protect
8208 (unless stmt
8209 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8210 (setq stmt (js2-statement-helper))))
8211 ;; remove the labels for this statement from the global set
8212 (dolist (label (js2-labeled-stmt-node-labels bundle))
8213 (setq js2-label-set (remove label js2-label-set))))
8214 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8215 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8216 (js2-node-add-children bundle stmt)
8217 bundle)))
8218
8219 (defun js2-parse-expr-stmt ()
8220 "Default parser in statement context, if no recognized statement found."
8221 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8222
8223 (defun js2-parse-variables (decl-type pos)
8224 "Parse a comma-separated list of variable declarations.
8225 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8226
8227 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8228 For 'var' or 'const', the keyword should be the token last scanned.
8229
8230 POS is the position where the node should start. It's sometimes the
8231 var/const/let keyword, and other times the beginning of the first token
8232 in the first variable declaration.
8233
8234 Returns the parsed `js2-var-decl-node' expression node."
8235 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8236 :pos pos))
8237 destructuring kid-pos tt init name end nbeg nend vi
8238 (continue t))
8239 ;; Example:
8240 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8241 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8242 ;; var {a, b} = baz;
8243 (while continue
8244 (setq destructuring nil
8245 name nil
8246 tt (js2-peek-token)
8247 kid-pos js2-token-beg
8248 end js2-token-end
8249 init nil)
8250 (if (or (= tt js2-LB) (= tt js2-LC))
8251 ;; Destructuring assignment, e.g., var [a, b] = ...
8252 (setq destructuring (js2-parse-primary-expr-lhs)
8253 end (js2-node-end destructuring))
8254 ;; Simple variable name
8255 (when (js2-must-match js2-NAME "msg.bad.var")
8256 (setq name (js2-create-name-node)
8257 nbeg js2-token-beg
8258 nend js2-token-end
8259 end nend)
8260 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8261 (when (js2-match-token js2-ASSIGN)
8262 (setq init (js2-parse-assign-expr)
8263 end (js2-node-end init))
8264 (if (and js2-parse-ide-mode
8265 (or (js2-object-node-p init)
8266 (js2-function-node-p init)))
8267 (js2-record-imenu-functions init name)))
8268 (when name
8269 (js2-set-face nbeg nend (if (js2-function-node-p init)
8270 'font-lock-function-name-face
8271 'font-lock-variable-name-face)
8272 'record))
8273 (setq vi (make-js2-var-init-node :pos kid-pos
8274 :len (- end kid-pos)
8275 :type decl-type))
8276 (if destructuring
8277 (progn
8278 (if (and (null init) (not js2-in-for-init))
8279 (js2-report-error "msg.destruct.assign.no.init"))
8280 (js2-define-destruct-symbols destructuring
8281 decl-type
8282 'font-lock-variable-name-face)
8283 (setf (js2-var-init-node-target vi) destructuring))
8284 (setf (js2-var-init-node-target vi) name))
8285 (setf (js2-var-init-node-initializer vi) init)
8286 (js2-node-add-children vi name destructuring init)
8287 (js2-block-node-push result vi)
8288 (unless (js2-match-token js2-COMMA)
8289 (setq continue nil)))
8290 (setf (js2-node-len result) (- end pos))
8291 result))
8292
8293 (defun js2-parse-let (pos &optional stmt-p)
8294 "Parse a let expression or statement.
8295 A let-expression is of the form `let (vars) expr'.
8296 A let-statment is of the form `let (vars) {statements}'.
8297 The third form of let is a variable declaration list, handled
8298 by `js2-parse-variables'."
8299 (let ((pn (make-js2-let-node :pos pos))
8300 beg vars body)
8301 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8302 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8303 (js2-push-scope pn)
8304 (unwind-protect
8305 (progn
8306 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8307 (if (js2-must-match js2-RP "msg.no.paren.let")
8308 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8309 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8310 ;; let statement
8311 (progn
8312 (js2-consume-token)
8313 (setf beg js2-token-beg ; position stmt at LC
8314 body (js2-parse-statements))
8315 (js2-must-match js2-RC "msg.no.curly.let")
8316 (setf (js2-node-len body) (- js2-token-end beg)
8317 (js2-node-len pn) (- js2-token-end pos)
8318 (js2-let-node-body pn) body
8319 (js2-node-type pn) js2-LET))
8320 ;; let expression
8321 (setf body (js2-parse-expr)
8322 (js2-node-len pn) (- (js2-node-end body) pos)
8323 (js2-let-node-body pn) body))
8324 (js2-node-add-children pn vars body))
8325 (js2-pop-scope))
8326 pn))
8327
8328 (defun js2-define-new-symbol (decl-type name node &optional scope)
8329 (js2-scope-put-symbol (or scope js2-current-scope)
8330 name
8331 (make-js2-symbol decl-type name node)))
8332
8333 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8334 "Define a symbol in the current scope.
8335 If NODE is non-nil, it is the AST node associated with the symbol."
8336 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8337 (symbol (if defining-scope
8338 (js2-scope-get-symbol defining-scope name)))
8339 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8340 (cond
8341 ((and symbol ; already defined
8342 (or (= sdt js2-CONST) ; old version is const
8343 (= decl-type js2-CONST) ; new version is const
8344 ;; two let-bound vars in this block have same name
8345 (and (= sdt js2-LET)
8346 (eq defining-scope js2-current-scope))))
8347 (js2-report-error
8348 (cond
8349 ((= sdt js2-CONST) "msg.const.redecl")
8350 ((= sdt js2-LET) "msg.let.redecl")
8351 ((= sdt js2-VAR) "msg.var.redecl")
8352 ((= sdt js2-FUNCTION) "msg.function.redecl")
8353 (t "msg.parm.redecl"))
8354 name))
8355 ((= decl-type js2-LET)
8356 (if (and (not ignore-not-in-block)
8357 (or (= (js2-node-type js2-current-scope) js2-IF)
8358 (js2-loop-node-p js2-current-scope)))
8359 (js2-report-error "msg.let.decl.not.in.block")
8360 (js2-define-new-symbol decl-type name node)))
8361 ((or (= decl-type js2-VAR)
8362 (= decl-type js2-CONST)
8363 (= decl-type js2-FUNCTION))
8364 (if symbol
8365 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8366 (js2-add-strict-warning "msg.var.redecl" name)
8367 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8368 (js2-add-strict-warning "msg.var.hides.arg" name)))
8369 (js2-define-new-symbol decl-type name node
8370 js2-current-script-or-fn)))
8371 ((= decl-type js2-LP)
8372 (if symbol
8373 ;; must be duplicate parameter. Second parameter hides the
8374 ;; first, so go ahead and add the second pararameter
8375 (js2-report-warning "msg.dup.parms" name))
8376 (js2-define-new-symbol decl-type name node))
8377 (t (js2-code-bug)))))
8378
8379 (defun js2-parse-expr (&optional oneshot)
8380 (let* ((pn (js2-parse-assign-expr))
8381 (pos (js2-node-pos pn))
8382 left
8383 right
8384 op-pos)
8385 (while (and (not oneshot)
8386 (js2-match-token js2-COMMA))
8387 (setq op-pos (- js2-token-beg pos)) ; relative
8388 (if (= (js2-peek-token) js2-YIELD)
8389 (js2-report-error "msg.yield.parenthesized"))
8390 (setq right (js2-parse-assign-expr)
8391 left pn
8392 pn (make-js2-infix-node :type js2-COMMA
8393 :pos pos
8394 :len (- js2-ts-cursor pos)
8395 :op-pos op-pos
8396 :left left
8397 :right right))
8398 (js2-node-add-children pn left right))
8399 pn))
8400
8401 (defun js2-parse-assign-expr ()
8402 (let ((tt (js2-peek-token))
8403 (pos js2-token-beg)
8404 pn left right op-pos)
8405 (if (= tt js2-YIELD)
8406 (js2-parse-return-or-yield tt t)
8407 ;; not yield - parse assignment expression
8408 (setq pn (js2-parse-cond-expr)
8409 tt (js2-peek-token))
8410 (when (and (<= js2-first-assign tt)
8411 (<= tt js2-last-assign))
8412 ;; tt express assignment (=, |=, ^=, ..., %=)
8413 (js2-consume-token)
8414 (setq op-pos (- js2-token-beg pos) ; relative
8415 left pn
8416 right (js2-parse-assign-expr)
8417 pn (make-js2-assign-node :type tt
8418 :pos pos
8419 :len (- (js2-node-end right) pos)
8420 :op-pos op-pos
8421 :left left
8422 :right right))
8423 (when js2-parse-ide-mode
8424 (js2-highlight-assign-targets pn left right)
8425 (if (or (js2-function-node-p right)
8426 (js2-object-node-p right))
8427 (js2-record-imenu-functions right left)))
8428 ;; do this last so ide checks above can use absolute positions
8429 (js2-node-add-children pn left right))
8430 pn)))
8431
8432 (defun js2-parse-cond-expr ()
8433 (let ((pos js2-token-beg)
8434 (pn (js2-parse-or-expr))
8435 test-expr
8436 if-true
8437 if-false
8438 q-pos
8439 c-pos)
8440 (when (js2-match-token js2-HOOK)
8441 (setq q-pos (- js2-token-beg pos)
8442 if-true (js2-parse-assign-expr))
8443 (js2-must-match js2-COLON "msg.no.colon.cond")
8444 (setq c-pos (- js2-token-beg pos)
8445 if-false (js2-parse-assign-expr)
8446 test-expr pn
8447 pn (make-js2-cond-node :pos pos
8448 :len (- (js2-node-end if-false) pos)
8449 :test-expr test-expr
8450 :true-expr if-true
8451 :false-expr if-false
8452 :q-pos q-pos
8453 :c-pos c-pos))
8454 (js2-node-add-children pn test-expr if-true if-false))
8455 pn))
8456
8457 (defun js2-make-binary (type left parser)
8458 "Helper for constructing a binary-operator AST node.
8459 LEFT is the left-side-expression, already parsed, and the
8460 binary operator should have just been matched.
8461 PARSER is a function to call to parse the right operand,
8462 or a `js2-node' struct if it has already been parsed."
8463 (let* ((pos (js2-node-pos left))
8464 (op-pos (- js2-token-beg pos))
8465 (right (if (js2-node-p parser)
8466 parser
8467 (funcall parser)))
8468 (pn (make-js2-infix-node :type type
8469 :pos pos
8470 :len (- (js2-node-end right) pos)
8471 :op-pos op-pos
8472 :left left
8473 :right right)))
8474 (js2-node-add-children pn left right)
8475 pn))
8476
8477 (defun js2-parse-or-expr ()
8478 (let ((pn (js2-parse-and-expr)))
8479 (when (js2-match-token js2-OR)
8480 (setq pn (js2-make-binary js2-OR
8481 pn
8482 'js2-parse-or-expr)))
8483 pn))
8484
8485 (defun js2-parse-and-expr ()
8486 (let ((pn (js2-parse-bit-or-expr)))
8487 (when (js2-match-token js2-AND)
8488 (setq pn (js2-make-binary js2-AND
8489 pn
8490 'js2-parse-and-expr)))
8491 pn))
8492
8493 (defun js2-parse-bit-or-expr ()
8494 (let ((pn (js2-parse-bit-xor-expr)))
8495 (while (js2-match-token js2-BITOR)
8496 (setq pn (js2-make-binary js2-BITOR
8497 pn
8498 'js2-parse-bit-xor-expr)))
8499 pn))
8500
8501 (defun js2-parse-bit-xor-expr ()
8502 (let ((pn (js2-parse-bit-and-expr)))
8503 (while (js2-match-token js2-BITXOR)
8504 (setq pn (js2-make-binary js2-BITXOR
8505 pn
8506 'js2-parse-bit-and-expr)))
8507 pn))
8508
8509 (defun js2-parse-bit-and-expr ()
8510 (let ((pn (js2-parse-eq-expr)))
8511 (while (js2-match-token js2-BITAND)
8512 (setq pn (js2-make-binary js2-BITAND
8513 pn
8514 'js2-parse-eq-expr)))
8515 pn))
8516
8517 (defconst js2-parse-eq-ops
8518 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8519
8520 (defun js2-parse-eq-expr ()
8521 (let ((pn (js2-parse-rel-expr))
8522 tt)
8523 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8524 (js2-consume-token)
8525 (setq pn (js2-make-binary tt
8526 pn
8527 'js2-parse-rel-expr)))
8528 pn))
8529
8530 (defconst js2-parse-rel-ops
8531 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8532
8533 (defun js2-parse-rel-expr ()
8534 (let ((pn (js2-parse-shift-expr))
8535 (continue t)
8536 tt)
8537 (while continue
8538 (setq tt (js2-peek-token))
8539 (cond
8540 ((and js2-in-for-init (= tt js2-IN))
8541 (setq continue nil))
8542 ((memq tt js2-parse-rel-ops)
8543 (js2-consume-token)
8544 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8545 (t
8546 (setq continue nil))))
8547 pn))
8548
8549 (defconst js2-parse-shift-ops
8550 (list js2-LSH js2-URSH js2-RSH))
8551
8552 (defun js2-parse-shift-expr ()
8553 (let ((pn (js2-parse-add-expr))
8554 tt
8555 (continue t))
8556 (while continue
8557 (setq tt (js2-peek-token))
8558 (if (memq tt js2-parse-shift-ops)
8559 (progn
8560 (js2-consume-token)
8561 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8562 (setq continue nil)))
8563 pn))
8564
8565 (defun js2-parse-add-expr ()
8566 (let ((pn (js2-parse-mul-expr))
8567 tt
8568 (continue t))
8569 (while continue
8570 (setq tt (js2-peek-token))
8571 (if (or (= tt js2-ADD) (= tt js2-SUB))
8572 (progn
8573 (js2-consume-token)
8574 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8575 (setq continue nil)))
8576 pn))
8577
8578 (defconst js2-parse-mul-ops
8579 (list js2-MUL js2-DIV js2-MOD))
8580
8581 (defun js2-parse-mul-expr ()
8582 (let ((pn (js2-parse-unary-expr))
8583 tt
8584 (continue t))
8585 (while continue
8586 (setq tt (js2-peek-token))
8587 (if (memq tt js2-parse-mul-ops)
8588 (progn
8589 (js2-consume-token)
8590 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8591 (setq continue nil)))
8592 pn))
8593
8594 (defun js2-make-unary (type parser &rest args)
8595 "Make a unary node of type TYPE.
8596 PARSER is either a node (for postfix operators) or a function to call
8597 to parse the operand (for prefix operators)."
8598 (let* ((pos js2-token-beg)
8599 (postfix (js2-node-p parser))
8600 (expr (if postfix
8601 parser
8602 (apply parser args)))
8603 end
8604 pn)
8605 (if postfix ; e.g. i++
8606 (setq pos (js2-node-pos expr)
8607 end js2-token-end)
8608 (setq end (js2-node-end expr)))
8609 (setq pn (make-js2-unary-node :type type
8610 :pos pos
8611 :len (- end pos)
8612 :operand expr))
8613 (js2-node-add-children pn expr)
8614 pn))
8615
8616 (defconst js2-incrementable-node-types
8617 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8618 "Node types that can be the operand of a ++ or -- operator.")
8619
8620 (defun js2-check-bad-inc-dec (tt beg end unary)
8621 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8622 js2-incrementable-node-types)
8623 (js2-report-error (if (= tt js2-INC)
8624 "msg.bad.incr"
8625 "msg.bad.decr")
8626 nil beg (- end beg))))
8627
8628 (defun js2-parse-unary-expr ()
8629 (let ((tt (js2-peek-token))
8630 pn expr beg end)
8631 (cond
8632 ((or (= tt js2-VOID)
8633 (= tt js2-NOT)
8634 (= tt js2-BITNOT)
8635 (= tt js2-TYPEOF))
8636 (js2-consume-token)
8637 (js2-make-unary tt 'js2-parse-unary-expr))
8638 ((= tt js2-ADD)
8639 (js2-consume-token)
8640 ;; Convert to special POS token in decompiler and parse tree
8641 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8642 ((= tt js2-SUB)
8643 (js2-consume-token)
8644 ;; Convert to special NEG token in decompiler and parse tree
8645 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8646 ((or (= tt js2-INC)
8647 (= tt js2-DEC))
8648 (js2-consume-token)
8649 (prog1
8650 (setq beg js2-token-beg
8651 end js2-token-end
8652 expr (js2-make-unary tt 'js2-parse-member-expr t))
8653 (js2-check-bad-inc-dec tt beg end expr)))
8654 ((= tt js2-DELPROP)
8655 (js2-consume-token)
8656 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8657 ((= tt js2-ERROR)
8658 (js2-consume-token)
8659 (make-js2-error-node)) ; try to continue
8660 ((and (= tt js2-LT)
8661 js2-compiler-xml-available)
8662 ;; XML stream encountered in expression.
8663 (js2-consume-token)
8664 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8665 (t
8666 (setq pn (js2-parse-member-expr t)
8667 ;; Don't look across a newline boundary for a postfix incop.
8668 tt (js2-peek-token-or-eol))
8669 (when (or (= tt js2-INC) (= tt js2-DEC))
8670 (js2-consume-token)
8671 (setf expr pn
8672 pn (js2-make-unary tt expr))
8673 (js2-node-set-prop pn 'postfix t)
8674 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8675 pn))))
8676
8677 (defun js2-parse-xml-initializer ()
8678 "Parse an E4X XML initializer.
8679 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8680 Then I'll postprocess the result, depending on whether we're in IDE
8681 mode or codegen mode, and generate the appropriate rewritten AST.
8682 IDE mode uses a rich AST that models the XML structure. Codegen mode
8683 just concatenates everything and makes a new XML or XMLList out of it."
8684 (let ((tt (js2-get-first-xml-token))
8685 pn-xml pn expr kids expr-pos
8686 (continue t)
8687 (first-token t))
8688 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8689 (js2-report-error "msg.syntax"))
8690 (setq pn-xml (make-js2-xml-node))
8691 (while continue
8692 (if first-token
8693 (setq first-token nil)
8694 (setq tt (js2-get-next-xml-token)))
8695 (cond
8696 ;; js2-XML means we found a {expr} in the XML stream.
8697 ;; The js2-ts-string is the XML up to the left-curly.
8698 ((= tt js2-XML)
8699 (push (make-js2-string-node :pos js2-token-beg
8700 :len (- js2-ts-cursor js2-token-beg))
8701 kids)
8702 (js2-must-match js2-LC "msg.syntax")
8703 (setq expr-pos js2-ts-cursor
8704 expr (if (eq (js2-peek-token) js2-RC)
8705 (make-js2-empty-expr-node :pos expr-pos)
8706 (js2-parse-expr)))
8707 (js2-must-match js2-RC "msg.syntax")
8708 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8709 :len (js2-node-len expr)
8710 :expr expr))
8711 (js2-node-add-children pn expr)
8712 (push pn kids))
8713 ;; a js2-XMLEND token means we hit the final close-tag.
8714 ((= tt js2-XMLEND)
8715 (push (make-js2-string-node :pos js2-token-beg
8716 :len (- js2-ts-cursor js2-token-beg))
8717 kids)
8718 (dolist (kid (nreverse kids))
8719 (js2-block-node-push pn-xml kid))
8720 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8721 (js2-node-pos pn-xml))
8722 continue nil))
8723 (t
8724 (js2-report-error "msg.syntax")
8725 (setq continue nil))))
8726 pn-xml))
8727
8728
8729 (defun js2-parse-argument-list ()
8730 "Parse an argument list and return it as a Lisp list of nodes.
8731 Returns the list in reverse order. Consumes the right-paren token."
8732 (let (result)
8733 (unless (js2-match-token js2-RP)
8734 (loop do
8735 (if (= (js2-peek-token) js2-YIELD)
8736 (js2-report-error "msg.yield.parenthesized"))
8737 (push (js2-parse-assign-expr) result)
8738 while
8739 (js2-match-token js2-COMMA))
8740 (js2-must-match js2-RP "msg.no.paren.arg")
8741 result)))
8742
8743 (defun js2-parse-member-expr (&optional allow-call-syntax)
8744 (let ((tt (js2-peek-token))
8745 pn pos target args beg end init tail)
8746 (if (/= tt js2-NEW)
8747 (setq pn (js2-parse-primary-expr))
8748 ;; parse a 'new' expression
8749 (js2-consume-token)
8750 (setq pos js2-token-beg
8751 beg pos
8752 target (js2-parse-member-expr)
8753 end (js2-node-end target)
8754 pn (make-js2-new-node :pos pos
8755 :target target
8756 :len (- end pos)))
8757 (js2-node-add-children pn target)
8758 (when (js2-match-token js2-LP)
8759 ;; Add the arguments to pn, if any are supplied.
8760 (setf beg pos ; start of "new" keyword
8761 pos js2-token-beg
8762 args (nreverse (js2-parse-argument-list))
8763 (js2-new-node-args pn) args
8764 end js2-token-end
8765 (js2-new-node-lp pn) (- pos beg)
8766 (js2-new-node-rp pn) (- end 1 beg))
8767 (apply #'js2-node-add-children pn args))
8768 (when (and js2-allow-rhino-new-expr-initializer
8769 (js2-match-token js2-LC))
8770 (setf init (js2-parse-object-literal)
8771 end (js2-node-end init)
8772 (js2-new-node-initializer pn) init)
8773 (js2-node-add-children pn init))
8774 (setf (js2-node-len pn) (- end beg))) ; end outer if
8775 (js2-parse-member-expr-tail allow-call-syntax pn)))
8776
8777 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8778 "Parse a chain of property/array accesses or function calls.
8779 Includes parsing for E4X operators like `..' and `.@'.
8780 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8781 Returns an expression tree that includes PN, the parent node."
8782 (let ((beg (js2-node-pos pn))
8783 tt
8784 (continue t))
8785 (while continue
8786 (setq tt (js2-peek-token))
8787 (cond
8788 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8789 (setq pn (js2-parse-property-access tt pn)))
8790 ((= tt js2-DOTQUERY)
8791 (setq pn (js2-parse-dot-query pn)))
8792 ((= tt js2-LB)
8793 (setq pn (js2-parse-element-get pn)))
8794 ((= tt js2-LP)
8795 (if allow-call-syntax
8796 (setq pn (js2-parse-function-call pn))
8797 (setq continue nil)))
8798 (t
8799 (setq continue nil))))
8800 (if (>= js2-highlight-level 2)
8801 (js2-parse-highlight-member-expr-node pn))
8802 pn))
8803
8804 (defun js2-parse-dot-query (pn)
8805 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8806 Last token parsed must be `js2-DOTQUERY'."
8807 (let ((pos (js2-node-pos pn))
8808 op-pos expr end)
8809 (js2-consume-token)
8810 (js2-must-have-xml)
8811 (js2-set-requires-activation)
8812 (setq op-pos js2-token-beg
8813 expr (js2-parse-expr)
8814 end (js2-node-end expr)
8815 pn (make-js2-xml-dot-query-node :left pn
8816 :pos pos
8817 :op-pos op-pos
8818 :right expr))
8819 (js2-node-add-children pn
8820 (js2-xml-dot-query-node-left pn)
8821 (js2-xml-dot-query-node-right pn))
8822 (if (js2-must-match js2-RP "msg.no.paren")
8823 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8824 end js2-token-end))
8825 (setf (js2-node-len pn) (- end pos))
8826 pn))
8827
8828 (defun js2-parse-element-get (pn)
8829 "Parse an element-get expression, e.g. foo[bar].
8830 Last token parsed must be `js2-RB'."
8831 (let ((lb js2-token-beg)
8832 (pos (js2-node-pos pn))
8833 rb expr)
8834 (js2-consume-token)
8835 (setq expr (js2-parse-expr))
8836 (if (js2-must-match js2-RB "msg.no.bracket.index")
8837 (setq rb js2-token-beg))
8838 (setq pn (make-js2-elem-get-node :target pn
8839 :pos pos
8840 :element expr
8841 :lb (js2-relpos lb pos)
8842 :rb (js2-relpos rb pos)
8843 :len (- js2-token-end pos)))
8844 (js2-node-add-children pn
8845 (js2-elem-get-node-target pn)
8846 (js2-elem-get-node-element pn))
8847 pn))
8848
8849 (defun js2-parse-function-call (pn)
8850 (let (args
8851 (pos (js2-node-pos pn)))
8852 (js2-consume-token)
8853 (setq pn (make-js2-call-node :pos pos
8854 :target pn
8855 :lp (- js2-token-beg pos)))
8856 (js2-node-add-children pn (js2-call-node-target pn))
8857 ;; Add the arguments to pn, if any are supplied.
8858 (setf args (nreverse (js2-parse-argument-list))
8859 (js2-call-node-rp pn) (- js2-token-beg pos)
8860 (js2-call-node-args pn) args)
8861 (apply #'js2-node-add-children pn args)
8862 (setf (js2-node-len pn) (- js2-ts-cursor pos))
8863 pn))
8864
8865 (defun js2-parse-property-access (tt pn)
8866 "Parse a property access, XML descendants access, or XML attr access."
8867 (let ((member-type-flags 0)
8868 (dot-pos js2-token-beg)
8869 (dot-len (if (= tt js2-DOTDOT) 2 1))
8870 name
8871 ref ; right side of . or .. operator
8872 result)
8873 (js2-consume-token)
8874 (when (= tt js2-DOTDOT)
8875 (js2-must-have-xml)
8876 (setq member-type-flags js2-descendants-flag))
8877 (if (not js2-compiler-xml-available)
8878 (progn
8879 (js2-must-match-prop-name "msg.no.name.after.dot")
8880 (setq name (js2-create-name-node t js2-GETPROP)
8881 result (make-js2-prop-get-node :left pn
8882 :pos js2-token-beg
8883 :right name
8884 :len (- js2-token-end
8885 js2-token-beg)))
8886 (js2-node-add-children result pn name)
8887 result)
8888 ;; otherwise look for XML operators
8889 (setf result (if (= tt js2-DOT)
8890 (make-js2-prop-get-node)
8891 (make-js2-infix-node :type js2-DOTDOT))
8892 (js2-node-pos result) (js2-node-pos pn)
8893 (js2-infix-node-op-pos result) dot-pos
8894 (js2-infix-node-left result) pn ; do this after setting position
8895 tt (js2-next-token))
8896 (cond
8897 ;; needed for generator.throw()
8898 ((= tt js2-THROW)
8899 (js2-save-name-token-data js2-token-beg "throw")
8900 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
8901 ;; handles: name, ns::name, ns::*, ns::[expr]
8902 ((js2-valid-prop-name-token tt)
8903 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
8904 ;; handles: *, *::name, *::*, *::[expr]
8905 ((= tt js2-MUL)
8906 (js2-save-name-token-data js2-token-beg "*")
8907 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
8908 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
8909 ((= tt js2-XMLATTR)
8910 (setq result (js2-parse-attribute-access)))
8911 (t
8912 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
8913 (if ref
8914 (setf (js2-node-len result) (- (js2-node-end ref)
8915 (js2-node-pos result))
8916 (js2-infix-node-right result) ref))
8917 (if (js2-infix-node-p result)
8918 (js2-node-add-children result
8919 (js2-infix-node-left result)
8920 (js2-infix-node-right result)))
8921 result)))
8922
8923 (defun js2-parse-attribute-access ()
8924 "Parse an E4X XML attribute expression.
8925 This includes expressions of the forms:
8926
8927 @attr @ns::attr @ns::*
8928 @* @*::attr @*::*
8929 @[expr] @*::[expr] @ns::[expr]
8930
8931 Called if we peeked an '@' token."
8932 (let ((tt (js2-next-token))
8933 (at-pos js2-token-beg))
8934 (cond
8935 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
8936 ((js2-valid-prop-name-token tt)
8937 (js2-parse-property-name at-pos js2-ts-string 0))
8938 ;; handles: @*, @*::name, @*::*, @*::[expr]
8939 ((= tt js2-MUL)
8940 (js2-save-name-token-data js2-token-beg "*")
8941 (js2-parse-property-name js2-token-beg "*" 0))
8942 ;; handles @[expr]
8943 ((= tt js2-LB)
8944 (js2-parse-xml-elem-ref at-pos))
8945 (t
8946 (js2-report-error "msg.no.name.after.xmlAttr")
8947 ;; Avoid cascaded errors that happen if we make an error node here.
8948 (js2-save-name-token-data js2-token-beg "")
8949 (js2-parse-property-name js2-token-beg "" 0)))))
8950
8951 (defun js2-parse-property-name (at-pos s member-type-flags)
8952 "Check if :: follows name in which case it becomes qualified name.
8953
8954 AT-POS is a natural number if we just read an '@' token, else nil.
8955 S is the name or string that was matched: an identifier, 'throw' or '*'.
8956 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
8957
8958 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
8959 operator, or the name is followed by ::. For a plain name, returns a
8960 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
8961 (let ((pos (or at-pos js2-token-beg))
8962 colon-pos
8963 (name (js2-create-name-node t js2-current-token))
8964 ns tt ref pn)
8965 (catch 'return
8966 (when (js2-match-token js2-COLONCOLON)
8967 (setq ns name
8968 colon-pos js2-token-beg
8969 tt (js2-next-token))
8970 (cond
8971 ;; handles name::name
8972 ((js2-valid-prop-name-token tt)
8973 (setq name (js2-create-name-node)))
8974 ;; handles name::*
8975 ((= tt js2-MUL)
8976 (js2-save-name-token-data js2-token-beg "*")
8977 (setq name (js2-create-name-node)))
8978 ;; handles name::[expr]
8979 ((= tt js2-LB)
8980 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
8981 (t
8982 (js2-report-error "msg.no.name.after.coloncolon"))))
8983 (if (and (null ns) (zerop member-type-flags))
8984 name
8985 (prog1
8986 (setq pn
8987 (make-js2-xml-prop-ref-node :pos pos
8988 :len (- (js2-node-end name) pos)
8989 :at-pos at-pos
8990 :colon-pos colon-pos
8991 :propname name))
8992 (js2-node-add-children pn name))))))
8993
8994 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
8995 "Parse the [expr] portion of an xml element reference.
8996 For instance, @[expr], @*::[expr], or ns::[expr]."
8997 (let* ((lb js2-token-beg)
8998 (pos (or at-pos lb))
8999 rb
9000 (expr (js2-parse-expr))
9001 (end (js2-node-end expr))
9002 pn)
9003 (if (js2-must-match js2-RB "msg.no.bracket.index")
9004 (setq rb js2-token-beg
9005 end js2-token-end))
9006 (prog1
9007 (setq pn
9008 (make-js2-xml-elem-ref-node :pos pos
9009 :len (- end pos)
9010 :namespace namespace
9011 :colon-pos colon-pos
9012 :at-pos at-pos
9013 :expr expr
9014 :lb (js2-relpos lb pos)
9015 :rb (js2-relpos rb pos)))
9016 (js2-node-add-children pn namespace expr))))
9017
9018 (defun js2-parse-primary-expr-lhs ()
9019 (let ((js2-is-in-lhs t))
9020 (js2-parse-primary-expr)))
9021
9022 (defun js2-parse-primary-expr ()
9023 "Parse a literal (leaf) expression of some sort.
9024 Includes complex literals such as functions, object-literals,
9025 array-literals, array comprehensions and regular expressions."
9026 (let ((tt-flagged (js2-next-flagged-token))
9027 pn ; parent node (usually return value)
9028 tt
9029 px-pos ; paren-expr pos
9030 len
9031 flags ; regexp flags
9032 expr)
9033 (setq tt js2-current-token)
9034 (cond
9035 ((= tt js2-FUNCTION)
9036 (js2-parse-function 'FUNCTION_EXPRESSION))
9037 ((= tt js2-LB)
9038 (js2-parse-array-literal))
9039 ((= tt js2-LC)
9040 (js2-parse-object-literal))
9041 ((= tt js2-LET)
9042 (js2-parse-let js2-token-beg))
9043 ((= tt js2-LP)
9044 (setq px-pos js2-token-beg
9045 expr (js2-parse-expr))
9046 (js2-must-match js2-RP "msg.no.paren")
9047 (setq pn (make-js2-paren-node :pos px-pos
9048 :expr expr
9049 :len (- js2-token-end px-pos)))
9050 (js2-node-add-children pn (js2-paren-node-expr pn))
9051 pn)
9052 ((= tt js2-XMLATTR)
9053 (js2-must-have-xml)
9054 (js2-parse-attribute-access))
9055 ((= tt js2-NAME)
9056 (js2-parse-name tt-flagged tt))
9057 ((= tt js2-NUMBER)
9058 (make-js2-number-node))
9059 ((= tt js2-STRING)
9060 (prog1
9061 (make-js2-string-node)
9062 (js2-record-face 'font-lock-string-face)))
9063 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9064 ;; Got / or /= which in this context means a regexp literal
9065 (setq px-pos js2-token-beg)
9066 (js2-read-regexp tt)
9067 (setq flags js2-ts-regexp-flags
9068 js2-ts-regexp-flags nil)
9069 (prog1
9070 (make-js2-regexp-node :pos px-pos
9071 :len (- js2-ts-cursor px-pos)
9072 :value js2-ts-string
9073 :flags flags)
9074 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9075 (js2-record-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9076 ((or (= tt js2-NULL)
9077 (= tt js2-THIS)
9078 (= tt js2-FALSE)
9079 (= tt js2-TRUE))
9080 (make-js2-keyword-node :type tt))
9081 ((= tt js2-RESERVED)
9082 (js2-report-error "msg.reserved.id")
9083 (make-js2-name-node))
9084 ((= tt js2-ERROR)
9085 ;; the scanner or one of its subroutines reported the error.
9086 (make-js2-error-node))
9087 ((= tt js2-EOF)
9088 (setq px-pos (point-at-bol)
9089 len (- js2-ts-cursor px-pos))
9090 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9091 (make-js2-error-node :pos px-pos :len len))
9092 (t
9093 (js2-report-error "msg.syntax")
9094 (make-js2-error-node)))))
9095
9096 (defun js2-parse-name (tt-flagged tt)
9097 (let ((name js2-ts-string)
9098 (name-pos js2-token-beg)
9099 node)
9100 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9101 (= (js2-peek-token) js2-COLON))
9102 (prog1
9103 ;; Do not consume colon, it is used as unwind indicator
9104 ;; to return to statementHelper.
9105 (make-js2-label-node :pos name-pos
9106 :len (- js2-token-end name-pos)
9107 :name name)
9108 (js2-set-face name-pos
9109 js2-token-end
9110 'font-lock-variable-name-face 'record))
9111 ;; Otherwise not a label, just a name. Unfortunately peeking
9112 ;; the next token to check for a colon has biffed js2-token-beg
9113 ;; and js2-token-end. We store the name's bounds in buffer vars
9114 ;; and `js2-create-name-node' uses them.
9115 (js2-save-name-token-data name-pos name)
9116 (setq node (if js2-compiler-xml-available
9117 (js2-parse-property-name nil name 0)
9118 (js2-create-name-node 'check-activation)))
9119 (if js2-highlight-external-variables
9120 (js2-record-name-node node))
9121 node)))
9122
9123 (defun js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9124 (js2-add-strict-warning
9125 msg nil
9126 ;; back up from comma to beginning of line or array/objlit
9127 (max (if elems
9128 (js2-node-pos (car elems))
9129 pos)
9130 (save-excursion
9131 (goto-char comma-pos)
9132 (back-to-indentation)
9133 (point)))
9134 comma-pos))
9135
9136 (defun js2-parse-array-literal ()
9137 (let ((pos js2-token-beg)
9138 (end js2-token-end)
9139 (after-lb-or-comma t)
9140 after-comma tt elems pn
9141 (continue t))
9142 (unless js2-is-in-lhs
9143 (js2-push-scope (make-js2-scope))) ; for array comp
9144 (while continue
9145 (setq tt (js2-peek-token))
9146 (cond
9147 ;; comma
9148 ((= tt js2-COMMA)
9149 (js2-consume-token)
9150 (setq after-comma js2-token-end)
9151 (if (not after-lb-or-comma)
9152 (setq after-lb-or-comma t)
9153 (push nil elems)))
9154 ;; end of array
9155 ((or (= tt js2-RB)
9156 (= tt js2-EOF)) ; prevent infinite loop
9157 (if (= tt js2-EOF)
9158 (js2-report-error "msg.no.bracket.arg" nil pos)
9159 (js2-consume-token))
9160 (setq continue nil
9161 end js2-token-end
9162 pn (make-js2-array-node :pos pos
9163 :len (- js2-ts-cursor pos)
9164 :elems (nreverse elems)))
9165 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9166 (when (and after-comma (not js2-is-in-lhs))
9167 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9168 pos elems after-comma)))
9169 ;; destructuring binding
9170 (js2-is-in-lhs
9171 (push (if (or (= tt js2-LC)
9172 (= tt js2-LB)
9173 (= tt js2-NAME))
9174 ;; [a, b, c] | {a, b, c} | {a:x, b:y, c:z} | a
9175 (js2-parse-primary-expr-lhs)
9176 ;; invalid pattern
9177 (js2-consume-token)
9178 (js2-report-error "msg.bad.var")
9179 (make-js2-error-node))
9180 elems)
9181 (setq after-lb-or-comma nil
9182 after-comma nil))
9183 ;; array comp
9184 ((and (>= js2-language-version 170)
9185 (= tt js2-FOR) ; check for array comprehension
9186 (not after-lb-or-comma) ; "for" can't follow a comma
9187 elems ; must have at least 1 element
9188 (not (cdr elems))) ; but no 2nd element
9189 (setf continue nil
9190 pn (js2-parse-array-comprehension (car elems) pos)))
9191
9192 ;; another element
9193 (t
9194 (unless after-lb-or-comma
9195 (js2-report-error "msg.no.bracket.arg"))
9196 (push (js2-parse-assign-expr) elems)
9197 (setq after-lb-or-comma nil
9198 after-comma nil))))
9199 (unless js2-is-in-lhs
9200 (js2-pop-scope))
9201 pn))
9202
9203 (defun js2-parse-array-comprehension (expr pos)
9204 "Parse a JavaScript 1.7 Array Comprehension.
9205 EXPR is the first expression after the opening left-bracket.
9206 POS is the beginning of the LB token preceding EXPR.
9207 We should have just parsed the 'for' keyword before calling this function."
9208 (let (loops loop first prev filter if-pos result)
9209 (while (= (js2-peek-token) js2-FOR)
9210 (let ((prev (car loops))) ; rearrange scope chain
9211 (push (setq loop (js2-parse-array-comp-loop)) loops)
9212 (if prev ; each loop is parent scope to the next one
9213 (setf (js2-scope-parent-scope loop) prev)
9214 ; first loop takes expr scope's parent
9215 (setf (js2-scope-parent-scope (setq first loop))
9216 (js2-scope-parent-scope js2-current-scope)))))
9217 ;; set expr scope's parent to the last loop
9218 (setf (js2-scope-parent-scope js2-current-scope) (car loops))
9219 (when (= (js2-peek-token) js2-IF)
9220 (js2-consume-token)
9221 (setq if-pos (- js2-token-beg pos) ; relative
9222 filter (js2-parse-condition)))
9223 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9224 (setq result (make-js2-array-comp-node :pos pos
9225 :len (- js2-ts-cursor pos)
9226 :result expr
9227 :loops (nreverse loops)
9228 :filter (car filter)
9229 :lp (js2-relpos (second filter) pos)
9230 :rp (js2-relpos (third filter) pos)
9231 :if-pos if-pos))
9232 (apply #'js2-node-add-children result expr (car filter)
9233 (js2-array-comp-node-loops result))
9234 (setq js2-current-scope first) ; pop to the first loop
9235 result))
9236
9237 (defun js2-parse-array-comp-loop ()
9238 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9239 Last token peeked should be the initial FOR."
9240 (let ((pos js2-token-beg)
9241 (pn (make-js2-array-comp-loop-node))
9242 tt iter obj foreach-p in-pos each-pos lp rp)
9243 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9244 (js2-push-scope pn)
9245 (unwind-protect
9246 (progn
9247 (when (js2-match-token js2-NAME)
9248 (if (string= js2-ts-string "each")
9249 (progn
9250 (setq foreach-p t
9251 each-pos (- js2-token-beg pos)) ; relative
9252 (js2-record-face 'font-lock-keyword-face))
9253 (js2-report-error "msg.no.paren.for")))
9254 (if (js2-must-match js2-LP "msg.no.paren.for")
9255 (setq lp (- js2-token-beg pos)))
9256 (setq tt (js2-peek-token))
9257 (cond
9258 ((or (= tt js2-LB)
9259 (= tt js2-LC))
9260 ;; handle destructuring assignment
9261 (setq iter (js2-parse-primary-expr-lhs))
9262 (js2-define-destruct-symbols iter js2-LET
9263 'font-lock-variable-name-face t))
9264 ((js2-valid-prop-name-token tt)
9265 (js2-consume-token)
9266 (setq iter (js2-create-name-node)))
9267 (t
9268 (js2-report-error "msg.bad.var")))
9269 ;; Define as a let since we want the scope of the variable to
9270 ;; be restricted to the array comprehension
9271 (if (js2-name-node-p iter)
9272 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9273 (if (js2-must-match js2-IN "msg.in.after.for.name")
9274 (setq in-pos (- js2-token-beg pos)))
9275 (setq obj (js2-parse-expr))
9276 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9277 (setq rp (- js2-token-beg pos)))
9278 (setf (js2-node-pos pn) pos
9279 (js2-node-len pn) (- js2-ts-cursor pos)
9280 (js2-array-comp-loop-node-iterator pn) iter
9281 (js2-array-comp-loop-node-object pn) obj
9282 (js2-array-comp-loop-node-in-pos pn) in-pos
9283 (js2-array-comp-loop-node-each-pos pn) each-pos
9284 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9285 (js2-array-comp-loop-node-lp pn) lp
9286 (js2-array-comp-loop-node-rp pn) rp)
9287 (js2-node-add-children pn iter obj))
9288 (js2-pop-scope))
9289 pn))
9290
9291 (defun js2-parse-object-literal ()
9292 (let ((pos js2-token-beg)
9293 tt elems result after-comma
9294 (continue t))
9295 (while continue
9296 (setq tt (js2-peek-token))
9297 (cond
9298 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...},
9299 ;; {get foo() {...}}, or {set foo(x) {...}}
9300 ((or (js2-valid-prop-name-token tt)
9301 (= tt js2-STRING))
9302 (setq after-comma nil
9303 result (js2-parse-named-prop tt))
9304 (if (and (null result)
9305 (not js2-recover-from-parse-errors))
9306 (setq continue nil)
9307 (push result elems)))
9308 ;; {12: x} or {10.7: x}
9309 ((= tt js2-NUMBER)
9310 (js2-consume-token)
9311 (setq after-comma nil)
9312 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9313 ;; trailing comma
9314 ((= tt js2-RC)
9315 (setq continue nil)
9316 (if after-comma
9317 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9318 pos elems after-comma)))
9319 (t
9320 (js2-report-error "msg.bad.prop")
9321 (unless js2-recover-from-parse-errors
9322 (setq continue nil)))) ; end switch
9323 (if (js2-match-token js2-COMMA)
9324 (setq after-comma js2-token-end)
9325 (setq continue nil))) ; end loop
9326 (js2-must-match js2-RC "msg.no.brace.prop")
9327 (setq result (make-js2-object-node :pos pos
9328 :len (- js2-ts-cursor pos)
9329 :elems (nreverse elems)))
9330 (apply #'js2-node-add-children result (js2-object-node-elems result))
9331 result))
9332
9333 (defun js2-parse-named-prop (tt)
9334 "Parse a name, string, or getter/setter object property.
9335 When `js2-is-in-lhs' is t, forms like {a, b, c} will be permitted."
9336 (js2-consume-token)
9337 (let ((string-prop (and (= tt js2-STRING)
9338 (make-js2-string-node)))
9339 expr
9340 (ppos js2-token-beg)
9341 (pend js2-token-end)
9342 (name (js2-create-name-node))
9343 (prop js2-ts-string))
9344 (cond
9345 ;; getter/setter prop
9346 ((and (= tt js2-NAME)
9347 (= (js2-peek-token) js2-NAME)
9348 (or (string= prop "get")
9349 (string= prop "set")))
9350 (js2-consume-token)
9351 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9352 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9353 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9354 (js2-parse-getter-setter-prop ppos name (string= prop "get")))
9355 ;; abbreviated destructuring bind e.g., {a, b} = c;
9356 ;; XXX: To be honest, the value of `js2-is-in-lhs' becomes t only when
9357 ;; patterns are appeared in variable declaration, function parameters, and catch-clause.
9358 ;; We have to set t to `js2-is-in-lhs' when the current expressions are part of any
9359 ;; assignment but it's difficult because it requires looking ahead of expression.
9360 ((and js2-is-in-lhs
9361 (= tt js2-NAME)
9362 (let ((ctk (js2-peek-token)))
9363 (or (= ctk js2-COMMA)
9364 (= ctk js2-RC)
9365 (js2-valid-prop-name-token ctk))))
9366 name)
9367 ;; regular prop
9368 (t
9369 (prog1
9370 (setq expr (js2-parse-plain-property (or string-prop name)))
9371 (js2-set-face ppos pend
9372 (if (js2-function-node-p
9373 (js2-object-prop-node-right expr))
9374 'font-lock-function-name-face
9375 'font-lock-variable-name-face)
9376 'record))))))
9377
9378 (defun js2-parse-plain-property (prop)
9379 "Parse a non-getter/setter property in an object literal.
9380 PROP is the node representing the property: a number, name or string."
9381 (js2-must-match js2-COLON "msg.no.colon.prop")
9382 (let* ((pos (js2-node-pos prop))
9383 (colon (- js2-token-beg pos))
9384 (expr (js2-parse-assign-expr))
9385 (result (make-js2-object-prop-node
9386 :pos pos
9387 ;; don't include last consumed token in length
9388 :len (- (+ (js2-node-pos expr)
9389 (js2-node-len expr))
9390 pos)
9391 :left prop
9392 :right expr
9393 :op-pos colon)))
9394 (js2-node-add-children result prop expr)
9395 result))
9396
9397 (defun js2-parse-getter-setter-prop (pos prop get-p)
9398 "Parse getter or setter property in an object literal.
9399 JavaScript syntax is:
9400
9401 { get foo() {...}, set foo(x) {...} }
9402
9403 and expression closure style is also supported
9404
9405 { get foo() x, set foo(x) _x = x }
9406
9407 POS is the start position of the `get' or `set' keyword.
9408 PROP is the `js2-name-node' representing the property name.
9409 GET-P is non-nil if the keyword was `get'."
9410 (let ((type (if get-p js2-GET js2-SET))
9411 result end
9412 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9413 ;; it has to be an anonymous function, as we already parsed the name
9414 (if (/= (js2-node-type fn) js2-FUNCTION)
9415 (js2-report-error "msg.bad.prop")
9416 (if (plusp (length (js2-function-name fn)))
9417 (js2-report-error "msg.bad.prop")))
9418 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9419 (setq end (js2-node-end fn)
9420 result (make-js2-getter-setter-node :type type
9421 :pos pos
9422 :len (- end pos)
9423 :left prop
9424 :right fn))
9425 (js2-node-add-children result prop fn)
9426 result))
9427
9428 (defun js2-create-name-node (&optional check-activation-p token)
9429 "Create a name node using the token info from last scanned name.
9430 In some cases we need to either synthesize a name node, or we lost
9431 the name token information by peeking. If the TOKEN parameter is
9432 not `js2-NAME', then we use the token info saved in instance vars."
9433 (let ((beg js2-token-beg)
9434 (s js2-ts-string)
9435 name)
9436 (when (/= js2-current-token js2-NAME)
9437 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9438 s js2-prev-name-token-string
9439 js2-prev-name-token-start nil
9440 js2-prev-name-token-string nil))
9441 (setq name (make-js2-name-node :pos beg
9442 :name s
9443 :len (length s)))
9444 (if check-activation-p
9445 (js2-check-activation-name s (or token js2-NAME)))
9446 name))
9447
9448 ;;; Indentation support
9449
9450 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9451 ;; Karl cleverly deduces that the desired indentation level is often a
9452 ;; function of paren/bracket/brace nesting depth, which can be determined
9453 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9454 ;; then does some equally clever checks to see if we're in the context of a
9455 ;; substatement of a possibly braceless statement keyword such as if, while,
9456 ;; or finally. This approach yields pretty good results.
9457
9458 ;; The indenter is often "wrong", however, and needs to be overridden.
9459 ;; The right long-term solution is probably to emulate (or integrate
9460 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9461 ;; parse tree from `js2-parse' is present, which is not true at the
9462 ;; moment the user is typing, computing indentation is still thousands
9463 ;; of lines of code to handle every possible syntactic edge case.
9464
9465 ;; In the meantime, the compromise solution is that we offer a "bounce
9466 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9467 ;; current line indent among various likely guess points. This approach
9468 ;; is far from perfect, but should at least make it slightly easier to
9469 ;; move the line towards its desired indentation when manually
9470 ;; overriding Karl's heuristic nesting guesser.
9471
9472 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9473 ;; extensions such as `let' and Array comprehensions. Major kudos to
9474 ;; Karl for coming up with the initial approach, which packs a lot of
9475 ;; punch for so little code.
9476
9477 (defconst js2-possibly-braceless-keywords-re
9478 (concat "else[ \t]+if\\|for[ \t]+each\\|"
9479 (regexp-opt '("catch" "do" "else" "finally" "for" "if"
9480 "try" "while" "with" "let")))
9481 "Regular expression matching keywords that are optionally
9482 followed by an opening brace.")
9483
9484 (defconst js2-indent-operator-re
9485 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9486 (regexp-opt '("in" "instanceof") 'words))
9487 "Regular expression matching operators that affect indentation
9488 of continued expressions.")
9489
9490 (defconst js2-declaration-keyword-re
9491 (regexp-opt '("var" "let" "const") 'words)
9492 "Regular expression matching variable declaration keywords.")
9493
9494 ;; This function has horrible results if you're typing an array
9495 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9496 ;; in conjunction with electric-indent, so just disabling it.
9497 (defsubst js2-code-at-bol-p ()
9498 "Return t if the first character on line is non-whitespace."
9499 nil)
9500
9501 (defun js2-insert-and-indent (key)
9502 "Run command bound to KEY and indent current line.
9503 Runs the command bound to KEY in the global keymap and indents
9504 the current line."
9505 (interactive (list (this-command-keys)))
9506 (let ((cmd (lookup-key (current-global-map) key)))
9507 (if (commandp cmd)
9508 (call-interactively cmd)))
9509 ;; don't do the electric keys inside comments or strings,
9510 ;; and don't do bounce-indent with them.
9511 (let ((parse-state (syntax-ppss (point)))
9512 (js2-bounce-indent-p (js2-code-at-bol-p)))
9513 (unless (or (nth 3 parse-state)
9514 (nth 4 parse-state))
9515 (indent-according-to-mode))))
9516
9517 (defun js2-re-search-forward-inner (regexp &optional bound count)
9518 "Auxiliary function for `js2-re-search-forward'."
9519 (let (parse saved-point)
9520 (while (> count 0)
9521 (re-search-forward regexp bound)
9522 (setq parse (if saved-point
9523 (parse-partial-sexp saved-point (point))
9524 (syntax-ppss (point))))
9525 (cond ((nth 3 parse)
9526 (re-search-forward
9527 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9528 (save-excursion (end-of-line) (point)) t))
9529 ((nth 7 parse)
9530 (forward-line))
9531 ((or (nth 4 parse)
9532 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9533 (re-search-forward "\\*/"))
9534 (t
9535 (setq count (1- count))))
9536 (setq saved-point (point))))
9537 (point))
9538
9539 (defun js2-re-search-forward (regexp &optional bound noerror count)
9540 "Search forward but ignore strings and comments.
9541 Invokes `re-search-forward' but treats the buffer as if strings
9542 and comments have been removed."
9543 (let ((saved-point (point))
9544 (search-expr
9545 (cond ((null count)
9546 '(js2-re-search-forward-inner regexp bound 1))
9547 ((< count 0)
9548 '(js2-re-search-backward-inner regexp bound (- count)))
9549 ((> count 0)
9550 '(js2-re-search-forward-inner regexp bound count)))))
9551 (condition-case err
9552 (eval search-expr)
9553 (search-failed
9554 (goto-char saved-point)
9555 (unless noerror
9556 (error (error-message-string err)))))))
9557
9558 (defun js2-re-search-backward-inner (regexp &optional bound count)
9559 "Auxiliary function for `js2-re-search-backward'."
9560 (let (parse)
9561 (while (> count 0)
9562 (re-search-backward regexp bound)
9563 (setq parse (syntax-ppss (point)))
9564 (cond ((nth 3 parse)
9565 (re-search-backward
9566 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9567 (line-beginning-position) t))
9568 ((nth 7 parse)
9569 (goto-char (nth 8 parse)))
9570 ((or (nth 4 parse)
9571 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9572 (re-search-backward "/\\*"))
9573 (t
9574 (setq count (1- count))))))
9575 (point))
9576
9577 (defun js2-re-search-backward (regexp &optional bound noerror count)
9578 "Search backward but ignore strings and comments.
9579 Invokes `re-search-backward' but treats the buffer as if strings
9580 and comments have been removed."
9581 (let ((saved-point (point))
9582 (search-expr
9583 (cond ((null count)
9584 '(js2-re-search-backward-inner regexp bound 1))
9585 ((< count 0)
9586 '(js2-re-search-forward-inner regexp bound (- count)))
9587 ((> count 0)
9588 '(js2-re-search-backward-inner regexp bound count)))))
9589 (condition-case err
9590 (eval search-expr)
9591 (search-failed
9592 (goto-char saved-point)
9593 (unless noerror
9594 (error (error-message-string err)))))))
9595
9596 (defun js2-looking-at-operator-p ()
9597 "Return non-nil if text after point is a non-comma operator."
9598 (and (looking-at js2-indent-operator-re)
9599 (or (not (looking-at ":"))
9600 (save-excursion
9601 (and (js2-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9602 (looking-at "?"))))))
9603
9604 (defun js2-continued-expression-p ()
9605 "Return non-nil if the current line continues an expression."
9606 (save-excursion
9607 (back-to-indentation)
9608 (or (js2-looking-at-operator-p)
9609 (when (js2-re-search-backward "\n" nil t) ;; skip comments
9610 (skip-chars-backward " \t")
9611 (unless (bolp) ;; previous line is empty
9612 (backward-char)
9613 (when (js2-looking-at-operator-p)
9614 (backward-char)
9615 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))
9616
9617 (defun js2-end-of-do-while-loop-p ()
9618 "Return non-nil if word after point is `while' of a do-while
9619 statement, else returns nil. A braceless do-while statement
9620 spanning several lines requires that the start of the loop is
9621 indented to the same column as the current line."
9622 (interactive)
9623 (save-excursion
9624 (when (looking-at "\\s-*\\<while\\>")
9625 (if (save-excursion
9626 (skip-chars-backward "[ \t\n]*}")
9627 (looking-at "[ \t\n]*}"))
9628 (save-excursion
9629 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9630 (js2-re-search-backward "\\<do\\>" (point-at-bol) t)
9631 (or (looking-at "\\<do\\>")
9632 (let ((saved-indent (current-indentation)))
9633 (while (and (js2-re-search-backward "^[ \t]*\\<" nil t)
9634 (/= (current-indentation) saved-indent)))
9635 (and (looking-at "[ \t]*\\<do\\>")
9636 (not (js2-re-search-forward
9637 "\\<while\\>" (point-at-eol) t))
9638 (= (current-indentation) saved-indent))))))))
9639
9640 (defun js2-multiline-decl-indentation ()
9641 "Returns the declaration indentation column if the current line belongs
9642 to a multiline declaration statement. All declarations are lined up vertically:
9643
9644 var a = 10,
9645 b = 20,
9646 c = 30;
9647
9648 Note that if `js2-always-indent-assigned-expr-in-decls-p' is nil, and the first
9649 assigned expression is a function or array/object literal, it will be indented
9650 differently:
9651
9652 var o = { var bar = 2,
9653 foo: 3 o = {
9654 }, foo: 3
9655 bar = 2; };
9656 "
9657 (let (forward-sexp-function ; use Lisp version
9658 at-opening-bracket)
9659 (save-excursion
9660 (back-to-indentation)
9661 (when (not (looking-at js2-declaration-keyword-re))
9662 (when (looking-at js2-indent-operator-re)
9663 (goto-char (match-end 0))) ; continued expressions are ok
9664 (while (and (not at-opening-bracket)
9665 (not (bobp))
9666 (let ((pos (point)))
9667 (save-excursion
9668 (js2-backward-sws)
9669 (or (eq (char-before) ?,)
9670 (and (not (eq (char-before) ?\;))
9671 (and
9672 (prog2 (skip-chars-backward "[[:punct:]]")
9673 (looking-at js2-indent-operator-re)
9674 (js2-backward-sws))
9675 (not (eq (char-before) ?\;))))
9676 (js2-same-line pos)))))
9677 (condition-case err
9678 (backward-sexp)
9679 (scan-error (setq at-opening-bracket t))))
9680 (when (looking-at js2-declaration-keyword-re)
9681 (- (1+ (match-end 0)) (point-at-bol)))))))
9682
9683 (defun js2-ctrl-statement-indentation ()
9684 "Return the proper indentation of current line if it is a control statement.
9685 Returns an indentation if this line starts the body of a control
9686 statement without braces, else returns nil."
9687 (let (forward-sexp-function)
9688 (save-excursion
9689 (back-to-indentation)
9690 (when (and (not (js2-same-line (point-min)))
9691 (not (looking-at "{"))
9692 (js2-re-search-backward "[[:graph:]]" nil t)
9693 (not (looking-at "[{([]"))
9694 (progn
9695 (forward-char)
9696 (when (= (char-before) ?\))
9697 ;; scan-sexps sometimes throws an error
9698 (ignore-errors (backward-sexp))
9699 (skip-chars-backward " \t" (point-at-bol)))
9700 (let ((pt (point)))
9701 (back-to-indentation)
9702 (and (looking-at js2-possibly-braceless-keywords-re)
9703 (= (match-end 0) pt)
9704 (not (js2-end-of-do-while-loop-p))))))
9705 (+ (current-indentation) js2-basic-offset)))))
9706
9707 (defun js2-indent-in-array-comp (parse-status)
9708 "Return non-nil if we think we're in an array comprehension.
9709 In particular, return the buffer position of the first `for' kwd."
9710 (let ((bracket (nth 1 parse-status))
9711 (end (point)))
9712 (when bracket
9713 (save-excursion
9714 (goto-char bracket)
9715 (when (looking-at "\\[")
9716 (forward-char 1)
9717 (js2-forward-sws)
9718 (if (looking-at "[[{]")
9719 (let (forward-sexp-function) ; use Lisp version
9720 (forward-sexp) ; skip destructuring form
9721 (js2-forward-sws)
9722 (if (and (/= (char-after) ?,) ; regular array
9723 (looking-at "for"))
9724 (match-beginning 0)))
9725 ;; to skip arbitrary expressions we need the parser,
9726 ;; so we'll just guess at it.
9727 (if (and (> end (point)) ; not empty literal
9728 (re-search-forward "[^,]]* \\(for\\) " end t)
9729 ;; not inside a string literal
9730 (not (nth 3 (parse-partial-sexp bracket (point)))))
9731 (match-beginning 1))))))))
9732
9733 (defun js2-array-comp-indentation (parse-status for-kwd)
9734 (if (js2-same-line for-kwd)
9735 ;; first continuation line
9736 (save-excursion
9737 (goto-char (nth 1 parse-status))
9738 (forward-char 1)
9739 (skip-chars-forward " \t")
9740 (current-column))
9741 (save-excursion
9742 (goto-char for-kwd)
9743 (current-column))))
9744
9745 (defun js2-proper-indentation (parse-status)
9746 "Return the proper indentation for the current line."
9747 (save-excursion
9748 (back-to-indentation)
9749 (let ((ctrl-stmt-indent (js2-ctrl-statement-indentation))
9750 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9751 (continued-expr-p (js2-continued-expression-p))
9752 (declaration-indent (and js2-pretty-multiline-decl-indentation-p
9753 (js2-multiline-decl-indentation)))
9754 (bracket (nth 1 parse-status))
9755 beg)
9756 (cond
9757 ;; indent array comprehension continuation lines specially
9758 ((and bracket
9759 (not (js2-same-line bracket))
9760 (setq beg (js2-indent-in-array-comp parse-status))
9761 (>= (point) (save-excursion
9762 (goto-char beg)
9763 (point-at-bol)))) ; at or after first loop?
9764 (js2-array-comp-indentation parse-status beg))
9765
9766 (ctrl-stmt-indent)
9767
9768 ((and declaration-indent continued-expr-p)
9769 (+ declaration-indent js2-basic-offset))
9770
9771 (declaration-indent)
9772
9773 (bracket
9774 (goto-char bracket)
9775 (cond
9776 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9777 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9778 (when (save-excursion (skip-chars-backward " \t)")
9779 (looking-at ")"))
9780 (backward-list))
9781 (if (and (nth 1 p)
9782 (not js2-consistent-level-indent-inner-bracket-p))
9783 (progn (goto-char (1+ (nth 1 p)))
9784 (skip-chars-forward " \t"))
9785 (back-to-indentation)
9786 (when (and js2-pretty-multiline-decl-indentation-p
9787 js2-always-indent-assigned-expr-in-decls-p
9788 (looking-at js2-declaration-keyword-re))
9789 (goto-char (1+ (match-end 0)))))
9790 (cond (same-indent-p
9791 (current-column))
9792 (continued-expr-p
9793 (+ (current-column) (* 2 js2-basic-offset)))
9794 (t
9795 (+ (current-column) js2-basic-offset)))))
9796 (t
9797 (unless same-indent-p
9798 (forward-char)
9799 (skip-chars-forward " \t"))
9800 (current-column))))
9801
9802 (continued-expr-p js2-basic-offset)
9803
9804 (t 0)))))
9805
9806 (defun js2-lineup-comment (parse-status)
9807 "Indent a multi-line block comment continuation line."
9808 (let* ((beg (nth 8 parse-status))
9809 (first-line (js2-same-line beg))
9810 (offset (save-excursion
9811 (goto-char beg)
9812 (if (looking-at "/\\*")
9813 (+ 1 (current-column))
9814 0))))
9815 (unless first-line
9816 (indent-line-to offset))))
9817
9818 (defun js2-backward-sws ()
9819 "Move backward through whitespace and comments."
9820 (interactive)
9821 (while (forward-comment -1)))
9822
9823 (defun js2-forward-sws ()
9824 "Move forward through whitespace and comments."
9825 (interactive)
9826 (while (forward-comment 1)))
9827
9828 (defun js2-current-indent (&optional pos)
9829 "Return column of indentation on current line.
9830 If POS is non-nil, go to that point and return indentation for that line."
9831 (save-excursion
9832 (if pos
9833 (goto-char pos))
9834 (back-to-indentation)
9835 (current-column)))
9836
9837 (defun js2-arglist-close ()
9838 "Return non-nil if we're on a line beginning with a close-paren/brace."
9839 (save-excursion
9840 (goto-char (point-at-bol))
9841 (js2-forward-sws)
9842 (looking-at "[])}]")))
9843
9844 (defun js2-indent-looks-like-label-p ()
9845 (goto-char (point-at-bol))
9846 (js2-forward-sws)
9847 (looking-at (concat js2-mode-identifier-re ":")))
9848
9849 (defun js2-indent-in-objlit-p (parse-status)
9850 "Return non-nil if this looks like an object-literal entry."
9851 (let ((start (nth 1 parse-status)))
9852 (and
9853 start
9854 (save-excursion
9855 (and (zerop (forward-line -1))
9856 (not (< (point) start)) ; crossed a {} boundary
9857 (js2-indent-looks-like-label-p)))
9858 (save-excursion
9859 (js2-indent-looks-like-label-p)))))
9860
9861 ;; If prev line looks like foobar({ then we're passing an object
9862 ;; literal to a function call, and people pretty much always want to
9863 ;; de-dent back to the previous line, so move the 'basic-offset'
9864 ;; position to the front.
9865 (defun js2-indent-objlit-arg-p (parse-status)
9866 (save-excursion
9867 (back-to-indentation)
9868 (js2-backward-sws)
9869 (and (eq (1- (point)) (nth 1 parse-status))
9870 (eq (char-before) ?{)
9871 (progn
9872 (forward-char -1)
9873 (skip-chars-backward " \t")
9874 (eq (char-before) ?\()))))
9875
9876 (defun js2-indent-case-block-p ()
9877 (save-excursion
9878 (back-to-indentation)
9879 (js2-backward-sws)
9880 (goto-char (point-at-bol))
9881 (skip-chars-forward " \t")
9882 (looking-at "case\\s-.+:")))
9883
9884 (defun js2-syntax-bol ()
9885 "Return the point at the first non-whitespace char on the line.
9886 Returns `point-at-bol' if the line is empty."
9887 (save-excursion
9888 (beginning-of-line)
9889 (skip-chars-forward " \t")
9890 (point)))
9891
9892 (defun js2-bounce-indent (normal-col parse-status &optional backwards)
9893 "Cycle among alternate computed indentation positions.
9894 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9895 of the buffer to the current point. NORMAL-COL is the indentation
9896 column computed by the heuristic guesser based on current paren,
9897 bracket, brace and statement nesting. If BACKWARDS, cycle positions
9898 in reverse."
9899 (let ((cur-indent (js2-current-indent))
9900 (old-buffer-undo-list buffer-undo-list)
9901 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9902 (current-line (save-excursion
9903 (forward-line 0) ; move to bol
9904 (1+ (count-lines (point-min) (point)))))
9905 positions pos main-pos anchor arglist-cont same-indent
9906 prev-line-col basic-offset computed-pos)
9907 ;; temporarily don't record undo info, if user requested this
9908 (when js2-mode-indent-inhibit-undo
9909 (setq buffer-undo-list t))
9910 (unwind-protect
9911 (progn
9912 ;; First likely point: indent from beginning of previous code line
9913 (push (setq basic-offset
9914 (+ (save-excursion
9915 (back-to-indentation)
9916 (js2-backward-sws)
9917 (back-to-indentation)
9918 (setq prev-line-col (current-column)))
9919 js2-basic-offset))
9920 positions)
9921
9922 ;; (First + epsilon) likely point: indent 2x from beginning of
9923 ;; previous code line. Google does it this way.
9924 (push (setq basic-offset
9925 (+ (save-excursion
9926 (back-to-indentation)
9927 (js2-backward-sws)
9928 (back-to-indentation)
9929 (setq prev-line-col (current-column)))
9930 (* 2 js2-basic-offset)))
9931 positions)
9932
9933 ;; Second likely point: indent from assign-expr RHS. This
9934 ;; is just a crude guess based on finding " = " on the previous
9935 ;; line containing actual code.
9936 (setq pos (save-excursion
9937 (forward-line -1)
9938 (goto-char (point-at-bol))
9939 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
9940 (point-at-eol) t)
9941 (goto-char (match-end 1))
9942 (skip-chars-forward " \t\r\n")
9943 (current-column))))
9944 (when pos
9945 (incf pos js2-basic-offset)
9946 (push pos positions))
9947
9948 ;; Third likely point: same indent as previous line of code.
9949 ;; Make it the first likely point if we're not on an
9950 ;; arglist-close line and previous line ends in a comma, or
9951 ;; both this line and prev line look like object-literal
9952 ;; elements.
9953 (setq pos (save-excursion
9954 (goto-char (point-at-bol))
9955 (js2-backward-sws)
9956 (back-to-indentation)
9957 (prog1
9958 (current-column)
9959 ;; while we're here, look for trailing comma
9960 (if (save-excursion
9961 (goto-char (point-at-eol))
9962 (js2-backward-sws)
9963 (eq (char-before) ?,))
9964 (setq arglist-cont (1- (point)))))))
9965 (when pos
9966 (if (and (or arglist-cont
9967 (js2-indent-in-objlit-p parse-status))
9968 (not (js2-arglist-close)))
9969 (setq same-indent pos))
9970 (push pos positions))
9971
9972 ;; Fourth likely point: first preceding code with less indentation.
9973 ;; than the immediately preceding code line.
9974 (setq pos (save-excursion
9975 (back-to-indentation)
9976 (js2-backward-sws)
9977 (back-to-indentation)
9978 (setq anchor (current-column))
9979 (while (and (zerop (forward-line -1))
9980 (>= (progn
9981 (back-to-indentation)
9982 (current-column))
9983 anchor)))
9984 (setq pos (current-column))))
9985 (push pos positions)
9986
9987 ;; nesting-heuristic position, main by default
9988 (push (setq main-pos normal-col) positions)
9989
9990 ;; delete duplicates and sort positions list
9991 (setq positions (sort (delete-dups positions) '<))
9992
9993 ;; comma-list continuation lines: prev line indent takes precedence
9994 (if same-indent
9995 (setq main-pos same-indent))
9996
9997 ;; common special cases where we want to indent in from previous line
9998 (if (or (js2-indent-case-block-p)
9999 (js2-indent-objlit-arg-p parse-status))
10000 (setq main-pos basic-offset))
10001
10002 ;; if bouncing backwards, reverse positions list
10003 (if backwards
10004 (setq positions (reverse positions)))
10005
10006 ;; record whether we're already sitting on one of the alternatives
10007 (setq pos (member cur-indent positions))
10008
10009 (cond
10010 ;; case 0: we're one one of the alternatives and this is the
10011 ;; first time they've pressed TAB on this line (best-guess).
10012 ((and js2-mode-indent-ignore-first-tab
10013 pos
10014 ;; first time pressing TAB on this line?
10015 (not (eq js2-mode-last-indented-line current-line)))
10016 ;; do nothing
10017 (setq computed-pos nil))
10018 ;; case 1: only one computed position => use it
10019 ((null (cdr positions))
10020 (setq computed-pos 0))
10021 ;; case 2: not on any of the computed spots => use main spot
10022 ((not pos)
10023 (setq computed-pos (js2-position main-pos positions)))
10024 ;; case 3: on last position: cycle to first position
10025 ((null (cdr pos))
10026 (setq computed-pos 0))
10027 ;; case 4: on intermediate position: cycle to next position
10028 (t
10029 (setq computed-pos (js2-position (second pos) positions))))
10030
10031 ;; see if any hooks want to indent; otherwise we do it
10032 (loop with result = nil
10033 for hook in js2-indent-hook
10034 while (null result)
10035 do
10036 (setq result (funcall hook positions computed-pos))
10037 finally do
10038 (unless (or result (null computed-pos))
10039 (indent-line-to (nth computed-pos positions)))))
10040
10041 ;; finally
10042 (if js2-mode-indent-inhibit-undo
10043 (setq buffer-undo-list old-buffer-undo-list))
10044 ;; see commentary for `js2-mode-last-indented-line'
10045 (setq js2-mode-last-indented-line current-line))))
10046
10047 (defun js2-indent-bounce-backwards ()
10048 "Calls `js2-indent-line'. When `js2-bounce-indent-p',
10049 cycles between the computed indentation positions in reverse order."
10050 (interactive)
10051 (js2-indent-line t))
10052
10053 (defun js2-1-line-comment-continuation-p ()
10054 "Return t if we're in a 1-line comment continuation.
10055 If so, we don't ever want to use bounce-indent."
10056 (save-excursion
10057 (and (progn
10058 (forward-line 0)
10059 (looking-at "\\s-*//"))
10060 (progn
10061 (forward-line -1)
10062 (forward-line 0)
10063 (when (looking-at "\\s-*$")
10064 (js2-backward-sws)
10065 (forward-line 0))
10066 (looking-at "\\s-*//")))))
10067
10068 (defun js2-indent-line (&optional bounce-backwards)
10069 "Indent the current line as JavaScript source text."
10070 (interactive)
10071 (let (parse-status current-indent offset indent-col moved
10072 ;; Don't whine about errors/warnings when we're indenting.
10073 ;; This has to be set before calling parse-partial-sexp below.
10074 (inhibit-point-motion-hooks t))
10075 (setq parse-status (save-excursion
10076 (syntax-ppss (point-at-bol)))
10077 offset (- (point) (save-excursion
10078 (back-to-indentation)
10079 (point))))
10080 (js2-with-underscore-as-word-syntax
10081 (if (nth 4 parse-status)
10082 (js2-lineup-comment parse-status)
10083 (setq indent-col (js2-proper-indentation parse-status))
10084 ;; See comments below about `js2-mode-last-indented-line'.
10085 (cond
10086 ;; bounce-indenting is disabled during electric-key indent.
10087 ;; It doesn't work well on first line of buffer.
10088 ((and js2-bounce-indent-p
10089 (not (js2-same-line (point-min)))
10090 (not (js2-1-line-comment-continuation-p)))
10091 (js2-bounce-indent indent-col parse-status bounce-backwards))
10092 ;; just indent to the guesser's likely spot
10093 (t (indent-line-to indent-col)))
10094 (when (plusp offset)
10095 (forward-char offset))))))
10096
10097 (defun js2-indent-region (start end)
10098 "Indent the region, but don't use bounce indenting."
10099 (let ((js2-bounce-indent-p nil)
10100 (indent-region-function nil)
10101 (after-change-functions (remq 'js2-mode-edit
10102 after-change-functions)))
10103 (indent-region start end nil) ; nil for byte-compiler
10104 (js2-mode-edit start end (- end start))))
10105
10106 (defvar js2-minor-mode-map
10107 (let ((map (make-sparse-keymap)))
10108 (define-key map (kbd "C-c C-`") #'js2-next-error)
10109 (define-key map [mouse-1] #'js2-mode-show-node)
10110 map)
10111 "Keymap used when `js2-minor-mode' is active.")
10112
10113 ;;;###autoload
10114 (define-minor-mode js2-minor-mode
10115 "Minor mode for running js2 as a background linter.
10116 This allows you to use a different major mode for JavaScript editing,
10117 such as `espresso-mode', while retaining the asynchronous error/warning
10118 highlighting features of `js2-mode'."
10119 :group 'js2-mode
10120 :lighter " js-lint"
10121 (if js2-minor-mode
10122 (js2-minor-mode-enter)
10123 (js2-minor-mode-exit)))
10124
10125 (defun js2-minor-mode-enter ()
10126 "Initialization for `js2-minor-mode'."
10127 (set (make-local-variable 'max-lisp-eval-depth)
10128 (max max-lisp-eval-depth 3000))
10129 (setq next-error-function #'js2-next-error)
10130 (setq js2-default-externs
10131 (append js2-ecma-262-externs
10132 (if js2-include-browser-externs js2-browser-externs)
10133 (if js2-include-gears-externs js2-gears-externs)
10134 (if js2-include-rhino-externs js2-rhino-externs)))
10135 ;; Experiment: make reparse-delay longer for longer files.
10136 (if (plusp js2-dynamic-idle-timer-adjust)
10137 (setq js2-idle-timer-delay
10138 (* js2-idle-timer-delay
10139 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10140 (setq js2-mode-buffer-dirty-p t
10141 js2-mode-parsing nil
10142 js2-highlight-level 0) ; no syntax highlighting
10143 (add-hook 'after-change-functions #'js2-minor-mode-edit nil t)
10144 (add-hook 'change-major-mode-hook #'js2-minor-mode-exit nil t)
10145 (js2-reparse))
10146
10147 (defun js2-minor-mode-exit ()
10148 "Turn off `js2-minor-mode'."
10149 (setq next-error-function nil)
10150 (remove-hook 'after-change-functions #'js2-mode-edit t)
10151 (remove-hook 'change-major-mode-hook #'js2-minor-mode-exit t)
10152 (when js2-mode-node-overlay
10153 (delete-overlay js2-mode-node-overlay)
10154 (setq js2-mode-node-overlay nil))
10155 (js2-remove-overlays)
10156 (setq js2-mode-ast nil))
10157
10158 (defun js2-display-error-list ()
10159 "Display a navigable buffer listing parse errors/warnings."
10160 (interactive)
10161 (if (not (js2-have-errors-p))
10162 (message "No errors")
10163 (let ((srcbuf (current-buffer))
10164 (errbuf (get-buffer-create "*js-lint*"))
10165 (errs (js2-errors-and-warnings)))
10166 (setq errs (sort errs (lambda (e1 e2)
10167 (funcall '< (second e1) (second e2)))))
10168 (with-current-buffer errbuf
10169 (let ((inhibit-read-only t))
10170 (erase-buffer)
10171 (dolist (err errs)
10172 (insert (format "%s\n" err)))
10173 (pop-to-buffer errbuf))))))
10174
10175 ;;;###autoload
10176 (define-derived-mode js2-mode prog-mode "Javascript-IDE"
10177 ;; FIXME: Should derive from js-mode.
10178 "Major mode for editing JavaScript code."
10179 (setq comment-start "//" ; used by comment-region; don't change it
10180 comment-end "")
10181 (set (make-local-variable 'max-lisp-eval-depth)
10182 (max max-lisp-eval-depth 3000))
10183 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10184 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10185 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10186 (set (make-local-variable 'comment-line-break-function) #'js2-line-break)
10187 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10188 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10189 ;; We un-confuse `parse-partial-sexp' by setting syntax-table properties
10190 ;; for characters inside regexp literals.
10191 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10192 ;; this is necessary to make `show-paren-function' work properly
10193 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10194 ;; needed for M-x rgrep, among other things
10195 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10196
10197 (set (make-local-variable 'electric-indent-chars)
10198 (append '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
10199 electric-indent-chars))
10200 (set (make-local-variable 'electric-layout-rules)
10201 '((?\; . after) (?\{ . after) (?\} . before)))
10202
10203 ;; some variables needed by cc-engine for paragraph-fill, etc.
10204 (setq c-comment-prefix-regexp js2-comment-prefix-regexp
10205 c-comment-start-regexp "/[*/]\\|\\s|"
10206 c-line-comment-starter "//"
10207 c-paragraph-start js2-paragraph-start
10208 c-paragraph-separate "$"
10209 comment-start-skip js2-comment-start-skip
10210 c-syntactic-ws-start js2-syntactic-ws-start
10211 c-syntactic-ws-end js2-syntactic-ws-end
10212 c-syntactic-eol js2-syntactic-eol)
10213
10214 (let ((c-buffer-is-cc-mode t))
10215 ;; Copied from `js-mode'. Also see Bug#6071.
10216 (make-local-variable 'paragraph-start)
10217 (make-local-variable 'paragraph-separate)
10218 (make-local-variable 'paragraph-ignore-fill-prefix)
10219 (make-local-variable 'adaptive-fill-mode)
10220 (make-local-variable 'adaptive-fill-regexp)
10221 (c-setup-paragraph-variables))
10222
10223 (setq js2-default-externs
10224 (append js2-ecma-262-externs
10225 (if js2-include-browser-externs js2-browser-externs)
10226 (if js2-include-gears-externs js2-gears-externs)
10227 (if js2-include-rhino-externs js2-rhino-externs)))
10228
10229 (setq font-lock-defaults '(nil t))
10230
10231 ;; Experiment: make reparse-delay longer for longer files.
10232 (when (plusp js2-dynamic-idle-timer-adjust)
10233 (setq js2-idle-timer-delay
10234 (* js2-idle-timer-delay
10235 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10236
10237 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10238 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10239 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10240 (imenu-add-to-menubar (concat "IM-" mode-name))
10241 (add-to-invisibility-spec '(js2-outline . t))
10242 (set (make-local-variable 'line-move-ignore-invisible) t)
10243 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10244
10245 (if (fboundp 'run-mode-hooks)
10246 (run-mode-hooks 'js2-mode-hook)
10247 (run-hooks 'js2-mode-hook))
10248
10249 (setq js2-mode-functions-hidden nil
10250 js2-mode-comments-hidden nil
10251 js2-mode-buffer-dirty-p t
10252 js2-mode-parsing nil)
10253 (js2-reparse))
10254
10255 (defun js2-mode-exit ()
10256 "Exit `js2-mode' and clean up."
10257 (interactive)
10258 (when js2-mode-node-overlay
10259 (delete-overlay js2-mode-node-overlay)
10260 (setq js2-mode-node-overlay nil))
10261 (js2-remove-overlays)
10262 (setq js2-mode-ast nil)
10263 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10264 (remove-from-invisibility-spec '(js2-outline . t))
10265 (js2-mode-show-all)
10266 (with-silent-modifications
10267 (js2-clear-face (point-min) (point-max))))
10268
10269 (defun js2-mode-reset-timer ()
10270 "Cancel any existing parse timer and schedule a new one."
10271 (if js2-mode-parse-timer
10272 (cancel-timer js2-mode-parse-timer))
10273 (setq js2-mode-parsing nil)
10274 (setq js2-mode-parse-timer
10275 (run-with-idle-timer js2-idle-timer-delay nil
10276 #'js2-mode-idle-reparse (current-buffer))))
10277
10278 (defun js2-mode-idle-reparse (buffer)
10279 "Run `js2-reparse' if BUFFER is the current buffer, or schedule
10280 it to be reparsed when the buffer is selected."
10281 (if (eq buffer (current-buffer))
10282 (js2-reparse)
10283 ;; reparse when the buffer is selected again
10284 (with-current-buffer buffer
10285 (add-hook 'window-configuration-change-hook
10286 #'js2-mode-idle-reparse-inner
10287 nil t))))
10288
10289 (defun js2-mode-idle-reparse-inner ()
10290 (remove-hook 'window-configuration-change-hook
10291 #'js2-mode-idle-reparse-inner
10292 t)
10293 (js2-reparse))
10294
10295 (defun js2-mode-edit (beg end len)
10296 "Schedule a new parse after buffer is edited.
10297 Buffer edit spans from BEG to END and is of length LEN."
10298 (setq js2-mode-buffer-dirty-p t)
10299 (js2-mode-hide-overlay)
10300 (js2-mode-reset-timer))
10301
10302 (defun js2-minor-mode-edit (beg end len)
10303 "Callback for buffer edits in `js2-mode'.
10304 Schedules a new parse after buffer is edited.
10305 Buffer edit spans from BEG to END and is of length LEN."
10306 (setq js2-mode-buffer-dirty-p t)
10307 (js2-mode-hide-overlay)
10308 (js2-mode-reset-timer))
10309
10310 (defun js2-reparse (&optional force)
10311 "Re-parse current buffer after user finishes some data entry.
10312 If we get any user input while parsing, including cursor motion,
10313 we discard the parse and reschedule it. If FORCE is nil, then the
10314 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10315 (let (time
10316 interrupted-p
10317 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10318 (unless js2-mode-parsing
10319 (setq js2-mode-parsing t)
10320 (unwind-protect
10321 (when (or js2-mode-buffer-dirty-p force)
10322 (js2-remove-overlays)
10323 (with-silent-modifications
10324 (setq js2-mode-buffer-dirty-p nil
10325 js2-mode-fontifications nil
10326 js2-mode-deferred-properties nil)
10327 (if js2-mode-verbose-parse-p
10328 (message "parsing..."))
10329 (setq time
10330 (js2-time
10331 (setq interrupted-p
10332 (catch 'interrupted
10333 (setq js2-mode-ast (js2-parse))
10334 ;; if parsing is interrupted, comments and regex
10335 ;; literals stay ignored by `parse-partial-sexp'
10336 (remove-text-properties (point-min) (point-max)
10337 '(syntax-table))
10338 (js2-mode-apply-deferred-properties)
10339 (js2-mode-remove-suppressed-warnings)
10340 (js2-mode-show-warnings)
10341 (js2-mode-show-errors)
10342 (if (>= js2-highlight-level 1)
10343 (js2-highlight-jsdoc js2-mode-ast))
10344 nil))))
10345 (if interrupted-p
10346 (progn
10347 ;; unfinished parse => try again
10348 (setq js2-mode-buffer-dirty-p t)
10349 (js2-mode-reset-timer))
10350 (if js2-mode-verbose-parse-p
10351 (message "Parse time: %s" time)))))
10352 (setq js2-mode-parsing nil)
10353 (unless interrupted-p
10354 (setq js2-mode-parse-timer nil))))))
10355
10356 (defun js2-mode-show-node ()
10357 "Debugging aid: highlight selected AST node on mouse click."
10358 (interactive)
10359 (let ((node (js2-node-at-point))
10360 beg end)
10361 (when js2-mode-show-overlay
10362 (if (null node)
10363 (message "No node found at location %s" (point))
10364 (setq beg (js2-node-abs-pos node)
10365 end (+ beg (js2-node-len node)))
10366 (if js2-mode-node-overlay
10367 (move-overlay js2-mode-node-overlay beg end)
10368 (setq js2-mode-node-overlay (make-overlay beg end))
10369 (overlay-put js2-mode-node-overlay 'font-lock-face 'highlight))
10370 (with-silent-modifications
10371 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10372 (message "%s, parent: %s"
10373 (js2-node-short-name node)
10374 (if (js2-node-parent node)
10375 (js2-node-short-name (js2-node-parent node))
10376 "nil"))))))
10377
10378 (defun js2-mode-hide-overlay (&optional p1 p2)
10379 "Remove the debugging overlay when the point moves.
10380 P1 and P2 are the old and new values of point, respectively."
10381 (when js2-mode-node-overlay
10382 (let ((beg (overlay-start js2-mode-node-overlay))
10383 (end (overlay-end js2-mode-node-overlay)))
10384 ;; Sometimes we're called spuriously.
10385 (unless (and p2
10386 (>= p2 beg)
10387 (<= p2 end))
10388 (with-silent-modifications
10389 (remove-text-properties beg end '(point-left nil)))
10390 (delete-overlay js2-mode-node-overlay)
10391 (setq js2-mode-node-overlay nil)))))
10392
10393 (defun js2-mode-reset ()
10394 "Debugging helper: reset everything."
10395 (interactive)
10396 (js2-mode-exit)
10397 (js2-mode))
10398
10399 (defun js2-mode-show-warn-or-err (e face)
10400 "Highlight a warning or error E with FACE.
10401 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10402 (let* ((key (first e))
10403 (beg (second e))
10404 (end (+ beg (third e)))
10405 ;; Don't inadvertently go out of bounds.
10406 (beg (max (point-min) (min beg (point-max))))
10407 (end (max (point-min) (min end (point-max))))
10408 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10409 (ovl (make-overlay beg end)))
10410 (overlay-put ovl 'font-lock-face face)
10411 (overlay-put ovl 'js2-error t)
10412 (put-text-property beg end 'help-echo (js2-get-msg key))
10413 (put-text-property beg end 'point-entered #'js2-echo-error)))
10414
10415 (defun js2-remove-overlays ()
10416 "Remove overlays from buffer that have a `js2-error' property."
10417 (let ((beg (point-min))
10418 (end (point-max)))
10419 (save-excursion
10420 (dolist (o (overlays-in beg end))
10421 (when (overlay-get o 'js2-error)
10422 (delete-overlay o))))))
10423
10424 (defun js2-error-at-point (&optional pos)
10425 "Return non-nil if there's an error overlay at POS.
10426 Defaults to point."
10427 (loop with pos = (or pos (point))
10428 for o in (overlays-at pos)
10429 thereis (overlay-get o 'js2-error)))
10430
10431 (defun js2-mode-apply-deferred-properties ()
10432 "Apply fontifications and other text properties recorded during parsing."
10433 (when (plusp js2-highlight-level)
10434 ;; We defer clearing faces as long as possible to eliminate flashing.
10435 (js2-clear-face (point-min) (point-max))
10436 ;; Have to reverse the recorded fontifications list so that errors
10437 ;; and warnings overwrite the normal fontifications.
10438 (dolist (f (nreverse js2-mode-fontifications))
10439 (put-text-property (first f) (second f) 'font-lock-face (third f)))
10440 (setq js2-mode-fontifications nil))
10441 (dolist (p js2-mode-deferred-properties)
10442 (apply #'put-text-property p))
10443 (setq js2-mode-deferred-properties nil))
10444
10445 (defun js2-mode-show-errors ()
10446 "Highlight syntax errors."
10447 (when js2-mode-show-parse-errors
10448 (dolist (e (js2-ast-root-errors js2-mode-ast))
10449 (js2-mode-show-warn-or-err e 'js2-error))))
10450
10451 (defun js2-mode-remove-suppressed-warnings ()
10452 "Take suppressed warnings out of the AST warnings list.
10453 This ensures that the counts and `next-error' are correct."
10454 (setf (js2-ast-root-warnings js2-mode-ast)
10455 (js2-delete-if
10456 (lambda (e)
10457 (let ((key (caar e)))
10458 (or
10459 (and (not js2-strict-trailing-comma-warning)
10460 (string-match "trailing\\.comma" key))
10461 (and (not js2-strict-cond-assign-warning)
10462 (string= key "msg.equal.as.assign"))
10463 (and js2-missing-semi-one-line-override
10464 (string= key "msg.missing.semi")
10465 (let* ((beg (second e))
10466 (node (js2-node-at-point beg))
10467 (fn (js2-mode-find-parent-fn node))
10468 (body (and fn (js2-function-node-body fn)))
10469 (lc (and body (js2-node-abs-pos body)))
10470 (rc (and lc (+ lc (js2-node-len body)))))
10471 (and fn
10472 (or (null body)
10473 (save-excursion
10474 (goto-char beg)
10475 (and (js2-same-line lc)
10476 (js2-same-line rc))))))))))
10477 (js2-ast-root-warnings js2-mode-ast))))
10478
10479 (defun js2-mode-show-warnings ()
10480 "Highlight strict-mode warnings."
10481 (when js2-mode-show-strict-warnings
10482 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10483 (js2-mode-show-warn-or-err e 'js2-warning))))
10484
10485 (defun js2-echo-error (old-point new-point)
10486 "Called by point-motion hooks."
10487 (let ((msg (get-text-property new-point 'help-echo)))
10488 (if (and msg (or (not (current-message))
10489 (string= (current-message) "Quit")))
10490 (message msg))))
10491
10492 (defalias #'js2-echo-help #'js2-echo-error)
10493
10494 (defun js2-line-break (&optional soft)
10495 "Break line at point."
10496 (let ((parse-status (syntax-ppss)))
10497 (cond
10498 ;; Check if we're inside a string.
10499 ((nth 3 parse-status)
10500 (js2-mode-split-string parse-status))
10501 ;; Check if inside a block comment.
10502 ((nth 4 parse-status)
10503 (js2-mode-extend-comment))
10504 (t
10505 (newline)))))
10506
10507 (defun js2-mode-split-string (parse-status)
10508 "Turn a newline in mid-string into a string concatenation.
10509 PARSE-STATUS is as documented in `parse-partial-sexp'."
10510 (let* ((col (current-column))
10511 (quote-char (nth 3 parse-status))
10512 (quote-string (string quote-char))
10513 (string-beg (nth 8 parse-status))
10514 (indent (or
10515 (save-excursion
10516 (back-to-indentation)
10517 (if (looking-at "\\+")
10518 (current-column)))
10519 (save-excursion
10520 (goto-char string-beg)
10521 (if (looking-back "\\+\\s-+")
10522 (goto-char (match-beginning 0)))
10523 (current-column)))))
10524 (insert quote-char "\n")
10525 (indent-to indent)
10526 (insert "+ " quote-string)
10527 (when (eolp)
10528 (insert quote-string)
10529 (backward-char 1))))
10530
10531 (defun js2-mode-extend-comment ()
10532 "Indent the line and, when inside a comment block, add comment prefix."
10533 (let (star single col first-line needs-close)
10534 (save-excursion
10535 (back-to-indentation)
10536 (cond
10537 ((looking-at "\\*[^/]")
10538 (setq star t
10539 col (current-column)))
10540 ((looking-at "/\\*")
10541 (setq star t
10542 first-line t
10543 col (1+ (current-column))))
10544 ((looking-at "//")
10545 (setq single t
10546 col (current-column)))))
10547 ;; Heuristic for whether we need to close the comment:
10548 ;; if we've got a parse error here, assume it's an unterminated
10549 ;; comment.
10550 (setq needs-close
10551 (or
10552 (eq (get-text-property (1- (point)) 'point-entered)
10553 'js2-echo-error)
10554 ;; The heuristic above doesn't work well when we're
10555 ;; creating a comment and there's another one downstream,
10556 ;; as our parser thinks this one ends at the end of the
10557 ;; next one. (You can have a /* inside a js block comment.)
10558 ;; So just close it if the next non-ws char isn't a *.
10559 (and first-line
10560 (eolp)
10561 (save-excursion
10562 (skip-chars-forward " \t\r\n")
10563 (not (eq (char-after) ?*))))))
10564 (insert "\n")
10565 (cond
10566 (star
10567 (indent-to col)
10568 (insert "* ")
10569 (if (and first-line needs-close)
10570 (save-excursion
10571 (insert "\n")
10572 (indent-to col)
10573 (insert "*/"))))
10574 ((and single
10575 (save-excursion
10576 (and (zerop (forward-line 1))
10577 (looking-at "\\s-*//"))))
10578 (indent-to col)
10579 (insert "// "))
10580 ;; don't need to extend the comment after all
10581 (js2-enter-indents-newline
10582 (js2-indent-line)))))
10583
10584 (defun js2-beginning-of-line ()
10585 "Toggles point between bol and first non-whitespace char in line.
10586 Also moves past comment delimiters when inside comments."
10587 (interactive)
10588 (let (node beg)
10589 (cond
10590 ((bolp)
10591 (back-to-indentation))
10592 ((looking-at "//")
10593 (skip-chars-forward "/ \t"))
10594 ((and (eq (char-after) ?*)
10595 (setq node (js2-comment-at-point))
10596 (memq (js2-comment-node-format node) '(jsdoc block))
10597 (save-excursion
10598 (skip-chars-backward " \t")
10599 (bolp)))
10600 (skip-chars-forward "\* \t"))
10601 (t
10602 (goto-char (point-at-bol))))))
10603
10604 (defun js2-end-of-line ()
10605 "Toggles point between eol and last non-whitespace char in line."
10606 (interactive)
10607 (if (eolp)
10608 (skip-chars-backward " \t")
10609 (goto-char (point-at-eol))))
10610
10611 (defsubst js2-mode-inside-string ()
10612 "Return non-nil if inside a string.
10613 Actually returns the quote character that begins the string."
10614 (nth 3 (syntax-ppss)))
10615
10616 (defun js2-mode-inside-comment-or-string ()
10617 "Return non-nil if inside a comment or string."
10618 (or
10619 (let ((comment-start
10620 (save-excursion
10621 (goto-char (point-at-bol))
10622 (if (re-search-forward "//" (point-at-eol) t)
10623 (match-beginning 0)))))
10624 (and comment-start
10625 (<= comment-start (point))))
10626 (let ((parse-state (syntax-ppss)))
10627 (or (nth 3 parse-state)
10628 (nth 4 parse-state)))))
10629
10630
10631 (defun js2-insert-catch-skel (try-pos)
10632 "Complete a try/catch block after inserting a { following a try keyword.
10633 Rationale is that a try always needs a catch or a finally, and the catch is
10634 the more likely of the two.
10635
10636 TRY-POS is the buffer position of the try keyword. The open-curly should
10637 already have been inserted."
10638 (insert "{")
10639 (let ((try-col (save-excursion
10640 (goto-char try-pos)
10641 (current-column))))
10642 (insert "\n")
10643 (undo-boundary)
10644 (js2-indent-line) ;; indent the blank line where cursor will end up
10645 (save-excursion
10646 (insert "\n")
10647 (indent-to try-col)
10648 (insert "} catch (x) {\n\n")
10649 (indent-to try-col)
10650 (insert "}"))))
10651
10652
10653 (defun js2-mode-wait-for-parse (callback)
10654 "Invoke CALLBACK when parsing is finished.
10655 If parsing is already finished, calls CALLBACK immediately."
10656 (if (not js2-mode-buffer-dirty-p)
10657 (funcall callback)
10658 (push callback js2-mode-pending-parse-callbacks)
10659 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10660
10661 (defun js2-mode-parse-finished ()
10662 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10663 ;; We can't let errors propagate up, since it prevents the
10664 ;; `js2-parse' method from completing normally and returning
10665 ;; the ast, which makes things mysteriously not work right.
10666 (unwind-protect
10667 (dolist (cb js2-mode-pending-parse-callbacks)
10668 (condition-case err
10669 (funcall cb)
10670 (error (message "%s" err))))
10671 (setq js2-mode-pending-parse-callbacks nil)))
10672
10673 (defun js2-mode-flag-region (from to flag)
10674 "Hide or show text from FROM to TO, according to FLAG.
10675 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10676 Returns the created overlay if FLAG is non-nil."
10677 (remove-overlays from to 'invisible 'js2-outline)
10678 (when flag
10679 (let ((o (make-overlay from to)))
10680 (overlay-put o 'invisible 'js2-outline)
10681 (overlay-put o 'isearch-open-invisible
10682 'js2-isearch-open-invisible)
10683 o)))
10684
10685 ;; Function to be set as an outline-isearch-open-invisible' property
10686 ;; to the overlay that makes the outline invisible (see
10687 ;; `js2-mode-flag-region').
10688 (defun js2-isearch-open-invisible (overlay)
10689 ;; We rely on the fact that isearch places point on the matched text.
10690 (js2-mode-show-element))
10691
10692 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10693 "Return cons cell of bounds of folding overlay at POS.
10694 Returns nil if not found."
10695 (let ((overlays (overlays-at (or pos (point))))
10696 o)
10697 (while (and overlays
10698 (not o))
10699 (if (overlay-get (car overlays) 'invisible)
10700 (setq o (car overlays))
10701 (setq overlays (cdr overlays))))
10702 (if o
10703 (cons (overlay-start o) (overlay-end o)))))
10704
10705 (defun js2-mode-function-at-point (&optional pos)
10706 "Return the innermost function node enclosing current point.
10707 Returns nil if point is not in a function."
10708 (let ((node (js2-node-at-point pos)))
10709 (while (and node (not (js2-function-node-p node)))
10710 (setq node (js2-node-parent node)))
10711 (if (js2-function-node-p node)
10712 node)))
10713
10714 (defun js2-mode-toggle-element ()
10715 "Hide or show the foldable element at the point."
10716 (interactive)
10717 (let (comment fn pos)
10718 (save-excursion
10719 (cond
10720 ;; /* ... */ comment?
10721 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10722 (if (js2-mode-invisible-overlay-bounds
10723 (setq pos (+ 3 (js2-node-abs-pos comment))))
10724 (progn
10725 (goto-char pos)
10726 (js2-mode-show-element))
10727 (js2-mode-hide-element)))
10728 ;; //-comment?
10729 ((save-excursion
10730 (back-to-indentation)
10731 (looking-at js2-mode-//-comment-re))
10732 (js2-mode-toggle-//-comment))
10733 ;; function?
10734 ((setq fn (js2-mode-function-at-point))
10735 (setq pos (and (js2-function-node-body fn)
10736 (js2-node-abs-pos (js2-function-node-body fn))))
10737 (goto-char (1+ pos))
10738 (if (js2-mode-invisible-overlay-bounds)
10739 (js2-mode-show-element)
10740 (js2-mode-hide-element)))
10741 (t
10742 (message "Nothing at point to hide or show"))))))
10743
10744 (defun js2-mode-hide-element ()
10745 "Fold/hide contents of a block, showing ellipses.
10746 Show the hidden text with \\[js2-mode-show-element]."
10747 (interactive)
10748 (if js2-mode-buffer-dirty-p
10749 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10750 (let (node body beg end)
10751 (cond
10752 ((js2-mode-invisible-overlay-bounds)
10753 (message "already hidden"))
10754 (t
10755 (setq node (js2-node-at-point))
10756 (cond
10757 ((js2-block-comment-p node)
10758 (js2-mode-hide-comment node))
10759 (t
10760 (while (and node (not (js2-function-node-p node)))
10761 (setq node (js2-node-parent node)))
10762 (if (and node
10763 (setq body (js2-function-node-body node)))
10764 (progn
10765 (setq beg (js2-node-abs-pos body)
10766 end (+ beg (js2-node-len body)))
10767 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
10768 (message "No collapsable element found at point"))))))))
10769
10770 (defun js2-mode-show-element ()
10771 "Show the hidden element at current point."
10772 (interactive)
10773 (let ((bounds (js2-mode-invisible-overlay-bounds)))
10774 (if bounds
10775 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
10776 (message "Nothing to un-hide"))))
10777
10778 (defun js2-mode-show-all ()
10779 "Show all of the text in the buffer."
10780 (interactive)
10781 (js2-mode-flag-region (point-min) (point-max) nil))
10782
10783 (defun js2-mode-toggle-hide-functions ()
10784 (interactive)
10785 (if js2-mode-functions-hidden
10786 (js2-mode-show-functions)
10787 (js2-mode-hide-functions)))
10788
10789 (defun js2-mode-hide-functions ()
10790 "Hides all non-nested function bodies in the buffer.
10791 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10792 to open an individual entry."
10793 (interactive)
10794 (if js2-mode-buffer-dirty-p
10795 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
10796 (if (null js2-mode-ast)
10797 (message "Oops - parsing failed")
10798 (setq js2-mode-functions-hidden t)
10799 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
10800
10801 (defun js2-mode-function-hider (n endp)
10802 (when (not endp)
10803 (let ((tt (js2-node-type n))
10804 body beg end)
10805 (cond
10806 ((and (= tt js2-FUNCTION)
10807 (setq body (js2-function-node-body n)))
10808 (setq beg (js2-node-abs-pos body)
10809 end (+ beg (js2-node-len body)))
10810 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
10811 nil) ; don't process children of function
10812 (t
10813 t))))) ; keep processing other AST nodes
10814
10815 (defun js2-mode-show-functions ()
10816 "Un-hide any folded function bodies in the buffer."
10817 (interactive)
10818 (setq js2-mode-functions-hidden nil)
10819 (save-excursion
10820 (goto-char (point-min))
10821 (while (/= (goto-char (next-overlay-change (point)))
10822 (point-max))
10823 (dolist (o (overlays-at (point)))
10824 (when (and (overlay-get o 'invisible)
10825 (not (overlay-get o 'comment)))
10826 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10827
10828 (defun js2-mode-hide-comment (n)
10829 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
10830 3 ; /**
10831 2)) ; /*
10832 (beg (+ (js2-node-abs-pos n) head))
10833 (end (- (+ beg (js2-node-len n)) head 2))
10834 (o (js2-mode-flag-region beg end 'hide)))
10835 (overlay-put o 'comment t)))
10836
10837 (defun js2-mode-toggle-hide-comments ()
10838 "Folds all block comments in the buffer.
10839 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
10840 to open an individual entry."
10841 (interactive)
10842 (if js2-mode-comments-hidden
10843 (js2-mode-show-comments)
10844 (js2-mode-hide-comments)))
10845
10846 (defun js2-mode-hide-comments ()
10847 (interactive)
10848 (if js2-mode-buffer-dirty-p
10849 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
10850 (if (null js2-mode-ast)
10851 (message "Oops - parsing failed")
10852 (setq js2-mode-comments-hidden t)
10853 (dolist (n (js2-ast-root-comments js2-mode-ast))
10854 (let ((format (js2-comment-node-format n)))
10855 (when (js2-block-comment-p n)
10856 (js2-mode-hide-comment n))))
10857 (js2-mode-hide-//-comments)))
10858
10859 (defun js2-mode-extend-//-comment (direction)
10860 "Find start or end of a block of similar //-comment lines.
10861 DIRECTION is -1 to look back, 1 to look forward.
10862 INDENT is the indentation level to match.
10863 Returns the end-of-line position of the furthest adjacent
10864 //-comment line with the same indentation as the current line.
10865 If there is no such matching line, returns current end of line."
10866 (let ((pos (point-at-eol))
10867 (indent (current-indentation)))
10868 (save-excursion
10869 (while (and (zerop (forward-line direction))
10870 (looking-at js2-mode-//-comment-re)
10871 (eq indent (length (match-string 1))))
10872 (setq pos (point-at-eol))
10873 pos))))
10874
10875 (defun js2-mode-hide-//-comments ()
10876 "Fold adjacent 1-line comments, showing only snippet of first one."
10877 (let (beg end)
10878 (save-excursion
10879 (goto-char (point-min))
10880 (while (re-search-forward js2-mode-//-comment-re nil t)
10881 (setq beg (point)
10882 end (js2-mode-extend-//-comment 1))
10883 (unless (eq beg end)
10884 (overlay-put (js2-mode-flag-region beg end 'hide)
10885 'comment t))
10886 (goto-char end)
10887 (forward-char 1)))))
10888
10889 (defun js2-mode-toggle-//-comment ()
10890 "Fold or un-fold any multi-line //-comment at point.
10891 Caller should have determined that this line starts with a //-comment."
10892 (let* ((beg (point-at-eol))
10893 (end beg))
10894 (save-excursion
10895 (goto-char end)
10896 (if (js2-mode-invisible-overlay-bounds)
10897 (js2-mode-show-element)
10898 ;; else hide the comment
10899 (setq beg (js2-mode-extend-//-comment -1)
10900 end (js2-mode-extend-//-comment 1))
10901 (unless (eq beg end)
10902 (overlay-put (js2-mode-flag-region beg end 'hide)
10903 'comment t))))))
10904
10905 (defun js2-mode-show-comments ()
10906 "Un-hide any hidden comments, leaving other hidden elements alone."
10907 (interactive)
10908 (setq js2-mode-comments-hidden nil)
10909 (save-excursion
10910 (goto-char (point-min))
10911 (while (/= (goto-char (next-overlay-change (point)))
10912 (point-max))
10913 (dolist (o (overlays-at (point)))
10914 (when (overlay-get o 'comment)
10915 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
10916
10917 (defun js2-mode-display-warnings-and-errors ()
10918 "Turn on display of warnings and errors."
10919 (interactive)
10920 (setq js2-mode-show-parse-errors t
10921 js2-mode-show-strict-warnings t)
10922 (js2-reparse 'force))
10923
10924 (defun js2-mode-hide-warnings-and-errors ()
10925 "Turn off display of warnings and errors."
10926 (interactive)
10927 (setq js2-mode-show-parse-errors nil
10928 js2-mode-show-strict-warnings nil)
10929 (js2-reparse 'force))
10930
10931 (defun js2-mode-toggle-warnings-and-errors ()
10932 "Toggle the display of warnings and errors.
10933 Some users don't like having warnings/errors reported while they type."
10934 (interactive)
10935 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
10936 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
10937 (if (called-interactively-p 'any)
10938 (message "warnings and errors %s"
10939 (if js2-mode-show-parse-errors
10940 "enabled"
10941 "disabled")))
10942 (js2-reparse 'force))
10943
10944 (defun js2-mode-customize ()
10945 (interactive)
10946 (customize-group 'js2-mode))
10947
10948 (defun js2-mode-forward-sexp (&optional arg)
10949 "Move forward across one statement or balanced expression.
10950 With ARG, do it that many times. Negative arg -N means
10951 move backward across N balanced expressions."
10952 (interactive "p")
10953 (setq arg (or arg 1))
10954 (let (node end (start (point)))
10955 (cond
10956 ;; backward-sexp
10957 ;; could probably make this better for some cases:
10958 ;; - if in statement block (e.g. function body), go to parent
10959 ;; - infix exprs like (foo in bar) - maybe go to beginning
10960 ;; of infix expr if in the right-side expression?
10961 ((and arg (minusp arg))
10962 (dotimes (i (- arg))
10963 (js2-backward-sws)
10964 (forward-char -1) ; enter the node we backed up to
10965 (setq node (js2-node-at-point (point) t))
10966 (goto-char (if node
10967 (js2-node-abs-pos node)
10968 (point-min)))))
10969 (t
10970 ;; forward-sexp
10971 (js2-forward-sws)
10972 (dotimes (i arg)
10973 (js2-forward-sws)
10974 (setq node (js2-node-at-point (point) t)
10975 end (if node (+ (js2-node-abs-pos node)
10976 (js2-node-len node))))
10977 (goto-char (or end (point-max))))))))
10978
10979 (defun js2-errors ()
10980 "Return a list of errors found."
10981 (and js2-mode-ast
10982 (js2-ast-root-errors js2-mode-ast)))
10983
10984 (defun js2-warnings ()
10985 "Return a list of warnings found."
10986 (and js2-mode-ast
10987 (js2-ast-root-warnings js2-mode-ast)))
10988
10989 (defun js2-have-errors-p ()
10990 "Return non-nil if any parse errors or warnings were found."
10991 (or (js2-errors) (js2-warnings)))
10992
10993 (defun js2-errors-and-warnings ()
10994 "Return a copy of the concatenated errors and warnings lists."
10995 (and js2-mode-ast
10996 (append (js2-ast-root-errors js2-mode-ast)
10997 (copy-sequence (js2-ast-root-warnings js2-mode-ast)))))
10998
10999 (defun js2-next-error (&optional arg reset)
11000 "Move to next parse error.
11001 Typically invoked via \\[next-error].
11002 ARG is the number of errors, forward or backward, to move.
11003 RESET means start over from the beginning."
11004 (interactive "p")
11005 (if (not (or (js2-errors) (js2-warnings)))
11006 (message "No errors")
11007 (when reset
11008 (goto-char (point-min)))
11009 (let* ((errs (js2-errors-and-warnings))
11010 (continue t)
11011 (start (point))
11012 (count (or arg 1))
11013 (backward (minusp count))
11014 (sorter (if backward '> '<))
11015 (stopper (if backward '< '>))
11016 (count (abs count))
11017 all-errs err)
11018 ;; Sort by start position.
11019 (setq errs (sort errs (lambda (e1 e2)
11020 (funcall sorter (second e1) (second e2))))
11021 all-errs errs)
11022 ;; Find nth error with pos > start.
11023 (while (and errs continue)
11024 (when (funcall stopper (cadar errs) start)
11025 (setq err (car errs))
11026 (if (zerop (decf count))
11027 (setq continue nil)))
11028 (setq errs (cdr errs)))
11029 (if err
11030 (goto-char (second err))
11031 ;; Wrap around to first error.
11032 (goto-char (second (car all-errs)))
11033 ;; If we were already on it, echo msg again.
11034 (if (= (point) start)
11035 (js2-echo-error (point) (point)))))))
11036
11037 (defun js2-down-mouse-3 ()
11038 "Make right-click move the point to the click location.
11039 This makes right-click context menu operations a bit more intuitive.
11040 The point will not move if the region is active, however, to avoid
11041 destroying the region selection."
11042 (interactive)
11043 (when (and js2-move-point-on-right-click
11044 (not mark-active))
11045 (let ((e last-input-event))
11046 (ignore-errors
11047 (goto-char (cadadr e))))))
11048
11049 (defun js2-mode-create-imenu-index ()
11050 "Return an alist for `imenu--index-alist'."
11051 ;; This is built up in `js2-parse-record-imenu' during parsing.
11052 (when js2-mode-ast
11053 ;; if we have an ast but no recorder, they're requesting a rescan
11054 (unless js2-imenu-recorder
11055 (js2-reparse 'force))
11056 (prog1
11057 (js2-build-imenu-index)
11058 (setq js2-imenu-recorder nil
11059 js2-imenu-function-map nil))))
11060
11061 (defun js2-mode-find-tag ()
11062 "Replacement for `find-tag-default'.
11063 `find-tag-default' returns a ridiculous answer inside comments."
11064 (let (beg end)
11065 (js2-with-underscore-as-word-syntax
11066 (save-excursion
11067 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11068 (looking-back "[A-Za-z0-9_$]"))
11069 (setq beg (progn (forward-word -1) (point))
11070 end (progn (forward-word 1) (point)))
11071 (setq beg (progn (forward-word 1) (point))
11072 end (progn (forward-word -1) (point))))
11073 (replace-regexp-in-string
11074 "[\"']" ""
11075 (buffer-substring-no-properties beg end))))))
11076
11077 (defun js2-mode-forward-sibling ()
11078 "Move to the end of the sibling following point in parent.
11079 Returns non-nil if successful, or nil if there was no following sibling."
11080 (let* ((node (js2-node-at-point))
11081 (parent (js2-mode-find-enclosing-fn node))
11082 sib)
11083 (when (setq sib (js2-node-find-child-after (point) parent))
11084 (goto-char (+ (js2-node-abs-pos sib)
11085 (js2-node-len sib))))))
11086
11087 (defun js2-mode-backward-sibling ()
11088 "Move to the beginning of the sibling node preceding point in parent.
11089 Parent is defined as the enclosing script or function."
11090 (let* ((node (js2-node-at-point))
11091 (parent (js2-mode-find-enclosing-fn node))
11092 sib)
11093 (when (setq sib (js2-node-find-child-before (point) parent))
11094 (goto-char (js2-node-abs-pos sib)))))
11095
11096 (defun js2-beginning-of-defun (&optional arg)
11097 "Go to line on which current function starts, and return t on success.
11098 If we're not in a function or already at the beginning of one, go
11099 to beginning of previous script-level element.
11100 With ARG N, do that N times. If N is negative, move forward."
11101 (setq arg (or arg 1))
11102 (if (plusp arg)
11103 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11104 (when (cond
11105 ((js2-function-node-p parent)
11106 (goto-char (js2-node-abs-pos parent)))
11107 (t
11108 (js2-mode-backward-sibling)))
11109 (if (> arg 1)
11110 (js2-beginning-of-defun (1- arg))
11111 t)))
11112 (when (js2-end-of-defun)
11113 (if (>= arg -1)
11114 (js2-beginning-of-defun 1)
11115 (js2-beginning-of-defun (1+ arg))))))
11116
11117 (defun js2-end-of-defun ()
11118 "Go to the char after the last position of the current function
11119 or script-level element."
11120 (let* ((node (js2-node-at-point))
11121 (parent (or (and (js2-function-node-p node) node)
11122 (js2-node-parent-script-or-fn node)))
11123 script)
11124 (unless (js2-function-node-p parent)
11125 ;; Use current script-level node, or, if none, the next one.
11126 (setq script (or parent node)
11127 parent (js2-node-find-child-before (point) script))
11128 (when (or (null parent)
11129 (>= (point) (+ (js2-node-abs-pos parent)
11130 (js2-node-len parent))))
11131 (setq parent (js2-node-find-child-after (point) script))))
11132 (when parent
11133 (goto-char (+ (js2-node-abs-pos parent)
11134 (js2-node-len parent))))))
11135
11136 (defun js2-mark-defun (&optional allow-extend)
11137 "Put mark at end of this function, point at beginning.
11138 The function marked is the one that contains point.
11139
11140 Interactively, if this command is repeated,
11141 or (in Transient Mark mode) if the mark is active,
11142 it marks the next defun after the ones already marked."
11143 (interactive "p")
11144 (let (extended)
11145 (when (and allow-extend
11146 (or (and (eq last-command this-command) (mark t))
11147 (and transient-mark-mode mark-active)))
11148 (let ((sib (save-excursion
11149 (goto-char (mark))
11150 (if (js2-mode-forward-sibling)
11151 (point))))
11152 node)
11153 (if sib
11154 (progn
11155 (set-mark sib)
11156 (setq extended t))
11157 ;; no more siblings - try extending to enclosing node
11158 (goto-char (mark t)))))
11159 (when (not extended)
11160 (let ((node (js2-node-at-point (point) t)) ; skip comments
11161 ast fn stmt parent beg end)
11162 (when (js2-ast-root-p node)
11163 (setq ast node
11164 node (or (js2-node-find-child-after (point) node)
11165 (js2-node-find-child-before (point) node))))
11166 ;; only mark whole buffer if we can't find any children
11167 (if (null node)
11168 (setq node ast))
11169 (if (js2-function-node-p node)
11170 (setq parent node)
11171 (setq fn (js2-mode-find-enclosing-fn node)
11172 stmt (if (or (null fn)
11173 (js2-ast-root-p fn))
11174 (js2-mode-find-first-stmt node))
11175 parent (or stmt fn)))
11176 (setq beg (js2-node-abs-pos parent)
11177 end (+ beg (js2-node-len parent)))
11178 (push-mark beg)
11179 (goto-char end)
11180 (exchange-point-and-mark)))))
11181
11182 (defun js2-narrow-to-defun ()
11183 "Narrow to the function enclosing point."
11184 (interactive)
11185 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11186 (fn (if (js2-script-node-p node)
11187 node
11188 (js2-mode-find-enclosing-fn node)))
11189 (beg (js2-node-abs-pos fn)))
11190 (unless (js2-ast-root-p fn)
11191 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11192
11193 (provide 'js2-mode)
11194
11195 ;;; js2-mode.el ends here