]> code.delx.au - gnu-emacs-elpa/blob - js2-mode.el
Allow abbreviated destructuring assignment in array comprehension
[gnu-emacs-elpa] / js2-mode.el
1 ;;; js2-mode.el --- an improved JavaScript editing mode
2
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4
5 ;; Author: Steve Yegge <steve.yegge@gmail.com>
6 ;; mooz <stillpedant@gmail.com>
7 ;; Version: See `js2-mode-version'
8 ;; Keywords: languages, javascript
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This JavaScript editing mode supports:
28
29 ;; - strict recognition of the Ecma-262 language standard
30 ;; - support for most Rhino and SpiderMonkey extensions from 1.5 to 1.8
31 ;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
32 ;; - accurate syntax highlighting using a recursive-descent parser
33 ;; - on-the-fly reporting of syntax errors and strict-mode warnings
34 ;; - undeclared-variable warnings using a configurable externs framework
35 ;; - "bouncing" line indentation to choose among alternate indentation points
36 ;; - smart line-wrapping within comments and strings
37 ;; - code folding:
38 ;; - show some or all function bodies as {...}
39 ;; - show some or all block comments as /*...*/
40 ;; - context-sensitive menu bar and popup menus
41 ;; - code browsing using the `imenu' package
42 ;; - typing helpers such as automatic insertion of matching braces/parens
43 ;; - many customization options
44
45 ;; To customize how it works:
46 ;; M-x customize-group RET js2-mode RET
47
48 ;; Notes:
49
50 ;; This mode includes a port of Mozilla Rhino's scanner, parser and
51 ;; symbol table. Ideally it should stay in sync with Rhino, keeping
52 ;; `js2-mode' current as the EcmaScript language standard evolves.
53
54 ;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
55 ;; customizable. It is a surprising amount of work to support customizable
56 ;; indentation. The current compromise is that the tab key lets you cycle among
57 ;; various likely indentation points, similar to the behavior of python-mode.
58
59 ;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
60 ;; and `mumamo', although it could be made to do so with some effort.
61 ;; This means that `js2-mode' is currently only useful for editing JavaScript
62 ;; files, and not for editing JavaScript within <script> tags or templates.
63
64 ;;; Code:
65
66 (eval-when-compile
67 (require 'cl))
68
69 (require 'imenu)
70 (require 'cc-cmds) ; for `c-fill-paragraph'
71
72 (eval-and-compile
73 (require 'cc-mode) ; (only) for `c-populate-syntax-table'
74 (require 'cc-langs) ; it's here in Emacs 21...
75 (require 'cc-engine)) ; for `c-paragraph-start' et. al.
76
77 ;;; Externs (variables presumed to be defined by the host system)
78
79 (defvar js2-ecma-262-externs
80 (mapcar 'symbol-name
81 '(Array Boolean Date Error EvalError Function Infinity
82 Math NaN Number Object RangeError ReferenceError RegExp
83 String SyntaxError TypeError URIError arguments
84 decodeURI decodeURIComponent encodeURI
85 encodeURIComponent escape eval isFinite isNaN
86 parseFloat parseInt undefined unescape))
87 "Ecma-262 externs. Included in `js2-externs' by default.")
88
89 (defvar js2-browser-externs
90 (mapcar 'symbol-name
91 '(;; DOM level 1
92 Attr CDATASection CharacterData Comment DOMException
93 DOMImplementation Document DocumentFragment
94 DocumentType Element Entity EntityReference
95 ExceptionCode NamedNodeMap Node NodeList Notation
96 ProcessingInstruction Text
97
98 ;; DOM level 2
99 HTMLAnchorElement HTMLAppletElement HTMLAreaElement
100 HTMLBRElement HTMLBaseElement HTMLBaseFontElement
101 HTMLBodyElement HTMLButtonElement HTMLCollection
102 HTMLDListElement HTMLDirectoryElement HTMLDivElement
103 HTMLDocument HTMLElement HTMLFieldSetElement
104 HTMLFontElement HTMLFormElement HTMLFrameElement
105 HTMLFrameSetElement HTMLHRElement HTMLHeadElement
106 HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
107 HTMLImageElement HTMLInputElement HTMLIsIndexElement
108 HTMLLIElement HTMLLabelElement HTMLLegendElement
109 HTMLLinkElement HTMLMapElement HTMLMenuElement
110 HTMLMetaElement HTMLModElement HTMLOListElement
111 HTMLObjectElement HTMLOptGroupElement
112 HTMLOptionElement HTMLOptionsCollection
113 HTMLParagraphElement HTMLParamElement HTMLPreElement
114 HTMLQuoteElement HTMLScriptElement HTMLSelectElement
115 HTMLStyleElement HTMLTableCaptionElement
116 HTMLTableCellElement HTMLTableColElement
117 HTMLTableElement HTMLTableRowElement
118 HTMLTableSectionElement HTMLTextAreaElement
119 HTMLTitleElement HTMLUListElement
120
121 ;; DOM level 3
122 DOMConfiguration DOMError DOMException
123 DOMImplementationList DOMImplementationSource
124 DOMLocator DOMStringList NameList TypeInfo
125 UserDataHandler
126
127 ;; Window
128 alert confirm document java navigator prompt screen
129 self top
130
131 ;; W3C CSS
132 CSSCharsetRule CSSFontFace CSSFontFaceRule
133 CSSImportRule CSSMediaRule CSSPageRule
134 CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
135 CSSStyleDeclaration CSSStyleRule CSSStyleSheet
136 CSSValue CSSValueList Counter DOMImplementationCSS
137 DocumentCSS DocumentStyle ElementCSSInlineStyle
138 LinkStyle MediaList RGBColor Rect StyleSheet
139 StyleSheetList ViewCSS
140
141 ;; W3C Event
142 EventListener EventTarget Event DocumentEvent UIEvent
143 MouseEvent MutationEvent KeyboardEvent
144
145 ;; W3C Range
146 DocumentRange Range RangeException
147
148 ;; W3C XML
149 XPathResult XMLHttpRequest))
150 "Browser externs.
151 You can cause these to be included or excluded with the custom
152 variable `js2-include-browser-externs'.")
153
154 (defvar js2-rhino-externs
155 (mapcar 'symbol-name
156 '(Packages importClass importPackage com org java
157 ;; Global object (shell) externs
158 defineClass deserialize doctest gc help load
159 loadClass print quit readFile readUrl runCommand seal
160 serialize spawn sync toint32 version))
161 "Mozilla Rhino externs.
162 Set `js2-include-rhino-externs' to t to include them.")
163
164 (defvar js2-gears-externs
165 (mapcar 'symbol-name
166 '(
167 ;; TODO(stevey): add these
168 ))
169 "Google Gears externs.
170 Set `js2-include-gears-externs' to t to include them.")
171
172 ;;; Variables
173
174 (defvar js2-emacs22 (>= emacs-major-version 22))
175
176 (defcustom js2-highlight-level 2
177 "Amount of syntax highlighting to perform.
178 0 or a negative value means do no highlighting.
179 1 adds basic syntax highlighting.
180 2 adds highlighting of some Ecma built-in properties.
181 3 adds highlighting of many Ecma built-in functions."
182 :group 'js2-mode
183 :type '(choice (const :tag "None" 0)
184 (const :tag "Basic" 1)
185 (const :tag "Include Properties" 2)
186 (const :tag "Include Functions" 3)))
187
188 (defvar js2-mode-dev-mode-p nil
189 "Non-nil if running in development mode. Normally nil.")
190
191 (defgroup js2-mode nil
192 "An improved JavaScript mode."
193 :group 'languages)
194
195 (defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
196 (numberp c-basic-offset))
197 c-basic-offset
198 4)
199 "Number of spaces to indent nested statements.
200 Similar to `c-basic-offset'."
201 :group 'js2-mode
202 :type 'integer)
203 (make-variable-buffer-local 'js2-basic-offset)
204
205 ;; TODO(stevey): move this code into a separate minor mode.
206 (defcustom js2-mirror-mode nil
207 "Non-nil to insert closing brackets, parens, etc. automatically."
208 :group 'js2-mode
209 :type 'boolean)
210
211 (defcustom js2-auto-indent-p nil
212 "Automatic indentation with punctuation characters.
213 If non-nil, the current line is indented when certain punctuations
214 are inserted."
215 :group 'js2-mode
216 :type 'boolean)
217
218 (defcustom js2-bounce-indent-p nil
219 "Non-nil to have indent-line function choose among alternatives.
220 If nil, the indent-line function will indent to a predetermined column
221 based on heuristic guessing. If non-nil, then if the current line is
222 already indented to that predetermined column, indenting will choose
223 another likely column and indent to that spot. Repeated invocation of
224 the indent-line function will cycle among the computed alternatives.
225 See the function `js2-bounce-indent' for details."
226 :type 'boolean
227 :group 'js2-mode)
228
229 (defcustom js2-consistent-level-indent-inner-bracket-p t
230 "Non-nil to make indentation level inner bracket consistent,
231 regardless of the beginning bracket position."
232 :group 'js2-mode
233 :type 'boolean)
234
235 (defcustom js2-indent-on-enter-key nil
236 "Non-nil to have Enter/Return key indent the line.
237 This is unusual for Emacs modes but common in IDEs like Eclipse."
238 :type 'boolean
239 :group 'js2-mode)
240
241 (defcustom js2-enter-indents-newline nil
242 "Non-nil to have Enter/Return key indent the newly-inserted line.
243 This is unusual for Emacs modes but common in IDEs like Eclipse."
244 :type 'boolean
245 :group 'js2-mode)
246
247 (defcustom js2-rebind-eol-bol-keys t
248 "Non-nil to rebind `beginning-of-line' and `end-of-line' keys.
249 If non-nil, bounce between bol/eol and first/last non-whitespace char."
250 :group 'js2-mode
251 :type 'boolean)
252
253 (defcustom js2-electric-keys '("{" "}" "(" ")" "[" "]" ":" ";" "," "*")
254 "Keys that auto-indent when `js2-auto-indent-p' is non-nil.
255 Each value in the list is passed to `define-key'."
256 :type 'list
257 :group 'js2-mode)
258
259 (defcustom js2-idle-timer-delay 0.2
260 "Delay in secs before re-parsing after user makes changes.
261 Multiplied by `js2-dynamic-idle-timer-adjust', which see."
262 :type 'number
263 :group 'js2-mode)
264 (make-variable-buffer-local 'js2-idle-timer-delay)
265
266 (defcustom js2-dynamic-idle-timer-adjust 0
267 "Positive to adjust `js2-idle-timer-delay' based on file size.
268 The idea is that for short files, parsing is faster so we can be
269 more responsive to user edits without interfering with editing.
270 The buffer length in characters (typically bytes) is divided by
271 this value and used to multiply `js2-idle-timer-delay' for the
272 buffer. For example, a 21k file and 10k adjust yields 21k/10k
273 == 2, so js2-idle-timer-delay is multiplied by 2.
274 If `js2-dynamic-idle-timer-adjust' is 0 or negative,
275 `js2-idle-timer-delay' is not dependent on the file size."
276 :type 'number
277 :group 'js2-mode)
278
279 (defcustom js2-mode-escape-quotes t
280 "Non-nil to disable automatic quote-escaping inside strings."
281 :type 'boolean
282 :group 'js2-mode)
283
284 (defcustom js2-mode-squeeze-spaces t
285 "Non-nil to normalize whitespace when filling in comments.
286 Multiple runs of spaces are converted to a single space."
287 :type 'boolean
288 :group 'js2-mode)
289
290 (defcustom js2-mode-show-parse-errors t
291 "True to highlight parse errors."
292 :type 'boolean
293 :group 'js2-mode)
294
295 (defcustom js2-mode-show-strict-warnings t
296 "Non-nil to emit Ecma strict-mode warnings.
297 Some of the warnings can be individually disabled by other flags,
298 even if this flag is non-nil."
299 :type 'boolean
300 :group 'js2-mode)
301
302 (defcustom js2-strict-trailing-comma-warning t
303 "Non-nil to warn about trailing commas in array literals.
304 Ecma-262 forbids them, but many browsers permit them. IE is the
305 big exception, and can produce bugs if you have trailing commas."
306 :type 'boolean
307 :group 'js2-mode)
308
309 (defcustom js2-strict-missing-semi-warning t
310 "Non-nil to warn about semicolon auto-insertion after statement.
311 Technically this is legal per Ecma-262, but some style guides disallow
312 depending on it."
313 :type 'boolean
314 :group 'js2-mode)
315
316 (defcustom js2-missing-semi-one-line-override nil
317 "Non-nil to permit missing semicolons in one-line functions.
318 In one-liner functions such as `function identity(x) {return x}'
319 people often omit the semicolon for a cleaner look. If you are
320 such a person, you can suppress the missing-semicolon warning
321 by setting this variable to t."
322 :type 'boolean
323 :group 'js2-mode)
324
325 (defcustom js2-strict-inconsistent-return-warning t
326 "Non-nil to warn about mixing returns with value-returns.
327 It's perfectly legal to have a `return' and a `return foo' in the
328 same function, but it's often an indicator of a bug, and it also
329 interferes with type inference (in systems that support it.)"
330 :type 'boolean
331 :group 'js2-mode)
332
333 (defcustom js2-strict-cond-assign-warning t
334 "Non-nil to warn about expressions like if (a = b).
335 This often should have been '==' instead of '='. If the warning
336 is enabled, you can suppress it on a per-expression basis by
337 parenthesizing the expression, e.g. if ((a = b)) ..."
338 :type 'boolean
339 :group 'js2-mode)
340
341 (defcustom js2-strict-cond-assign-warning t
342 "Non-nil to warn about expressions like if (a = b).
343 This often should have been '==' instead of '='. If the warning
344 is enabled, you can suppress it on a per-expression basis by
345 parenthesizing the expression, e.g. if ((a = b)) ..."
346 :type 'boolean
347 :group 'js2-mode)
348
349 (defcustom js2-strict-var-redeclaration-warning t
350 "Non-nil to warn about redeclaring variables in a script or function."
351 :type 'boolean
352 :group 'js2-mode)
353
354 (defcustom js2-strict-var-hides-function-arg-warning t
355 "Non-nil to warn about a var decl hiding a function argument."
356 :type 'boolean
357 :group 'js2-mode)
358
359 (defcustom js2-skip-preprocessor-directives nil
360 "Non-nil to treat lines beginning with # as comments.
361 Useful for viewing Mozilla JavaScript source code."
362 :type 'boolean
363 :group 'js2-mode)
364
365 (defcustom js2-language-version 180
366 "Configures what JavaScript language version to recognize.
367 Currently versions 150, 160, 170 and 180 are supported, corresponding
368 to JavaScript 1.5, 1.6, 1.7 and 1.8, respectively. In a nutshell,
369 1.6 adds E4X support, 1.7 adds let, yield, and Array comprehensions,
370 and 1.8 adds function closures."
371 :type 'integer
372 :group 'js2-mode)
373
374 (defcustom js2-allow-keywords-as-property-names t
375 "If non-nil, you can use JavaScript keywords as object property names.
376 Examples:
377
378 var foo = {int: 5, while: 6, continue: 7};
379 foo.return = 8;
380
381 Ecma-262 forbids this syntax, but many browsers support it."
382 :type 'boolean
383 :group 'js2-mode)
384
385 (defcustom js2-instanceof-has-side-effects nil
386 "If non-nil, treats the instanceof operator as having side effects.
387 This is useful for xulrunner apps."
388 :type 'boolean
389 :group 'js2-mode)
390
391 (defcustom js2-cleanup-whitespace nil
392 "Non-nil to invoke `delete-trailing-whitespace' before saves."
393 :type 'boolean
394 :group 'js2-mode)
395
396 (defcustom js2-move-point-on-right-click t
397 "Non-nil to move insertion point when you right-click.
398 This makes right-click context menu behavior a bit more intuitive,
399 since menu operations generally apply to the point. The exception
400 is if there is a region selection, in which case the point does -not-
401 move, so cut/copy/paste etc. can work properly.
402
403 Note that IntelliJ moves the point, and Eclipse leaves it alone,
404 so this behavior is customizable."
405 :group 'js2-mode
406 :type 'boolean)
407
408 (defcustom js2-allow-rhino-new-expr-initializer t
409 "Non-nil to support a Rhino's experimental syntactic construct.
410
411 Rhino supports the ability to follow a `new' expression with an object
412 literal, which is used to set additional properties on the new object
413 after calling its constructor. Syntax:
414
415 new <expr> [ ( arglist ) ] [initializer]
416
417 Hence, this expression:
418
419 new Object {a: 1, b: 2}
420
421 results in an Object with properties a=1 and b=2. This syntax is
422 apparently not configurable in Rhino - it's currently always enabled,
423 as of Rhino version 1.7R2."
424 :type 'boolean
425 :group 'js2-mode)
426
427 (defcustom js2-allow-member-expr-as-function-name nil
428 "Non-nil to support experimental Rhino syntax for function names.
429
430 Rhino supports an experimental syntax configured via the Rhino Context
431 setting `allowMemberExprAsFunctionName'. The experimental syntax is:
432
433 function <member-expr> ( [ arg-list ] ) { <body> }
434
435 Where member-expr is a non-parenthesized 'member expression', which
436 is anything at the grammar level of a new-expression or lower, meaning
437 any expression that does not involve infix or unary operators.
438
439 When <member-expr> is not a simple identifier, then it is syntactic
440 sugar for assigning the anonymous function to the <member-expr>. Hence,
441 this code:
442
443 function a.b().c[2] (x, y) { ... }
444
445 is rewritten as:
446
447 a.b().c[2] = function(x, y) {...}
448
449 which doesn't seem particularly useful, but Rhino permits it."
450 :type 'boolean
451 :group 'js2-mode)
452
453 (defvar js2-mode-version 20100402
454 "Release number for `js2-mode'.")
455
456 ;; scanner variables
457
458 (defmacro js2-deflocal (name value &optional comment)
459 "Define a buffer-local variable NAME with VALUE and COMMENT."
460 `(progn
461 (defvar ,name ,value ,comment)
462 (make-variable-buffer-local ',name)))
463
464 ;; We record the start and end position of each token.
465 (js2-deflocal js2-token-beg 1)
466 (js2-deflocal js2-token-end -1)
467
468 (defvar js2-EOF_CHAR -1
469 "Represents end of stream. Distinct from js2-EOF token type.")
470
471 ;; I originally used symbols to represent tokens, but Rhino uses
472 ;; ints and then sets various flag bits in them, so ints it is.
473 ;; The upshot is that we need a `js2-' prefix in front of each name.
474 (defvar js2-ERROR -1)
475 (defvar js2-EOF 0)
476 (defvar js2-EOL 1)
477 (defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
478 (defvar js2-LEAVEWITH 3)
479 (defvar js2-RETURN 4)
480 (defvar js2-GOTO 5)
481 (defvar js2-IFEQ 6)
482 (defvar js2-IFNE 7)
483 (defvar js2-SETNAME 8)
484 (defvar js2-BITOR 9)
485 (defvar js2-BITXOR 10)
486 (defvar js2-BITAND 11)
487 (defvar js2-EQ 12)
488 (defvar js2-NE 13)
489 (defvar js2-LT 14)
490 (defvar js2-LE 15)
491 (defvar js2-GT 16)
492 (defvar js2-GE 17)
493 (defvar js2-LSH 18)
494 (defvar js2-RSH 19)
495 (defvar js2-URSH 20)
496 (defvar js2-ADD 21) ; infix plus
497 (defvar js2-SUB 22) ; infix minus
498 (defvar js2-MUL 23)
499 (defvar js2-DIV 24)
500 (defvar js2-MOD 25)
501 (defvar js2-NOT 26)
502 (defvar js2-BITNOT 27)
503 (defvar js2-POS 28) ; unary plus
504 (defvar js2-NEG 29) ; unary minus
505 (defvar js2-NEW 30)
506 (defvar js2-DELPROP 31)
507 (defvar js2-TYPEOF 32)
508 (defvar js2-GETPROP 33)
509 (defvar js2-GETPROPNOWARN 34)
510 (defvar js2-SETPROP 35)
511 (defvar js2-GETELEM 36)
512 (defvar js2-SETELEM 37)
513 (defvar js2-CALL 38)
514 (defvar js2-NAME 39) ; an identifier
515 (defvar js2-NUMBER 40)
516 (defvar js2-STRING 41)
517 (defvar js2-NULL 42)
518 (defvar js2-THIS 43)
519 (defvar js2-FALSE 44)
520 (defvar js2-TRUE 45)
521 (defvar js2-SHEQ 46) ; shallow equality (===)
522 (defvar js2-SHNE 47) ; shallow inequality (!==)
523 (defvar js2-REGEXP 48)
524 (defvar js2-BINDNAME 49)
525 (defvar js2-THROW 50)
526 (defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
527 (defvar js2-IN 52)
528 (defvar js2-INSTANCEOF 53)
529 (defvar js2-LOCAL_LOAD 54)
530 (defvar js2-GETVAR 55)
531 (defvar js2-SETVAR 56)
532 (defvar js2-CATCH_SCOPE 57)
533 (defvar js2-ENUM_INIT_KEYS 58)
534 (defvar js2-ENUM_INIT_VALUES 59)
535 (defvar js2-ENUM_INIT_ARRAY 60)
536 (defvar js2-ENUM_NEXT 61)
537 (defvar js2-ENUM_ID 62)
538 (defvar js2-THISFN 63)
539 (defvar js2-RETURN_RESULT 64) ; to return previously stored return result
540 (defvar js2-ARRAYLIT 65) ; array literal
541 (defvar js2-OBJECTLIT 66) ; object literal
542 (defvar js2-GET_REF 67) ; *reference
543 (defvar js2-SET_REF 68) ; *reference = something
544 (defvar js2-DEL_REF 69) ; delete reference
545 (defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
546 (defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
547 (defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
548
549 ;; XML support
550 (defvar js2-DEFAULTNAMESPACE 73)
551 (defvar js2-ESCXMLATTR 74)
552 (defvar js2-ESCXMLTEXT 75)
553 (defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
554 (defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
555 (defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
556 (defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
557
558 (defvar js2-first-bytecode js2-ENTERWITH)
559 (defvar js2-last-bytecode js2-REF_NS_NAME)
560
561 (defvar js2-TRY 80)
562 (defvar js2-SEMI 81) ; semicolon
563 (defvar js2-LB 82) ; left and right brackets
564 (defvar js2-RB 83)
565 (defvar js2-LC 84) ; left and right curly-braces
566 (defvar js2-RC 85)
567 (defvar js2-LP 86) ; left and right parens
568 (defvar js2-RP 87)
569 (defvar js2-COMMA 88) ; comma operator
570
571 (defvar js2-ASSIGN 89) ; simple assignment (=)
572 (defvar js2-ASSIGN_BITOR 90) ; |=
573 (defvar js2-ASSIGN_BITXOR 91) ; ^=
574 (defvar js2-ASSIGN_BITAND 92) ; &=
575 (defvar js2-ASSIGN_LSH 93) ; <<=
576 (defvar js2-ASSIGN_RSH 94) ; >>=
577 (defvar js2-ASSIGN_URSH 95) ; >>>=
578 (defvar js2-ASSIGN_ADD 96) ; +=
579 (defvar js2-ASSIGN_SUB 97) ; -=
580 (defvar js2-ASSIGN_MUL 98) ; *=
581 (defvar js2-ASSIGN_DIV 99) ; /=
582 (defvar js2-ASSIGN_MOD 100) ; %=
583
584 (defvar js2-first-assign js2-ASSIGN)
585 (defvar js2-last-assign js2-ASSIGN_MOD)
586
587 (defvar js2-HOOK 101) ; conditional (?:)
588 (defvar js2-COLON 102)
589 (defvar js2-OR 103) ; logical or (||)
590 (defvar js2-AND 104) ; logical and (&&)
591 (defvar js2-INC 105) ; increment/decrement (++ --)
592 (defvar js2-DEC 106)
593 (defvar js2-DOT 107) ; member operator (.)
594 (defvar js2-FUNCTION 108) ; function keyword
595 (defvar js2-EXPORT 109) ; export keyword
596 (defvar js2-IMPORT 110) ; import keyword
597 (defvar js2-IF 111) ; if keyword
598 (defvar js2-ELSE 112) ; else keyword
599 (defvar js2-SWITCH 113) ; switch keyword
600 (defvar js2-CASE 114) ; case keyword
601 (defvar js2-DEFAULT 115) ; default keyword
602 (defvar js2-WHILE 116) ; while keyword
603 (defvar js2-DO 117) ; do keyword
604 (defvar js2-FOR 118) ; for keyword
605 (defvar js2-BREAK 119) ; break keyword
606 (defvar js2-CONTINUE 120) ; continue keyword
607 (defvar js2-VAR 121) ; var keyword
608 (defvar js2-WITH 122) ; with keyword
609 (defvar js2-CATCH 123) ; catch keyword
610 (defvar js2-FINALLY 124) ; finally keyword
611 (defvar js2-VOID 125) ; void keyword
612 (defvar js2-RESERVED 126) ; reserved keywords
613
614 (defvar js2-EMPTY 127)
615
616 ;; Types used for the parse tree - never returned by scanner.
617
618 (defvar js2-BLOCK 128) ; statement block
619 (defvar js2-LABEL 129) ; label
620 (defvar js2-TARGET 130)
621 (defvar js2-LOOP 131)
622 (defvar js2-EXPR_VOID 132) ; expression statement in functions
623 (defvar js2-EXPR_RESULT 133) ; expression statement in scripts
624 (defvar js2-JSR 134)
625 (defvar js2-SCRIPT 135) ; top-level node for entire script
626 (defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
627 (defvar js2-USE_STACK 137)
628 (defvar js2-SETPROP_OP 138) ; x.y op= something
629 (defvar js2-SETELEM_OP 139) ; x[y] op= something
630 (defvar js2-LOCAL_BLOCK 140)
631 (defvar js2-SET_REF_OP 141) ; *reference op= something
632
633 ;; For XML support:
634 (defvar js2-DOTDOT 142) ; member operator (..)
635 (defvar js2-COLONCOLON 143) ; namespace::name
636 (defvar js2-XML 144) ; XML type
637 (defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
638 (defvar js2-XMLATTR 146) ; @
639 (defvar js2-XMLEND 147)
640
641 ;; Optimizer-only tokens
642 (defvar js2-TO_OBJECT 148)
643 (defvar js2-TO_DOUBLE 149)
644
645 (defvar js2-GET 150) ; JS 1.5 get pseudo keyword
646 (defvar js2-SET 151) ; JS 1.5 set pseudo keyword
647 (defvar js2-LET 152) ; JS 1.7 let pseudo keyword
648 (defvar js2-CONST 153)
649 (defvar js2-SETCONST 154)
650 (defvar js2-SETCONSTVAR 155)
651 (defvar js2-ARRAYCOMP 156)
652 (defvar js2-LETEXPR 157)
653 (defvar js2-WITHEXPR 158)
654 (defvar js2-DEBUGGER 159)
655
656 (defvar js2-COMMENT 160)
657 (defvar js2-ENUM 161) ; for "enum" reserved word
658
659 (defconst js2-num-tokens (1+ js2-ENUM))
660
661 (defconst js2-debug-print-trees nil)
662
663 ;; Rhino accepts any string or stream as input. Emacs character
664 ;; processing works best in buffers, so we'll assume the input is a
665 ;; buffer. JavaScript strings can be copied into temp buffers before
666 ;; scanning them.
667
668 ;; Buffer-local variables yield much cleaner code than using `defstruct'.
669 ;; They're the Emacs equivalent of instance variables, more or less.
670
671 (js2-deflocal js2-ts-dirty-line nil
672 "Token stream buffer-local variable.
673 Indicates stuff other than whitespace since start of line.")
674
675 (js2-deflocal js2-ts-regexp-flags nil
676 "Token stream buffer-local variable.")
677
678 (js2-deflocal js2-ts-string ""
679 "Token stream buffer-local variable.
680 Last string scanned.")
681
682 (js2-deflocal js2-ts-number nil
683 "Token stream buffer-local variable.
684 Last literal number scanned.")
685
686 (js2-deflocal js2-ts-hit-eof nil
687 "Token stream buffer-local variable.")
688
689 (js2-deflocal js2-ts-line-start 0
690 "Token stream buffer-local variable.")
691
692 (js2-deflocal js2-ts-lineno 1
693 "Token stream buffer-local variable.")
694
695 (js2-deflocal js2-ts-line-end-char -1
696 "Token stream buffer-local variable.")
697
698 (js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
699 "Token stream buffer-local variable.
700 Current scan position.")
701
702 (js2-deflocal js2-ts-is-xml-attribute nil
703 "Token stream buffer-local variable.")
704
705 (js2-deflocal js2-ts-xml-is-tag-content nil
706 "Token stream buffer-local variable.")
707
708 (js2-deflocal js2-ts-xml-open-tags-count 0
709 "Token stream buffer-local variable.")
710
711 (js2-deflocal js2-ts-string-buffer nil
712 "Token stream buffer-local variable.
713 List of chars built up while scanning various tokens.")
714
715 (js2-deflocal js2-ts-comment-type nil
716 "Token stream buffer-local variable.")
717
718 ;;; Parser variables
719
720 (js2-deflocal js2-parsed-errors nil
721 "List of errors produced during scanning/parsing.")
722
723 (js2-deflocal js2-parsed-warnings nil
724 "List of warnings produced during scanning/parsing.")
725
726 (js2-deflocal js2-recover-from-parse-errors t
727 "Non-nil to continue parsing after a syntax error.
728
729 In recovery mode, the AST will be built in full, and any error
730 nodes will be flagged with appropriate error information. If
731 this flag is nil, a syntax error will result in an error being
732 signaled.
733
734 The variable is automatically buffer-local, because different
735 modes that use the parser will need different settings.")
736
737 (js2-deflocal js2-parse-hook nil
738 "List of callbacks for receiving parsing progress.")
739
740 (defvar js2-parse-finished-hook nil
741 "List of callbacks to notify when parsing finishes.
742 Not called if parsing was interrupted.")
743
744 (js2-deflocal js2-is-eval-code nil
745 "True if we're evaluating code in a string.
746 If non-nil, the tokenizer will record the token text, and the AST nodes
747 will record their source text. Off by default for IDE modes, since the
748 text is available in the buffer.")
749
750 (defvar js2-parse-ide-mode t
751 "Non-nil if the parser is being used for `js2-mode'.
752 If non-nil, the parser will set text properties for fontification
753 and the syntax table. The value should be nil when using the
754 parser as a frontend to an interpreter or byte compiler.")
755
756 ;;; Parser instance variables (buffer-local vars for js2-parse)
757
758 (defconst js2-clear-ti-mask #xFFFF
759 "Mask to clear token information bits.")
760
761 (defconst js2-ti-after-eol (lsh 1 16)
762 "Flag: first token of the source line.")
763
764 (defconst js2-ti-check-label (lsh 1 17)
765 "Flag: indicates to check for label.")
766
767 ;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
768
769 (js2-deflocal js2-compiler-generate-debug-info t)
770 (js2-deflocal js2-compiler-use-dynamic-scope nil)
771 (js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
772 (js2-deflocal js2-compiler-xml-available t)
773 (js2-deflocal js2-compiler-optimization-level 0)
774 (js2-deflocal js2-compiler-generating-source t)
775 (js2-deflocal js2-compiler-strict-mode nil)
776 (js2-deflocal js2-compiler-report-warning-as-error nil)
777 (js2-deflocal js2-compiler-generate-observer-count nil)
778 (js2-deflocal js2-compiler-activation-names nil)
779
780 ;; SKIP: sourceURI
781
782 ;; There's a compileFunction method in Context.java - may need it.
783 (js2-deflocal js2-called-by-compile-function nil
784 "True if `js2-parse' was called by `js2-compile-function'.
785 Will only be used when we finish implementing the interpreter.")
786
787 ;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
788
789 (js2-deflocal js2-current-flagged-token js2-EOF)
790 (js2-deflocal js2-current-token js2-EOF)
791
792 ;; SKIP: node factory - we're going to just call functions directly,
793 ;; and eventually go to a unified AST format.
794
795 (js2-deflocal js2-nesting-of-function 0)
796
797 (js2-deflocal js2-recorded-assignments nil
798 "Tracks assignments found during parsing.")
799
800 (defcustom js2-global-externs nil
801 "A list of any extern names you'd like to consider always declared.
802 This list is global and is used by all js2-mode files.
803 You can create buffer-local externs list using `js2-additional-externs'.
804
805 There is also a buffer-local variable `js2-default-externs',
806 which is initialized by default to include the Ecma-262 externs
807 and the standard browser externs. The three lists are all
808 checked during highlighting."
809 :type 'list
810 :group 'js2-mode)
811
812 (js2-deflocal js2-default-externs nil
813 "Default external declarations.
814
815 These are currently only used for highlighting undeclared variables,
816 which only worries about top-level (unqualified) references.
817 As js2-mode's processing improves, we will flesh out this list.
818
819 The initial value is set to `js2-ecma-262-externs', unless you
820 have set `js2-include-browser-externs', in which case the browser
821 externs are also included.
822
823 See `js2-additional-externs' for more information.")
824
825 (defcustom js2-include-browser-externs t
826 "Non-nil to include browser externs in the master externs list.
827 If you work on JavaScript files that are not intended for browsers,
828 such as Mozilla Rhino server-side JavaScript, set this to nil.
829 You can always include them on a per-file basis by calling
830 `js2-add-browser-externs' from a function on `js2-mode-hook'.
831
832 See `js2-additional-externs' for more information about externs."
833 :type 'boolean
834 :group 'js2-mode)
835
836 (defcustom js2-include-rhino-externs t
837 "Non-nil to include Mozilla Rhino externs in the master externs list.
838 See `js2-additional-externs' for more information about externs."
839 :type 'boolean
840 :group 'js2-mode)
841
842 (defcustom js2-include-gears-externs t
843 "Non-nil to include Google Gears externs in the master externs list.
844 See `js2-additional-externs' for more information about externs."
845 :type 'boolean
846 :group 'js2-mode)
847
848 (js2-deflocal js2-additional-externs nil
849 "A buffer-local list of additional external declarations.
850 It is used to decide whether variables are considered undeclared
851 for purposes of highlighting.
852
853 Each entry is a lisp string. The string should be the fully qualified
854 name of an external entity. All externs should be added to this list,
855 so that as js2-mode's processing improves it can take advantage of them.
856
857 You may want to declare your externs in three ways.
858 First, you can add externs that are valid for all your JavaScript files.
859 You should probably do this by adding them to `js2-global-externs', which
860 is a global list used for all js2-mode files.
861
862 Next, you can add a function to `js2-mode-hook' that adds additional
863 externs appropriate for the specific file, perhaps based on its path.
864 These should go in `js2-additional-externs', which is buffer-local.
865
866 Finally, you can add a function to `js2-post-parse-callbacks',
867 which is called after parsing completes, and `root' is bound to
868 the root of the parse tree. At this stage you can set up an AST
869 node visitor using `js2-visit-ast' and examine the parse tree
870 for specific import patterns that may imply the existence of
871 other externs, possibly tied to your build system. These should also
872 be added to `js2-additional-externs'.
873
874 Your post-parse callback may of course also use the simpler and
875 faster (but perhaps less robust) approach of simply scanning the
876 buffer text for your imports, using regular expressions.")
877
878 ;; SKIP: decompiler
879 ;; SKIP: encoded-source
880
881 ;;; The following variables are per-function and should be saved/restored
882 ;;; during function parsing...
883
884 (js2-deflocal js2-current-script-or-fn nil)
885 (js2-deflocal js2-current-scope nil)
886 (js2-deflocal js2-nesting-of-with 0)
887 (js2-deflocal js2-label-set nil
888 "An alist mapping label names to nodes.")
889
890 (js2-deflocal js2-loop-set nil)
891 (js2-deflocal js2-loop-and-switch-set nil)
892 (js2-deflocal js2-has-return-value nil)
893 (js2-deflocal js2-end-flags 0)
894
895 ;;; ...end of per function variables
896
897 ;; Without 2-token lookahead, labels are a problem.
898 ;; These vars store the token info of the last matched name,
899 ;; iff it wasn't the last matched token. Only valid in some contexts.
900 (defvar js2-prev-name-token-start nil)
901 (defvar js2-prev-name-token-string nil)
902
903 (defsubst js2-save-name-token-data (pos name)
904 (setq js2-prev-name-token-start pos
905 js2-prev-name-token-string name))
906
907 ;; These flags enumerate the possible ways a statement/function can
908 ;; terminate. These flags are used by endCheck() and by the Parser to
909 ;; detect inconsistent return usage.
910 ;;
911 ;; END_UNREACHED is reserved for code paths that are assumed to always be
912 ;; able to execute (example: throw, continue)
913 ;;
914 ;; END_DROPS_OFF indicates if the statement can transfer control to the
915 ;; next one. Statement such as return dont. A compound statement may have
916 ;; some branch that drops off control to the next statement.
917 ;;
918 ;; END_RETURNS indicates that the statement can return (without arguments)
919 ;; END_RETURNS_VALUE indicates that the statement can return a value.
920 ;;
921 ;; A compound statement such as
922 ;; if (condition) {
923 ;; return value;
924 ;; }
925 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
926
927 (defconst js2-end-unreached #x0)
928 (defconst js2-end-drops-off #x1)
929 (defconst js2-end-returns #x2)
930 (defconst js2-end-returns-value #x4)
931 (defconst js2-end-yields #x8)
932
933 ;; Rhino awkwardly passes a statementLabel parameter to the
934 ;; statementHelper() function, the main statement parser, which
935 ;; is then used by quite a few of the sub-parsers. We just make
936 ;; it a buffer-local variable and make sure it's cleaned up properly.
937 (js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
938
939 ;; Similarly, Rhino passes an inForInit boolean through about half
940 ;; the expression parsers. We use a dynamically-scoped variable,
941 ;; which makes it easier to funcall the parsers individually without
942 ;; worrying about whether they take the parameter or not.
943 (js2-deflocal js2-in-for-init nil)
944 (js2-deflocal js2-temp-name-counter 0)
945 (js2-deflocal js2-parse-stmt-count 0)
946
947 (defsubst js2-get-next-temp-name ()
948 (format "$%d" (incf js2-temp-name-counter)))
949
950 (defvar js2-parse-interruptable-p t
951 "Set this to nil to force parse to continue until finished.
952 This will mostly be useful for interpreters.")
953
954 (defvar js2-statements-per-pause 50
955 "Pause after this many statements to check for user input.
956 If user input is pending, stop the parse and discard the tree.
957 This makes for a smoother user experience for large files.
958 You may have to wait a second or two before the highlighting
959 and error-reporting appear, but you can always type ahead if
960 you wish. This appears to be more or less how Eclipse, IntelliJ
961 and other editors work.")
962
963 (js2-deflocal js2-record-comments t
964 "Instructs the scanner to record comments in `js2-scanned-comments'.")
965
966 (js2-deflocal js2-scanned-comments nil
967 "List of all comments from the current parse.")
968
969 (defcustom js2-mode-indent-inhibit-undo nil
970 "Non-nil to disable collection of Undo information when indenting lines.
971 Some users have requested this behavior. It's nil by default because
972 other Emacs modes don't work this way."
973 :type 'boolean
974 :group 'js2-mode)
975
976 (defcustom js2-mode-indent-ignore-first-tab nil
977 "If non-nil, ignore first TAB keypress if we look indented properly.
978 It's fairly common for users to navigate to an already-indented line
979 and press TAB for reassurance that it's been indented. For this class
980 of users, we want the first TAB press on a line to be ignored if the
981 line is already indented to one of the precomputed alternatives.
982
983 This behavior is only partly implemented. If you TAB-indent a line,
984 navigate to another line, and then navigate back, it fails to clear
985 the last-indented variable, so it thinks you've already hit TAB once,
986 and performs the indent. A full solution would involve getting on the
987 point-motion hooks for the entire buffer. If we come across another
988 use cases that requires watching point motion, I'll consider doing it.
989
990 If you set this variable to nil, then the TAB key will always change
991 the indentation of the current line, if more than one alternative
992 indentation spot exists."
993 :type 'boolean
994 :group 'js2-mode)
995
996 (defvar js2-indent-hook nil
997 "A hook for user-defined indentation rules.
998
999 Functions on this hook should expect two arguments: (LIST INDEX)
1000 The LIST argument is the list of computed indentation points for
1001 the current line. INDEX is the list index of the indentation point
1002 that `js2-bounce-indent' plans to use. If INDEX is nil, then the
1003 indent function is not going to change the current line indentation.
1004
1005 If a hook function on this list returns a non-nil value, then
1006 `js2-bounce-indent' assumes the hook function has performed its own
1007 indentation, and will do nothing. If all hook functions on the list
1008 return nil, then `js2-bounce-indent' will use its computed indentation
1009 and reindent the line.
1010
1011 When hook functions on this hook list are called, the variable
1012 `js2-mode-ast' may or may not be set, depending on whether the
1013 parse tree is available. If the variable is nil, you can pass a
1014 callback to `js2-mode-wait-for-parse', and your callback will be
1015 called after the new parse tree is built. This can take some time
1016 in large files.")
1017
1018 (defface js2-warning-face
1019 `((((class color) (background light))
1020 (:underline "orange"))
1021 (((class color) (background dark))
1022 (:underline "orange"))
1023 (t (:underline t)))
1024 "Face for JavaScript warnings."
1025 :group 'js2-mode)
1026
1027 (defface js2-error-face
1028 `((((class color) (background light))
1029 (:foreground "red"))
1030 (((class color) (background dark))
1031 (:foreground "red"))
1032 (t (:foreground "red")))
1033 "Face for JavaScript errors."
1034 :group 'js2-mode)
1035
1036 (defface js2-jsdoc-tag-face
1037 '((t :foreground "SlateGray"))
1038 "Face used to highlight @whatever tags in jsdoc comments."
1039 :group 'js2-mode)
1040
1041 (defface js2-jsdoc-type-face
1042 '((t :foreground "SteelBlue"))
1043 "Face used to highlight {FooBar} types in jsdoc comments."
1044 :group 'js2-mode)
1045
1046 (defface js2-jsdoc-value-face
1047 '((t :foreground "PeachPuff3"))
1048 "Face used to highlight tag values in jsdoc comments."
1049 :group 'js2-mode)
1050
1051 (defface js2-function-param-face
1052 '((t :foreground "SeaGreen"))
1053 "Face used to highlight function parameters in javascript."
1054 :group 'js2-mode)
1055
1056 (defface js2-instance-member-face
1057 '((t :foreground "DarkOrchid"))
1058 "Face used to highlight instance variables in javascript.
1059 Not currently used."
1060 :group 'js2-mode)
1061
1062 (defface js2-private-member-face
1063 '((t :foreground "PeachPuff3"))
1064 "Face used to highlight calls to private methods in javascript.
1065 Not currently used."
1066 :group 'js2-mode)
1067
1068 (defface js2-private-function-call-face
1069 '((t :foreground "goldenrod"))
1070 "Face used to highlight calls to private functions in javascript.
1071 Not currently used."
1072 :group 'js2-mode)
1073
1074 (defface js2-jsdoc-html-tag-name-face
1075 (if js2-emacs22
1076 '((((class color) (min-colors 88) (background light))
1077 (:foreground "rosybrown"))
1078 (((class color) (min-colors 8) (background dark))
1079 (:foreground "yellow"))
1080 (((class color) (min-colors 8) (background light))
1081 (:foreground "magenta")))
1082 '((((type tty pc) (class color) (background light))
1083 (:foreground "magenta"))
1084 (((type tty pc) (class color) (background dark))
1085 (:foreground "yellow"))
1086 (t (:foreground "RosyBrown"))))
1087 "Face used to highlight jsdoc html tag names"
1088 :group 'js2-mode)
1089
1090 (defface js2-jsdoc-html-tag-delimiter-face
1091 (if js2-emacs22
1092 '((((class color) (min-colors 88) (background light))
1093 (:foreground "dark khaki"))
1094 (((class color) (min-colors 8) (background dark))
1095 (:foreground "green"))
1096 (((class color) (min-colors 8) (background light))
1097 (:foreground "green")))
1098 '((((type tty pc) (class color) (background light))
1099 (:foreground "green"))
1100 (((type tty pc) (class color) (background dark))
1101 (:foreground "green"))
1102 (t (:foreground "dark khaki"))))
1103 "Face used to highlight brackets in jsdoc html tags."
1104 :group 'js2-mode)
1105
1106 (defface js2-magic-paren-face
1107 '((t :underline t))
1108 "Face used to color parens that will be auto-overwritten."
1109 :group 'js2-mode)
1110
1111 (defcustom js2-post-parse-callbacks nil
1112 "A list of callback functions invoked after parsing finishes.
1113 Currently, the main use for this function is to add synthetic
1114 declarations to `js2-recorded-assignments', which see."
1115 :type 'list
1116 :group 'js2-mode)
1117
1118 (defface js2-external-variable-face
1119 '((t :foreground "orange"))
1120 "Face used to highlight assignments to undeclared variables.
1121 An undeclared variable is any variable not declared with var or let
1122 in the current scope or any lexically enclosing scope. If you assign
1123 to such a variable, then you are either expecting it to originate from
1124 another file, or you've got a potential bug."
1125 :group 'js2-mode)
1126
1127 (defcustom js2-highlight-external-variables t
1128 "Non-nil to higlight assignments to undeclared variables."
1129 :type 'boolean
1130 :group 'js2-mode)
1131
1132 (defcustom js2-auto-insert-catch-block t
1133 "Non-nil to insert matching catch block on open-curly after `try'."
1134 :type 'boolean
1135 :group 'js2-mode)
1136
1137 (defvar js2-mode-map
1138 (let ((map (make-sparse-keymap))
1139 keys)
1140 (define-key map [mouse-1] #'js2-mode-show-node)
1141 (define-key map (kbd "C-m") #'js2-enter-key)
1142 (when js2-rebind-eol-bol-keys
1143 (define-key map (kbd "C-a") #'js2-beginning-of-line)
1144 (define-key map (kbd "C-e") #'js2-end-of-line))
1145 (define-key map (kbd "C-c C-e") #'js2-mode-hide-element)
1146 (define-key map (kbd "C-c C-s") #'js2-mode-show-element)
1147 (define-key map (kbd "C-c C-a") #'js2-mode-show-all)
1148 (define-key map (kbd "C-c C-f") #'js2-mode-toggle-hide-functions)
1149 (define-key map (kbd "C-c C-t") #'js2-mode-toggle-hide-comments)
1150 (define-key map (kbd "C-c C-o") #'js2-mode-toggle-element)
1151 (define-key map (kbd "C-c C-w") #'js2-mode-toggle-warnings-and-errors)
1152 (define-key map (kbd "C-c C-`") #'js2-next-error)
1153 ;; also define user's preference for next-error, if available
1154 (if (setq keys (where-is-internal #'next-error))
1155 (define-key map (car keys) #'js2-next-error))
1156 (define-key map (or (car (where-is-internal #'mark-defun))
1157 (kbd "M-C-h"))
1158 #'js2-mark-defun)
1159 (define-key map (or (car (where-is-internal #'narrow-to-defun))
1160 (kbd "C-x nd"))
1161 #'js2-narrow-to-defun)
1162 (define-key map [down-mouse-3] #'js2-down-mouse-3)
1163 (when js2-auto-indent-p
1164 (mapc (lambda (key)
1165 (define-key map key #'js2-insert-and-indent))
1166 js2-electric-keys))
1167
1168 (define-key map [menu-bar javascript]
1169 (cons "JavaScript" (make-sparse-keymap "JavaScript")))
1170
1171 (define-key map [menu-bar javascript customize-js2-mode]
1172 '(menu-item "Customize js2-mode" js2-mode-customize
1173 :help "Customize the behavior of this mode"))
1174
1175 (define-key map [menu-bar javascript js2-force-refresh]
1176 '(menu-item "Force buffer refresh" js2-mode-reset
1177 :help "Re-parse the buffer from scratch"))
1178
1179 (define-key map [menu-bar javascript separator-2]
1180 '("--"))
1181
1182 (define-key map [menu-bar javascript next-error]
1183 '(menu-item "Next warning or error" js2-next-error
1184 :enabled (and js2-mode-ast
1185 (or (js2-ast-root-errors js2-mode-ast)
1186 (js2-ast-root-warnings js2-mode-ast)))
1187 :help "Move to next warning or error"))
1188
1189 (define-key map [menu-bar javascript display-errors]
1190 '(menu-item "Show errors and warnings" js2-mode-display-warnings-and-errors
1191 :visible (not js2-mode-show-parse-errors)
1192 :help "Turn on display of warnings and errors"))
1193
1194 (define-key map [menu-bar javascript hide-errors]
1195 '(menu-item "Hide errors and warnings" js2-mode-hide-warnings-and-errors
1196 :visible js2-mode-show-parse-errors
1197 :help "Turn off display of warnings and errors"))
1198
1199 (define-key map [menu-bar javascript separator-1]
1200 '("--"))
1201
1202 (define-key map [menu-bar javascript js2-toggle-function]
1203 '(menu-item "Show/collapse element" js2-mode-toggle-element
1204 :help "Hide or show function body or comment"))
1205
1206 (define-key map [menu-bar javascript show-comments]
1207 '(menu-item "Show block comments" js2-mode-toggle-hide-comments
1208 :visible js2-mode-comments-hidden
1209 :help "Expand all hidden block comments"))
1210
1211 (define-key map [menu-bar javascript hide-comments]
1212 '(menu-item "Hide block comments" js2-mode-toggle-hide-comments
1213 :visible (not js2-mode-comments-hidden)
1214 :help "Show block comments as /*...*/"))
1215
1216 (define-key map [menu-bar javascript show-all-functions]
1217 '(menu-item "Show function bodies" js2-mode-toggle-hide-functions
1218 :visible js2-mode-functions-hidden
1219 :help "Expand all hidden function bodies"))
1220
1221 (define-key map [menu-bar javascript hide-all-functions]
1222 '(menu-item "Hide function bodies" js2-mode-toggle-hide-functions
1223 :visible (not js2-mode-functions-hidden)
1224 :help "Show {...} for all top-level function bodies"))
1225
1226 map)
1227 "Keymap used in `js2-mode' buffers.")
1228
1229 (defconst js2-mode-identifier-re "[a-zA-Z_$][a-zA-Z0-9_$]*")
1230
1231 (defvar js2-mode-//-comment-re "^\\(\\s-*\\)//.+"
1232 "Matches a //-comment line. Must be first non-whitespace on line.
1233 First match-group is the leading whitespace.")
1234
1235 (defvar js2-mode-hook nil)
1236
1237 (js2-deflocal js2-mode-ast nil "Private variable.")
1238 (js2-deflocal js2-mode-parse-timer nil "Private variable.")
1239 (js2-deflocal js2-mode-buffer-dirty-p nil "Private variable.")
1240 (js2-deflocal js2-mode-parsing nil "Private variable.")
1241 (js2-deflocal js2-mode-node-overlay nil)
1242
1243 (defvar js2-mode-show-overlay js2-mode-dev-mode-p
1244 "Debug: Non-nil to highlight AST nodes on mouse-down.")
1245
1246 (js2-deflocal js2-mode-fontifications nil "Private variable")
1247 (js2-deflocal js2-mode-deferred-properties nil "Private variable")
1248 (js2-deflocal js2-imenu-recorder nil "Private variable")
1249 (js2-deflocal js2-imenu-function-map nil "Private variable")
1250
1251 (defvar js2-paragraph-start
1252 "\\(@[a-zA-Z]+\\>\\|$\\)")
1253
1254 ;; Note that we also set a 'c-in-sws text property in html comments,
1255 ;; so that `c-forward-sws' and `c-backward-sws' work properly.
1256 (defvar js2-syntactic-ws-start
1257 "\\s \\|/[*/]\\|[\n\r]\\|\\\\[\n\r]\\|\\s!\\|<!--\\|^\\s-*-->")
1258
1259 (defvar js2-syntactic-ws-end
1260 "\\s \\|[\n\r/]\\|\\s!")
1261
1262 (defvar js2-syntactic-eol
1263 (concat "\\s *\\(/\\*[^*\n\r]*"
1264 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*"
1265 "\\*+/\\s *\\)*"
1266 "\\(//\\|/\\*[^*\n\r]*"
1267 "\\(\\*+[^*\n\r/][^*\n\r]*\\)*$"
1268 "\\|\\\\$\\|$\\)")
1269 "Copied from `java-mode'. Needed for some cc-engine functions.")
1270
1271 (defvar js2-comment-prefix-regexp
1272 "//+\\|\\**")
1273
1274 (defvar js2-comment-start-skip
1275 "\\(//+\\|/\\*+\\)\\s *")
1276
1277 (defvar js2-mode-verbose-parse-p js2-mode-dev-mode-p
1278 "Non-nil to emit status messages during parsing.")
1279
1280 (defvar js2-mode-functions-hidden nil "private variable")
1281 (defvar js2-mode-comments-hidden nil "private variable")
1282
1283 (defvar js2-mode-syntax-table
1284 (let ((table (make-syntax-table)))
1285 (c-populate-syntax-table table)
1286 table)
1287 "Syntax table used in js2-mode buffers.")
1288
1289 (defvar js2-mode-abbrev-table nil
1290 "Abbrev table in use in `js2-mode' buffers.")
1291 (define-abbrev-table 'js2-mode-abbrev-table ())
1292
1293 (defvar js2-mode-pending-parse-callbacks nil
1294 "List of functions waiting to be notified that parse is finished.")
1295
1296 (defvar js2-mode-last-indented-line -1)
1297
1298 ;;; Localizable error and warning messages
1299
1300 ;; Messages are copied from Rhino's Messages.properties.
1301 ;; Many of the Java-specific messages have been elided.
1302 ;; Add any js2-specific ones at the end, so we can keep
1303 ;; this file synced with changes to Rhino's.
1304
1305 (defvar js2-message-table
1306 (make-hash-table :test 'equal :size 250)
1307 "Contains localized messages for js2-mode.")
1308
1309 ;; TODO(stevey): construct this table at compile-time.
1310 (defmacro js2-msg (key &rest strings)
1311 `(puthash ,key (funcall #'concat ,@strings)
1312 js2-message-table))
1313
1314 (defun js2-get-msg (msg-key)
1315 "Look up a localized message.
1316 MSG-KEY is a list of (MSG ARGS). If the message takes parameters,
1317 the correct number of ARGS must be provided."
1318 (let* ((key (if (listp msg-key) (car msg-key) msg-key))
1319 (args (if (listp msg-key) (cdr msg-key)))
1320 (msg (gethash key js2-message-table)))
1321 (if msg
1322 (apply #'format msg args)
1323 key))) ; default to showing the key
1324
1325 (js2-msg "msg.dup.parms"
1326 "Duplicate parameter name '%s'.")
1327
1328 (js2-msg "msg.too.big.jump"
1329 "Program too complex: jump offset too big.")
1330
1331 (js2-msg "msg.too.big.index"
1332 "Program too complex: internal index exceeds 64K limit.")
1333
1334 (js2-msg "msg.while.compiling.fn"
1335 "Encountered code generation error while compiling function '%s': %s")
1336
1337 (js2-msg "msg.while.compiling.script"
1338 "Encountered code generation error while compiling script: %s")
1339
1340 ;; Context
1341 (js2-msg "msg.ctor.not.found"
1342 "Constructor for '%s' not found.")
1343
1344 (js2-msg "msg.not.ctor"
1345 "'%s' is not a constructor.")
1346
1347 ;; FunctionObject
1348 (js2-msg "msg.varargs.ctor"
1349 "Method or constructor '%s' must be static "
1350 "with the signature (Context cx, Object[] args, "
1351 "Function ctorObj, boolean inNewExpr) "
1352 "to define a variable arguments constructor.")
1353
1354 (js2-msg "msg.varargs.fun"
1355 "Method '%s' must be static with the signature "
1356 "(Context cx, Scriptable thisObj, Object[] args, Function funObj) "
1357 "to define a variable arguments function.")
1358
1359 (js2-msg "msg.incompat.call"
1360 "Method '%s' called on incompatible object.")
1361
1362 (js2-msg "msg.bad.parms"
1363 "Unsupported parameter type '%s' in method '%s'.")
1364
1365 (js2-msg "msg.bad.method.return"
1366 "Unsupported return type '%s' in method '%s'.")
1367
1368 (js2-msg "msg.bad.ctor.return"
1369 "Construction of objects of type '%s' is not supported.")
1370
1371 (js2-msg "msg.no.overload"
1372 "Method '%s' occurs multiple times in class '%s'.")
1373
1374 (js2-msg "msg.method.not.found"
1375 "Method '%s' not found in '%s'.")
1376
1377 ;; IRFactory
1378
1379 (js2-msg "msg.bad.for.in.lhs"
1380 "Invalid left-hand side of for..in loop.")
1381
1382 (js2-msg "msg.mult.index"
1383 "Only one variable allowed in for..in loop.")
1384
1385 (js2-msg "msg.bad.for.in.destruct"
1386 "Left hand side of for..in loop must be an array of "
1387 "length 2 to accept key/value pair.")
1388
1389 (js2-msg "msg.cant.convert"
1390 "Can't convert to type '%s'.")
1391
1392 (js2-msg "msg.bad.assign.left"
1393 "Invalid assignment left-hand side.")
1394
1395 (js2-msg "msg.bad.decr"
1396 "Invalid decerement operand.")
1397
1398 (js2-msg "msg.bad.incr"
1399 "Invalid increment operand.")
1400
1401 (js2-msg "msg.bad.yield"
1402 "yield must be in a function.")
1403
1404 (js2-msg "msg.yield.parenthesized"
1405 "yield expression must be parenthesized.")
1406
1407 ;; NativeGlobal
1408 (js2-msg "msg.cant.call.indirect"
1409 "Function '%s' must be called directly, and not by way of a "
1410 "function of another name.")
1411
1412 (js2-msg "msg.eval.nonstring"
1413 "Calling eval() with anything other than a primitive "
1414 "string value will simply return the value. "
1415 "Is this what you intended?")
1416
1417 (js2-msg "msg.eval.nonstring.strict"
1418 "Calling eval() with anything other than a primitive "
1419 "string value is not allowed in strict mode.")
1420
1421 (js2-msg "msg.bad.destruct.op"
1422 "Invalid destructuring assignment operator")
1423
1424 ;; NativeCall
1425 (js2-msg "msg.only.from.new"
1426 "'%s' may only be invoked from a `new' expression.")
1427
1428 (js2-msg "msg.deprec.ctor"
1429 "The '%s' constructor is deprecated.")
1430
1431 ;; NativeFunction
1432 (js2-msg "msg.no.function.ref.found"
1433 "no source found to decompile function reference %s")
1434
1435 (js2-msg "msg.arg.isnt.array"
1436 "second argument to Function.prototype.apply must be an array")
1437
1438 ;; NativeGlobal
1439 (js2-msg "msg.bad.esc.mask"
1440 "invalid string escape mask")
1441
1442 ;; NativeRegExp
1443 (js2-msg "msg.bad.quant"
1444 "Invalid quantifier %s")
1445
1446 (js2-msg "msg.overlarge.backref"
1447 "Overly large back reference %s")
1448
1449 (js2-msg "msg.overlarge.min"
1450 "Overly large minimum %s")
1451
1452 (js2-msg "msg.overlarge.max"
1453 "Overly large maximum %s")
1454
1455 (js2-msg "msg.zero.quant"
1456 "Zero quantifier %s")
1457
1458 (js2-msg "msg.max.lt.min"
1459 "Maximum %s less than minimum")
1460
1461 (js2-msg "msg.unterm.quant"
1462 "Unterminated quantifier %s")
1463
1464 (js2-msg "msg.unterm.paren"
1465 "Unterminated parenthetical %s")
1466
1467 (js2-msg "msg.unterm.class"
1468 "Unterminated character class %s")
1469
1470 (js2-msg "msg.bad.range"
1471 "Invalid range in character class.")
1472
1473 (js2-msg "msg.trail.backslash"
1474 "Trailing \\ in regular expression.")
1475
1476 (js2-msg "msg.re.unmatched.right.paren"
1477 "unmatched ) in regular expression.")
1478
1479 (js2-msg "msg.no.regexp"
1480 "Regular expressions are not available.")
1481
1482 (js2-msg "msg.bad.backref"
1483 "back-reference exceeds number of capturing parentheses.")
1484
1485 (js2-msg "msg.bad.regexp.compile"
1486 "Only one argument may be specified if the first "
1487 "argument to RegExp.prototype.compile is a RegExp object.")
1488
1489 ;; Parser
1490 (js2-msg "msg.got.syntax.errors"
1491 "Compilation produced %s syntax errors.")
1492
1493 (js2-msg "msg.var.redecl"
1494 "TypeError: redeclaration of var %s.")
1495
1496 (js2-msg "msg.const.redecl"
1497 "TypeError: redeclaration of const %s.")
1498
1499 (js2-msg "msg.let.redecl"
1500 "TypeError: redeclaration of variable %s.")
1501
1502 (js2-msg "msg.parm.redecl"
1503 "TypeError: redeclaration of formal parameter %s.")
1504
1505 (js2-msg "msg.fn.redecl"
1506 "TypeError: redeclaration of function %s.")
1507
1508 (js2-msg "msg.let.decl.not.in.block"
1509 "SyntaxError: let declaration not directly within block")
1510
1511 ;; NodeTransformer
1512 (js2-msg "msg.dup.label"
1513 "duplicated label")
1514
1515 (js2-msg "msg.undef.label"
1516 "undefined label")
1517
1518 (js2-msg "msg.bad.break"
1519 "unlabelled break must be inside loop or switch")
1520
1521 (js2-msg "msg.continue.outside"
1522 "continue must be inside loop")
1523
1524 (js2-msg "msg.continue.nonloop"
1525 "continue can only use labels of iteration statements")
1526
1527 (js2-msg "msg.bad.throw.eol"
1528 "Line terminator is not allowed between the throw "
1529 "keyword and throw expression.")
1530
1531 (js2-msg "msg.no.paren.parms"
1532 "missing ( before function parameters.")
1533
1534 (js2-msg "msg.no.parm"
1535 "missing formal parameter")
1536
1537 (js2-msg "msg.no.paren.after.parms"
1538 "missing ) after formal parameters")
1539
1540 (js2-msg "msg.no.brace.body"
1541 "missing '{' before function body")
1542
1543 (js2-msg "msg.no.brace.after.body"
1544 "missing } after function body")
1545
1546 (js2-msg "msg.no.paren.cond"
1547 "missing ( before condition")
1548
1549 (js2-msg "msg.no.paren.after.cond"
1550 "missing ) after condition")
1551
1552 (js2-msg "msg.no.semi.stmt"
1553 "missing ; before statement")
1554
1555 (js2-msg "msg.missing.semi"
1556 "missing ; after statement")
1557
1558 (js2-msg "msg.no.name.after.dot"
1559 "missing name after . operator")
1560
1561 (js2-msg "msg.no.name.after.coloncolon"
1562 "missing name after :: operator")
1563
1564 (js2-msg "msg.no.name.after.dotdot"
1565 "missing name after .. operator")
1566
1567 (js2-msg "msg.no.name.after.xmlAttr"
1568 "missing name after .@")
1569
1570 (js2-msg "msg.no.bracket.index"
1571 "missing ] in index expression")
1572
1573 (js2-msg "msg.no.paren.switch"
1574 "missing ( before switch expression")
1575
1576 (js2-msg "msg.no.paren.after.switch"
1577 "missing ) after switch expression")
1578
1579 (js2-msg "msg.no.brace.switch"
1580 "missing '{' before switch body")
1581
1582 (js2-msg "msg.bad.switch"
1583 "invalid switch statement")
1584
1585 (js2-msg "msg.no.colon.case"
1586 "missing : after case expression")
1587
1588 (js2-msg "msg.double.switch.default"
1589 "double default label in the switch statement")
1590
1591 (js2-msg "msg.no.while.do"
1592 "missing while after do-loop body")
1593
1594 (js2-msg "msg.no.paren.for"
1595 "missing ( after for")
1596
1597 (js2-msg "msg.no.semi.for"
1598 "missing ; after for-loop initializer")
1599
1600 (js2-msg "msg.no.semi.for.cond"
1601 "missing ; after for-loop condition")
1602
1603 (js2-msg "msg.in.after.for.name"
1604 "missing in after for")
1605
1606 (js2-msg "msg.no.paren.for.ctrl"
1607 "missing ) after for-loop control")
1608
1609 (js2-msg "msg.no.paren.with"
1610 "missing ( before with-statement object")
1611
1612 (js2-msg "msg.no.paren.after.with"
1613 "missing ) after with-statement object")
1614
1615 (js2-msg "msg.no.paren.after.let"
1616 "missing ( after let")
1617
1618 (js2-msg "msg.no.paren.let"
1619 "missing ) after variable list")
1620
1621 (js2-msg "msg.no.curly.let"
1622 "missing } after let statement")
1623
1624 (js2-msg "msg.bad.return"
1625 "invalid return")
1626
1627 (js2-msg "msg.no.brace.block"
1628 "missing } in compound statement")
1629
1630 (js2-msg "msg.bad.label"
1631 "invalid label")
1632
1633 (js2-msg "msg.bad.var"
1634 "missing variable name")
1635
1636 (js2-msg "msg.bad.var.init"
1637 "invalid variable initialization")
1638
1639 (js2-msg "msg.no.colon.cond"
1640 "missing : in conditional expression")
1641
1642 (js2-msg "msg.no.paren.arg"
1643 "missing ) after argument list")
1644
1645 (js2-msg "msg.no.bracket.arg"
1646 "missing ] after element list")
1647
1648 (js2-msg "msg.bad.prop"
1649 "invalid property id")
1650
1651 (js2-msg "msg.no.colon.prop"
1652 "missing : after property id")
1653
1654 (js2-msg "msg.no.brace.prop"
1655 "missing } after property list")
1656
1657 (js2-msg "msg.no.paren"
1658 "missing ) in parenthetical")
1659
1660 (js2-msg "msg.reserved.id"
1661 "identifier is a reserved word")
1662
1663 (js2-msg "msg.no.paren.catch"
1664 "missing ( before catch-block condition")
1665
1666 (js2-msg "msg.bad.catchcond"
1667 "invalid catch block condition")
1668
1669 (js2-msg "msg.catch.unreachable"
1670 "any catch clauses following an unqualified catch are unreachable")
1671
1672 (js2-msg "msg.no.brace.try"
1673 "missing '{' before try block")
1674
1675 (js2-msg "msg.no.brace.catchblock"
1676 "missing '{' before catch-block body")
1677
1678 (js2-msg "msg.try.no.catchfinally"
1679 "'try' without 'catch' or 'finally'")
1680
1681 (js2-msg "msg.no.return.value"
1682 "function %s does not always return a value")
1683
1684 (js2-msg "msg.anon.no.return.value"
1685 "anonymous function does not always return a value")
1686
1687 (js2-msg "msg.return.inconsistent"
1688 "return statement is inconsistent with previous usage")
1689
1690 (js2-msg "msg.generator.returns"
1691 "TypeError: generator function '%s' returns a value")
1692
1693 (js2-msg "msg.anon.generator.returns"
1694 "TypeError: anonymous generator function returns a value")
1695
1696 (js2-msg "msg.syntax"
1697 "syntax error")
1698
1699 (js2-msg "msg.unexpected.eof"
1700 "Unexpected end of file")
1701
1702 (js2-msg "msg.XML.bad.form"
1703 "illegally formed XML syntax")
1704
1705 (js2-msg "msg.XML.not.available"
1706 "XML runtime not available")
1707
1708 (js2-msg "msg.too.deep.parser.recursion"
1709 "Too deep recursion while parsing")
1710
1711 (js2-msg "msg.no.side.effects"
1712 "Code has no side effects")
1713
1714 (js2-msg "msg.extra.trailing.comma"
1715 "Trailing comma is not legal in an ECMA-262 object initializer")
1716
1717 (js2-msg "msg.array.trailing.comma"
1718 "Trailing comma yields different behavior across browsers")
1719
1720 (js2-msg "msg.equal.as.assign"
1721 (concat "Test for equality (==) mistyped as assignment (=)?"
1722 " (parenthesize to suppress warning)"))
1723
1724 (js2-msg "msg.var.hides.arg"
1725 "Variable %s hides argument")
1726
1727 (js2-msg "msg.destruct.assign.no.init"
1728 "Missing = in destructuring declaration")
1729
1730 ;; ScriptRuntime
1731 (js2-msg "msg.no.properties"
1732 "%s has no properties.")
1733
1734 (js2-msg "msg.invalid.iterator"
1735 "Invalid iterator value")
1736
1737 (js2-msg "msg.iterator.primitive"
1738 "__iterator__ returned a primitive value")
1739
1740 (js2-msg "msg.assn.create.strict"
1741 "Assignment to undeclared variable %s")
1742
1743 (js2-msg "msg.ref.undefined.prop"
1744 "Reference to undefined property '%s'")
1745
1746 (js2-msg "msg.prop.not.found"
1747 "Property %s not found.")
1748
1749 (js2-msg "msg.invalid.type"
1750 "Invalid JavaScript value of type %s")
1751
1752 (js2-msg "msg.primitive.expected"
1753 "Primitive type expected (had %s instead)")
1754
1755 (js2-msg "msg.namespace.expected"
1756 "Namespace object expected to left of :: (found %s instead)")
1757
1758 (js2-msg "msg.null.to.object"
1759 "Cannot convert null to an object.")
1760
1761 (js2-msg "msg.undef.to.object"
1762 "Cannot convert undefined to an object.")
1763
1764 (js2-msg "msg.cyclic.value"
1765 "Cyclic %s value not allowed.")
1766
1767 (js2-msg "msg.is.not.defined"
1768 "'%s' is not defined.")
1769
1770 (js2-msg "msg.undef.prop.read"
1771 "Cannot read property '%s' from %s")
1772
1773 (js2-msg "msg.undef.prop.write"
1774 "Cannot set property '%s' of %s to '%s'")
1775
1776 (js2-msg "msg.undef.prop.delete"
1777 "Cannot delete property '%s' of %s")
1778
1779 (js2-msg "msg.undef.method.call"
1780 "Cannot call method '%s' of %s")
1781
1782 (js2-msg "msg.undef.with"
1783 "Cannot apply 'with' to %s")
1784
1785 (js2-msg "msg.isnt.function"
1786 "%s is not a function, it is %s.")
1787
1788 (js2-msg "msg.isnt.function.in"
1789 "Cannot call property %s in object %s. "
1790 "It is not a function, it is '%s'.")
1791
1792 (js2-msg "msg.function.not.found"
1793 "Cannot find function %s.")
1794
1795 (js2-msg "msg.function.not.found.in"
1796 "Cannot find function %s in object %s.")
1797
1798 (js2-msg "msg.isnt.xml.object"
1799 "%s is not an xml object.")
1800
1801 (js2-msg "msg.no.ref.to.get"
1802 "%s is not a reference to read reference value.")
1803
1804 (js2-msg "msg.no.ref.to.set"
1805 "%s is not a reference to set reference value to %s.")
1806
1807 (js2-msg "msg.no.ref.from.function"
1808 "Function %s can not be used as the left-hand "
1809 "side of assignment or as an operand of ++ or -- operator.")
1810
1811 (js2-msg "msg.bad.default.value"
1812 "Object's getDefaultValue() method returned an object.")
1813
1814 (js2-msg "msg.instanceof.not.object"
1815 "Can't use instanceof on a non-object.")
1816
1817 (js2-msg "msg.instanceof.bad.prototype"
1818 "'prototype' property of %s is not an object.")
1819
1820 (js2-msg "msg.bad.radix"
1821 "illegal radix %s.")
1822
1823 ;; ScriptableObject
1824 (js2-msg "msg.default.value"
1825 "Cannot find default value for object.")
1826
1827 (js2-msg "msg.zero.arg.ctor"
1828 "Cannot load class '%s' which has no zero-parameter constructor.")
1829
1830 (js2-msg "msg.ctor.multiple.parms"
1831 "Can't define constructor or class %s since more than "
1832 "one constructor has multiple parameters.")
1833
1834 (js2-msg "msg.extend.scriptable"
1835 "%s must extend ScriptableObject in order to define property %s.")
1836
1837 (js2-msg "msg.bad.getter.parms"
1838 "In order to define a property, getter %s must have zero "
1839 "parameters or a single ScriptableObject parameter.")
1840
1841 (js2-msg "msg.obj.getter.parms"
1842 "Expected static or delegated getter %s to take "
1843 "a ScriptableObject parameter.")
1844
1845 (js2-msg "msg.getter.static"
1846 "Getter and setter must both be static or neither be static.")
1847
1848 (js2-msg "msg.setter.return"
1849 "Setter must have void return type: %s")
1850
1851 (js2-msg "msg.setter2.parms"
1852 "Two-parameter setter must take a ScriptableObject as "
1853 "its first parameter.")
1854
1855 (js2-msg "msg.setter1.parms"
1856 "Expected single parameter setter for %s")
1857
1858 (js2-msg "msg.setter2.expected"
1859 "Expected static or delegated setter %s to take two parameters.")
1860
1861 (js2-msg "msg.setter.parms"
1862 "Expected either one or two parameters for setter.")
1863
1864 (js2-msg "msg.setter.bad.type"
1865 "Unsupported parameter type '%s' in setter '%s'.")
1866
1867 (js2-msg "msg.add.sealed"
1868 "Cannot add a property to a sealed object: %s.")
1869
1870 (js2-msg "msg.remove.sealed"
1871 "Cannot remove a property from a sealed object: %s.")
1872
1873 (js2-msg "msg.modify.sealed"
1874 "Cannot modify a property of a sealed object: %s.")
1875
1876 (js2-msg "msg.modify.readonly"
1877 "Cannot modify readonly property: %s.")
1878
1879 ;; TokenStream
1880 (js2-msg "msg.missing.exponent"
1881 "missing exponent")
1882
1883 (js2-msg "msg.caught.nfe"
1884 "number format error")
1885
1886 (js2-msg "msg.unterminated.string.lit"
1887 "unterminated string literal")
1888
1889 (js2-msg "msg.unterminated.comment"
1890 "unterminated comment")
1891
1892 (js2-msg "msg.unterminated.re.lit"
1893 "unterminated regular expression literal")
1894
1895 (js2-msg "msg.invalid.re.flag"
1896 "invalid flag after regular expression")
1897
1898 (js2-msg "msg.no.re.input.for"
1899 "no input for %s")
1900
1901 (js2-msg "msg.illegal.character"
1902 "illegal character")
1903
1904 (js2-msg "msg.invalid.escape"
1905 "invalid Unicode escape sequence")
1906
1907 (js2-msg "msg.bad.namespace"
1908 "not a valid default namespace statement. "
1909 "Syntax is: default xml namespace = EXPRESSION;")
1910
1911 ;; TokensStream warnings
1912 (js2-msg "msg.bad.octal.literal"
1913 "illegal octal literal digit %s; "
1914 "interpreting it as a decimal digit")
1915
1916 (js2-msg "msg.reserved.keyword"
1917 "illegal usage of future reserved keyword %s; "
1918 "interpreting it as ordinary identifier")
1919
1920 (js2-msg "msg.script.is.not.constructor"
1921 "Script objects are not constructors.")
1922
1923 ;; Arrays
1924 (js2-msg "msg.arraylength.bad"
1925 "Inappropriate array length.")
1926
1927 ;; Arrays
1928 (js2-msg "msg.arraylength.too.big"
1929 "Array length %s exceeds supported capacity limit.")
1930
1931 ;; URI
1932 (js2-msg "msg.bad.uri"
1933 "Malformed URI sequence.")
1934
1935 ;; Number
1936 (js2-msg "msg.bad.precision"
1937 "Precision %s out of range.")
1938
1939 ;; NativeGenerator
1940 (js2-msg "msg.send.newborn"
1941 "Attempt to send value to newborn generator")
1942
1943 (js2-msg "msg.already.exec.gen"
1944 "Already executing generator")
1945
1946 (js2-msg "msg.StopIteration.invalid"
1947 "StopIteration may not be changed to an arbitrary object.")
1948
1949 ;; Interpreter
1950 (js2-msg "msg.yield.closing"
1951 "Yield from closing generator")
1952
1953 ;;; Utilities
1954
1955 (defun js2-delete-if (predicate list)
1956 "Remove all items satisfying PREDICATE in LIST."
1957 (loop for item in list
1958 if (not (funcall predicate item))
1959 collect item))
1960
1961 (defun js2-position (element list)
1962 "Find 0-indexed position of ELEMENT in LIST comparing with `eq'.
1963 Returns nil if element is not found in the list."
1964 (let ((count 0)
1965 found)
1966 (while (and list (not found))
1967 (if (eq element (car list))
1968 (setq found t)
1969 (setq count (1+ count)
1970 list (cdr list))))
1971 (if found count)))
1972
1973 (defun js2-find-if (predicate list)
1974 "Find first item satisfying PREDICATE in LIST."
1975 (let (result)
1976 (while (and list (not result))
1977 (if (funcall predicate (car list))
1978 (setq result (car list)))
1979 (setq list (cdr list)))
1980 result))
1981
1982 (defmacro js2-time (form)
1983 "Evaluate FORM, discard result, and return elapsed time in sec"
1984 (declare (debug t))
1985 (let ((beg (make-symbol "--js2-time-beg--"))
1986 (delta (make-symbol "--js2-time-end--")))
1987 `(let ((,beg (current-time))
1988 ,delta)
1989 ,form
1990 (/ (truncate (* (- (float-time (current-time))
1991 (float-time ,beg)))
1992 10000)
1993 10000.0))))
1994
1995 (defsubst js2-same-line (pos)
1996 "Return t if POS is on the same line as current point."
1997 (and (>= pos (point-at-bol))
1998 (<= pos (point-at-eol))))
1999
2000 (defsubst js2-same-line-2 (p1 p2)
2001 "Return t if p1 is on the same line as p2."
2002 (save-excursion
2003 (goto-char p1)
2004 (js2-same-line p2)))
2005
2006 (defun js2-code-bug ()
2007 "Signal an error when we encounter an unexpected code path."
2008 (error "failed assertion"))
2009
2010 ;; I'd like to associate errors with nodes, but for now the
2011 ;; easiest thing to do is get the context info from the last token.
2012 (defsubst js2-record-parse-error (msg &optional arg pos len)
2013 (push (list (list msg arg)
2014 (or pos js2-token-beg)
2015 (or len (- js2-token-end js2-token-beg)))
2016 js2-parsed-errors))
2017
2018 (defsubst js2-report-error (msg &optional msg-arg pos len)
2019 "Signal a syntax error or record a parse error."
2020 (if js2-recover-from-parse-errors
2021 (js2-record-parse-error msg msg-arg pos len)
2022 (signal 'js2-syntax-error
2023 (list msg
2024 js2-ts-lineno
2025 (save-excursion
2026 (goto-char js2-ts-cursor)
2027 (current-column))
2028 js2-ts-hit-eof))))
2029
2030 (defsubst js2-report-warning (msg &optional msg-arg pos len)
2031 (if js2-compiler-report-warning-as-error
2032 (js2-report-error msg msg-arg pos len)
2033 (push (list (list msg msg-arg)
2034 (or pos js2-token-beg)
2035 (or len (- js2-token-end js2-token-beg)))
2036 js2-parsed-warnings)))
2037
2038 (defsubst js2-add-strict-warning (msg-id &optional msg-arg beg end)
2039 (if js2-compiler-strict-mode
2040 (js2-report-warning msg-id msg-arg beg
2041 (and beg end (- end beg)))))
2042
2043 (put 'js2-syntax-error 'error-conditions
2044 '(error syntax-error js2-syntax-error))
2045 (put 'js2-syntax-error 'error-message "Syntax error")
2046
2047 (put 'js2-parse-error 'error-conditions
2048 '(error parse-error js2-parse-error))
2049 (put 'js2-parse-error 'error-message "Parse error")
2050
2051 (defmacro js2-clear-flag (flags flag)
2052 `(setq ,flags (logand ,flags (lognot ,flag))))
2053
2054 (defmacro js2-set-flag (flags flag)
2055 "Logical-or FLAG into FLAGS."
2056 `(setq ,flags (logior ,flags ,flag)))
2057
2058 (defsubst js2-flag-set-p (flags flag)
2059 (/= 0 (logand flags flag)))
2060
2061 (defsubst js2-flag-not-set-p (flags flag)
2062 (zerop (logand flags flag)))
2063
2064 ;; Stolen shamelessly from James Clark's nxml-mode.
2065 (defmacro js2-with-unmodifying-text-property-changes (&rest body)
2066 "Evaluate BODY without any text property changes modifying the buffer.
2067 Any text properties changes happen as usual but the changes are not treated as
2068 modifications to the buffer."
2069 (declare (indent 0) (debug t))
2070 (let ((modified (make-symbol "modified")))
2071 `(let ((,modified (buffer-modified-p))
2072 (inhibit-read-only t)
2073 (inhibit-modification-hooks t)
2074 (buffer-undo-list t)
2075 (deactivate-mark nil)
2076 ;; Apparently these avoid file locking problems.
2077 (buffer-file-name nil)
2078 (buffer-file-truename nil))
2079 (unwind-protect
2080 (progn ,@body)
2081 (unless ,modified
2082 (restore-buffer-modified-p nil))))))
2083
2084 (defmacro js2-with-underscore-as-word-syntax (&rest body)
2085 "Evaluate BODY with the _ character set to be word-syntax."
2086 (declare (indent 0) (debug t))
2087 (let ((old-syntax (make-symbol "old-syntax")))
2088 `(let ((,old-syntax (string (char-syntax ?_))))
2089 (unwind-protect
2090 (progn
2091 (modify-syntax-entry ?_ "w" js2-mode-syntax-table)
2092 ,@body)
2093 (modify-syntax-entry ?_ ,old-syntax js2-mode-syntax-table)))))
2094
2095 (defsubst js2-char-uppercase-p (c)
2096 "Return t if C is an uppercase character.
2097 Handles unicode and latin chars properly."
2098 (/= c (downcase c)))
2099
2100 (defsubst js2-char-lowercase-p (c)
2101 "Return t if C is an uppercase character.
2102 Handles unicode and latin chars properly."
2103 (/= c (upcase c)))
2104
2105 ;;; AST struct and function definitions
2106
2107 ;; flags for ast node property 'member-type (used for e4x operators)
2108 (defvar js2-property-flag #x1 "property access: element is valid name")
2109 (defvar js2-attribute-flag #x2 "x.@y or x..@y")
2110 (defvar js2-descendants-flag #x4 "x..y or x..@i")
2111
2112 (defsubst js2-relpos (pos anchor)
2113 "Convert POS to be relative to ANCHOR.
2114 If POS is nil, returns nil."
2115 (and pos (- pos anchor)))
2116
2117 (defsubst js2-make-pad (indent)
2118 (if (zerop indent)
2119 ""
2120 (make-string (* indent js2-basic-offset) ? )))
2121
2122 (defsubst js2-visit-ast (node callback)
2123 "Visit every node in ast NODE with visitor CALLBACK.
2124
2125 CALLBACK is a function that takes two arguments: (NODE END-P). It is
2126 called twice: once to visit the node, and again after all the node's
2127 children have been processed. The END-P argument is nil on the first
2128 call and non-nil on the second call. The return value of the callback
2129 affects the traversal: if non-nil, the children of NODE are processed.
2130 If the callback returns nil, or if the node has no children, then the
2131 callback is called immediately with a non-nil END-P argument.
2132
2133 The node traversal is approximately lexical-order, although there
2134 are currently no guarantees around this."
2135 (let ((vfunc (get (aref node 0) 'js2-visitor)))
2136 ;; visit the node
2137 (when (funcall callback node nil)
2138 ;; visit the kids
2139 (cond
2140 ((eq vfunc 'js2-visit-none)
2141 nil) ; don't even bother calling it
2142 ;; Each AST node type has to define a `js2-visitor' function
2143 ;; that takes a node and a callback, and calls `js2-visit-ast'
2144 ;; on each child of the node.
2145 (vfunc
2146 (funcall vfunc node callback))
2147 (t
2148 (error "%s does not define a visitor-traversal function"
2149 (aref node 0)))))
2150 ;; call the end-visit
2151 (funcall callback node t)))
2152
2153 (defstruct (js2-node
2154 (:constructor nil)) ; abstract
2155 "Base AST node type."
2156 (type -1) ; token type
2157 (pos -1) ; start position of this AST node in parsed input
2158 (len 1) ; num characters spanned by the node
2159 props ; optional node property list (an alist)
2160 parent) ; link to parent node; null for root
2161
2162 (defsubst js2-node-get-prop (node prop &optional default)
2163 (or (cadr (assoc prop (js2-node-props node))) default))
2164
2165 (defsubst js2-node-set-prop (node prop value)
2166 (setf (js2-node-props node)
2167 (cons (list prop value) (js2-node-props node))))
2168
2169 (defsubst js2-fixup-starts (n nodes)
2170 "Adjust the start positions of NODES to be relative to N.
2171 Any node in the list may be nil, for convenience."
2172 (dolist (node nodes)
2173 (when node
2174 (setf (js2-node-pos node) (- (js2-node-pos node)
2175 (js2-node-pos n))))))
2176
2177 (defsubst js2-node-add-children (parent &rest nodes)
2178 "Set parent node of NODES to PARENT, and return PARENT.
2179 Does nothing if we're not recording parent links.
2180 If any given node in NODES is nil, doesn't record that link."
2181 (js2-fixup-starts parent nodes)
2182 (dolist (node nodes)
2183 (and node
2184 (setf (js2-node-parent node) parent))))
2185
2186 ;; Non-recursive since it's called a frightening number of times.
2187 (defsubst js2-node-abs-pos (n)
2188 (let ((pos (js2-node-pos n)))
2189 (while (setq n (js2-node-parent n))
2190 (setq pos (+ pos (js2-node-pos n))))
2191 pos))
2192
2193 (defsubst js2-node-abs-end (n)
2194 "Return absolute buffer position of end of N."
2195 (+ (js2-node-abs-pos n) (js2-node-len n)))
2196
2197 ;; It's important to make sure block nodes have a lisp list for the
2198 ;; child nodes, to limit printing recursion depth in an AST that
2199 ;; otherwise consists of defstruct vectors. Emacs will crash printing
2200 ;; a sufficiently large vector tree.
2201
2202 (defstruct (js2-block-node
2203 (:include js2-node)
2204 (:constructor nil)
2205 (:constructor make-js2-block-node (&key (type js2-BLOCK)
2206 (pos js2-token-beg)
2207 len
2208 props
2209 kids)))
2210 "A block of statements."
2211 kids) ; a lisp list of the child statement nodes
2212
2213 (put 'cl-struct-js2-block-node 'js2-visitor 'js2-visit-block)
2214 (put 'cl-struct-js2-block-node 'js2-printer 'js2-print-block)
2215
2216 (defsubst js2-visit-block (ast callback)
2217 "Visit the `js2-block-node' children of AST."
2218 (dolist (kid (js2-block-node-kids ast))
2219 (js2-visit-ast kid callback)))
2220
2221 (defun js2-print-block (n i)
2222 (let ((pad (js2-make-pad i)))
2223 (insert pad "{\n")
2224 (dolist (kid (js2-block-node-kids n))
2225 (js2-print-ast kid (1+ i)))
2226 (insert pad "}")))
2227
2228 (defstruct (js2-scope
2229 (:include js2-block-node)
2230 (:constructor nil)
2231 (:constructor make-js2-scope (&key (type js2-BLOCK)
2232 (pos js2-token-beg)
2233 len
2234 kids)))
2235 ;; The symbol-table is a LinkedHashMap<String,Symbol> in Rhino.
2236 ;; I don't have one of those handy, so I'll use an alist for now.
2237 ;; It's as fast as an emacs hashtable for up to about 50 elements,
2238 ;; and is much lighter-weight to construct (both CPU and mem).
2239 ;; The keys are interned strings (symbols) for faster lookup.
2240 ;; Should switch to hybrid alist/hashtable eventually.
2241 symbol-table ; an alist of (symbol . js2-symbol)
2242 parent-scope ; a `js2-scope'
2243 top) ; top-level `js2-scope' (script/function)
2244
2245 (put 'cl-struct-js2-scope 'js2-visitor 'js2-visit-block)
2246 (put 'cl-struct-js2-scope 'js2-printer 'js2-print-none)
2247
2248 (defun js2-scope-set-parent-scope (scope parent)
2249 (setf (js2-scope-parent-scope scope) parent
2250 (js2-scope-top scope) (if (null parent)
2251 scope
2252 (js2-scope-top parent))))
2253
2254 (defun js2-node-get-enclosing-scope (node)
2255 "Return the innermost `js2-scope' node surrounding NODE.
2256 Returns nil if there is no enclosing scope node."
2257 (let ((parent (js2-node-parent node)))
2258 (while (not (js2-scope-p parent))
2259 (setq parent (js2-node-parent parent)))
2260 parent))
2261
2262 (defun js2-get-defining-scope (scope name)
2263 "Search up scope chain from SCOPE looking for NAME, a string or symbol.
2264 Returns `js2-scope' in which NAME is defined, or nil if not found."
2265 (let ((sym (if (symbolp name)
2266 name
2267 (intern name)))
2268 table
2269 result
2270 (continue t))
2271 (while (and scope continue)
2272 (if (and (setq table (js2-scope-symbol-table scope))
2273 (assq sym table))
2274 (setq continue nil
2275 result scope)
2276 (setq scope (js2-scope-parent-scope scope))))
2277 result))
2278
2279 (defsubst js2-scope-get-symbol (scope name)
2280 "Return symbol table entry for NAME in SCOPE.
2281 NAME can be a string or symbol. Returns a `js2-symbol' or nil if not found."
2282 (and (js2-scope-symbol-table scope)
2283 (cdr (assq (if (symbolp name)
2284 name
2285 (intern name))
2286 (js2-scope-symbol-table scope)))))
2287
2288 (defsubst js2-scope-put-symbol (scope name symbol)
2289 "Enter SYMBOL into symbol-table for SCOPE under NAME.
2290 NAME can be a lisp symbol or string. SYMBOL is a `js2-symbol'."
2291 (let* ((table (js2-scope-symbol-table scope))
2292 (sym (if (symbolp name) name (intern name)))
2293 (entry (assq sym table)))
2294 (if entry
2295 (setcdr entry symbol)
2296 (push (cons sym symbol)
2297 (js2-scope-symbol-table scope)))))
2298
2299 (defstruct (js2-symbol
2300 (:constructor nil)
2301 (:constructor make-js2-symbol (decl-type name &optional ast-node)))
2302 "A symbol table entry."
2303 ;; One of js2-FUNCTION, js2-LP (for parameters), js2-VAR,
2304 ;; js2-LET, or js2-CONST
2305 decl-type
2306 name ; string
2307 ast-node) ; a `js2-node'
2308
2309 (defstruct (js2-error-node
2310 (:include js2-node)
2311 (:constructor nil) ; silence emacs21 byte-compiler
2312 (:constructor make-js2-error-node (&key (type js2-ERROR)
2313 (pos js2-token-beg)
2314 len)))
2315 "AST node representing a parse error.")
2316
2317 (put 'cl-struct-js2-error-node 'js2-visitor 'js2-visit-none)
2318 (put 'cl-struct-js2-error-node 'js2-printer 'js2-print-none)
2319
2320 (defstruct (js2-script-node
2321 (:include js2-scope)
2322 (:constructor nil)
2323 (:constructor make-js2-script-node (&key (type js2-SCRIPT)
2324 (pos js2-token-beg)
2325 len
2326 var-decls
2327 fun-decls)))
2328 functions ; lisp list of nested functions
2329 regexps ; lisp list of (string . flags)
2330 symbols ; alist (every symbol gets unique index)
2331 (param-count 0)
2332 var-names ; vector of string names
2333 consts ; bool-vector matching var-decls
2334 (temp-number 0)) ; for generating temp variables
2335
2336 (put 'cl-struct-js2-script-node 'js2-visitor 'js2-visit-block)
2337 (put 'cl-struct-js2-script-node 'js2-printer 'js2-print-script)
2338
2339 (defun js2-print-script (node indent)
2340 (dolist (kid (js2-block-node-kids node))
2341 (js2-print-ast kid indent)))
2342
2343 (defstruct (js2-ast-root
2344 (:include js2-script-node)
2345 (:constructor nil)
2346 (:constructor make-js2-ast-root (&key (type js2-SCRIPT)
2347 (pos js2-token-beg)
2348 len
2349 buffer)))
2350 "The root node of a js2 AST."
2351 buffer ; the source buffer from which the code was parsed
2352 comments ; a lisp list of comments, ordered by start position
2353 errors ; a lisp list of errors found during parsing
2354 warnings ; a lisp list of warnings found during parsing
2355 node-count) ; number of nodes in the tree, including the root
2356
2357 (put 'cl-struct-js2-ast-root 'js2-visitor 'js2-visit-ast-root)
2358 (put 'cl-struct-js2-ast-root 'js2-printer 'js2-print-script)
2359
2360 (defun js2-visit-ast-root (ast callback)
2361 (dolist (kid (js2-ast-root-kids ast))
2362 (js2-visit-ast kid callback))
2363 (dolist (comment (js2-ast-root-comments ast))
2364 (js2-visit-ast comment callback)))
2365
2366 (defstruct (js2-comment-node
2367 (:include js2-node)
2368 (:constructor nil)
2369 (:constructor make-js2-comment-node (&key (type js2-COMMENT)
2370 (pos js2-token-beg)
2371 len
2372 (format js2-ts-comment-type))))
2373 format) ; 'line, 'block, 'jsdoc or 'html
2374
2375 (put 'cl-struct-js2-comment-node 'js2-visitor 'js2-visit-none)
2376 (put 'cl-struct-js2-comment-node 'js2-printer 'js2-print-comment)
2377
2378 (defun js2-print-comment (n i)
2379 ;; We really ought to link end-of-line comments to their nodes.
2380 ;; Or maybe we could add a new comment type, 'endline.
2381 (insert (js2-make-pad i)
2382 (js2-node-string n)))
2383
2384 (defstruct (js2-expr-stmt-node
2385 (:include js2-node)
2386 (:constructor nil)
2387 (:constructor make-js2-expr-stmt-node (&key (type js2-EXPR_VOID)
2388 (pos js2-ts-cursor)
2389 len
2390 expr)))
2391 "An expression statement."
2392 expr)
2393
2394 (defsubst js2-expr-stmt-node-set-has-result (node)
2395 "Change the node type to `js2-EXPR_RESULT'. Used for code generation."
2396 (setf (js2-node-type node) js2-EXPR_RESULT))
2397
2398 (put 'cl-struct-js2-expr-stmt-node 'js2-visitor 'js2-visit-expr-stmt-node)
2399 (put 'cl-struct-js2-expr-stmt-node 'js2-printer 'js2-print-expr-stmt-node)
2400
2401 (defun js2-visit-expr-stmt-node (n v)
2402 (js2-visit-ast (js2-expr-stmt-node-expr n) v))
2403
2404 (defun js2-print-expr-stmt-node (n indent)
2405 (js2-print-ast (js2-expr-stmt-node-expr n) indent)
2406 (insert ";\n"))
2407
2408 (defstruct (js2-loop-node
2409 (:include js2-scope)
2410 (:constructor nil))
2411 "Abstract supertype of loop nodes."
2412 body ; a `js2-block-node'
2413 lp ; position of left-paren, nil if omitted
2414 rp) ; position of right-paren, nil if omitted
2415
2416 (defstruct (js2-do-node
2417 (:include js2-loop-node)
2418 (:constructor nil)
2419 (:constructor make-js2-do-node (&key (type js2-DO)
2420 (pos js2-token-beg)
2421 len
2422 body
2423 condition
2424 while-pos
2425 lp
2426 rp)))
2427 "AST node for do-loop."
2428 condition ; while (expression)
2429 while-pos) ; buffer position of 'while' keyword
2430
2431 (put 'cl-struct-js2-do-node 'js2-visitor 'js2-visit-do-node)
2432 (put 'cl-struct-js2-do-node 'js2-printer 'js2-print-do-node)
2433
2434 (defun js2-visit-do-node (n v)
2435 (js2-visit-ast (js2-do-node-body n) v)
2436 (js2-visit-ast (js2-do-node-condition n) v))
2437
2438 (defun js2-print-do-node (n i)
2439 (let ((pad (js2-make-pad i)))
2440 (insert pad "do {\n")
2441 (dolist (kid (js2-block-node-kids (js2-do-node-body n)))
2442 (js2-print-ast kid (1+ i)))
2443 (insert pad "} while (")
2444 (js2-print-ast (js2-do-node-condition n) 0)
2445 (insert ");\n")))
2446
2447 (defstruct (js2-while-node
2448 (:include js2-loop-node)
2449 (:constructor nil)
2450 (:constructor make-js2-while-node (&key (type js2-WHILE)
2451 (pos js2-token-beg)
2452 len
2453 body
2454 condition
2455 lp
2456 rp)))
2457 "AST node for while-loop."
2458 condition) ; while-condition
2459
2460 (put 'cl-struct-js2-while-node 'js2-visitor 'js2-visit-while-node)
2461 (put 'cl-struct-js2-while-node 'js2-printer 'js2-print-while-node)
2462
2463 (defun js2-visit-while-node (n v)
2464 (js2-visit-ast (js2-while-node-condition n) v)
2465 (js2-visit-ast (js2-while-node-body n) v))
2466
2467 (defun js2-print-while-node (n i)
2468 (let ((pad (js2-make-pad i)))
2469 (insert pad "while (")
2470 (js2-print-ast (js2-while-node-condition n) 0)
2471 (insert ") {\n")
2472 (js2-print-body (js2-while-node-body n) (1+ i))
2473 (insert pad "}\n")))
2474
2475 (defstruct (js2-for-node
2476 (:include js2-loop-node)
2477 (:constructor nil)
2478 (:constructor make-js2-for-node (&key (type js2-FOR)
2479 (pos js2-ts-cursor)
2480 len
2481 body
2482 init
2483 condition
2484 update
2485 lp
2486 rp)))
2487 "AST node for a C-style for-loop."
2488 init ; initialization expression
2489 condition ; loop condition
2490 update) ; update clause
2491
2492 (put 'cl-struct-js2-for-node 'js2-visitor 'js2-visit-for-node)
2493 (put 'cl-struct-js2-for-node 'js2-printer 'js2-print-for-node)
2494
2495 (defun js2-visit-for-node (n v)
2496 (js2-visit-ast (js2-for-node-init n) v)
2497 (js2-visit-ast (js2-for-node-condition n) v)
2498 (js2-visit-ast (js2-for-node-update n) v)
2499 (js2-visit-ast (js2-for-node-body n) v))
2500
2501 (defun js2-print-for-node (n i)
2502 (let ((pad (js2-make-pad i)))
2503 (insert pad "for (")
2504 (js2-print-ast (js2-for-node-init n) 0)
2505 (insert "; ")
2506 (js2-print-ast (js2-for-node-condition n) 0)
2507 (insert "; ")
2508 (js2-print-ast (js2-for-node-update n) 0)
2509 (insert ") {\n")
2510 (js2-print-body (js2-for-node-body n) (1+ i))
2511 (insert pad "}\n")))
2512
2513 (defstruct (js2-for-in-node
2514 (:include js2-loop-node)
2515 (:constructor nil)
2516 (:constructor make-js2-for-in-node (&key (type js2-FOR)
2517 (pos js2-ts-cursor)
2518 len
2519 body
2520 iterator
2521 object
2522 in-pos
2523 each-pos
2524 foreach-p
2525 lp
2526 rp)))
2527 "AST node for a for..in loop."
2528 iterator ; [var] foo in ...
2529 object ; object over which we're iterating
2530 in-pos ; buffer position of 'in' keyword
2531 each-pos ; buffer position of 'each' keyword, if foreach-p
2532 foreach-p) ; t if it's a for-each loop
2533
2534 (put 'cl-struct-js2-for-in-node 'js2-visitor 'js2-visit-for-in-node)
2535 (put 'cl-struct-js2-for-in-node 'js2-printer 'js2-print-for-in-node)
2536
2537 (defun js2-visit-for-in-node (n v)
2538 (js2-visit-ast (js2-for-in-node-iterator n) v)
2539 (js2-visit-ast (js2-for-in-node-object n) v)
2540 (js2-visit-ast (js2-for-in-node-body n) v))
2541
2542 (defun js2-print-for-in-node (n i)
2543 (let ((pad (js2-make-pad i))
2544 (foreach (js2-for-in-node-foreach-p n)))
2545 (insert pad "for ")
2546 (if foreach
2547 (insert "each "))
2548 (insert "(")
2549 (js2-print-ast (js2-for-in-node-iterator n) 0)
2550 (insert " in ")
2551 (js2-print-ast (js2-for-in-node-object n) 0)
2552 (insert ") {\n")
2553 (js2-print-body (js2-for-in-node-body n) (1+ i))
2554 (insert pad "}\n")))
2555
2556 (defstruct (js2-return-node
2557 (:include js2-node)
2558 (:constructor nil)
2559 (:constructor make-js2-return-node (&key (type js2-RETURN)
2560 (pos js2-ts-cursor)
2561 len
2562 retval)))
2563 "AST node for a return statement."
2564 retval) ; expression to return, or 'undefined
2565
2566 (put 'cl-struct-js2-return-node 'js2-visitor 'js2-visit-return-node)
2567 (put 'cl-struct-js2-return-node 'js2-printer 'js2-print-return-node)
2568
2569 (defun js2-visit-return-node (n v)
2570 (if (js2-return-node-retval n)
2571 (js2-visit-ast (js2-return-node-retval n) v)))
2572
2573 (defun js2-print-return-node (n i)
2574 (insert (js2-make-pad i) "return")
2575 (when (js2-return-node-retval n)
2576 (insert " ")
2577 (js2-print-ast (js2-return-node-retval n) 0))
2578 (insert ";\n"))
2579
2580 (defstruct (js2-if-node
2581 (:include js2-node)
2582 (:constructor nil)
2583 (:constructor make-js2-if-node (&key (type js2-IF)
2584 (pos js2-ts-cursor)
2585 len
2586 condition
2587 then-part
2588 else-pos
2589 else-part
2590 lp
2591 rp)))
2592 "AST node for an if-statement."
2593 condition ; expression
2594 then-part ; statement or block
2595 else-pos ; optional buffer position of 'else' keyword
2596 else-part ; optional statement or block
2597 lp ; position of left-paren, nil if omitted
2598 rp) ; position of right-paren, nil if omitted
2599
2600 (put 'cl-struct-js2-if-node 'js2-visitor 'js2-visit-if-node)
2601 (put 'cl-struct-js2-if-node 'js2-printer 'js2-print-if-node)
2602
2603 (defun js2-visit-if-node (n v)
2604 (js2-visit-ast (js2-if-node-condition n) v)
2605 (js2-visit-ast (js2-if-node-then-part n) v)
2606 (if (js2-if-node-else-part n)
2607 (js2-visit-ast (js2-if-node-else-part n) v)))
2608
2609 (defun js2-print-if-node (n i)
2610 (let ((pad (js2-make-pad i))
2611 (then-part (js2-if-node-then-part n))
2612 (else-part (js2-if-node-else-part n)))
2613 (insert pad "if (")
2614 (js2-print-ast (js2-if-node-condition n) 0)
2615 (insert ") {\n")
2616 (js2-print-body then-part (1+ i))
2617 (insert pad "}")
2618 (cond
2619 ((not else-part)
2620 (insert "\n"))
2621 ((js2-if-node-p else-part)
2622 (insert " else ")
2623 (js2-print-body else-part i))
2624 (t
2625 (insert " else {\n")
2626 (js2-print-body else-part (1+ i))
2627 (insert pad "}\n")))))
2628
2629 (defstruct (js2-try-node
2630 (:include js2-node)
2631 (:constructor nil)
2632 (:constructor make-js2-try-node (&key (type js2-TRY)
2633 (pos js2-ts-cursor)
2634 len
2635 try-block
2636 catch-clauses
2637 finally-block)))
2638 "AST node for a try-statement."
2639 try-block
2640 catch-clauses ; a lisp list of `js2-catch-node'
2641 finally-block) ; a `js2-finally-node'
2642
2643 (put 'cl-struct-js2-try-node 'js2-visitor 'js2-visit-try-node)
2644 (put 'cl-struct-js2-try-node 'js2-printer 'js2-print-try-node)
2645
2646 (defun js2-visit-try-node (n v)
2647 (js2-visit-ast (js2-try-node-try-block n) v)
2648 (dolist (clause (js2-try-node-catch-clauses n))
2649 (js2-visit-ast clause v))
2650 (if (js2-try-node-finally-block n)
2651 (js2-visit-ast (js2-try-node-finally-block n) v)))
2652
2653 (defun js2-print-try-node (n i)
2654 (let ((pad (js2-make-pad i))
2655 (catches (js2-try-node-catch-clauses n))
2656 (finally (js2-try-node-finally-block n)))
2657 (insert pad "try {\n")
2658 (js2-print-body (js2-try-node-try-block n) (1+ i))
2659 (insert pad "}")
2660 (when catches
2661 (dolist (catch catches)
2662 (js2-print-ast catch i)))
2663 (if finally
2664 (js2-print-ast finally i)
2665 (insert "\n"))))
2666
2667 (defstruct (js2-catch-node
2668 (:include js2-node)
2669 (:constructor nil)
2670 (:constructor make-js2-catch-node (&key (type js2-CATCH)
2671 (pos js2-ts-cursor)
2672 len
2673 var-name
2674 guard-kwd
2675 guard-expr
2676 block
2677 lp
2678 rp)))
2679 "AST node for a catch clause."
2680 var-name ; a `js2-name-node'
2681 guard-kwd ; relative buffer position of "if" in "catch (x if ...)"
2682 guard-expr ; catch condition, a `js2-node'
2683 block ; statements, a `js2-block-node'
2684 lp ; buffer position of left-paren, nil if omitted
2685 rp) ; buffer position of right-paren, nil if omitted
2686
2687 (put 'cl-struct-js2-catch-node 'js2-visitor 'js2-visit-catch-node)
2688 (put 'cl-struct-js2-catch-node 'js2-printer 'js2-print-catch-node)
2689
2690 (defun js2-visit-catch-node (n v)
2691 (js2-visit-ast (js2-catch-node-var-name n) v)
2692 (when (js2-catch-node-guard-kwd n)
2693 (js2-visit-ast (js2-catch-node-guard-expr n) v))
2694 (js2-visit-ast (js2-catch-node-block n) v))
2695
2696 (defun js2-print-catch-node (n i)
2697 (let ((pad (js2-make-pad i))
2698 (guard-kwd (js2-catch-node-guard-kwd n))
2699 (guard-expr (js2-catch-node-guard-expr n)))
2700 (insert " catch (")
2701 (js2-print-ast (js2-catch-node-var-name n) 0)
2702 (when guard-kwd
2703 (insert " if ")
2704 (js2-print-ast guard-expr 0))
2705 (insert ") {\n")
2706 (js2-print-body (js2-catch-node-block n) (1+ i))
2707 (insert pad "}")))
2708
2709 (defstruct (js2-finally-node
2710 (:include js2-node)
2711 (:constructor nil)
2712 (:constructor make-js2-finally-node (&key (type js2-FINALLY)
2713 (pos js2-ts-cursor)
2714 len
2715 body)))
2716 "AST node for a finally clause."
2717 body) ; a `js2-node', often but not always a block node
2718
2719 (put 'cl-struct-js2-finally-node 'js2-visitor 'js2-visit-finally-node)
2720 (put 'cl-struct-js2-finally-node 'js2-printer 'js2-print-finally-node)
2721
2722 (defun js2-visit-finally-node (n v)
2723 (js2-visit-ast (js2-finally-node-body n) v))
2724
2725 (defun js2-print-finally-node (n i)
2726 (let ((pad (js2-make-pad i)))
2727 (insert " finally {\n")
2728 (js2-print-body (js2-finally-node-body n) (1+ i))
2729 (insert pad "}\n")))
2730
2731 (defstruct (js2-switch-node
2732 (:include js2-node)
2733 (:constructor nil)
2734 (:constructor make-js2-switch-node (&key (type js2-SWITCH)
2735 (pos js2-ts-cursor)
2736 len
2737 discriminant
2738 cases
2739 lp
2740 rp)))
2741 "AST node for a switch statement."
2742 discriminant ; a `js2-node' (switch expression)
2743 cases ; a lisp list of `js2-case-node'
2744 lp ; position of open-paren for discriminant, nil if omitted
2745 rp) ; position of close-paren for discriminant, nil if omitted
2746
2747 (put 'cl-struct-js2-switch-node 'js2-visitor 'js2-visit-switch-node)
2748 (put 'cl-struct-js2-switch-node 'js2-printer 'js2-print-switch-node)
2749
2750 (defun js2-visit-switch-node (n v)
2751 (js2-visit-ast (js2-switch-node-discriminant n) v)
2752 (dolist (c (js2-switch-node-cases n))
2753 (js2-visit-ast c v)))
2754
2755 (defun js2-print-switch-node (n i)
2756 (let ((pad (js2-make-pad i))
2757 (cases (js2-switch-node-cases n)))
2758 (insert pad "switch (")
2759 (js2-print-ast (js2-switch-node-discriminant n) 0)
2760 (insert ") {\n")
2761 (dolist (case cases)
2762 (js2-print-ast case i))
2763 (insert pad "}\n")))
2764
2765 (defstruct (js2-case-node
2766 (:include js2-block-node)
2767 (:constructor nil)
2768 (:constructor make-js2-case-node (&key (type js2-CASE)
2769 (pos js2-ts-cursor)
2770 len
2771 kids
2772 expr)))
2773 "AST node for a case clause of a switch statement."
2774 expr) ; the case expression (nil for default)
2775
2776 (put 'cl-struct-js2-case-node 'js2-visitor 'js2-visit-case-node)
2777 (put 'cl-struct-js2-case-node 'js2-printer 'js2-print-case-node)
2778
2779 (defun js2-visit-case-node (n v)
2780 (if (js2-case-node-expr n) ; nil for default: case
2781 (js2-visit-ast (js2-case-node-expr n) v))
2782 (js2-visit-block n v))
2783
2784 (defun js2-print-case-node (n i)
2785 (let ((pad (js2-make-pad i))
2786 (expr (js2-case-node-expr n)))
2787 (insert pad)
2788 (if (null expr)
2789 (insert "default:\n")
2790 (insert "case ")
2791 (js2-print-ast expr 0)
2792 (insert ":\n"))
2793 (dolist (kid (js2-case-node-kids n))
2794 (js2-print-ast kid (1+ i)))))
2795
2796 (defstruct (js2-throw-node
2797 (:include js2-node)
2798 (:constructor nil)
2799 (:constructor make-js2-throw-node (&key (type js2-THROW)
2800 (pos js2-ts-cursor)
2801 len
2802 expr)))
2803 "AST node for a throw statement."
2804 expr) ; the expression to throw
2805
2806 (put 'cl-struct-js2-throw-node 'js2-visitor 'js2-visit-throw-node)
2807 (put 'cl-struct-js2-throw-node 'js2-printer 'js2-print-throw-node)
2808
2809 (defun js2-visit-throw-node (n v)
2810 (js2-visit-ast (js2-throw-node-expr n) v))
2811
2812 (defun js2-print-throw-node (n i)
2813 (insert (js2-make-pad i) "throw ")
2814 (js2-print-ast (js2-throw-node-expr n) 0)
2815 (insert ";\n"))
2816
2817 (defstruct (js2-with-node
2818 (:include js2-node)
2819 (:constructor nil)
2820 (:constructor make-js2-with-node (&key (type js2-WITH)
2821 (pos js2-ts-cursor)
2822 len
2823 object
2824 body
2825 lp
2826 rp)))
2827 "AST node for a with-statement."
2828 object
2829 body
2830 lp ; buffer position of left-paren around object, nil if omitted
2831 rp) ; buffer position of right-paren around object, nil if omitted
2832
2833 (put 'cl-struct-js2-with-node 'js2-visitor 'js2-visit-with-node)
2834 (put 'cl-struct-js2-with-node 'js2-printer 'js2-print-with-node)
2835
2836 (defun js2-visit-with-node (n v)
2837 (js2-visit-ast (js2-with-node-object n) v)
2838 (js2-visit-ast (js2-with-node-body n) v))
2839
2840 (defun js2-print-with-node (n i)
2841 (let ((pad (js2-make-pad i)))
2842 (insert pad "with (")
2843 (js2-print-ast (js2-with-node-object n) 0)
2844 (insert ") {\n")
2845 (js2-print-body (js2-with-node-body n) (1+ i))
2846 (insert pad "}\n")))
2847
2848 (defstruct (js2-label-node
2849 (:include js2-node)
2850 (:constructor nil)
2851 (:constructor make-js2-label-node (&key (type js2-LABEL)
2852 (pos js2-ts-cursor)
2853 len
2854 name)))
2855 "AST node for a statement label or case label."
2856 name ; a string
2857 loop) ; for validating and code-generating continue-to-label
2858
2859 (put 'cl-struct-js2-label-node 'js2-visitor 'js2-visit-none)
2860 (put 'cl-struct-js2-label-node 'js2-printer 'js2-print-label)
2861
2862 (defun js2-print-label (n i)
2863 (insert (js2-make-pad i)
2864 (js2-label-node-name n)
2865 ":\n"))
2866
2867 (defstruct (js2-labeled-stmt-node
2868 (:include js2-node)
2869 (:constructor nil)
2870 ;; type needs to be in `js2-side-effecting-tokens' to avoid spurious
2871 ;; no-side-effects warnings, hence js2-EXPR_RESULT.
2872 (:constructor make-js2-labeled-stmt-node (&key (type js2-EXPR_RESULT)
2873 (pos js2-ts-cursor)
2874 len
2875 labels
2876 stmt)))
2877 "AST node for a statement with one or more labels.
2878 Multiple labels for a statement are collapsed into the labels field."
2879 labels ; lisp list of `js2-label-node'
2880 stmt) ; the statement these labels are for
2881
2882 (put 'cl-struct-js2-labeled-stmt-node 'js2-visitor 'js2-visit-labeled-stmt)
2883 (put 'cl-struct-js2-labeled-stmt-node 'js2-printer 'js2-print-labeled-stmt)
2884
2885 (defun js2-get-label-by-name (lbl-stmt name)
2886 "Return a `js2-label-node' by NAME from LBL-STMT's labels list.
2887 Returns nil if no such label is in the list."
2888 (let ((label-list (js2-labeled-stmt-node-labels lbl-stmt))
2889 result)
2890 (while (and label-list (not result))
2891 (if (string= (js2-label-node-name (car label-list)) name)
2892 (setq result (car label-list))
2893 (setq label-list (cdr label-list))))
2894 result))
2895
2896 (defun js2-visit-labeled-stmt (n v)
2897 (dolist (label (js2-labeled-stmt-node-labels n))
2898 (js2-visit-ast label v))
2899 (js2-visit-ast (js2-labeled-stmt-node-stmt n) v))
2900
2901 (defun js2-print-labeled-stmt (n i)
2902 (dolist (label (js2-labeled-stmt-node-labels n))
2903 (js2-print-ast label i))
2904 (js2-print-ast (js2-labeled-stmt-node-stmt n) (1+ i)))
2905
2906 (defun js2-labeled-stmt-node-contains (node label)
2907 "Return t if NODE contains LABEL in its label set.
2908 NODE is a `js2-labels-node'. LABEL is an identifier."
2909 (loop for nl in (js2-labeled-stmt-node-labels node)
2910 if (string= label (js2-label-node-name nl))
2911 return t
2912 finally return nil))
2913
2914 (defsubst js2-labeled-stmt-node-add-label (node label)
2915 "Add a `js2-label-node' to the label set for this statement."
2916 (setf (js2-labeled-stmt-node-labels node)
2917 (nconc (js2-labeled-stmt-node-labels node) (list label))))
2918
2919 (defstruct (js2-jump-node
2920 (:include js2-node)
2921 (:constructor nil))
2922 "Abstract supertype of break and continue nodes."
2923 label ; `js2-name-node' for location of label identifier, if present
2924 target) ; target js2-labels-node or loop/switch statement
2925
2926 (defun js2-visit-jump-node (n v)
2927 ;; we don't visit the target, since it's a back-link
2928 (if (js2-jump-node-label n)
2929 (js2-visit-ast (js2-jump-node-label n) v)))
2930
2931 (defstruct (js2-break-node
2932 (:include js2-jump-node)
2933 (:constructor nil)
2934 (:constructor make-js2-break-node (&key (type js2-BREAK)
2935 (pos js2-ts-cursor)
2936 len
2937 label
2938 target)))
2939 "AST node for a break statement.
2940 The label field is a `js2-name-node', possibly nil, for the named label
2941 if provided. E.g. in 'break foo', it represents 'foo'. The target field
2942 is the target of the break - a label node or enclosing loop/switch statement.")
2943
2944 (put 'cl-struct-js2-break-node 'js2-visitor 'js2-visit-jump-node)
2945 (put 'cl-struct-js2-break-node 'js2-printer 'js2-print-break-node)
2946
2947 (defun js2-print-break-node (n i)
2948 (insert (js2-make-pad i) "break")
2949 (when (js2-break-node-label n)
2950 (insert " ")
2951 (js2-print-ast (js2-break-node-label n) 0))
2952 (insert ";\n"))
2953
2954 (defstruct (js2-continue-node
2955 (:include js2-jump-node)
2956 (:constructor nil)
2957 (:constructor make-js2-continue-node (&key (type js2-CONTINUE)
2958 (pos js2-ts-cursor)
2959 len
2960 label
2961 target)))
2962 "AST node for a continue statement.
2963 The label field is the user-supplied enclosing label name, a `js2-name-node'.
2964 It is nil if continue specifies no label. The target field is the jump target:
2965 a `js2-label-node' or the innermost enclosing loop.")
2966
2967 (put 'cl-struct-js2-continue-node 'js2-visitor 'js2-visit-jump-node)
2968 (put 'cl-struct-js2-continue-node 'js2-printer 'js2-print-continue-node)
2969
2970 (defun js2-print-continue-node (n i)
2971 (insert (js2-make-pad i) "continue")
2972 (when (js2-continue-node-label n)
2973 (insert " ")
2974 (js2-print-ast (js2-continue-node-label n) 0))
2975 (insert ";\n"))
2976
2977 (defstruct (js2-function-node
2978 (:include js2-script-node)
2979 (:constructor nil)
2980 (:constructor make-js2-function-node (&key (type js2-FUNCTION)
2981 (pos js2-ts-cursor)
2982 len
2983 (ftype 'FUNCTION)
2984 (form 'FUNCTION_STATEMENT)
2985 (name "")
2986 params
2987 body
2988 lp
2989 rp)))
2990 "AST node for a function declaration.
2991 The `params' field is a lisp list of nodes. Each node is either a simple
2992 `js2-name-node', or if it's a destructuring-assignment parameter, a
2993 `js2-array-node' or `js2-object-node'."
2994 ftype ; FUNCTION, GETTER or SETTER
2995 form ; FUNCTION_{STATEMENT|EXPRESSION|EXPRESSION_STATEMENT}
2996 name ; function name (a `js2-name-node', or nil if anonymous)
2997 params ; a lisp list of destructuring forms or simple name nodes
2998 body ; a `js2-block-node' or expression node (1.8 only)
2999 lp ; position of arg-list open-paren, or nil if omitted
3000 rp ; position of arg-list close-paren, or nil if omitted
3001 ignore-dynamic ; ignore value of the dynamic-scope flag (interpreter only)
3002 needs-activation ; t if we need an activation object for this frame
3003 is-generator ; t if this function contains a yield
3004 member-expr) ; nonstandard Ecma extension from Rhino
3005
3006 (put 'cl-struct-js2-function-node 'js2-visitor 'js2-visit-function-node)
3007 (put 'cl-struct-js2-function-node 'js2-printer 'js2-print-function-node)
3008
3009 (defun js2-visit-function-node (n v)
3010 (if (js2-function-node-name n)
3011 (js2-visit-ast (js2-function-node-name n) v))
3012 (dolist (p (js2-function-node-params n))
3013 (js2-visit-ast p v))
3014 (when (js2-function-node-body n)
3015 (js2-visit-ast (js2-function-node-body n) v)))
3016
3017 (defun js2-print-function-node (n i)
3018 (let ((pad (js2-make-pad i))
3019 (getter (js2-node-get-prop n 'GETTER_SETTER))
3020 (name (js2-function-node-name n))
3021 (params (js2-function-node-params n))
3022 (body (js2-function-node-body n))
3023 (expr (eq (js2-function-node-form n) 'FUNCTION_EXPRESSION)))
3024 (unless getter
3025 (insert pad "function"))
3026 (when name
3027 (insert " ")
3028 (js2-print-ast name 0))
3029 (insert "(")
3030 (loop with len = (length params)
3031 for param in params
3032 for count from 1
3033 do
3034 (js2-print-ast param 0)
3035 (if (< count len)
3036 (insert ", ")))
3037 (insert ") {")
3038 (unless expr
3039 (insert "\n"))
3040 ;; TODO: fix this to be smarter about indenting, etc.
3041 (js2-print-body body (1+ i))
3042 (insert pad "}")
3043 (unless expr
3044 (insert "\n"))))
3045
3046 (defsubst js2-function-name (node)
3047 "Return function name for NODE, a `js2-function-node', or nil if anonymous."
3048 (and (js2-function-node-name node)
3049 (js2-name-node-name (js2-function-node-name node))))
3050
3051 ;; Having this be an expression node makes it more flexible.
3052 ;; There are IDE contexts, such as indentation in a for-loop initializer,
3053 ;; that work better if you assume it's an expression. Whenever we have
3054 ;; a standalone var/const declaration, we just wrap with an expr stmt.
3055 ;; Eclipse apparently screwed this up and now has two versions, expr and stmt.
3056 (defstruct (js2-var-decl-node
3057 (:include js2-node)
3058 (:constructor nil)
3059 (:constructor make-js2-var-decl-node (&key (type js2-VAR)
3060 (pos js2-token-beg)
3061 len
3062 kids
3063 decl-type)))
3064 "AST node for a variable declaration list (VAR, CONST or LET).
3065 The node bounds differ depending on the declaration type. For VAR or
3066 CONST declarations, the bounds include the var/const keyword. For LET
3067 declarations, the node begins at the position of the first child."
3068 kids ; a lisp list of `js2-var-init-node' structs.
3069 decl-type) ; js2-VAR, js2-CONST or js2-LET
3070
3071 (put 'cl-struct-js2-var-decl-node 'js2-visitor 'js2-visit-var-decl)
3072 (put 'cl-struct-js2-var-decl-node 'js2-printer 'js2-print-var-decl)
3073
3074 (defun js2-visit-var-decl (n v)
3075 (dolist (kid (js2-var-decl-node-kids n))
3076 (js2-visit-ast kid v)))
3077
3078 (defun js2-print-var-decl (n i)
3079 (let ((pad (js2-make-pad i))
3080 (tt (js2-var-decl-node-decl-type n)))
3081 (insert pad)
3082 (insert (cond
3083 ((= tt js2-VAR) "var ")
3084 ((= tt js2-LET) "") ; handled by parent let-{expr/stmt}
3085 ((= tt js2-CONST) "const ")
3086 (t
3087 (error "malformed var-decl node"))))
3088 (loop with kids = (js2-var-decl-node-kids n)
3089 with len = (length kids)
3090 for kid in kids
3091 for count from 1
3092 do
3093 (js2-print-ast kid 0)
3094 (if (< count len)
3095 (insert ", ")))))
3096
3097 (defstruct (js2-var-init-node
3098 (:include js2-node)
3099 (:constructor nil)
3100 (:constructor make-js2-var-init-node (&key (type js2-VAR)
3101 (pos js2-ts-cursor)
3102 len
3103 target
3104 initializer)))
3105 "AST node for a variable declaration.
3106 The type field will be js2-CONST for a const decl."
3107 target ; `js2-name-node', `js2-object-node', or `js2-array-node'
3108 initializer) ; initializer expression, a `js2-node'
3109
3110 (put 'cl-struct-js2-var-init-node 'js2-visitor 'js2-visit-var-init-node)
3111 (put 'cl-struct-js2-var-init-node 'js2-printer 'js2-print-var-init-node)
3112
3113 (defun js2-visit-var-init-node (n v)
3114 (js2-visit-ast (js2-var-init-node-target n) v)
3115 (if (js2-var-init-node-initializer n)
3116 (js2-visit-ast (js2-var-init-node-initializer n) v)))
3117
3118 (defun js2-print-var-init-node (n i)
3119 (let ((pad (js2-make-pad i))
3120 (name (js2-var-init-node-target n))
3121 (init (js2-var-init-node-initializer n)))
3122 (insert pad)
3123 (js2-print-ast name 0)
3124 (when init
3125 (insert " = ")
3126 (js2-print-ast init 0))))
3127
3128 (defstruct (js2-cond-node
3129 (:include js2-node)
3130 (:constructor nil)
3131 (:constructor make-js2-cond-node (&key (type js2-HOOK)
3132 (pos js2-ts-cursor)
3133 len
3134 test-expr
3135 true-expr
3136 false-expr
3137 q-pos
3138 c-pos)))
3139 "AST node for the ternary operator"
3140 test-expr
3141 true-expr
3142 false-expr
3143 q-pos ; buffer position of ?
3144 c-pos) ; buffer position of :
3145
3146 (put 'cl-struct-js2-cond-node 'js2-visitor 'js2-visit-cond-node)
3147 (put 'cl-struct-js2-cond-node 'js2-printer 'js2-print-cond-node)
3148
3149 (defun js2-visit-cond-node (n v)
3150 (js2-visit-ast (js2-cond-node-test-expr n) v)
3151 (js2-visit-ast (js2-cond-node-true-expr n) v)
3152 (js2-visit-ast (js2-cond-node-false-expr n) v))
3153
3154 (defun js2-print-cond-node (n i)
3155 (let ((pad (js2-make-pad i)))
3156 (insert pad)
3157 (js2-print-ast (js2-cond-node-test-expr n) 0)
3158 (insert " ? ")
3159 (js2-print-ast (js2-cond-node-true-expr n) 0)
3160 (insert " : ")
3161 (js2-print-ast (js2-cond-node-false-expr n) 0)))
3162
3163 (defstruct (js2-infix-node
3164 (:include js2-node)
3165 (:constructor nil)
3166 (:constructor make-js2-infix-node (&key type
3167 (pos js2-ts-cursor)
3168 len
3169 op-pos
3170 left
3171 right)))
3172 "Represents infix expressions.
3173 Includes assignment ops like `|=', and the comma operator.
3174 The type field inherited from `js2-node' holds the operator."
3175 op-pos ; buffer position where operator begins
3176 left ; any `js2-node'
3177 right) ; any `js2-node'
3178
3179 (put 'cl-struct-js2-infix-node 'js2-visitor 'js2-visit-infix-node)
3180 (put 'cl-struct-js2-infix-node 'js2-printer 'js2-print-infix-node)
3181
3182 (defun js2-visit-infix-node (n v)
3183 (when (js2-infix-node-left n)
3184 (js2-visit-ast (js2-infix-node-left n) v))
3185 (when (js2-infix-node-right n)
3186 (js2-visit-ast (js2-infix-node-right n) v)))
3187
3188 (defconst js2-operator-tokens
3189 (let ((table (make-hash-table :test 'eq))
3190 (tokens
3191 (list (cons js2-IN "in")
3192 (cons js2-TYPEOF "typeof")
3193 (cons js2-INSTANCEOF "instanceof")
3194 (cons js2-DELPROP "delete")
3195 (cons js2-COMMA ",")
3196 (cons js2-COLON ":")
3197 (cons js2-OR "||")
3198 (cons js2-AND "&&")
3199 (cons js2-INC "++")
3200 (cons js2-DEC "--")
3201 (cons js2-BITOR "|")
3202 (cons js2-BITXOR "^")
3203 (cons js2-BITAND "&")
3204 (cons js2-EQ "==")
3205 (cons js2-NE "!=")
3206 (cons js2-LT "<")
3207 (cons js2-LE "<=")
3208 (cons js2-GT ">")
3209 (cons js2-GE ">=")
3210 (cons js2-LSH "<<")
3211 (cons js2-RSH ">>")
3212 (cons js2-URSH ">>>")
3213 (cons js2-ADD "+") ; infix plus
3214 (cons js2-SUB "-") ; infix minus
3215 (cons js2-MUL "*")
3216 (cons js2-DIV "/")
3217 (cons js2-MOD "%")
3218 (cons js2-NOT "!")
3219 (cons js2-BITNOT "~")
3220 (cons js2-POS "+") ; unary plus
3221 (cons js2-NEG "-") ; unary minus
3222 (cons js2-SHEQ "===") ; shallow equality
3223 (cons js2-SHNE "!==") ; shallow inequality
3224 (cons js2-ASSIGN "=")
3225 (cons js2-ASSIGN_BITOR "|=")
3226 (cons js2-ASSIGN_BITXOR "^=")
3227 (cons js2-ASSIGN_BITAND "&=")
3228 (cons js2-ASSIGN_LSH "<<=")
3229 (cons js2-ASSIGN_RSH ">>=")
3230 (cons js2-ASSIGN_URSH ">>>=")
3231 (cons js2-ASSIGN_ADD "+=")
3232 (cons js2-ASSIGN_SUB "-=")
3233 (cons js2-ASSIGN_MUL "*=")
3234 (cons js2-ASSIGN_DIV "/=")
3235 (cons js2-ASSIGN_MOD "%="))))
3236 (loop for (k . v) in tokens do
3237 (puthash k v table))
3238 table))
3239
3240 (defun js2-print-infix-node (n i)
3241 (let* ((tt (js2-node-type n))
3242 (op (gethash tt js2-operator-tokens)))
3243 (unless op
3244 (error "unrecognized infix operator %s" (js2-node-type n)))
3245 (insert (js2-make-pad i))
3246 (js2-print-ast (js2-infix-node-left n) 0)
3247 (unless (= tt js2-COMMA)
3248 (insert " "))
3249 (insert op)
3250 (insert " ")
3251 (js2-print-ast (js2-infix-node-right n) 0)))
3252
3253 (defstruct (js2-assign-node
3254 (:include js2-infix-node)
3255 (:constructor nil)
3256 (:constructor make-js2-assign-node (&key type
3257 (pos js2-ts-cursor)
3258 len
3259 op-pos
3260 left
3261 right)))
3262 "Represents any assignment.
3263 The type field holds the actual assignment operator.")
3264
3265 (put 'cl-struct-js2-assign-node 'js2-visitor 'js2-visit-infix-node)
3266 (put 'cl-struct-js2-assign-node 'js2-printer 'js2-print-infix-node)
3267
3268 (defstruct (js2-unary-node
3269 (:include js2-node)
3270 (:constructor nil)
3271 (:constructor make-js2-unary-node (&key type ; required
3272 (pos js2-ts-cursor)
3273 len
3274 operand)))
3275 "AST node type for unary operator nodes.
3276 The type field can be NOT, BITNOT, POS, NEG, INC, DEC,
3277 TYPEOF, or DELPROP. For INC or DEC, a 'postfix node
3278 property is added if the operator follows the operand."
3279 operand) ; a `js2-node' expression
3280
3281 (put 'cl-struct-js2-unary-node 'js2-visitor 'js2-visit-unary-node)
3282 (put 'cl-struct-js2-unary-node 'js2-printer 'js2-print-unary-node)
3283
3284 (defun js2-visit-unary-node (n v)
3285 (js2-visit-ast (js2-unary-node-operand n) v))
3286
3287 (defun js2-print-unary-node (n i)
3288 (let* ((tt (js2-node-type n))
3289 (op (gethash tt js2-operator-tokens))
3290 (postfix (js2-node-get-prop n 'postfix)))
3291 (unless op
3292 (error "unrecognized unary operator %s" tt))
3293 (insert (js2-make-pad i))
3294 (unless postfix
3295 (insert op))
3296 (if (or (= tt js2-TYPEOF)
3297 (= tt js2-DELPROP))
3298 (insert " "))
3299 (js2-print-ast (js2-unary-node-operand n) 0)
3300 (when postfix
3301 (insert op))))
3302
3303 (defstruct (js2-let-node
3304 (:include js2-scope)
3305 (:constructor nil)
3306 (:constructor make-js2-let-node (&key (type js2-LETEXPR)
3307 (pos js2-token-beg)
3308 len
3309 vars
3310 body
3311 lp
3312 rp)))
3313 "AST node for a let expression or a let statement.
3314 Note that a let declaration such as let x=6, y=7 is a `js2-var-decl-node'."
3315 vars ; a `js2-var-decl-node'
3316 body ; a `js2-node' representing the expression or body block
3317 lp
3318 rp)
3319
3320 (put 'cl-struct-js2-let-node 'js2-visitor 'js2-visit-let-node)
3321 (put 'cl-struct-js2-let-node 'js2-printer 'js2-print-let-node)
3322
3323 (defun js2-visit-let-node (n v)
3324 (when (js2-let-node-vars n)
3325 (js2-visit-ast (js2-let-node-vars n) v))
3326 (when (js2-let-node-body n)
3327 (js2-visit-ast (js2-let-node-body n) v)))
3328
3329 (defun js2-print-let-node (n i)
3330 (insert (js2-make-pad i) "let (")
3331 (js2-print-ast (js2-let-node-vars n) 0)
3332 (insert ") ")
3333 (js2-print-ast (js2-let-node-body n) i))
3334
3335 (defstruct (js2-keyword-node
3336 (:include js2-node)
3337 (:constructor nil)
3338 (:constructor make-js2-keyword-node (&key type
3339 (pos js2-token-beg)
3340 (len (- js2-ts-cursor pos)))))
3341 "AST node representing a literal keyword such as `null'.
3342 Used for `null', `this', `true', `false' and `debugger'.
3343 The node type is set to js2-NULL, js2-THIS, etc.")
3344
3345 (put 'cl-struct-js2-keyword-node 'js2-visitor 'js2-visit-none)
3346 (put 'cl-struct-js2-keyword-node 'js2-printer 'js2-print-keyword-node)
3347
3348 (defun js2-print-keyword-node (n i)
3349 (insert (js2-make-pad i)
3350 (let ((tt (js2-node-type n)))
3351 (cond
3352 ((= tt js2-THIS) "this")
3353 ((= tt js2-NULL) "null")
3354 ((= tt js2-TRUE) "true")
3355 ((= tt js2-FALSE) "false")
3356 ((= tt js2-DEBUGGER) "debugger")
3357 (t (error "Invalid keyword literal type: %d" tt))))))
3358
3359 (defsubst js2-this-node-p (node)
3360 "Return t if this node is a `js2-literal-node' of type js2-THIS."
3361 (eq (js2-node-type node) js2-THIS))
3362
3363 (defstruct (js2-new-node
3364 (:include js2-node)
3365 (:constructor nil)
3366 (:constructor make-js2-new-node (&key (type js2-NEW)
3367 (pos js2-token-beg)
3368 len
3369 target
3370 args
3371 initializer
3372 lp
3373 rp)))
3374 "AST node for new-expression such as new Foo()."
3375 target ; an identifier or reference
3376 args ; a lisp list of argument nodes
3377 lp ; position of left-paren, nil if omitted
3378 rp ; position of right-paren, nil if omitted
3379 initializer) ; experimental Rhino syntax: optional `js2-object-node'
3380
3381 (put 'cl-struct-js2-new-node 'js2-visitor 'js2-visit-new-node)
3382 (put 'cl-struct-js2-new-node 'js2-printer 'js2-print-new-node)
3383
3384 (defun js2-visit-new-node (n v)
3385 (js2-visit-ast (js2-new-node-target n) v)
3386 (dolist (arg (js2-new-node-args n))
3387 (js2-visit-ast arg v))
3388 (when (js2-new-node-initializer n)
3389 (js2-visit-ast (js2-new-node-initializer n) v)))
3390
3391 (defun js2-print-new-node (n i)
3392 (insert (js2-make-pad i) "new ")
3393 (js2-print-ast (js2-new-node-target n))
3394 (insert "(")
3395 (js2-print-list (js2-new-node-args n))
3396 (insert ")")
3397 (when (js2-new-node-initializer n)
3398 (insert " ")
3399 (js2-print-ast (js2-new-node-initializer n))))
3400
3401 (defstruct (js2-name-node
3402 (:include js2-node)
3403 (:constructor nil)
3404 (:constructor make-js2-name-node (&key (type js2-NAME)
3405 (pos js2-token-beg)
3406 (len (- js2-ts-cursor
3407 js2-token-beg))
3408 (name js2-ts-string))))
3409 "AST node for a JavaScript identifier"
3410 name ; a string
3411 scope) ; a `js2-scope' (optional, used for codegen)
3412
3413 (put 'cl-struct-js2-name-node 'js2-visitor 'js2-visit-none)
3414 (put 'cl-struct-js2-name-node 'js2-printer 'js2-print-name-node)
3415
3416 (defun js2-print-name-node (n i)
3417 (insert (js2-make-pad i)
3418 (js2-name-node-name n)))
3419
3420 (defsubst js2-name-node-length (node)
3421 "Return identifier length of NODE, a `js2-name-node'.
3422 Returns 0 if NODE is nil or its identifier field is nil."
3423 (if node
3424 (length (js2-name-node-name node))
3425 0))
3426
3427 (defstruct (js2-number-node
3428 (:include js2-node)
3429 (:constructor nil)
3430 (:constructor make-js2-number-node (&key (type js2-NUMBER)
3431 (pos js2-token-beg)
3432 (len (- js2-ts-cursor
3433 js2-token-beg))
3434 (value js2-ts-string)
3435 (num-value js2-ts-number))))
3436 "AST node for a number literal."
3437 value ; the original string, e.g. "6.02e23"
3438 num-value) ; the parsed number value
3439
3440 (put 'cl-struct-js2-number-node 'js2-visitor 'js2-visit-none)
3441 (put 'cl-struct-js2-number-node 'js2-printer 'js2-print-number-node)
3442
3443 (defun js2-print-number-node (n i)
3444 (insert (js2-make-pad i)
3445 (number-to-string (js2-number-node-num-value n))))
3446
3447 (defstruct (js2-regexp-node
3448 (:include js2-node)
3449 (:constructor nil)
3450 (:constructor make-js2-regexp-node (&key (type js2-REGEXP)
3451 (pos js2-token-beg)
3452 (len (- js2-ts-cursor
3453 js2-token-beg))
3454 value
3455 flags)))
3456 "AST node for a regular expression literal."
3457 value ; the regexp string, without // delimiters
3458 flags) ; a string of flags, e.g. `mi'.
3459
3460 (put 'cl-struct-js2-regexp-node 'js2-visitor 'js2-visit-none)
3461 (put 'cl-struct-js2-regexp-node 'js2-printer 'js2-print-regexp)
3462
3463 (defun js2-print-regexp (n i)
3464 (insert (js2-make-pad i)
3465 "/"
3466 (js2-regexp-node-value n)
3467 "/")
3468 (if (js2-regexp-node-flags n)
3469 (insert (js2-regexp-node-flags n))))
3470
3471 (defstruct (js2-string-node
3472 (:include js2-node)
3473 (:constructor nil)
3474 (:constructor make-js2-string-node (&key (type js2-STRING)
3475 (pos js2-token-beg)
3476 (len (- js2-ts-cursor
3477 js2-token-beg))
3478 (value js2-ts-string))))
3479 "String literal.
3480 Escape characters are not evaluated; e.g. \n is 2 chars in value field.
3481 You can tell the quote type by looking at the first character."
3482 value) ; the characters of the string, including the quotes
3483
3484 (put 'cl-struct-js2-string-node 'js2-visitor 'js2-visit-none)
3485 (put 'cl-struct-js2-string-node 'js2-printer 'js2-print-string-node)
3486
3487 (defun js2-print-string-node (n i)
3488 (insert (js2-make-pad i)
3489 (js2-node-string n)))
3490
3491 (defstruct (js2-array-node
3492 (:include js2-node)
3493 (:constructor nil)
3494 (:constructor make-js2-array-node (&key (type js2-ARRAYLIT)
3495 (pos js2-ts-cursor)
3496 len
3497 elems)))
3498 "AST node for an array literal."
3499 elems) ; list of expressions. [foo,,bar] yields a nil middle element.
3500
3501 (put 'cl-struct-js2-array-node 'js2-visitor 'js2-visit-array-node)
3502 (put 'cl-struct-js2-array-node 'js2-printer 'js2-print-array-node)
3503
3504 (defun js2-visit-array-node (n v)
3505 (dolist (e (js2-array-node-elems n))
3506 (when e ; can be nil, e.g. [a, ,b]
3507 (js2-visit-ast e v))))
3508
3509 (defun js2-print-array-node (n i)
3510 (insert (js2-make-pad i) "[")
3511 (js2-print-list (js2-array-node-elems n))
3512 (insert "]"))
3513
3514 (defstruct (js2-object-node
3515 (:include js2-node)
3516 (:constructor nil)
3517 (:constructor make-js2-object-node (&key (type js2-OBJECTLIT)
3518 (pos js2-ts-cursor)
3519 len
3520 elems)))
3521 "AST node for an object literal expression."
3522 elems) ; a lisp list of `js2-object-prop-node'
3523
3524 (put 'cl-struct-js2-object-node 'js2-visitor 'js2-visit-object-node)
3525 (put 'cl-struct-js2-object-node 'js2-printer 'js2-print-object-node)
3526
3527 (defun js2-visit-object-node (n v)
3528 (dolist (e (js2-object-node-elems n))
3529 (js2-visit-ast e v)))
3530
3531 (defun js2-print-object-node (n i)
3532 (insert (js2-make-pad i) "{")
3533 (js2-print-list (js2-object-node-elems n))
3534 (insert "}"))
3535
3536 (defstruct (js2-object-prop-node
3537 (:include js2-infix-node)
3538 (:constructor nil)
3539 (:constructor make-js2-object-prop-node (&key (type js2-COLON)
3540 (pos js2-ts-cursor)
3541 len
3542 left
3543 right
3544 op-pos)))
3545 "AST node for an object literal prop:value entry.
3546 The `left' field is the property: a name node, string node or number node.
3547 The `right' field is a `js2-node' representing the initializer value.")
3548
3549 (put 'cl-struct-js2-object-prop-node 'js2-visitor 'js2-visit-infix-node)
3550 (put 'cl-struct-js2-object-prop-node 'js2-printer 'js2-print-object-prop-node)
3551
3552 (defun js2-print-object-prop-node (n i)
3553 (insert (js2-make-pad i))
3554 (js2-print-ast (js2-object-prop-node-left n) 0)
3555 (insert ":")
3556 (js2-print-ast (js2-object-prop-node-right n) 0))
3557
3558 (defstruct (js2-getter-setter-node
3559 (:include js2-infix-node)
3560 (:constructor nil)
3561 (:constructor make-js2-getter-setter-node (&key type ; GET or SET
3562 (pos js2-ts-cursor)
3563 len
3564 left
3565 right)))
3566 "AST node for a getter/setter property in an object literal.
3567 The `left' field is the `js2-name-node' naming the getter/setter prop.
3568 The `right' field is always an anonymous `js2-function-node' with a node
3569 property `GETTER_SETTER' set to js2-GET or js2-SET. ")
3570
3571 (put 'cl-struct-js2-getter-setter-node 'js2-visitor 'js2-visit-infix-node)
3572 (put 'cl-struct-js2-getter-setter-node 'js2-printer 'js2-print-getter-setter)
3573
3574 (defun js2-print-getter-setter (n i)
3575 (let ((pad (js2-make-pad i))
3576 (left (js2-getter-setter-node-left n))
3577 (right (js2-getter-setter-node-right n)))
3578 (insert pad)
3579 (insert (if (= (js2-node-type n) js2-GET) "get " "set "))
3580 (js2-print-ast left 0)
3581 (js2-print-ast right 0)))
3582
3583 (defstruct (js2-prop-get-node
3584 (:include js2-infix-node)
3585 (:constructor nil)
3586 (:constructor make-js2-prop-get-node (&key (type js2-GETPROP)
3587 (pos js2-ts-cursor)
3588 len
3589 left
3590 right)))
3591 "AST node for a dotted property reference, e.g. foo.bar or foo().bar")
3592
3593 (put 'cl-struct-js2-prop-get-node 'js2-visitor 'js2-visit-prop-get-node)
3594 (put 'cl-struct-js2-prop-get-node 'js2-printer 'js2-print-prop-get-node)
3595
3596 (defun js2-visit-prop-get-node (n v)
3597 (when (js2-prop-get-node-left n)
3598 (js2-visit-ast (js2-prop-get-node-left n) v))
3599 (when (js2-prop-get-node-right n)
3600 (js2-visit-ast (js2-prop-get-node-right n) v)))
3601
3602 (defun js2-print-prop-get-node (n i)
3603 (insert (js2-make-pad i))
3604 (js2-print-ast (js2-prop-get-node-left n) 0)
3605 (insert ".")
3606 (js2-print-ast (js2-prop-get-node-right n) 0))
3607
3608 (defstruct (js2-elem-get-node
3609 (:include js2-node)
3610 (:constructor nil)
3611 (:constructor make-js2-elem-get-node (&key (type js2-GETELEM)
3612 (pos js2-ts-cursor)
3613 len
3614 target
3615 element
3616 lb
3617 rb)))
3618 "AST node for an array index expression such as foo[bar]."
3619 target ; a `js2-node' - the expression preceding the "."
3620 element ; a `js2-node' - the expression in brackets
3621 lb ; position of left-bracket, nil if omitted
3622 rb) ; position of right-bracket, nil if omitted
3623
3624 (put 'cl-struct-js2-elem-get-node 'js2-visitor 'js2-visit-elem-get-node)
3625 (put 'cl-struct-js2-elem-get-node 'js2-printer 'js2-print-elem-get-node)
3626
3627 (defun js2-visit-elem-get-node (n v)
3628 (when (js2-elem-get-node-target n)
3629 (js2-visit-ast (js2-elem-get-node-target n) v))
3630 (when (js2-elem-get-node-element n)
3631 (js2-visit-ast (js2-elem-get-node-element n) v)))
3632
3633 (defun js2-print-elem-get-node (n i)
3634 (insert (js2-make-pad i))
3635 (js2-print-ast (js2-elem-get-node-target n) 0)
3636 (insert "[")
3637 (js2-print-ast (js2-elem-get-node-element n) 0)
3638 (insert "]"))
3639
3640 (defstruct (js2-call-node
3641 (:include js2-node)
3642 (:constructor nil)
3643 (:constructor make-js2-call-node (&key (type js2-CALL)
3644 (pos js2-ts-cursor)
3645 len
3646 target
3647 args
3648 lp
3649 rp)))
3650 "AST node for a JavaScript function call."
3651 target ; a `js2-node' evaluating to the function to call
3652 args ; a lisp list of `js2-node' arguments
3653 lp ; position of open-paren, or nil if missing
3654 rp) ; position of close-paren, or nil if missing
3655
3656 (put 'cl-struct-js2-call-node 'js2-visitor 'js2-visit-call-node)
3657 (put 'cl-struct-js2-call-node 'js2-printer 'js2-print-call-node)
3658
3659 (defun js2-visit-call-node (n v)
3660 (js2-visit-ast (js2-call-node-target n) v)
3661 (dolist (arg (js2-call-node-args n))
3662 (js2-visit-ast arg v)))
3663
3664 (defun js2-print-call-node (n i)
3665 (insert (js2-make-pad i))
3666 (js2-print-ast (js2-call-node-target n) 0)
3667 (insert "(")
3668 (js2-print-list (js2-call-node-args n))
3669 (insert ")"))
3670
3671 (defstruct (js2-yield-node
3672 (:include js2-node)
3673 (:constructor nil)
3674 (:constructor make-js2-yield-node (&key (type js2-YIELD)
3675 (pos js2-ts-cursor)
3676 len
3677 value)))
3678 "AST node for yield statement or expression."
3679 value) ; optional: value to be yielded
3680
3681 (put 'cl-struct-js2-yield-node 'js2-visitor 'js2-visit-yield-node)
3682 (put 'cl-struct-js2-yield-node 'js2-printer 'js2-print-yield-node)
3683
3684 (defun js2-visit-yield-node (n v)
3685 (js2-visit-ast (js2-yield-node-value n) v))
3686
3687 (defun js2-print-yield-node (n i)
3688 (insert (js2-make-pad i))
3689 (insert "yield")
3690 (when (js2-yield-node-value n)
3691 (insert " ")
3692 (js2-print-ast (js2-yield-node-value n) 0)))
3693
3694 (defstruct (js2-paren-node
3695 (:include js2-node)
3696 (:constructor nil)
3697 (:constructor make-js2-paren-node (&key (type js2-LP)
3698 (pos js2-ts-cursor)
3699 len
3700 expr)))
3701 "AST node for a parenthesized expression.
3702 In particular, used when the parens are syntactically optional,
3703 as opposed to required parens such as those enclosing an if-conditional."
3704 expr) ; `js2-node'
3705
3706 (put 'cl-struct-js2-paren-node 'js2-visitor 'js2-visit-paren-node)
3707 (put 'cl-struct-js2-paren-node 'js2-printer 'js2-print-paren-node)
3708
3709 (defun js2-visit-paren-node (n v)
3710 (js2-visit-ast (js2-paren-node-expr n) v))
3711
3712 (defun js2-print-paren-node (n i)
3713 (insert (js2-make-pad i))
3714 (insert "(")
3715 (js2-print-ast (js2-paren-node-expr n) 0)
3716 (insert ")"))
3717
3718 (defstruct (js2-array-comp-node
3719 (:include js2-scope)
3720 (:constructor nil)
3721 (:constructor make-js2-array-comp-node (&key (type js2-ARRAYCOMP)
3722 (pos js2-ts-cursor)
3723 len
3724 result
3725 loops
3726 filter
3727 if-pos
3728 lp
3729 rp)))
3730 "AST node for an Array comprehension such as [[x,y] for (x in foo) for (y in bar)]."
3731 result ; result expression (just after left-bracket)
3732 loops ; a lisp list of `js2-array-comp-loop-node'
3733 filter ; guard/filter expression
3734 if-pos ; buffer pos of 'if' keyword, if present, else nil
3735 lp ; buffer position of if-guard left-paren, or nil if not present
3736 rp) ; buffer position of if-guard right-paren, or nil if not present
3737
3738 (put 'cl-struct-js2-array-comp-node 'js2-visitor 'js2-visit-array-comp-node)
3739 (put 'cl-struct-js2-array-comp-node 'js2-printer 'js2-print-array-comp-node)
3740
3741 (defun js2-visit-array-comp-node (n v)
3742 (js2-visit-ast (js2-array-comp-node-result n) v)
3743 (dolist (l (js2-array-comp-node-loops n))
3744 (js2-visit-ast l v))
3745 (if (js2-array-comp-node-filter n)
3746 (js2-visit-ast (js2-array-comp-node-filter n) v)))
3747
3748 (defun js2-print-array-comp-node (n i)
3749 (let ((pad (js2-make-pad i))
3750 (result (js2-array-comp-node-result n))
3751 (loops (js2-array-comp-node-loops n))
3752 (filter (js2-array-comp-node-filter n)))
3753 (insert pad "[")
3754 (js2-print-ast result 0)
3755 (dolist (l loops)
3756 (insert " ")
3757 (js2-print-ast l 0))
3758 (when filter
3759 (insert " if (")
3760 (js2-print-ast filter 0))
3761 (insert ")]")))
3762
3763 (defstruct (js2-array-comp-loop-node
3764 (:include js2-for-in-node)
3765 (:constructor nil)
3766 (:constructor make-js2-array-comp-loop-node (&key (type js2-FOR)
3767 (pos js2-ts-cursor)
3768 len
3769 iterator
3770 object
3771 in-pos
3772 foreach-p
3773 each-pos
3774 lp
3775 rp)))
3776 "AST subtree for each 'for (foo in bar)' loop in an array comprehension.")
3777
3778 (put 'cl-struct-js2-array-comp-loop-node 'js2-visitor 'js2-visit-array-comp-loop)
3779 (put 'cl-struct-js2-array-comp-loop-node 'js2-printer 'js2-print-array-comp-loop)
3780
3781 (defun js2-visit-array-comp-loop (n v)
3782 (js2-visit-ast (js2-array-comp-loop-node-iterator n) v)
3783 (js2-visit-ast (js2-array-comp-loop-node-object n) v))
3784
3785 (defun js2-print-array-comp-loop (n i)
3786 (insert "for (")
3787 (js2-print-ast (js2-array-comp-loop-node-iterator n) 0)
3788 (insert " in ")
3789 (js2-print-ast (js2-array-comp-loop-node-object n) 0)
3790 (insert ")"))
3791
3792 (defstruct (js2-empty-expr-node
3793 (:include js2-node)
3794 (:constructor nil)
3795 (:constructor make-js2-empty-expr-node (&key (type js2-EMPTY)
3796 (pos js2-token-beg)
3797 len)))
3798 "AST node for an empty expression.")
3799
3800 (put 'cl-struct-js2-empty-expr-node 'js2-visitor 'js2-visit-none)
3801 (put 'cl-struct-js2-empty-expr-node 'js2-printer 'js2-print-none)
3802
3803 (defstruct (js2-xml-node
3804 (:include js2-block-node)
3805 (:constructor nil)
3806 (:constructor make-js2-xml-node (&key (type js2-XML)
3807 (pos js2-token-beg)
3808 len
3809 kids)))
3810 "AST node for initial parse of E4X literals.
3811 The kids field is a list of XML fragments, each a `js2-string-node' or
3812 a `js2-xml-js-expr-node'. Equivalent to Rhino's XmlLiteral node.")
3813
3814 (put 'cl-struct-js2-xml-node 'js2-visitor 'js2-visit-block)
3815 (put 'cl-struct-js2-xml-node 'js2-printer 'js2-print-xml-node)
3816
3817 (defun js2-print-xml-node (n i)
3818 (dolist (kid (js2-xml-node-kids n))
3819 (js2-print-ast kid i)))
3820
3821 (defstruct (js2-xml-js-expr-node
3822 (:include js2-xml-node)
3823 (:constructor nil)
3824 (:constructor make-js2-xml-js-expr-node (&key (type js2-XML)
3825 (pos js2-ts-cursor)
3826 len
3827 expr)))
3828 "AST node for an embedded JavaScript {expression} in an E4X literal.
3829 The start and end fields correspond to the curly-braces."
3830 expr) ; a `js2-expr-node' of some sort
3831
3832 (put 'cl-struct-js2-xml-js-expr-node 'js2-visitor 'js2-visit-xml-js-expr)
3833 (put 'cl-struct-js2-xml-js-expr-node 'js2-printer 'js2-print-xml-js-expr)
3834
3835 (defun js2-visit-xml-js-expr (n v)
3836 (js2-visit-ast (js2-xml-js-expr-node-expr n) v))
3837
3838 (defun js2-print-xml-js-expr (n i)
3839 (insert (js2-make-pad i))
3840 (insert "{")
3841 (js2-print-ast (js2-xml-js-expr-node-expr n) 0)
3842 (insert "}"))
3843
3844 (defstruct (js2-xml-dot-query-node
3845 (:include js2-infix-node)
3846 (:constructor nil)
3847 (:constructor make-js2-xml-dot-query-node (&key (type js2-DOTQUERY)
3848 (pos js2-ts-cursor)
3849 op-pos
3850 len
3851 left
3852 right
3853 rp)))
3854 "AST node for an E4X foo.(bar) filter expression.
3855 Note that the left-paren is automatically the character immediately
3856 following the dot (.) in the operator. No whitespace is permitted
3857 between the dot and the lp by the scanner."
3858 rp)
3859
3860 (put 'cl-struct-js2-xml-dot-query-node 'js2-visitor 'js2-visit-infix-node)
3861 (put 'cl-struct-js2-xml-dot-query-node 'js2-printer 'js2-print-xml-dot-query)
3862
3863 (defun js2-print-xml-dot-query (n i)
3864 (insert (js2-make-pad i))
3865 (js2-print-ast (js2-xml-dot-query-node-left n) 0)
3866 (insert ".(")
3867 (js2-print-ast (js2-xml-dot-query-node-right n) 0)
3868 (insert ")"))
3869
3870 (defstruct (js2-xml-ref-node
3871 (:include js2-node)
3872 (:constructor nil)) ; abstract
3873 "Base type for E4X XML attribute-access or property-get expressions.
3874 Such expressions can take a variety of forms. The general syntax has
3875 three parts:
3876
3877 - (optional) an @ (specifying an attribute access)
3878 - (optional) a namespace (a `js2-name-node') and double-colon
3879 - (required) either a `js2-name-node' or a bracketed [expression]
3880
3881 The property-name expressions (examples: ns::name, @name) are
3882 represented as `js2-xml-prop-ref' nodes. The bracketed-expression
3883 versions (examples: ns::[name], @[name]) become `js2-xml-elem-ref' nodes.
3884
3885 This node type (or more specifically, its subclasses) will sometimes
3886 be the right-hand child of a `js2-prop-get-node' or a
3887 `js2-infix-node' of type `js2-DOTDOT', the .. xml-descendants operator.
3888 The `js2-xml-ref-node' may also be a standalone primary expression with
3889 no explicit target, which is valid in certain expression contexts such as
3890
3891 company..employee.(@id < 100)
3892
3893 in this case, the @id is a `js2-xml-ref' that is part of an infix '<'
3894 expression whose parent is a `js2-xml-dot-query-node'."
3895 namespace
3896 at-pos
3897 colon-pos)
3898
3899 (defsubst js2-xml-ref-node-attr-access-p (node)
3900 "Return non-nil if this expression began with an @-token."
3901 (and (numberp (js2-xml-ref-node-at-pos node))
3902 (plusp (js2-xml-ref-node-at-pos node))))
3903
3904 (defstruct (js2-xml-prop-ref-node
3905 (:include js2-xml-ref-node)
3906 (:constructor nil)
3907 (:constructor make-js2-xml-prop-ref-node (&key (type js2-REF_NAME)
3908 (pos js2-token-beg)
3909 len
3910 propname
3911 namespace
3912 at-pos
3913 colon-pos)))
3914 "AST node for an E4X XML [expr] property-ref expression.
3915 The JavaScript syntax is an optional @, an optional ns::, and a name.
3916
3917 [ '@' ] [ name '::' ] name
3918
3919 Examples include name, ns::name, ns::*, *::name, *::*, @attr, @ns::attr,
3920 @ns::*, @*::attr, @*::*, and @*.
3921
3922 The node starts at the @ token, if present. Otherwise it starts at the
3923 namespace name. The node bounds extend through the closing right-bracket,
3924 or if it is missing due to a syntax error, through the end of the index
3925 expression."
3926 propname)
3927
3928 (put 'cl-struct-js2-xml-prop-ref-node 'js2-visitor 'js2-visit-xml-prop-ref-node)
3929 (put 'cl-struct-js2-xml-prop-ref-node 'js2-printer 'js2-print-xml-prop-ref-node)
3930
3931 (defun js2-visit-xml-prop-ref-node (n v)
3932 (if (js2-xml-prop-ref-node-namespace n)
3933 (js2-visit-ast (js2-xml-prop-ref-node-namespace n) v))
3934 (if (js2-xml-prop-ref-node-propname n)
3935 (js2-visit-ast (js2-xml-prop-ref-node-propname n) v)))
3936
3937 (defun js2-print-xml-prop-ref-node (n i)
3938 (insert (js2-make-pad i))
3939 (if (js2-xml-ref-node-attr-access-p n)
3940 (insert "@"))
3941 (when (js2-xml-prop-ref-node-namespace n)
3942 (js2-print-ast (js2-xml-prop-ref-node-namespace n) 0)
3943 (insert "::"))
3944 (if (js2-xml-prop-ref-node-propname n)
3945 (js2-print-ast (js2-xml-prop-ref-node-propname n) 0)))
3946
3947 (defstruct (js2-xml-elem-ref-node
3948 (:include js2-xml-ref-node)
3949 (:constructor nil)
3950 (:constructor make-js2-xml-elem-ref-node (&key (type js2-REF_MEMBER)
3951 (pos js2-token-beg)
3952 len
3953 expr
3954 lb
3955 rb
3956 namespace
3957 at-pos
3958 colon-pos)))
3959 "AST node for an E4X XML [expr] member-ref expression.
3960 Syntax:
3961
3962 [ '@' ] [ name '::' ] '[' expr ']'
3963
3964 Examples include ns::[expr], @ns::[expr], @[expr], *::[expr] and @*::[expr].
3965
3966 Note that the form [expr] (i.e. no namespace or attribute-qualifier)
3967 is not a legal E4X XML element-ref expression, since it's already used
3968 for standard JavaScript element-get array indexing. Hence, a
3969 `js2-xml-elem-ref-node' always has either the attribute-qualifier, a
3970 non-nil namespace node, or both.
3971
3972 The node starts at the @ token, if present. Otherwise it starts
3973 at the namespace name. The node bounds extend through the closing
3974 right-bracket, or if it is missing due to a syntax error, through the
3975 end of the index expression."
3976 expr ; the bracketed index expression
3977 lb
3978 rb)
3979
3980 (put 'cl-struct-js2-xml-elem-ref-node 'js2-visitor 'js2-visit-xml-elem-ref-node)
3981 (put 'cl-struct-js2-xml-elem-ref-node 'js2-printer 'js2-print-xml-elem-ref-node)
3982
3983 (defun js2-visit-xml-elem-ref-node (n v)
3984 (if (js2-xml-elem-ref-node-namespace n)
3985 (js2-visit-ast (js2-xml-elem-ref-node-namespace n) v))
3986 (if (js2-xml-elem-ref-node-expr n)
3987 (js2-visit-ast (js2-xml-elem-ref-node-expr n) v)))
3988
3989 (defun js2-print-xml-elem-ref-node (n i)
3990 (insert (js2-make-pad i))
3991 (if (js2-xml-ref-node-attr-access-p n)
3992 (insert "@"))
3993 (when (js2-xml-elem-ref-node-namespace n)
3994 (js2-print-ast (js2-xml-elem-ref-node-namespace n) 0)
3995 (insert "::"))
3996 (insert "[")
3997 (if (js2-xml-elem-ref-node-expr n)
3998 (js2-print-ast (js2-xml-elem-ref-node-expr n) 0))
3999 (insert "]"))
4000
4001 ;;; Placeholder nodes for when we try parsing the XML literals structurally.
4002
4003 (defstruct (js2-xml-start-tag-node
4004 (:include js2-xml-node)
4005 (:constructor nil)
4006 (:constructor make-js2-xml-start-tag-node (&key (type js2-XML)
4007 (pos js2-ts-cursor)
4008 len
4009 name
4010 attrs
4011 kids
4012 empty-p)))
4013 "AST node for an XML start-tag. Not currently used.
4014 The `kids' field is a lisp list of child content nodes."
4015 name ; a `js2-xml-name-node'
4016 attrs ; a lisp list of `js2-xml-attr-node'
4017 empty-p) ; t if this is an empty element such as <foo bar="baz"/>
4018
4019 (put 'cl-struct-js2-xml-start-tag-node 'js2-visitor 'js2-visit-xml-start-tag)
4020 (put 'cl-struct-js2-xml-start-tag-node 'js2-printer 'js2-print-xml-start-tag)
4021
4022 (defun js2-visit-xml-start-tag (n v)
4023 (js2-visit-ast (js2-xml-start-tag-node-name n) v)
4024 (dolist (attr (js2-xml-start-tag-node-attrs n))
4025 (js2-visit-ast attr v))
4026 (js2-visit-block n v))
4027
4028 (defun js2-print-xml-start-tag (n i)
4029 (insert (js2-make-pad i) "<")
4030 (js2-print-ast (js2-xml-start-tag-node-name n) 0)
4031 (when (js2-xml-start-tag-node-attrs n)
4032 (insert " ")
4033 (js2-print-list (js2-xml-start-tag-node-attrs n) " "))
4034 (insert ">"))
4035
4036 ;; I -think- I'm going to make the parent node the corresponding start-tag,
4037 ;; and add the end-tag to the kids list of the parent as well.
4038 (defstruct (js2-xml-end-tag-node
4039 (:include js2-xml-node)
4040 (:constructor nil)
4041 (:constructor make-js2-xml-end-tag-node (&key (type js2-XML)
4042 (pos js2-ts-cursor)
4043 len
4044 name)))
4045 "AST node for an XML end-tag. Not currently used."
4046 name) ; a `js2-xml-name-node'
4047
4048 (put 'cl-struct-js2-xml-end-tag-node 'js2-visitor 'js2-visit-xml-end-tag)
4049 (put 'cl-struct-js2-xml-end-tag-node 'js2-printer 'js2-print-xml-end-tag)
4050
4051 (defun js2-visit-xml-end-tag (n v)
4052 (js2-visit-ast (js2-xml-end-tag-node-name n) v))
4053
4054 (defun js2-print-xml-end-tag (n i)
4055 (insert (js2-make-pad i))
4056 (insert "</")
4057 (js2-print-ast (js2-xml-end-tag-node-name n) 0)
4058 (insert ">"))
4059
4060 (defstruct (js2-xml-name-node
4061 (:include js2-xml-node)
4062 (:constructor nil)
4063 (:constructor make-js2-xml-name-node (&key (type js2-XML)
4064 (pos js2-ts-cursor)
4065 len
4066 namespace
4067 kids)))
4068 "AST node for an E4X XML name. Not currently used.
4069 Any XML name can be qualified with a namespace, hence the namespace field.
4070 Further, any E4X name can be comprised of arbitrary JavaScript {} expressions.
4071 The kids field is a list of `js2-name-node' and `js2-xml-js-expr-node'.
4072 For a simple name, the kids list has exactly one node, a `js2-name-node'."
4073 namespace) ; a `js2-string-node'
4074
4075 (put 'cl-struct-js2-xml-name-node 'js2-visitor 'js2-visit-xml-name-node)
4076 (put 'cl-struct-js2-xml-name-node 'js2-printer 'js2-print-xml-name-node)
4077
4078 (defun js2-visit-xml-name-node (n v)
4079 (js2-visit-ast (js2-xml-name-node-namespace n) v))
4080
4081 (defun js2-print-xml-name-node (n i)
4082 (insert (js2-make-pad i))
4083 (when (js2-xml-name-node-namespace n)
4084 (js2-print-ast (js2-xml-name-node-namespace n) 0)
4085 (insert "::"))
4086 (dolist (kid (js2-xml-name-node-kids n))
4087 (js2-print-ast kid 0)))
4088
4089 (defstruct (js2-xml-pi-node
4090 (:include js2-xml-node)
4091 (:constructor nil)
4092 (:constructor make-js2-xml-pi-node (&key (type js2-XML)
4093 (pos js2-ts-cursor)
4094 len
4095 name
4096 attrs)))
4097 "AST node for an E4X XML processing instruction. Not currently used."
4098 name ; a `js2-xml-name-node'
4099 attrs) ; a list of `js2-xml-attr-node'
4100
4101 (put 'cl-struct-js2-xml-pi-node 'js2-visitor 'js2-visit-xml-pi-node)
4102 (put 'cl-struct-js2-xml-pi-node 'js2-printer 'js2-print-xml-pi-node)
4103
4104 (defun js2-visit-xml-pi-node (n v)
4105 (js2-visit-ast (js2-xml-pi-node-name n) v)
4106 (dolist (attr (js2-xml-pi-node-attrs n))
4107 (js2-visit-ast attr v)))
4108
4109 (defun js2-print-xml-pi-node (n i)
4110 (insert (js2-make-pad i) "<?")
4111 (js2-print-ast (js2-xml-pi-node-name n))
4112 (when (js2-xml-pi-node-attrs n)
4113 (insert " ")
4114 (js2-print-list (js2-xml-pi-node-attrs n)))
4115 (insert "?>"))
4116
4117 (defstruct (js2-xml-cdata-node
4118 (:include js2-xml-node)
4119 (:constructor nil)
4120 (:constructor make-js2-xml-cdata-node (&key (type js2-XML)
4121 (pos js2-ts-cursor)
4122 len
4123 content)))
4124 "AST node for a CDATA escape section. Not currently used."
4125 content) ; a `js2-string-node' with node-property 'quote-type 'cdata
4126
4127 (put 'cl-struct-js2-xml-cdata-node 'js2-visitor 'js2-visit-xml-cdata-node)
4128 (put 'cl-struct-js2-xml-cdata-node 'js2-printer 'js2-print-xml-cdata-node)
4129
4130 (defun js2-visit-xml-cdata-node (n v)
4131 (js2-visit-ast (js2-xml-cdata-node-content n) v))
4132
4133 (defun js2-print-xml-cdata-node (n i)
4134 (insert (js2-make-pad i))
4135 (js2-print-ast (js2-xml-cdata-node-content n)))
4136
4137 (defstruct (js2-xml-attr-node
4138 (:include js2-xml-node)
4139 (:constructor nil)
4140 (:constructor make-js2-attr-node (&key (type js2-XML)
4141 (pos js2-ts-cursor)
4142 len
4143 name
4144 value
4145 eq-pos
4146 quote-type)))
4147 "AST node representing a foo='bar' XML attribute value. Not yet used."
4148 name ; a `js2-xml-name-node'
4149 value ; a `js2-xml-name-node'
4150 eq-pos ; buffer position of "=" sign
4151 quote-type) ; 'single or 'double
4152
4153 (put 'cl-struct-js2-xml-attr-node 'js2-visitor 'js2-visit-xml-attr-node)
4154 (put 'cl-struct-js2-xml-attr-node 'js2-printer 'js2-print-xml-attr-node)
4155
4156 (defun js2-visit-xml-attr-node (n v)
4157 (js2-visit-ast (js2-xml-attr-node-name n) v)
4158 (js2-visit-ast (js2-xml-attr-node-value n) v))
4159
4160 (defun js2-print-xml-attr-node (n i)
4161 (let ((quote (if (eq (js2-xml-attr-node-quote-type n) 'single)
4162 "'"
4163 "\"")))
4164 (insert (js2-make-pad i))
4165 (js2-print-ast (js2-xml-attr-node-name n) 0)
4166 (insert "=" quote)
4167 (js2-print-ast (js2-xml-attr-node-value n) 0)
4168 (insert quote)))
4169
4170 (defstruct (js2-xml-text-node
4171 (:include js2-xml-node)
4172 (:constructor nil)
4173 (:constructor make-js2-text-node (&key (type js2-XML)
4174 (pos js2-ts-cursor)
4175 len
4176 content)))
4177 "AST node for an E4X XML text node. Not currently used."
4178 content) ; a lisp list of `js2-string-node' and `js2-xml-js-expr-node'
4179
4180 (put 'cl-struct-js2-xml-text-node 'js2-visitor 'js2-visit-xml-text-node)
4181 (put 'cl-struct-js2-xml-text-node 'js2-printer 'js2-print-xml-text-node)
4182
4183 (defun js2-visit-xml-text-node (n v)
4184 (js2-visit-ast (js2-xml-text-node-content n) v))
4185
4186 (defun js2-print-xml-text-node (n i)
4187 (insert (js2-make-pad i))
4188 (dolist (kid (js2-xml-text-node-content n))
4189 (js2-print-ast kid)))
4190
4191 (defstruct (js2-xml-comment-node
4192 (:include js2-xml-node)
4193 (:constructor nil)
4194 (:constructor make-js2-xml-comment-node (&key (type js2-XML)
4195 (pos js2-ts-cursor)
4196 len)))
4197 "AST node for E4X XML comment. Not currently used.")
4198
4199 (put 'cl-struct-js2-xml-comment-node 'js2-visitor 'js2-visit-none)
4200 (put 'cl-struct-js2-xml-comment-node 'js2-printer 'js2-print-xml-comment)
4201
4202 (defun js2-print-xml-comment (n i)
4203 (insert (js2-make-pad i)
4204 (js2-node-string n)))
4205
4206 ;;; Node utilities
4207
4208 (defsubst js2-node-line (n)
4209 "Fetch the source line number at the start of node N.
4210 This is O(n) in the length of the source buffer; use prudently."
4211 (1+ (count-lines (point-min) (js2-node-abs-pos n))))
4212
4213 (defsubst js2-block-node-kid (n i)
4214 "Return child I of node N, or nil if there aren't that many."
4215 (nth i (js2-block-node-kids n)))
4216
4217 (defsubst js2-block-node-first (n)
4218 "Return first child of block node N, or nil if there is none."
4219 (first (js2-block-node-kids n)))
4220
4221 (defun js2-node-root (n)
4222 "Return the root of the AST containing N.
4223 If N has no parent pointer, returns N."
4224 (let ((parent (js2-node-parent n)))
4225 (if parent
4226 (js2-node-root parent)
4227 n)))
4228
4229 (defun js2-node-position-in-parent (node &optional parent)
4230 "Return the position of NODE in parent's block-kids list.
4231 PARENT can be supplied if known. Positioned returned is zero-indexed.
4232 Returns 0 if NODE is not a child of a block statement, or if NODE
4233 is not a statement node."
4234 (let ((p (or parent (js2-node-parent node)))
4235 (i 0))
4236 (if (not (js2-block-node-p p))
4237 i
4238 (or (js2-position node (js2-block-node-kids p))
4239 0))))
4240
4241 (defsubst js2-node-short-name (n)
4242 "Return the short name of node N as a string, e.g. `js2-if-node'."
4243 (substring (symbol-name (aref n 0))
4244 (length "cl-struct-")))
4245
4246 (defsubst js2-node-child-list (node)
4247 "Return the child list for NODE, a lisp list of nodes.
4248 Works for block nodes, array nodes, obj literals, funarg lists,
4249 var decls and try nodes (for catch clauses). Note that you should call
4250 `js2-block-node-kids' on the function body for the body statements.
4251 Returns nil for zero-length child lists or unsupported nodes."
4252 (cond
4253 ((js2-function-node-p node)
4254 (js2-function-node-params node))
4255 ((js2-block-node-p node)
4256 (js2-block-node-kids node))
4257 ((js2-try-node-p node)
4258 (js2-try-node-catch-clauses node))
4259 ((js2-array-node-p node)
4260 (js2-array-node-elems node))
4261 ((js2-object-node-p node)
4262 (js2-object-node-elems node))
4263 ((js2-call-node-p node)
4264 (js2-call-node-args node))
4265 ((js2-new-node-p node)
4266 (js2-new-node-args node))
4267 ((js2-var-decl-node-p node)
4268 (js2-var-decl-node-kids node))
4269 (t
4270 nil)))
4271
4272 (defsubst js2-node-set-child-list (node kids)
4273 "Set the child list for NODE to KIDS."
4274 (cond
4275 ((js2-function-node-p node)
4276 (setf (js2-function-node-params node) kids))
4277 ((js2-block-node-p node)
4278 (setf (js2-block-node-kids node) kids))
4279 ((js2-try-node-p node)
4280 (setf (js2-try-node-catch-clauses node) kids))
4281 ((js2-array-node-p node)
4282 (setf (js2-array-node-elems node) kids))
4283 ((js2-object-node-p node)
4284 (setf (js2-object-node-elems node) kids))
4285 ((js2-call-node-p node)
4286 (setf (js2-call-node-args node) kids))
4287 ((js2-new-node-p node)
4288 (setf (js2-new-node-args node) kids))
4289 ((js2-var-decl-node-p node)
4290 (setf (js2-var-decl-node-kids node) kids))
4291 (t
4292 (error "Unsupported node type: %s" (js2-node-short-name node))))
4293 kids)
4294
4295 ;; All because Common Lisp doesn't support multiple inheritance for defstructs.
4296 (defconst js2-paren-expr-nodes
4297 '(cl-struct-js2-array-comp-loop-node
4298 cl-struct-js2-array-comp-node
4299 cl-struct-js2-call-node
4300 cl-struct-js2-catch-node
4301 cl-struct-js2-do-node
4302 cl-struct-js2-elem-get-node
4303 cl-struct-js2-for-in-node
4304 cl-struct-js2-for-node
4305 cl-struct-js2-function-node
4306 cl-struct-js2-if-node
4307 cl-struct-js2-let-node
4308 cl-struct-js2-new-node
4309 cl-struct-js2-paren-node
4310 cl-struct-js2-switch-node
4311 cl-struct-js2-while-node
4312 cl-struct-js2-with-node
4313 cl-struct-js2-xml-dot-query-node)
4314 "Node types that can have a parenthesized child expression.
4315 In particular, nodes that respond to `js2-node-lp' and `js2-node-rp'.")
4316
4317 (defsubst js2-paren-expr-node-p (node)
4318 "Return t for nodes that typically have a parenthesized child expression.
4319 Useful for computing the indentation anchors for arg-lists and conditions.
4320 Note that it may return a false positive, for instance when NODE is
4321 a `js2-new-node' and there are no arguments or parentheses."
4322 (memq (aref node 0) js2-paren-expr-nodes))
4323
4324 ;; Fake polymorphism... yech.
4325 (defsubst js2-node-lp (node)
4326 "Return relative left-paren position for NODE, if applicable.
4327 For `js2-elem-get-node' structs, returns left-bracket position.
4328 Note that the position may be nil in the case of a parse error."
4329 (cond
4330 ((js2-elem-get-node-p node)
4331 (js2-elem-get-node-lb node))
4332 ((js2-loop-node-p node)
4333 (js2-loop-node-lp node))
4334 ((js2-function-node-p node)
4335 (js2-function-node-lp node))
4336 ((js2-if-node-p node)
4337 (js2-if-node-lp node))
4338 ((js2-new-node-p node)
4339 (js2-new-node-lp node))
4340 ((js2-call-node-p node)
4341 (js2-call-node-lp node))
4342 ((js2-paren-node-p node)
4343 (js2-node-pos node))
4344 ((js2-switch-node-p node)
4345 (js2-switch-node-lp node))
4346 ((js2-catch-node-p node)
4347 (js2-catch-node-lp node))
4348 ((js2-let-node-p node)
4349 (js2-let-node-lp node))
4350 ((js2-array-comp-node-p node)
4351 (js2-array-comp-node-lp node))
4352 ((js2-with-node-p node)
4353 (js2-with-node-lp node))
4354 ((js2-xml-dot-query-node-p node)
4355 (1+ (js2-infix-node-op-pos node)))
4356 (t
4357 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4358
4359 ;; Fake polymorphism... blech.
4360 (defsubst js2-node-rp (node)
4361 "Return relative right-paren position for NODE, if applicable.
4362 For `js2-elem-get-node' structs, returns right-bracket position.
4363 Note that the position may be nil in the case of a parse error."
4364 (cond
4365 ((js2-elem-get-node-p node)
4366 (js2-elem-get-node-lb node))
4367 ((js2-loop-node-p node)
4368 (js2-loop-node-rp node))
4369 ((js2-function-node-p node)
4370 (js2-function-node-rp node))
4371 ((js2-if-node-p node)
4372 (js2-if-node-rp node))
4373 ((js2-new-node-p node)
4374 (js2-new-node-rp node))
4375 ((js2-call-node-p node)
4376 (js2-call-node-rp node))
4377 ((js2-paren-node-p node)
4378 (+ (js2-node-pos node) (js2-node-len node)))
4379 ((js2-switch-node-p node)
4380 (js2-switch-node-rp node))
4381 ((js2-catch-node-p node)
4382 (js2-catch-node-rp node))
4383 ((js2-let-node-p node)
4384 (js2-let-node-rp node))
4385 ((js2-array-comp-node-p node)
4386 (js2-array-comp-node-rp node))
4387 ((js2-with-node-p node)
4388 (js2-with-node-rp node))
4389 ((js2-xml-dot-query-node-p node)
4390 (1+ (js2-xml-dot-query-node-rp node)))
4391 (t
4392 (error "Unsupported node type: %s" (js2-node-short-name node)))))
4393
4394 (defsubst js2-node-first-child (node)
4395 "Returns the first element of `js2-node-child-list' for NODE."
4396 (car (js2-node-child-list node)))
4397
4398 (defsubst js2-node-last-child (node)
4399 "Returns the last element of `js2-node-last-child' for NODE."
4400 (car (last (js2-node-child-list node))))
4401
4402 (defun js2-node-prev-sibling (node)
4403 "Return the previous statement in parent.
4404 Works for parents supported by `js2-node-child-list'.
4405 Returns nil if NODE is not in the parent, or PARENT is
4406 not a supported node, or if NODE is the first child."
4407 (let* ((p (js2-node-parent node))
4408 (kids (js2-node-child-list p))
4409 (sib (car kids)))
4410 (while (and kids
4411 (not (eq node (cadr kids))))
4412 (setq kids (cdr kids)
4413 sib (car kids)))
4414 sib))
4415
4416 (defun js2-node-next-sibling (node)
4417 "Return the next statement in parent block.
4418 Returns nil if NODE is not in the block, or PARENT is not
4419 a block node, or if NODE is the last statement."
4420 (let* ((p (js2-node-parent node))
4421 (kids (js2-node-child-list p)))
4422 (while (and kids
4423 (not (eq node (car kids))))
4424 (setq kids (cdr kids)))
4425 (cadr kids)))
4426
4427 (defun js2-node-find-child-before (pos parent &optional after)
4428 "Find the last child that starts before POS in parent.
4429 If AFTER is non-nil, returns first child starting after POS.
4430 POS is an absolute buffer position. PARENT is any node
4431 supported by `js2-node-child-list'.
4432 Returns nil if no applicable child is found."
4433 (let ((kids (if (js2-function-node-p parent)
4434 (js2-block-node-kids (js2-function-node-body parent))
4435 (js2-node-child-list parent)))
4436 (beg (if (js2-function-node-p parent)
4437 (js2-node-abs-pos (js2-function-node-body parent))
4438 (js2-node-abs-pos parent)))
4439 kid
4440 result
4441 fn
4442 (continue t))
4443 (setq fn (if after '> '<))
4444 (while (and kids continue)
4445 (setq kid (car kids))
4446 (if (funcall fn (+ beg (js2-node-pos kid)) pos)
4447 (setq result kid
4448 continue (if after nil t))
4449 (setq continue (if after t nil)))
4450 (setq kids (cdr kids)))
4451 result))
4452
4453 (defun js2-node-find-child-after (pos parent)
4454 "Find first child that starts after POS in parent.
4455 POS is an absolute buffer position. PARENT is any node
4456 supported by `js2-node-child-list'.
4457 Returns nil if no applicable child is found."
4458 (js2-node-find-child-before pos parent 'after))
4459
4460 (defun js2-node-replace-child (pos parent new-node)
4461 "Replace node at index POS in PARENT with NEW-NODE.
4462 Only works for parents supported by `js2-node-child-list'."
4463 (let ((kids (js2-node-child-list parent))
4464 (i 0))
4465 (while (< i pos)
4466 (setq kids (cdr kids)
4467 i (1+ i)))
4468 (setcar kids new-node)
4469 (js2-node-add-children parent new-node)))
4470
4471 (defun js2-node-buffer (n)
4472 "Return the buffer associated with AST N.
4473 Returns nil if the buffer is not set as a property on the root
4474 node, or if parent links were not recorded during parsing."
4475 (let ((root (js2-node-root n)))
4476 (and root
4477 (js2-ast-root-p root)
4478 (js2-ast-root-buffer root))))
4479
4480 (defsubst js2-block-node-push (n kid)
4481 "Push js2-node KID onto the end of js2-block-node N's child list.
4482 KID is always added to the -end- of the kids list.
4483 Function also calls `js2-node-add-children' to add the parent link."
4484 (let ((kids (js2-node-child-list n)))
4485 (if kids
4486 (setcdr kids (nconc (cdr kids) (list kid)))
4487 (js2-node-set-child-list n (list kid)))
4488 (js2-node-add-children n kid)))
4489
4490 (defun js2-node-string (node)
4491 (let ((buf (js2-node-buffer node))
4492 pos)
4493 (unless buf
4494 (error "No buffer available for node %s" node))
4495 (save-excursion
4496 (set-buffer buf)
4497 (buffer-substring-no-properties (setq pos (js2-node-abs-pos node))
4498 (+ pos (js2-node-len node))))))
4499
4500 ;; Container for storing the node we're looking for in a traversal.
4501 (js2-deflocal js2-discovered-node nil)
4502
4503 ;; Keep track of absolute node position during traversals.
4504 (js2-deflocal js2-visitor-offset nil)
4505
4506 (js2-deflocal js2-node-search-point nil)
4507
4508 (when js2-mode-dev-mode-p
4509 (defun js2-find-node-at-point ()
4510 (interactive)
4511 (let ((node (js2-node-at-point)))
4512 (message "%s" (or node "No node found at point"))))
4513 (defun js2-node-name-at-point ()
4514 (interactive)
4515 (let ((node (js2-node-at-point)))
4516 (message "%s" (if node
4517 (js2-node-short-name node)
4518 "No node found at point.")))))
4519
4520 (defun js2-node-at-point (&optional pos skip-comments)
4521 "Return AST node at POS, a buffer position, defaulting to current point.
4522 The `js2-mode-ast' variable must be set to the current parse tree.
4523 Signals an error if the AST (`js2-mode-ast') is nil.
4524 Always returns a node - if it can't find one, it returns the root.
4525 If SKIP-COMMENTS is non-nil, comment nodes are ignored."
4526 (let ((ast js2-mode-ast)
4527 result)
4528 (unless ast
4529 (error "No JavaScript AST available"))
4530 ;; Look through comments first, since they may be inside nodes that
4531 ;; would otherwise report a match.
4532 (setq pos (or pos (point))
4533 result (if (> pos (js2-node-abs-end ast))
4534 ast
4535 (if (not skip-comments)
4536 (js2-comment-at-point pos))))
4537 (unless result
4538 (setq js2-discovered-node nil
4539 js2-visitor-offset 0
4540 js2-node-search-point pos)
4541 (unwind-protect
4542 (catch 'js2-visit-done
4543 (js2-visit-ast ast #'js2-node-at-point-visitor))
4544 (setq js2-visitor-offset nil
4545 js2-node-search-point nil))
4546 (setq result js2-discovered-node))
4547 ;; may have found a comment beyond end of last child node,
4548 ;; since visiting the ast-root looks at the comment-list last.
4549 (if (and skip-comments
4550 (js2-comment-node-p result))
4551 (setq result nil))
4552 (or result js2-mode-ast)))
4553
4554 (defun js2-node-at-point-visitor (node end-p)
4555 (let ((rel-pos (js2-node-pos node))
4556 abs-pos
4557 abs-end
4558 (point js2-node-search-point))
4559 (cond
4560 (end-p
4561 ;; this evaluates to a non-nil return value, even if it's zero
4562 (decf js2-visitor-offset rel-pos))
4563 ;; we already looked for comments before visiting, and don't want them now
4564 ((js2-comment-node-p node)
4565 nil)
4566 (t
4567 (setq abs-pos (incf js2-visitor-offset rel-pos)
4568 ;; we only want to use the node if the point is before
4569 ;; the last character position in the node, so we decrement
4570 ;; the absolute end by 1.
4571 abs-end (+ abs-pos (js2-node-len node) -1))
4572 (cond
4573 ;; If this node starts after search-point, stop the search.
4574 ((> abs-pos point)
4575 (throw 'js2-visit-done nil))
4576 ;; If this node ends before the search-point, don't check kids.
4577 ((> point abs-end)
4578 nil)
4579 (t
4580 ;; Otherwise point is within this node, possibly in a child.
4581 (setq js2-discovered-node node)
4582 t)))))) ; keep processing kids to look for more specific match
4583
4584 (defsubst js2-block-comment-p (node)
4585 "Return non-nil if NODE is a comment node of format `jsdoc' or `block'."
4586 (and (js2-comment-node-p node)
4587 (memq (js2-comment-node-format node) '(jsdoc block))))
4588
4589 ;; TODO: put the comments in a vector and binary-search them instead
4590 (defun js2-comment-at-point (&optional pos)
4591 "Look through scanned comment nodes for one containing POS.
4592 POS is a buffer position that defaults to current point.
4593 Function returns nil if POS was not in any comment node."
4594 (let ((ast js2-mode-ast)
4595 (x (or pos (point)))
4596 beg
4597 end)
4598 (unless ast
4599 (error "No JavaScript AST available"))
4600 (catch 'done
4601 ;; Comments are stored in lexical order.
4602 (dolist (comment (js2-ast-root-comments ast) nil)
4603 (setq beg (js2-node-abs-pos comment)
4604 end (+ beg (js2-node-len comment)))
4605 (if (and (>= x beg)
4606 (<= x end))
4607 (throw 'done comment))))))
4608
4609 (defun js2-mode-find-parent-fn (node)
4610 "Find function enclosing NODE.
4611 Returns nil if NODE is not inside a function."
4612 (setq node (js2-node-parent node))
4613 (while (and node (not (js2-function-node-p node)))
4614 (setq node (js2-node-parent node)))
4615 (and (js2-function-node-p node) node))
4616
4617 (defun js2-mode-find-enclosing-fn (node)
4618 "Find function or root enclosing NODE."
4619 (if (js2-ast-root-p node)
4620 node
4621 (setq node (js2-node-parent node))
4622 (while (not (or (js2-ast-root-p node)
4623 (js2-function-node-p node)))
4624 (setq node (js2-node-parent node)))
4625 node))
4626
4627 (defun js2-mode-find-enclosing-node (beg end)
4628 "Find script or function fully enclosing BEG and END."
4629 (let ((node (js2-node-at-point beg))
4630 pos
4631 (continue t))
4632 (while continue
4633 (if (or (js2-ast-root-p node)
4634 (and (js2-function-node-p node)
4635 (<= (setq pos (js2-node-abs-pos node)) beg)
4636 (>= (+ pos (js2-node-len node)) end)))
4637 (setq continue nil)
4638 (setq node (js2-node-parent node))))
4639 node))
4640
4641 (defun js2-node-parent-script-or-fn (node)
4642 "Find script or function immediately enclosing NODE.
4643 If NODE is the ast-root, returns nil."
4644 (if (js2-ast-root-p node)
4645 nil
4646 (setq node (js2-node-parent node))
4647 (while (and node (not (or (js2-function-node-p node)
4648 (js2-script-node-p node))))
4649 (setq node (js2-node-parent node)))
4650 node))
4651
4652 (defsubst js2-nested-function-p (node)
4653 "Return t if NODE is a nested function, or is inside a nested function."
4654 (js2-function-node-p (if (js2-function-node-p node)
4655 (js2-node-parent-script-or-fn node)
4656 (js2-node-parent-script-or-fn
4657 (js2-node-parent-script-or-fn node)))))
4658
4659 (defsubst js2-function-param-node-p (node)
4660 "Return non-nil if NODE is a param node of a `js2-function-node'."
4661 (let ((parent (js2-node-parent node)))
4662 (and parent
4663 (js2-function-node-p parent)
4664 (memq node (js2-function-node-params parent)))))
4665
4666 (defsubst js2-mode-shift-kids (kids start offset)
4667 (dolist (kid kids)
4668 (if (> (js2-node-pos kid) start)
4669 (incf (js2-node-pos kid) offset))))
4670
4671 (defsubst js2-mode-shift-children (parent start offset)
4672 "Update start-positions of all children of PARENT beyond START."
4673 (let ((root (js2-node-root parent)))
4674 (js2-mode-shift-kids (js2-node-child-list parent) start offset)
4675 (js2-mode-shift-kids (js2-ast-root-comments root) start offset)))
4676
4677 (defsubst js2-node-is-descendant (node ancestor)
4678 "Return t if NODE is a descendant of ANCESTOR."
4679 (while (and node
4680 (not (eq node ancestor)))
4681 (setq node (js2-node-parent node)))
4682 node)
4683
4684 ;;; visitor infrastructure
4685
4686 (defun js2-visit-none (node callback)
4687 "Visitor for AST node that have no node children."
4688 nil)
4689
4690 (defun js2-print-none (node indent)
4691 "Visitor for AST node with no printed representation.")
4692
4693 (defun js2-print-body (node indent)
4694 "Print a statement, or a block without braces."
4695 (if (js2-block-node-p node)
4696 (dolist (kid (js2-block-node-kids node))
4697 (js2-print-ast kid indent))
4698 (js2-print-ast node indent)))
4699
4700 (defun js2-print-list (args &optional delimiter)
4701 (loop with len = (length args)
4702 for arg in args
4703 for count from 1
4704 do
4705 (js2-print-ast arg 0)
4706 (if (< count len)
4707 (insert (or delimiter ", ")))))
4708
4709 (defun js2-print-tree (ast)
4710 "Prints an AST to the current buffer.
4711 Makes `js2-ast-parent-nodes' available to the printer functions."
4712 (let ((max-lisp-eval-depth (max max-lisp-eval-depth 1500)))
4713 (js2-print-ast ast)))
4714
4715 (defun js2-print-ast (node &optional indent)
4716 "Helper function for printing AST nodes.
4717 Requires `js2-ast-parent-nodes' to be non-nil.
4718 You should use `js2-print-tree' instead of this function."
4719 (let ((printer (get (aref node 0) 'js2-printer))
4720 (i (or indent 0))
4721 (pos (js2-node-abs-pos node)))
4722 ;; TODO: wedge comments in here somewhere
4723 (if printer
4724 (funcall printer node i))))
4725
4726 (defconst js2-side-effecting-tokens
4727 (let ((tokens (make-bool-vector js2-num-tokens nil)))
4728 (dolist (tt (list js2-ASSIGN
4729 js2-ASSIGN_ADD
4730 js2-ASSIGN_BITAND
4731 js2-ASSIGN_BITOR
4732 js2-ASSIGN_BITXOR
4733 js2-ASSIGN_DIV
4734 js2-ASSIGN_LSH
4735 js2-ASSIGN_MOD
4736 js2-ASSIGN_MUL
4737 js2-ASSIGN_RSH
4738 js2-ASSIGN_SUB
4739 js2-ASSIGN_URSH
4740 js2-BLOCK
4741 js2-BREAK
4742 js2-CALL
4743 js2-CATCH
4744 js2-CATCH_SCOPE
4745 js2-CONST
4746 js2-CONTINUE
4747 js2-DEBUGGER
4748 js2-DEC
4749 js2-DELPROP
4750 js2-DEL_REF
4751 js2-DO
4752 js2-ELSE
4753 js2-EMPTY
4754 js2-ENTERWITH
4755 js2-EXPORT
4756 js2-EXPR_RESULT
4757 js2-FINALLY
4758 js2-FOR
4759 js2-FUNCTION
4760 js2-GOTO
4761 js2-IF
4762 js2-IFEQ
4763 js2-IFNE
4764 js2-IMPORT
4765 js2-INC
4766 js2-JSR
4767 js2-LABEL
4768 js2-LEAVEWITH
4769 js2-LET
4770 js2-LETEXPR
4771 js2-LOCAL_BLOCK
4772 js2-LOOP
4773 js2-NEW
4774 js2-REF_CALL
4775 js2-RETHROW
4776 js2-RETURN
4777 js2-RETURN_RESULT
4778 js2-SEMI
4779 js2-SETELEM
4780 js2-SETELEM_OP
4781 js2-SETNAME
4782 js2-SETPROP
4783 js2-SETPROP_OP
4784 js2-SETVAR
4785 js2-SET_REF
4786 js2-SET_REF_OP
4787 js2-SWITCH
4788 js2-TARGET
4789 js2-THROW
4790 js2-TRY
4791 js2-VAR
4792 js2-WHILE
4793 js2-WITH
4794 js2-WITHEXPR
4795 js2-YIELD))
4796 (aset tokens tt t))
4797 (if js2-instanceof-has-side-effects
4798 (aset tokens js2-INSTANCEOF t))
4799 tokens))
4800
4801 (defun js2-node-has-side-effects (node)
4802 "Return t if NODE has side effects."
4803 (when node ; makes it easier to handle malformed expressions
4804 (let ((tt (js2-node-type node)))
4805 (cond
4806 ;; This doubtless needs some work, since EXPR_VOID is used
4807 ;; in several ways in Rhino, and I may not have caught them all.
4808 ;; I'll wait for people to notice incorrect warnings.
4809 ((and (= tt js2-EXPR_VOID)
4810 (js2-expr-stmt-node-p node)) ; but not if EXPR_RESULT
4811 (js2-node-has-side-effects (js2-expr-stmt-node-expr node)))
4812 ((= tt js2-COMMA)
4813 (js2-node-has-side-effects (js2-infix-node-right node)))
4814 ((or (= tt js2-AND)
4815 (= tt js2-OR))
4816 (or (js2-node-has-side-effects (js2-infix-node-right node))
4817 (js2-node-has-side-effects (js2-infix-node-left node))))
4818 ((= tt js2-HOOK)
4819 (and (js2-node-has-side-effects (js2-cond-node-true-expr node))
4820 (js2-node-has-side-effects (js2-cond-node-false-expr node))))
4821 ((js2-paren-node-p node)
4822 (js2-node-has-side-effects (js2-paren-node-expr node)))
4823 ((= tt js2-ERROR) ; avoid cascaded error messages
4824 nil)
4825 (t
4826 (aref js2-side-effecting-tokens tt))))))
4827
4828 (defun js2-member-expr-leftmost-name (node)
4829 "For an expr such as foo.bar.baz, return leftmost node foo.
4830 NODE is any `js2-node' object. If it represents a member expression,
4831 which is any sequence of property gets, element-gets, function calls,
4832 or xml descendants/filter operators, then we look at the lexically
4833 leftmost (first) node in the chain. If it is a name-node we return it.
4834 Note that NODE can be a raw name-node and it will be returned as well.
4835 If NODE is not a name-node or member expression, or if it is a member
4836 expression whose leftmost target is not a name node, returns nil."
4837 (let ((continue t)
4838 result)
4839 (while (and continue (not result))
4840 (cond
4841 ((js2-name-node-p node)
4842 (setq result node))
4843 ((js2-prop-get-node-p node)
4844 (setq node (js2-prop-get-node-left node)))
4845 ;; TODO: handle call-nodes, xml-nodes, others?
4846 (t
4847 (setq continue nil))))
4848 result))
4849
4850 (defconst js2-stmt-node-types
4851 (list js2-BLOCK
4852 js2-BREAK
4853 js2-CONTINUE
4854 js2-DEFAULT ; e4x "default xml namespace" statement
4855 js2-DO
4856 js2-EXPR_RESULT
4857 js2-EXPR_VOID
4858 js2-FOR
4859 js2-IF
4860 js2-RETURN
4861 js2-SWITCH
4862 js2-THROW
4863 js2-TRY
4864 js2-WHILE
4865 js2-WITH)
4866 "Node types that only appear in statement contexts.
4867 The list does not include nodes that always appear as the child
4868 of another specific statement type, such as switch-cases,
4869 catch and finally blocks, and else-clauses. The list also excludes
4870 nodes like yield, let and var, which may appear in either expression
4871 or statement context, and in the latter context always have a
4872 `js2-expr-stmt-node' parent. Finally, the list does not include
4873 functions or scripts, which are treated separately from statements
4874 by the JavaScript parser and runtime.")
4875
4876 (defun js2-stmt-node-p (node)
4877 "Heuristic for figuring out if NODE is a statement.
4878 Some node types can appear in either an expression context or a
4879 statement context, e.g. let-nodes, yield-nodes, and var-decl nodes.
4880 For these node types in a statement context, the parent will be a
4881 `js2-expr-stmt-node'.
4882 Functions aren't included in the check."
4883 (memq (js2-node-type node) js2-stmt-node-types))
4884
4885 (defsubst js2-mode-find-first-stmt (node)
4886 "Search upward starting from NODE looking for a statement.
4887 For purposes of this function, a `js2-function-node' counts."
4888 (while (not (or (js2-stmt-node-p node)
4889 (js2-function-node-p node)))
4890 (setq node (js2-node-parent node)))
4891 node)
4892
4893 (defun js2-node-parent-stmt (node)
4894 "Return the node's first ancestor that is a statement.
4895 Returns nil if NODE is a `js2-ast-root'. Note that any expression
4896 appearing in a statement context will have a parent that is a
4897 `js2-expr-stmt-node' that will be returned by this function."
4898 (let ((parent (js2-node-parent node)))
4899 (if (or (null parent)
4900 (js2-stmt-node-p parent)
4901 (and (js2-function-node-p parent)
4902 (not (eq (js2-function-node-form parent)
4903 'FUNCTION_EXPRESSION))))
4904 parent
4905 (js2-node-parent-stmt parent))))
4906
4907 ;; In the Mozilla Rhino sources, Roshan James writes:
4908 ;; Does consistent-return analysis on the function body when strict mode is
4909 ;; enabled.
4910 ;;
4911 ;; function (x) { return (x+1) }
4912 ;;
4913 ;; is ok, but
4914 ;;
4915 ;; function (x) { if (x < 0) return (x+1); }
4916 ;;
4917 ;; is not because the function can potentially return a value when the
4918 ;; condition is satisfied and if not, the function does not explicitly
4919 ;; return a value.
4920 ;;
4921 ;; This extends to checking mismatches such as "return" and "return <value>"
4922 ;; used in the same function. Warnings are not emitted if inconsistent
4923 ;; returns exist in code that can be statically shown to be unreachable.
4924 ;; Ex.
4925 ;; function (x) { while (true) { ... if (..) { return value } ... } }
4926 ;;
4927 ;; emits no warning. However if the loop had a break statement, then a
4928 ;; warning would be emitted.
4929 ;;
4930 ;; The consistency analysis looks at control structures such as loops, ifs,
4931 ;; switch, try-catch-finally blocks, examines the reachable code paths and
4932 ;; warns the user about an inconsistent set of termination possibilities.
4933 ;;
4934 ;; These flags enumerate the possible ways a statement/function can
4935 ;; terminate. These flags are used by endCheck() and by the Parser to
4936 ;; detect inconsistent return usage.
4937 ;;
4938 ;; END_UNREACHED is reserved for code paths that are assumed to always be
4939 ;; able to execute (example: throw, continue)
4940 ;;
4941 ;; END_DROPS_OFF indicates if the statement can transfer control to the
4942 ;; next one. Statement such as return dont. A compound statement may have
4943 ;; some branch that drops off control to the next statement.
4944 ;;
4945 ;; END_RETURNS indicates that the statement can return with no value.
4946 ;; END_RETURNS_VALUE indicates that the statement can return a value.
4947 ;;
4948 ;; A compound statement such as
4949 ;; if (condition) {
4950 ;; return value;
4951 ;; }
4952 ;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
4953
4954 (defconst js2-END_UNREACHED 0)
4955 (defconst js2-END_DROPS_OFF 1)
4956 (defconst js2-END_RETURNS 2)
4957 (defconst js2-END_RETURNS_VALUE 4)
4958 (defconst js2-END_YIELDS 8)
4959
4960 (defun js2-has-consistent-return-usage (node)
4961 "Check that every return usage in a function body is consistent.
4962 Returns t if the function satisfies strict mode requirement."
4963 (let ((n (js2-end-check node)))
4964 ;; either it doesn't return a value in any branch...
4965 (or (js2-flag-not-set-p n js2-END_RETURNS_VALUE)
4966 ;; or it returns a value (or is unreached) at every branch
4967 (js2-flag-not-set-p n (logior js2-END_DROPS_OFF
4968 js2-END_RETURNS
4969 js2-END_YIELDS)))))
4970
4971 (defun js2-end-check-if (node)
4972 "Returns in the then and else blocks must be consistent with each other.
4973 If there is no else block, then the return statement can fall through.
4974 Returns logical OR of END_* flags"
4975 (let ((th (js2-if-node-then-part node))
4976 (el (js2-if-node-else-part node)))
4977 (if (null th)
4978 js2-END_UNREACHED
4979 (logior (js2-end-check th) (if el
4980 (js2-end-check el)
4981 js2-END_DROPS_OFF)))))
4982
4983 (defun js2-end-check-switch (node)
4984 "Consistency of return statements is checked between the case statements.
4985 If there is no default, then the switch can fall through. If there is a
4986 default, we check to see if all code paths in the default return or if
4987 there is a code path that can fall through.
4988 Returns logical OR of END_* flags."
4989 (let ((rv js2-END_UNREACHED)
4990 default-case)
4991 ;; examine the cases
4992 (catch 'break
4993 (dolist (c (js2-switch-node-cases node))
4994 (if (js2-case-node-expr c)
4995 (js2-set-flag rv (js2-end-check-block c))
4996 (setq default-case c)
4997 (throw 'break nil))))
4998 ;; we don't care how the cases drop into each other
4999 (js2-clear-flag rv js2-END_DROPS_OFF)
5000 ;; examine the default
5001 (js2-set-flag rv (if default-case
5002 (js2-end-check default-case)
5003 js2-END_DROPS_OFF))
5004 rv))
5005
5006 (defun js2-end-check-try (node)
5007 "If the block has a finally, return consistency is checked in the
5008 finally block. If all code paths in the finally return, then the
5009 returns in the try-catch blocks don't matter. If there is a code path
5010 that does not return or if there is no finally block, the returns
5011 of the try and catch blocks are checked for mismatch.
5012 Returns logical OR of END_* flags."
5013 (let ((finally (js2-try-node-finally-block node))
5014 rv)
5015 ;; check the finally if it exists
5016 (setq rv (if finally
5017 (js2-end-check (js2-finally-node-body finally))
5018 js2-END_DROPS_OFF))
5019 ;; If the finally block always returns, then none of the returns
5020 ;; in the try or catch blocks matter.
5021 (when (js2-flag-set-p rv js2-END_DROPS_OFF)
5022 (js2-clear-flag rv js2-END_DROPS_OFF)
5023 ;; examine the try block
5024 (js2-set-flag rv (js2-end-check (js2-try-node-try-block node)))
5025 ;; check each catch block
5026 (dolist (cb (js2-try-node-catch-clauses node))
5027 (js2-set-flag rv (js2-end-check (js2-catch-node-block cb)))))
5028 rv))
5029
5030 (defun js2-end-check-loop (node)
5031 "Return statement in the loop body must be consistent. The default
5032 assumption for any kind of a loop is that it will eventually terminate.
5033 The only exception is a loop with a constant true condition. Code that
5034 follows such a loop is examined only if one can statically determine
5035 that there is a break out of the loop.
5036
5037 for(... ; ... ; ...) {}
5038 for(... in ... ) {}
5039 while(...) { }
5040 do { } while(...)
5041
5042 Returns logical OR of END_* flags."
5043 (let ((rv (js2-end-check (js2-loop-node-body node)))
5044 (condition (cond
5045 ((js2-while-node-p node)
5046 (js2-while-node-condition node))
5047 ((js2-do-node-p node)
5048 (js2-do-node-condition node))
5049 ((js2-for-node-p node)
5050 (js2-for-node-condition node)))))
5051
5052 ;; check to see if the loop condition is always true
5053 (if (and condition
5054 (eq (js2-always-defined-boolean-p condition) 'ALWAYS_TRUE))
5055 (js2-clear-flag rv js2-END_DROPS_OFF))
5056
5057 ;; look for effect of breaks
5058 (js2-set-flag rv (js2-node-get-prop node
5059 'CONTROL_BLOCK_PROP
5060 js2-END_UNREACHED))
5061 rv))
5062
5063 (defun js2-end-check-block (node)
5064 "A general block of code is examined statement by statement.
5065 If any statement (even a compound one) returns in all branches, then
5066 subsequent statements are not examined.
5067 Returns logical OR of END_* flags."
5068 (let* ((rv js2-END_DROPS_OFF)
5069 (kids (js2-block-node-kids node))
5070 (n (car kids)))
5071 ;; Check each statment. If the statement can continue onto the next
5072 ;; one (i.e. END_DROPS_OFF is set), then check the next statement.
5073 (while (and n (js2-flag-set-p rv js2-END_DROPS_OFF))
5074 (js2-clear-flag rv js2-END_DROPS_OFF)
5075 (js2-set-flag rv (js2-end-check n))
5076 (setq kids (cdr kids)
5077 n (car kids)))
5078 rv))
5079
5080 (defun js2-end-check-label (node)
5081 "A labeled statement implies that there may be a break to the label.
5082 The function processes the labeled statement and then checks the
5083 CONTROL_BLOCK_PROP property to see if there is ever a break to the
5084 particular label.
5085 Returns logical OR of END_* flags."
5086 (let ((rv (js2-end-check (js2-labeled-stmt-node-stmt node))))
5087 (logior rv (js2-node-get-prop node
5088 'CONTROL_BLOCK_PROP
5089 js2-END_UNREACHED))))
5090
5091 (defun js2-end-check-break (node)
5092 "When a break is encountered annotate the statement being broken
5093 out of by setting its CONTROL_BLOCK_PROP property.
5094 Returns logical OR of END_* flags."
5095 (and (js2-break-node-target node)
5096 (js2-node-set-prop (js2-break-node-target node)
5097 'CONTROL_BLOCK_PROP
5098 js2-END_DROPS_OFF))
5099 js2-END_UNREACHED)
5100
5101 (defun js2-end-check (node)
5102 "Examine the body of a function, doing a basic reachability analysis.
5103 Returns a combination of flags END_* flags that indicate
5104 how the function execution can terminate. These constitute only the
5105 pessimistic set of termination conditions. It is possible that at
5106 runtime certain code paths will never be actually taken. Hence this
5107 analysis will flag errors in cases where there may not be errors.
5108 Returns logical OR of END_* flags"
5109 (let (kid)
5110 (cond
5111 ((js2-break-node-p node)
5112 (js2-end-check-break node))
5113 ((js2-expr-stmt-node-p node)
5114 (if (setq kid (js2-expr-stmt-node-expr node))
5115 (js2-end-check kid)
5116 js2-END_DROPS_OFF))
5117 ((or (js2-continue-node-p node)
5118 (js2-throw-node-p node))
5119 js2-END_UNREACHED)
5120 ((js2-return-node-p node)
5121 (if (setq kid (js2-return-node-retval node))
5122 js2-END_RETURNS_VALUE
5123 js2-END_RETURNS))
5124 ((js2-loop-node-p node)
5125 (js2-end-check-loop node))
5126 ((js2-switch-node-p node)
5127 (js2-end-check-switch node))
5128 ((js2-labeled-stmt-node-p node)
5129 (js2-end-check-label node))
5130 ((js2-if-node-p node)
5131 (js2-end-check-if node))
5132 ((js2-try-node-p node)
5133 (js2-end-check-try node))
5134 ((js2-block-node-p node)
5135 (if (null (js2-block-node-kids node))
5136 js2-END_DROPS_OFF
5137 (js2-end-check-block node)))
5138 ((js2-yield-node-p node)
5139 js2-END_YIELDS)
5140 (t
5141 js2-END_DROPS_OFF))))
5142
5143 (defun js2-always-defined-boolean-p (node)
5144 "Check if NODE always evaluates to true or false in boolean context.
5145 Returns 'ALWAYS_TRUE, 'ALWAYS_FALSE, or nil if it's neither always true
5146 nor always false."
5147 (let ((tt (js2-node-type node))
5148 num)
5149 (cond
5150 ((or (= tt js2-FALSE) (= tt js2-NULL))
5151 'ALWAYS_FALSE)
5152 ((= tt js2-TRUE)
5153 'ALWAYS_TRUE)
5154 ((= tt js2-NUMBER)
5155 (setq num (js2-number-node-num-value node))
5156 (if (and (not (eq num 0.0e+NaN))
5157 (not (zerop num)))
5158 'ALWAYS_TRUE
5159 'ALWAYS_FALSE))
5160 (t
5161 nil))))
5162
5163 ;;; Scanner -- a port of Mozilla Rhino's lexer.
5164 ;; Corresponds to Rhino files Token.java and TokenStream.java.
5165
5166 (defvar js2-tokens nil
5167 "List of all defined token names.") ; initialized in `js2-token-names'
5168
5169 (defconst js2-token-names
5170 (let* ((names (make-vector js2-num-tokens -1))
5171 (case-fold-search nil) ; only match js2-UPPER_CASE
5172 (syms (apropos-internal "^js2-\\(?:[A-Z_]+\\)")))
5173 (loop for sym in syms
5174 for i from 0
5175 do
5176 (unless (or (memq sym '(js2-EOF_CHAR js2-ERROR))
5177 (not (boundp sym)))
5178 (aset names (symbol-value sym) ; code, e.g. 152
5179 (substring (symbol-name sym) 4)) ; name, e.g. "LET"
5180 (push sym js2-tokens)))
5181 names)
5182 "Vector mapping int values to token string names, sans `js2-' prefix.")
5183
5184 (defun js2-token-name (tok)
5185 "Return a string name for TOK, a token symbol or code.
5186 Signals an error if it's not a recognized token."
5187 (let ((code tok))
5188 (if (symbolp tok)
5189 (setq code (symbol-value tok)))
5190 (if (eq code -1)
5191 "ERROR"
5192 (if (and (numberp code)
5193 (not (minusp code))
5194 (< code js2-num-tokens))
5195 (aref js2-token-names code)
5196 (error "Invalid token: %s" code)))))
5197
5198 (defsubst js2-token-sym (tok)
5199 "Return symbol for TOK given its code, e.g. 'js2-LP for code 86."
5200 (intern (js2-token-name tok)))
5201
5202 (defconst js2-token-codes
5203 (let ((table (make-hash-table :test 'eq :size 256)))
5204 (loop for name across js2-token-names
5205 for sym = (intern (concat "js2-" name))
5206 do
5207 (puthash sym (symbol-value sym) table))
5208 ;; clean up a few that are "wrong" in Rhino's token codes
5209 (puthash 'js2-DELETE js2-DELPROP table)
5210 table)
5211 "Hashtable mapping token symbols to their bytecodes.")
5212
5213 (defsubst js2-token-code (sym)
5214 "Return code for token symbol SYM, e.g. 86 for 'js2-LP."
5215 (or (gethash sym js2-token-codes)
5216 (error "Invalid token symbol: %s " sym))) ; signal code bug
5217
5218 (defsubst js2-report-scan-error (msg &optional no-throw beg len)
5219 (setq js2-token-end js2-ts-cursor)
5220 (js2-report-error msg nil
5221 (or beg js2-token-beg)
5222 (or len (- js2-token-end js2-token-beg)))
5223 (unless no-throw
5224 (throw 'return js2-ERROR)))
5225
5226 (defsubst js2-get-string-from-buffer ()
5227 "Reverse the char accumulator and return it as a string."
5228 (setq js2-token-end js2-ts-cursor)
5229 (if js2-ts-string-buffer
5230 (apply #'string (nreverse js2-ts-string-buffer))
5231 ""))
5232
5233 ;; TODO: could potentially avoid a lot of consing by allocating a
5234 ;; char buffer the way Rhino does.
5235 (defsubst js2-add-to-string (c)
5236 (push c js2-ts-string-buffer))
5237
5238 ;; Note that when we "read" the end-of-file, we advance js2-ts-cursor
5239 ;; to (1+ (point-max)), which lets the scanner treat end-of-file like
5240 ;; any other character: when it's not part of the current token, we
5241 ;; unget it, allowing it to be read again by the following call.
5242 (defsubst js2-unget-char ()
5243 (decf js2-ts-cursor))
5244
5245 ;; Rhino distinguishes \r and \n line endings. We don't need to
5246 ;; because we only scan from Emacs buffers, which always use \n.
5247 (defsubst js2-get-char ()
5248 "Read and return the next character from the input buffer.
5249 Increments `js2-ts-lineno' if the return value is a newline char.
5250 Updates `js2-ts-cursor' to the point after the returned char.
5251 Returns `js2-EOF_CHAR' if we hit the end of the buffer.
5252 Also updates `js2-ts-hit-eof' and `js2-ts-line-start' as needed."
5253 (let (c)
5254 ;; check for end of buffer
5255 (if (>= js2-ts-cursor (point-max))
5256 (setq js2-ts-hit-eof t
5257 js2-ts-cursor (1+ js2-ts-cursor)
5258 c js2-EOF_CHAR) ; return value
5259 ;; otherwise read next char
5260 (setq c (char-before (incf js2-ts-cursor)))
5261 ;; if we read a newline, update counters
5262 (if (= c ?\n)
5263 (setq js2-ts-line-start js2-ts-cursor
5264 js2-ts-lineno (1+ js2-ts-lineno)))
5265 ;; TODO: skip over format characters
5266 c)))
5267
5268 (defsubst js2-read-unicode-escape ()
5269 "Read a \\uNNNN sequence from the input.
5270 Assumes the ?\ and ?u have already been read.
5271 Returns the unicode character, or nil if it wasn't a valid character.
5272 Doesn't change the values of any scanner variables."
5273 ;; I really wish I knew a better way to do this, but I can't
5274 ;; find the Emacs function that takes a 16-bit int and converts
5275 ;; it to a Unicode/utf-8 character. So I basically eval it with (read).
5276 ;; Have to first check that it's 4 hex characters or it may stop
5277 ;; the read early.
5278 (ignore-errors
5279 (let ((s (buffer-substring-no-properties js2-ts-cursor
5280 (+ 4 js2-ts-cursor))))
5281 (if (string-match "[a-zA-Z0-9]\\{4\\}" s)
5282 (read (concat "?\\u" s))))))
5283
5284 (defsubst js2-match-char (test)
5285 "Consume and return next character if it matches TEST, a character.
5286 Returns nil and consumes nothing if TEST is not the next character."
5287 (let ((c (js2-get-char)))
5288 (if (eq c test)
5289 t
5290 (js2-unget-char)
5291 nil)))
5292
5293 (defsubst js2-peek-char ()
5294 (prog1
5295 (js2-get-char)
5296 (js2-unget-char)))
5297
5298 (defsubst js2-java-identifier-start-p (c)
5299 (or
5300 (memq c '(?$ ?_))
5301 (js2-char-uppercase-p c)
5302 (js2-char-lowercase-p c)))
5303
5304 (defsubst js2-java-identifier-part-p (c)
5305 "Implementation of java.lang.Character.isJavaIdentifierPart()"
5306 ;; TODO: make me Unicode-friendly. See comments above.
5307 (or
5308 (memq c '(?$ ?_))
5309 (js2-char-uppercase-p c)
5310 (js2-char-lowercase-p c)
5311 (and (>= c ?0) (<= c ?9))))
5312
5313 (defsubst js2-alpha-p (c)
5314 (cond ((and (<= ?A c) (<= c ?Z)) t)
5315 ((and (<= ?a c) (<= c ?z)) t)
5316 (t nil)))
5317
5318 (defsubst js2-digit-p (c)
5319 (and (<= ?0 c) (<= c ?9)))
5320
5321 (defsubst js2-js-space-p (c)
5322 (if (<= c 127)
5323 (memq c '(#x20 #x9 #xB #xC #xD))
5324 (or
5325 (eq c #xA0)
5326 ;; TODO: change this nil to check for Unicode space character
5327 nil)))
5328
5329 (defconst js2-eol-chars (list js2-EOF_CHAR ?\n ?\r))
5330
5331 (defsubst js2-skip-line ()
5332 "Skip to end of line"
5333 (let (c)
5334 (while (not (memq (setq c (js2-get-char)) js2-eol-chars)))
5335 (js2-unget-char)
5336 (setq js2-token-end js2-ts-cursor)))
5337
5338 (defun js2-init-scanner (&optional buf line)
5339 "Create token stream for BUF starting on LINE.
5340 BUF defaults to current-buffer and line defaults to 1.
5341
5342 A buffer can only have one scanner active at a time, which yields
5343 dramatically simpler code than using a defstruct. If you need to
5344 have simultaneous scanners in a buffer, copy the regions to scan
5345 into temp buffers."
5346 (save-excursion
5347 (when buf
5348 (set-buffer buf))
5349 (setq js2-ts-dirty-line nil
5350 js2-ts-regexp-flags nil
5351 js2-ts-string ""
5352 js2-ts-number nil
5353 js2-ts-hit-eof nil
5354 js2-ts-line-start 0
5355 js2-ts-lineno (or line 1)
5356 js2-ts-line-end-char -1
5357 js2-ts-cursor (point-min)
5358 js2-ts-is-xml-attribute nil
5359 js2-ts-xml-is-tag-content nil
5360 js2-ts-xml-open-tags-count 0
5361 js2-ts-string-buffer nil)))
5362
5363 ;; This function uses the cached op, string and number fields in
5364 ;; TokenStream; if getToken has been called since the passed token
5365 ;; was scanned, the op or string printed may be incorrect.
5366 (defun js2-token-to-string (token)
5367 ;; Not sure where this function is used in Rhino. Not tested.
5368 (if (not js2-debug-print-trees)
5369 ""
5370 (let ((name (js2-token-name token)))
5371 (cond
5372 ((memq token (list js2-STRING js2-REGEXP js2-NAME))
5373 (concat name " `" js2-ts-string "'"))
5374 ((eq token js2-NUMBER)
5375 (format "NUMBER %g" js2-ts-number))
5376 (t
5377 name)))))
5378
5379 (defconst js2-keywords
5380 '(break
5381 case catch const continue
5382 debugger default delete do
5383 else enum
5384 false finally for function
5385 if in instanceof import
5386 let
5387 new null
5388 return
5389 switch
5390 this throw true try typeof
5391 var void
5392 while with
5393 yield))
5394
5395 ;; Token names aren't exactly the same as the keywords, unfortunately.
5396 ;; E.g. enum isn't in the tokens, and delete is js2-DELPROP.
5397 (defconst js2-kwd-tokens
5398 (let ((table (make-vector js2-num-tokens nil))
5399 (tokens
5400 (list js2-BREAK
5401 js2-CASE js2-CATCH js2-CONST js2-CONTINUE
5402 js2-DEBUGGER js2-DEFAULT js2-DELPROP js2-DO
5403 js2-ELSE
5404 js2-FALSE js2-FINALLY js2-FOR js2-FUNCTION
5405 js2-IF js2-IN js2-INSTANCEOF js2-IMPORT
5406 js2-LET
5407 js2-NEW js2-NULL
5408 js2-RETURN
5409 js2-SWITCH
5410 js2-THIS js2-THROW js2-TRUE js2-TRY js2-TYPEOF
5411 js2-VAR
5412 js2-WHILE js2-WITH
5413 js2-YIELD)))
5414 (dolist (i tokens)
5415 (aset table i 'font-lock-keyword-face))
5416 (aset table js2-STRING 'font-lock-string-face)
5417 (aset table js2-REGEXP 'font-lock-string-face)
5418 (aset table js2-COMMENT 'font-lock-comment-face)
5419 (aset table js2-THIS 'font-lock-builtin-face)
5420 (aset table js2-VOID 'font-lock-constant-face)
5421 (aset table js2-NULL 'font-lock-constant-face)
5422 (aset table js2-TRUE 'font-lock-constant-face)
5423 (aset table js2-FALSE 'font-lock-constant-face)
5424 table)
5425 "Vector whose values are non-nil for tokens that are keywords.
5426 The values are default faces to use for highlighting the keywords.")
5427
5428 (defconst js2-reserved-words
5429 '(abstract
5430 boolean byte
5431 char class
5432 double
5433 enum export extends
5434 final float
5435 goto
5436 implements import int interface
5437 long
5438 native
5439 package private protected public
5440 short static super synchronized
5441 throws transient
5442 volatile))
5443
5444 (defconst js2-keyword-names
5445 (let ((table (make-hash-table :test 'equal)))
5446 (loop for k in js2-keywords
5447 do (puthash
5448 (symbol-name k) ; instanceof
5449 (intern (concat "js2-"
5450 (upcase (symbol-name k)))) ; js2-INSTANCEOF
5451 table))
5452 table)
5453 "JavaScript keywords by name, mapped to their symbols.")
5454
5455 (defconst js2-reserved-word-names
5456 (let ((table (make-hash-table :test 'equal)))
5457 (loop for k in js2-reserved-words
5458 do
5459 (puthash (symbol-name k) 'js2-RESERVED table))
5460 table)
5461 "JavaScript reserved words by name, mapped to 'js2-RESERVED.")
5462
5463 (defsubst js2-collect-string (buf)
5464 "Convert BUF, a list of chars, to a string.
5465 Reverses BUF before converting."
5466 (cond
5467 ((stringp buf)
5468 buf)
5469 ((null buf) ; for emacs21 compat
5470 "")
5471 (t
5472 (if buf
5473 (apply #'string (nreverse buf))
5474 ""))))
5475
5476 (defun js2-string-to-keyword (s)
5477 "Return token for S, a string, if S is a keyword or reserved word.
5478 Returns a symbol such as 'js2-BREAK, or nil if not keyword/reserved."
5479 (or (gethash s js2-keyword-names)
5480 (gethash s js2-reserved-word-names)))
5481
5482 (defsubst js2-ts-set-char-token-bounds ()
5483 "Used when next token is one character."
5484 (setq js2-token-beg (1- js2-ts-cursor)
5485 js2-token-end js2-ts-cursor))
5486
5487 (defsubst js2-ts-return (token)
5488 "Return an N-character TOKEN from `js2-get-token'.
5489 Updates `js2-token-end' accordingly."
5490 (setq js2-token-end js2-ts-cursor)
5491 (throw 'return token))
5492
5493 (defsubst js2-x-digit-to-int (c accumulator)
5494 "Build up a hex number.
5495 If C is a hexadecimal digit, return ACCUMULATOR * 16 plus
5496 corresponding number. Otherwise return -1."
5497 (catch 'return
5498 (catch 'check
5499 ;; Use 0..9 < A..Z < a..z
5500 (cond
5501 ((<= c ?9)
5502 (decf c ?0)
5503 (if (<= 0 c)
5504 (throw 'check nil)))
5505 ((<= c ?F)
5506 (when (<= ?A c)
5507 (decf c (- ?A 10))
5508 (throw 'check nil)))
5509 ((<= c ?f)
5510 (when (<= ?a c)
5511 (decf c (- ?a 10))
5512 (throw 'check nil))))
5513 (throw 'return -1))
5514 (logior c (lsh accumulator 4))))
5515
5516 (defun js2-get-token ()
5517 "Return next JavaScript token, an int such as js2-RETURN."
5518 (let (c
5519 c1
5520 identifier-start
5521 is-unicode-escape-start
5522 contains-escape
5523 escape-val
5524 escape-start
5525 str
5526 result
5527 base
5528 is-integer
5529 quote-char
5530 val
5531 look-for-slash
5532 continue)
5533 (catch 'return
5534 (while t
5535 ;; Eat whitespace, possibly sensitive to newlines.
5536 (setq continue t)
5537 (while continue
5538 (setq c (js2-get-char))
5539 (cond
5540 ((eq c js2-EOF_CHAR)
5541 (js2-ts-set-char-token-bounds)
5542 (throw 'return js2-EOF))
5543 ((eq c ?\n)
5544 (js2-ts-set-char-token-bounds)
5545 (setq js2-ts-dirty-line nil)
5546 (throw 'return js2-EOL))
5547 ((not (js2-js-space-p c))
5548 (if (/= c ?-) ; in case end of HTML comment
5549 (setq js2-ts-dirty-line t))
5550 (setq continue nil))))
5551 ;; Assume the token will be 1 char - fixed up below.
5552 (js2-ts-set-char-token-bounds)
5553 (when (eq c ?@)
5554 (throw 'return js2-XMLATTR))
5555 ;; identifier/keyword/instanceof?
5556 ;; watch out for starting with a <backslash>
5557 (cond
5558 ((eq c ?\\)
5559 (setq c (js2-get-char))
5560 (if (eq c ?u)
5561 (setq identifier-start t
5562 is-unicode-escape-start t
5563 js2-ts-string-buffer nil)
5564 (setq identifier-start nil)
5565 (js2-unget-char)
5566 (setq c ?\\)))
5567 (t
5568 (when (setq identifier-start (js2-java-identifier-start-p c))
5569 (setq js2-ts-string-buffer nil)
5570 (js2-add-to-string c))))
5571 (when identifier-start
5572 (setq contains-escape is-unicode-escape-start)
5573 (catch 'break
5574 (while t
5575 (if is-unicode-escape-start
5576 ;; strictly speaking we should probably push-back
5577 ;; all the bad characters if the <backslash>uXXXX
5578 ;; sequence is malformed. But since there isn't a
5579 ;; correct context(is there?) for a bad Unicode
5580 ;; escape sequence in an identifier, we can report
5581 ;; an error here.
5582 (progn
5583 (setq escape-val 0)
5584 (dotimes (i 4)
5585 (setq c (js2-get-char)
5586 escape-val (js2-x-digit-to-int c escape-val))
5587 ;; Next check takes care of c < 0 and bad escape
5588 (if (minusp escape-val)
5589 (throw 'break nil)))
5590 (if (minusp escape-val)
5591 (js2-report-scan-error "msg.invalid.escape" t))
5592 (js2-add-to-string escape-val)
5593 (setq is-unicode-escape-start nil))
5594 (setq c (js2-get-char))
5595 (cond
5596 ((eq c ?\\)
5597 (setq c (js2-get-char))
5598 (if (eq c ?u)
5599 (setq is-unicode-escape-start t
5600 contains-escape t)
5601 (js2-report-scan-error "msg.illegal.character" t)))
5602 (t
5603 (if (or (eq c js2-EOF_CHAR)
5604 (not (js2-java-identifier-part-p c)))
5605 (throw 'break nil))
5606 (js2-add-to-string c))))))
5607 (js2-unget-char)
5608 (setq str (js2-get-string-from-buffer))
5609 (unless contains-escape
5610 ;; OPT we shouldn't have to make a string (object!) to
5611 ;; check if it's a keyword.
5612 ;; Return the corresponding token if it's a keyword
5613 (when (setq result (js2-string-to-keyword str))
5614 (if (and (< js2-language-version 170)
5615 (memq result '(js2-LET js2-YIELD)))
5616 ;; LET and YIELD are tokens only in 1.7 and later
5617 (setq result 'js2-NAME))
5618 (if (not (eq result 'js2-RESERVED))
5619 (throw 'return (js2-token-code result)))
5620 (js2-report-warning "msg.reserved.keyword" str)))
5621 ;; If we want to intern these as Rhino does, just use (intern str)
5622 (setq js2-ts-string str)
5623 (throw 'return js2-NAME)) ; end identifier/kwd check
5624 ;; is it a number?
5625 (when (or (js2-digit-p c)
5626 (and (eq c ?.) (js2-digit-p (js2-peek-char))))
5627 (setq js2-ts-string-buffer nil
5628 base 10)
5629 (when (eq c ?0)
5630 (setq c (js2-get-char))
5631 (cond
5632 ((or (eq c ?x) (eq c ?X))
5633 (setq base 16)
5634 (setq c (js2-get-char)))
5635 ((js2-digit-p c)
5636 (setq base 8))
5637 (t
5638 (js2-add-to-string ?0))))
5639 (if (eq base 16)
5640 (while (<= 0 (js2-x-digit-to-int c 0))
5641 (js2-add-to-string c)
5642 (setq c (js2-get-char)))
5643 (while (and (<= ?0 c) (<= c ?9))
5644 ;; We permit 08 and 09 as decimal numbers, which
5645 ;; makes our behavior a superset of the ECMA
5646 ;; numeric grammar. We might not always be so
5647 ;; permissive, so we warn about it.
5648 (when (and (eq base 8) (>= c ?8))
5649 (js2-report-warning "msg.bad.octal.literal"
5650 (if (eq c ?8) "8" "9"))
5651 (setq base 10))
5652 (js2-add-to-string c)
5653 (setq c (js2-get-char))))
5654 (setq is-integer t)
5655 (when (and (eq base 10) (memq c '(?. ?e ?E)))
5656 (setq is-integer nil)
5657 (when (eq c ?.)
5658 (loop do
5659 (js2-add-to-string c)
5660 (setq c (js2-get-char))
5661 while (js2-digit-p c)))
5662 (when (memq c '(?e ?E))
5663 (js2-add-to-string c)
5664 (setq c (js2-get-char))
5665 (when (memq c '(?+ ?-))
5666 (js2-add-to-string c)
5667 (setq c (js2-get-char)))
5668 (unless (js2-digit-p c)
5669 (js2-report-scan-error "msg.missing.exponent" t))
5670 (loop do
5671 (js2-add-to-string c)
5672 (setq c (js2-get-char))
5673 while (js2-digit-p c))))
5674 (js2-unget-char)
5675 (setq js2-ts-string (js2-get-string-from-buffer)
5676 js2-ts-number
5677 (if (and (eq base 10) (not is-integer))
5678 (string-to-number js2-ts-string)
5679 ;; TODO: call runtime number-parser. Some of it is in
5680 ;; js2-util.el, but I need to port ScriptRuntime.stringToNumber.
5681 (string-to-number js2-ts-string)))
5682 (throw 'return js2-NUMBER))
5683 ;; is it a string?
5684 (when (memq c '(?\" ?\'))
5685 ;; We attempt to accumulate a string the fast way, by
5686 ;; building it directly out of the reader. But if there
5687 ;; are any escaped characters in the string, we revert to
5688 ;; building it out of a string buffer.
5689 (setq quote-char c
5690 js2-ts-string-buffer nil
5691 c (js2-get-char))
5692 (catch 'break
5693 (while (/= c quote-char)
5694 (catch 'continue
5695 (when (or (eq c ?\n) (eq c js2-EOF_CHAR))
5696 (js2-unget-char)
5697 (setq js2-token-end js2-ts-cursor)
5698 (js2-report-error "msg.unterminated.string.lit")
5699 (throw 'return js2-STRING))
5700 (when (eq c ?\\)
5701 ;; We've hit an escaped character
5702 (setq c (js2-get-char))
5703 (case c
5704 (?b (setq c ?\b))
5705 (?f (setq c ?\f))
5706 (?n (setq c ?\n))
5707 (?r (setq c ?\r))
5708 (?t (setq c ?\t))
5709 (?v (setq c ?\v))
5710 (?u
5711 (setq c1 (js2-read-unicode-escape))
5712 (if js2-parse-ide-mode
5713 (if c1
5714 (progn
5715 ;; just copy the string in IDE-mode
5716 (js2-add-to-string ?\\)
5717 (js2-add-to-string ?u)
5718 (dotimes (i 3)
5719 (js2-add-to-string (js2-get-char)))
5720 (setq c (js2-get-char))) ; added at end of loop
5721 ;; flag it as an invalid escape
5722 (js2-report-warning "msg.invalid.escape"
5723 nil (- js2-ts-cursor 2) 6))
5724 ;; Get 4 hex digits; if the u escape is not
5725 ;; followed by 4 hex digits, use 'u' + the
5726 ;; literal character sequence that follows.
5727 (js2-add-to-string ?u)
5728 (setq escape-val 0)
5729 (dotimes (i 4)
5730 (setq c (js2-get-char)
5731 escape-val (js2-x-digit-to-int c escape-val))
5732 (if (minusp escape-val)
5733 (throw 'continue nil))
5734 (js2-add-to-string c))
5735 ;; prepare for replace of stored 'u' sequence by escape value
5736 (setq js2-ts-string-buffer (nthcdr 5 js2-ts-string-buffer)
5737 c escape-val)))
5738 (?x
5739 ;; Get 2 hex digits, defaulting to 'x'+literal
5740 ;; sequence, as above.
5741 (setq c (js2-get-char)
5742 escape-val (js2-x-digit-to-int c 0))
5743 (if (minusp escape-val)
5744 (progn
5745 (js2-add-to-string ?x)
5746 (throw 'continue nil))
5747 (setq c1 c
5748 c (js2-get-char)
5749 escape-val (js2-x-digit-to-int c escape-val))
5750 (if (minusp escape-val)
5751 (progn
5752 (js2-add-to-string ?x)
5753 (js2-add-to-string c1)
5754 (throw 'continue nil))
5755 ;; got 2 hex digits
5756 (setq c escape-val))))
5757 (?\n
5758 ;; Remove line terminator after escape to follow
5759 ;; SpiderMonkey and C/C++
5760 (setq c (js2-get-char))
5761 (throw 'continue nil))
5762 (t
5763 (when (and (<= ?0 c) (< c ?8))
5764 (setq val (- c ?0)
5765 c (js2-get-char))
5766 (when (and (<= ?0 c) (< c ?8))
5767 (setq val (- (+ (* 8 val) c) ?0)
5768 c (js2-get-char))
5769 (when (and (<= ?0 c)
5770 (< c ?8)
5771 (< val #o37))
5772 ;; c is 3rd char of octal sequence only
5773 ;; if the resulting val <= 0377
5774 (setq val (- (+ (* 8 val) c) ?0)
5775 c (js2-get-char))))
5776 (js2-unget-char)
5777 (setq c val)))))
5778 (js2-add-to-string c)
5779 (setq c (js2-get-char)))))
5780 (setq js2-ts-string (js2-get-string-from-buffer))
5781 (throw 'return js2-STRING))
5782 (case c
5783 (?\;
5784 (throw 'return js2-SEMI))
5785 (?\[
5786 (throw 'return js2-LB))
5787 (?\]
5788 (throw 'return js2-RB))
5789 (?{
5790 (throw 'return js2-LC))
5791 (?}
5792 (throw 'return js2-RC))
5793 (?\(
5794 (throw 'return js2-LP))
5795 (?\)
5796 (throw 'return js2-RP))
5797 (?,
5798 (throw 'return js2-COMMA))
5799 (??
5800 (throw 'return js2-HOOK))
5801 (?:
5802 (if (js2-match-char ?:)
5803 (js2-ts-return js2-COLONCOLON)
5804 (throw 'return js2-COLON)))
5805 (?.
5806 (if (js2-match-char ?.)
5807 (js2-ts-return js2-DOTDOT)
5808 (if (js2-match-char ?\()
5809 (js2-ts-return js2-DOTQUERY)
5810 (throw 'return js2-DOT))))
5811 (?|
5812 (if (js2-match-char ?|)
5813 (throw 'return js2-OR)
5814 (if (js2-match-char ?=)
5815 (js2-ts-return js2-ASSIGN_BITOR)
5816 (throw 'return js2-BITOR))))
5817 (?^
5818 (if (js2-match-char ?=)
5819 (js2-ts-return js2-ASSIGN_BITOR)
5820 (throw 'return js2-BITXOR)))
5821 (?&
5822 (if (js2-match-char ?&)
5823 (throw 'return js2-AND)
5824 (if (js2-match-char ?=)
5825 (js2-ts-return js2-ASSIGN_BITAND)
5826 (throw 'return js2-BITAND))))
5827 (?=
5828 (if (js2-match-char ?=)
5829 (if (js2-match-char ?=)
5830 (js2-ts-return js2-SHEQ)
5831 (throw 'return js2-EQ))
5832 (throw 'return js2-ASSIGN)))
5833 (?!
5834 (if (js2-match-char ?=)
5835 (if (js2-match-char ?=)
5836 (js2-ts-return js2-SHNE)
5837 (js2-ts-return js2-NE))
5838 (throw 'return js2-NOT)))
5839 (?<
5840 ;; NB:treat HTML begin-comment as comment-till-eol
5841 (when (js2-match-char ?!)
5842 (when (js2-match-char ?-)
5843 (when (js2-match-char ?-)
5844 (js2-skip-line)
5845 (setq js2-ts-comment-type 'html)
5846 (throw 'return js2-COMMENT)))
5847 (js2-unget-char))
5848 (if (js2-match-char ?<)
5849 (if (js2-match-char ?=)
5850 (js2-ts-return js2-ASSIGN_LSH)
5851 (js2-ts-return js2-LSH))
5852 (if (js2-match-char ?=)
5853 (js2-ts-return js2-LE)
5854 (throw 'return js2-LT))))
5855 (?>
5856 (if (js2-match-char ?>)
5857 (if (js2-match-char ?>)
5858 (if (js2-match-char ?=)
5859 (js2-ts-return js2-ASSIGN_URSH)
5860 (js2-ts-return js2-URSH))
5861 (if (js2-match-char ?=)
5862 (js2-ts-return js2-ASSIGN_RSH)
5863 (js2-ts-return js2-RSH)))
5864 (if (js2-match-char ?=)
5865 (js2-ts-return js2-GE)
5866 (throw 'return js2-GT))))
5867 (?*
5868 (if (js2-match-char ?=)
5869 (js2-ts-return js2-ASSIGN_MUL)
5870 (throw 'return js2-MUL)))
5871 (?/
5872 ;; is it a // comment?
5873 (when (js2-match-char ?/)
5874 (setq js2-token-beg (- js2-ts-cursor 2))
5875 (js2-skip-line)
5876 (setq js2-ts-comment-type 'line)
5877 ;; include newline so highlighting goes to end of window
5878 (incf js2-token-end)
5879 (throw 'return js2-COMMENT))
5880 ;; is it a /* comment?
5881 (when (js2-match-char ?*)
5882 (setq look-for-slash nil
5883 js2-token-beg (- js2-ts-cursor 2)
5884 js2-ts-comment-type
5885 (if (js2-match-char ?*)
5886 (progn
5887 (setq look-for-slash t)
5888 'jsdoc)
5889 'block))
5890 (while t
5891 (setq c (js2-get-char))
5892 (cond
5893 ((eq c js2-EOF_CHAR)
5894 (setq js2-token-end (1- js2-ts-cursor))
5895 (js2-report-error "msg.unterminated.comment")
5896 (throw 'return js2-COMMENT))
5897 ((eq c ?*)
5898 (setq look-for-slash t))
5899 ((eq c ?/)
5900 (if look-for-slash
5901 (js2-ts-return js2-COMMENT)))
5902 (t
5903 (setq look-for-slash nil
5904 js2-token-end js2-ts-cursor)))))
5905 (if (js2-match-char ?=)
5906 (js2-ts-return js2-ASSIGN_DIV)
5907 (throw 'return js2-DIV)))
5908 (?#
5909 (when js2-skip-preprocessor-directives
5910 (js2-skip-line)
5911 (setq js2-ts-comment-type 'preprocessor
5912 js2-token-end js2-ts-cursor)
5913 (throw 'return js2-COMMENT))
5914 (throw 'return js2-ERROR))
5915 (?%
5916 (if (js2-match-char ?=)
5917 (js2-ts-return js2-ASSIGN_MOD)
5918 (throw 'return js2-MOD)))
5919 (?~
5920 (throw 'return js2-BITNOT))
5921 (?+
5922 (if (js2-match-char ?=)
5923 (js2-ts-return js2-ASSIGN_ADD)
5924 (if (js2-match-char ?+)
5925 (js2-ts-return js2-INC)
5926 (throw 'return js2-ADD))))
5927 (?-
5928 (cond
5929 ((js2-match-char ?=)
5930 (setq c js2-ASSIGN_SUB))
5931 ((js2-match-char ?-)
5932 (unless js2-ts-dirty-line
5933 ;; treat HTML end-comment after possible whitespace
5934 ;; after line start as comment-until-eol
5935 (when (js2-match-char ?>)
5936 (js2-skip-line)
5937 (setq js2-ts-comment-type 'html)
5938 (throw 'return js2-COMMENT)))
5939 (setq c js2-DEC))
5940 (t
5941 (setq c js2-SUB)))
5942 (setq js2-ts-dirty-line t)
5943 (js2-ts-return c))
5944 (otherwise
5945 (js2-report-scan-error "msg.illegal.character")))))))
5946
5947 (defun js2-read-regexp (start-token)
5948 "Called by parser when it gets / or /= in literal context."
5949 (let (c
5950 err
5951 in-class ; inside a '[' .. ']' character-class
5952 flags
5953 (continue t))
5954 (setq js2-token-beg js2-ts-cursor
5955 js2-ts-string-buffer nil
5956 js2-ts-regexp-flags nil)
5957 (if (eq start-token js2-ASSIGN_DIV)
5958 ;; mis-scanned /=
5959 (js2-add-to-string ?=)
5960 (if (not (eq start-token js2-DIV))
5961 (error "failed assertion")))
5962 (while (and (not err)
5963 (or (/= (setq c (js2-get-char)) ?/)
5964 in-class))
5965 (cond
5966 ((or (= c ?\n)
5967 (= c js2-EOF_CHAR))
5968 (setq js2-token-end (1- js2-ts-cursor)
5969 err t
5970 js2-ts-string (js2-collect-string js2-ts-string-buffer))
5971 (js2-report-error "msg.unterminated.re.lit"))
5972 (t (cond
5973 ((= c ?\\)
5974 (js2-add-to-string c)
5975 (setq c (js2-get-char)))
5976 ((= c ?\[)
5977 (setq in-class t))
5978 ((= c ?\])
5979 (setq in-class nil)))
5980 (js2-add-to-string c))))
5981 (unless err
5982 (while continue
5983 (cond
5984 ((js2-match-char ?g)
5985 (push ?g flags))
5986 ((js2-match-char ?i)
5987 (push ?i flags))
5988 ((js2-match-char ?m)
5989 (push ?m flags))
5990 (t
5991 (setq continue nil))))
5992 (if (js2-alpha-p (js2-peek-char))
5993 (js2-report-scan-error "msg.invalid.re.flag" t
5994 js2-ts-cursor 1))
5995 (setq js2-ts-string (js2-collect-string js2-ts-string-buffer)
5996 js2-ts-regexp-flags (js2-collect-string flags)
5997 js2-token-end js2-ts-cursor)
5998 ;; tell `parse-partial-sexp' to ignore this range of chars
5999 (put-text-property js2-token-beg js2-token-end 'syntax-class '(2)))))
6000
6001 (defun js2-get-first-xml-token ()
6002 (setq js2-ts-xml-open-tags-count 0
6003 js2-ts-is-xml-attribute nil
6004 js2-ts-xml-is-tag-content nil)
6005 (js2-unget-char)
6006 (js2-get-next-xml-token))
6007
6008 (defsubst js2-xml-discard-string ()
6009 "Throw away the string in progress and flag an XML parse error."
6010 (setq js2-ts-string-buffer nil
6011 js2-ts-string nil)
6012 (js2-report-scan-error "msg.XML.bad.form" t))
6013
6014 (defun js2-get-next-xml-token ()
6015 (setq js2-ts-string-buffer nil ; for recording the XML
6016 js2-token-beg js2-ts-cursor)
6017 (let (c result)
6018 (setq result
6019 (catch 'return
6020 (while t
6021 (setq c (js2-get-char))
6022 (cond
6023 ((= c js2-EOF_CHAR)
6024 (throw 'return js2-ERROR))
6025 (js2-ts-xml-is-tag-content
6026 (case c
6027 (?>
6028 (js2-add-to-string c)
6029 (setq js2-ts-xml-is-tag-content nil
6030 js2-ts-is-xml-attribute nil))
6031 (?/
6032 (js2-add-to-string c)
6033 (when (eq ?> (js2-peek-char))
6034 (setq c (js2-get-char))
6035 (js2-add-to-string c)
6036 (setq js2-ts-xml-is-tag-content nil)
6037 (decf js2-ts-xml-open-tags-count)))
6038 (?{
6039 (js2-unget-char)
6040 (setq js2-ts-string (js2-get-string-from-buffer))
6041 (throw 'return js2-XML))
6042 ((?\' ?\")
6043 (js2-add-to-string c)
6044 (unless (js2-read-quoted-string c)
6045 (throw 'return js2-ERROR)))
6046 (?=
6047 (js2-add-to-string c)
6048 (setq js2-ts-is-xml-attribute t))
6049 ((? ?\t ?\r ?\n)
6050 (js2-add-to-string c))
6051 (t
6052 (js2-add-to-string c)
6053 (setq js2-ts-is-xml-attribute nil)))
6054 (when (and (not js2-ts-xml-is-tag-content)
6055 (zerop js2-ts-xml-open-tags-count))
6056 (setq js2-ts-string (js2-get-string-from-buffer))
6057 (throw 'return js2-XMLEND)))
6058 (t
6059 ;; else not tag content
6060 (case c
6061 (?<
6062 (js2-add-to-string c)
6063 (setq c (js2-peek-char))
6064 (case c
6065 (?!
6066 (setq c (js2-get-char)) ;; skip !
6067 (js2-add-to-string c)
6068 (setq c (js2-peek-char))
6069 (case c
6070 (?-
6071 (setq c (js2-get-char)) ;; skip -
6072 (js2-add-to-string c)
6073 (if (eq c ?-)
6074 (progn
6075 (js2-add-to-string c)
6076 (unless (js2-read-xml-comment)
6077 (throw 'return js2-ERROR)))
6078 (js2-xml-discard-string)
6079 (throw 'return js2-ERROR)))
6080 (?\[
6081 (setq c (js2-get-char)) ;; skip [
6082 (js2-add-to-string c)
6083 (if (and (= (js2-get-char) ?C)
6084 (= (js2-get-char) ?D)
6085 (= (js2-get-char) ?A)
6086 (= (js2-get-char) ?T)
6087 (= (js2-get-char) ?A)
6088 (= (js2-get-char) ?\[))
6089 (progn
6090 (js2-add-to-string ?C)
6091 (js2-add-to-string ?D)
6092 (js2-add-to-string ?A)
6093 (js2-add-to-string ?T)
6094 (js2-add-to-string ?A)
6095 (js2-add-to-string ?\[)
6096 (unless (js2-read-cdata)
6097 (throw 'return js2-ERROR)))
6098 (js2-xml-discard-string)
6099 (throw 'return js2-ERROR)))
6100 (t
6101 (unless (js2-read-entity)
6102 (throw 'return js2-ERROR)))))
6103 (??
6104 (setq c (js2-get-char)) ;; skip ?
6105 (js2-add-to-string c)
6106 (unless (js2-read-PI)
6107 (throw 'return js2-ERROR)))
6108 (?/
6109 ;; end tag
6110 (setq c (js2-get-char)) ;; skip /
6111 (js2-add-to-string c)
6112 (when (zerop js2-ts-xml-open-tags-count)
6113 (js2-xml-discard-string)
6114 (throw 'return js2-ERROR))
6115 (setq js2-ts-xml-is-tag-content t)
6116 (decf js2-ts-xml-open-tags-count))
6117 (t
6118 ;; start tag
6119 (setq js2-ts-xml-is-tag-content t)
6120 (incf js2-ts-xml-open-tags-count))))
6121 (?{
6122 (js2-unget-char)
6123 (setq js2-ts-string (js2-get-string-from-buffer))
6124 (throw 'return js2-XML))
6125 (t
6126 (js2-add-to-string c))))))))
6127 (setq js2-token-end js2-ts-cursor)
6128 result))
6129
6130 (defun js2-read-quoted-string (quote)
6131 (let (c)
6132 (catch 'return
6133 (while (/= (setq c (js2-get-char)) js2-EOF_CHAR)
6134 (js2-add-to-string c)
6135 (if (eq c quote)
6136 (throw 'return t)))
6137 (js2-xml-discard-string) ;; throw away string in progress
6138 nil)))
6139
6140 (defun js2-read-xml-comment ()
6141 (let ((c (js2-get-char)))
6142 (catch 'return
6143 (while (/= c js2-EOF_CHAR)
6144 (catch 'continue
6145 (js2-add-to-string c)
6146 (when (and (eq c ?-) (eq ?- (js2-peek-char)))
6147 (setq c (js2-get-char))
6148 (js2-add-to-string c)
6149 (if (eq (js2-peek-char) ?>)
6150 (progn
6151 (setq c (js2-get-char)) ;; skip >
6152 (js2-add-to-string c)
6153 (throw 'return t))
6154 (throw 'continue nil)))
6155 (setq c (js2-get-char))))
6156 (js2-xml-discard-string)
6157 nil)))
6158
6159 (defun js2-read-cdata ()
6160 (let ((c (js2-get-char)))
6161 (catch 'return
6162 (while (/= c js2-EOF_CHAR)
6163 (catch 'continue
6164 (js2-add-to-string c)
6165 (when (and (eq c ?\]) (eq (js2-peek-char) ?\]))
6166 (setq c (js2-get-char))
6167 (js2-add-to-string c)
6168 (if (eq (js2-peek-char) ?>)
6169 (progn
6170 (setq c (js2-get-char)) ;; Skip >
6171 (js2-add-to-string c)
6172 (throw 'return t))
6173 (throw 'continue nil)))
6174 (setq c (js2-get-char))))
6175 (js2-xml-discard-string)
6176 nil)))
6177
6178 (defun js2-read-entity ()
6179 (let ((decl-tags 1)
6180 c)
6181 (catch 'return
6182 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6183 (js2-add-to-string c)
6184 (case c
6185 (?<
6186 (incf decl-tags))
6187 (?>
6188 (decf decl-tags)
6189 (if (zerop decl-tags)
6190 (throw 'return t)))))
6191 (js2-xml-discard-string)
6192 nil)))
6193
6194 (defun js2-read-PI ()
6195 "Scan an XML processing instruction."
6196 (let (c)
6197 (catch 'return
6198 (while (/= js2-EOF_CHAR (setq c (js2-get-char)))
6199 (js2-add-to-string c)
6200 (when (and (eq c ??) (eq (js2-peek-char) ?>))
6201 (setq c (js2-get-char)) ;; Skip >
6202 (js2-add-to-string c)
6203 (throw 'return t)))
6204 (js2-xml-discard-string)
6205 nil)))
6206
6207 (defun js2-scanner-get-line ()
6208 "Return the text of the current scan line."
6209 (buffer-substring (point-at-bol) (point-at-eol)))
6210
6211 ;;; Highlighting
6212
6213 (defsubst js2-set-face (beg end face &optional record)
6214 "Fontify a region. If RECORD is non-nil, record for later."
6215 (when (plusp js2-highlight-level)
6216 (setq beg (min (point-max) beg)
6217 beg (max (point-min) beg)
6218 end (min (point-max) end)
6219 end (max (point-min) end))
6220 (if record
6221 (push (list beg end face) js2-mode-fontifications)
6222 (put-text-property beg end 'face face))))
6223
6224 (defsubst js2-set-kid-face (pos kid len face)
6225 "Set-face on a child node.
6226 POS is absolute buffer position of parent.
6227 KID is the child node.
6228 LEN is the length to fontify.
6229 FACE is the face to fontify with."
6230 (js2-set-face (+ pos (js2-node-pos kid))
6231 (+ pos (js2-node-pos kid) (js2-node-len kid))
6232 face))
6233
6234 (defsubst js2-fontify-kwd (start length)
6235 (js2-set-face start (+ start length) 'font-lock-keyword-face))
6236
6237 (defsubst js2-clear-face (beg end)
6238 (remove-text-properties beg end '(face nil
6239 help-echo nil
6240 point-entered nil
6241 c-in-sws nil)))
6242
6243 (defsubst js2-record-text-property (beg end prop value)
6244 "Record a text property to set when parsing finishes."
6245 (push (list beg end prop value) js2-mode-deferred-properties))
6246
6247 (defconst js2-ecma-global-props
6248 (concat "^"
6249 (regexp-opt
6250 '("Infinity" "NaN" "undefined" "arguments") t)
6251 "$")
6252 "Value properties of the Ecma-262 Global Object.
6253 Shown at or above `js2-highlight-level' 2.")
6254
6255 ;; might want to add the name "arguments" to this list?
6256 (defconst js2-ecma-object-props
6257 (concat "^"
6258 (regexp-opt
6259 '("prototype" "__proto__" "__parent__") t)
6260 "$")
6261 "Value properties of the Ecma-262 Object constructor.
6262 Shown at or above `js2-highlight-level' 2.")
6263
6264 (defconst js2-ecma-global-funcs
6265 (concat
6266 "^"
6267 (regexp-opt
6268 '("decodeURI" "decodeURIComponent" "encodeURI" "encodeURIComponent"
6269 "eval" "isFinite" "isNaN" "parseFloat" "parseInt") t)
6270 "$")
6271 "Function properties of the Ecma-262 Global object.
6272 Shown at or above `js2-highlight-level' 2.")
6273
6274 (defconst js2-ecma-number-props
6275 (concat "^"
6276 (regexp-opt '("MAX_VALUE" "MIN_VALUE" "NaN"
6277 "NEGATIVE_INFINITY"
6278 "POSITIVE_INFINITY") t)
6279 "$")
6280 "Properties of the Ecma-262 Number constructor.
6281 Shown at or above `js2-highlight-level' 2.")
6282
6283 (defconst js2-ecma-date-props "^\\(parse\\|UTC\\)$"
6284 "Properties of the Ecma-262 Date constructor.
6285 Shown at or above `js2-highlight-level' 2.")
6286
6287 (defconst js2-ecma-math-props
6288 (concat "^"
6289 (regexp-opt
6290 '("E" "LN10" "LN2" "LOG2E" "LOG10E" "PI" "SQRT1_2" "SQRT2")
6291 t)
6292 "$")
6293 "Properties of the Ecma-262 Math object.
6294 Shown at or above `js2-highlight-level' 2.")
6295
6296 (defconst js2-ecma-math-funcs
6297 (concat "^"
6298 (regexp-opt
6299 '("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "exp" "floor"
6300 "log" "max" "min" "pow" "random" "round" "sin" "sqrt" "tan") t)
6301 "$")
6302 "Function properties of the Ecma-262 Math object.
6303 Shown at or above `js2-highlight-level' 2.")
6304
6305 (defconst js2-ecma-function-props
6306 (concat
6307 "^"
6308 (regexp-opt
6309 '(;; properties of the Object prototype object
6310 "hasOwnProperty" "isPrototypeOf" "propertyIsEnumerable"
6311 "toLocaleString" "toString" "valueOf"
6312 ;; properties of the Function prototype object
6313 "apply" "call"
6314 ;; properties of the Array prototype object
6315 "concat" "join" "pop" "push" "reverse" "shift" "slice" "sort"
6316 "splice" "unshift"
6317 ;; properties of the String prototype object
6318 "charAt" "charCodeAt" "fromCharCode" "indexOf" "lastIndexOf"
6319 "localeCompare" "match" "replace" "search" "split" "substring"
6320 "toLocaleLowerCase" "toLocaleUpperCase" "toLowerCase"
6321 "toUpperCase"
6322 ;; properties of the Number prototype object
6323 "toExponential" "toFixed" "toPrecision"
6324 ;; properties of the Date prototype object
6325 "getDate" "getDay" "getFullYear" "getHours" "getMilliseconds"
6326 "getMinutes" "getMonth" "getSeconds" "getTime"
6327 "getTimezoneOffset" "getUTCDate" "getUTCDay" "getUTCFullYear"
6328 "getUTCHours" "getUTCMilliseconds" "getUTCMinutes" "getUTCMonth"
6329 "getUTCSeconds" "setDate" "setFullYear" "setHours"
6330 "setMilliseconds" "setMinutes" "setMonth" "setSeconds" "setTime"
6331 "setUTCDate" "setUTCFullYear" "setUTCHours" "setUTCMilliseconds"
6332 "setUTCMinutes" "setUTCMonth" "setUTCSeconds" "toDateString"
6333 "toLocaleDateString" "toLocaleString" "toLocaleTimeString"
6334 "toTimeString" "toUTCString"
6335 ;; properties of the RegExp prototype object
6336 "exec" "test"
6337 ;; SpiderMonkey/Rhino extensions, versions 1.5+
6338 "toSource" "__defineGetter__" "__defineSetter__"
6339 "__lookupGetter__" "__lookupSetter__" "__noSuchMethod__"
6340 "every" "filter" "forEach" "lastIndexOf" "map" "some")
6341 t)
6342 "$")
6343 "Built-in functions defined by Ecma-262 and SpiderMonkey extensions.
6344 Shown at or above `js2-highlight-level' 3.")
6345
6346 (defsubst js2-parse-highlight-prop-get (parent target prop call-p)
6347 (let ((target-name (and target
6348 (js2-name-node-p target)
6349 (js2-name-node-name target)))
6350 (prop-name (if prop (js2-name-node-name prop)))
6351 (level1 (>= js2-highlight-level 1))
6352 (level2 (>= js2-highlight-level 2))
6353 (level3 (>= js2-highlight-level 3))
6354 pos
6355 face)
6356 (when level2
6357 (if call-p
6358 (cond
6359 ((and target prop)
6360 (cond
6361 ((and level3 (string-match js2-ecma-function-props prop-name))
6362 (setq face 'font-lock-builtin-face))
6363 ((and target-name prop)
6364 (cond
6365 ((string= target-name "Date")
6366 (if (string-match js2-ecma-date-props prop-name)
6367 (setq face 'font-lock-builtin-face)))
6368 ((string= target-name "Math")
6369 (if (string-match js2-ecma-math-funcs prop-name)
6370 (setq face 'font-lock-builtin-face)))))))
6371 (prop
6372 (if (string-match js2-ecma-global-funcs prop-name)
6373 (setq face 'font-lock-builtin-face))))
6374 (cond
6375 ((and target prop)
6376 (cond
6377 ((string= target-name "Number")
6378 (if (string-match js2-ecma-number-props prop-name)
6379 (setq face 'font-lock-constant-face)))
6380 ((string= target-name "Math")
6381 (if (string-match js2-ecma-math-props prop-name)
6382 (setq face 'font-lock-constant-face)))))
6383 (prop
6384 (if (string-match js2-ecma-object-props prop-name)
6385 (setq face 'font-lock-constant-face)))))
6386 (when face
6387 (js2-set-face (setq pos (+ (js2-node-pos parent) ; absolute
6388 (js2-node-pos prop))) ; relative
6389 (+ pos (js2-node-len prop))
6390 face)))))
6391
6392 (defun js2-parse-highlight-member-expr-node (node)
6393 "Perform syntax highlighting of EcmaScript built-in properties.
6394 The variable `js2-highlight-level' governs this highighting."
6395 (let (face target prop name pos end parent call-p callee)
6396 (cond
6397 ;; case 1: simple name, e.g. foo
6398 ((js2-name-node-p node)
6399 (setq name (js2-name-node-name node))
6400 ;; possible for name to be nil in rare cases - saw it when
6401 ;; running js2-mode on an elisp buffer. Might as well try to
6402 ;; make it so js2-mode never barfs.
6403 (when name
6404 (setq face (if (string-match js2-ecma-global-props name)
6405 'font-lock-constant-face))
6406 (when face
6407 (setq pos (js2-node-pos node)
6408 end (+ pos (js2-node-len node)))
6409 (js2-set-face pos end face))))
6410 ;; case 2: property access or function call
6411 ((or (js2-prop-get-node-p node)
6412 ;; highlight function call if expr is a prop-get node
6413 ;; or a plain name (i.e. unqualified function call)
6414 (and (setq call-p (js2-call-node-p node))
6415 (setq callee (js2-call-node-target node)) ; separate setq!
6416 (or (js2-prop-get-node-p callee)
6417 (js2-name-node-p callee))))
6418 (setq parent node
6419 node (if call-p callee node))
6420 (if (and call-p (js2-name-node-p callee))
6421 (setq prop callee)
6422 (setq target (js2-prop-get-node-left node)
6423 prop (js2-prop-get-node-right node)))
6424 (cond
6425 ((js2-name-node-p target)
6426 (if (js2-name-node-p prop)
6427 ;; case 2a: simple target, simple prop name, e.g. foo.bar
6428 (js2-parse-highlight-prop-get parent target prop call-p)
6429 ;; case 2b: simple target, complex name, e.g. foo.x[y]
6430 (js2-parse-highlight-prop-get parent target nil call-p)))
6431 ((js2-name-node-p prop)
6432 ;; case 2c: complex target, simple name, e.g. x[y].bar
6433 (js2-parse-highlight-prop-get parent target prop call-p)))))))
6434
6435 (defun js2-parse-highlight-member-expr-fn-name (expr)
6436 "Highlight the `baz' in function foo.bar.baz(args) {...}.
6437 This is experimental Rhino syntax. EXPR is the foo.bar.baz member expr.
6438 We currently only handle the case where the last component is a prop-get
6439 of a simple name. Called before EXPR has a parent node."
6440 (let (pos
6441 (name (and (js2-prop-get-node-p expr)
6442 (js2-prop-get-node-right expr))))
6443 (when (js2-name-node-p name)
6444 (js2-set-face (setq pos (+ (js2-node-pos expr) ; parent is absolute
6445 (js2-node-pos name)))
6446 (+ pos (js2-node-len name))
6447 'font-lock-function-name-face
6448 'record))))
6449
6450 ;; source: http://jsdoc.sourceforge.net/
6451 ;; Note - this syntax is for Google's enhanced jsdoc parser that
6452 ;; allows type specifications, and needs work before entering the wild.
6453
6454 (defconst js2-jsdoc-param-tag-regexp
6455 (concat "^\\s-*\\*+\\s-*\\(@"
6456 "\\(?:param\\|argument\\)"
6457 "\\)"
6458 "\\s-*\\({[^}]+}\\)?" ; optional type
6459 "\\s-*\\([a-zA-Z0-9_$]+\\)?" ; name
6460 "\\>")
6461 "Matches jsdoc tags with optional type and optional param name.")
6462
6463 (defconst js2-jsdoc-typed-tag-regexp
6464 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6465 (regexp-opt
6466 '("enum"
6467 "extends"
6468 "field"
6469 "id"
6470 "implements"
6471 "lends"
6472 "mods"
6473 "requires"
6474 "return"
6475 "returns"
6476 "throw"
6477 "throws"))
6478 "\\)\\)\\s-*\\({[^}]+}\\)?")
6479 "Matches jsdoc tags with optional type.")
6480
6481 (defconst js2-jsdoc-arg-tag-regexp
6482 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6483 (regexp-opt
6484 '("alias"
6485 "augments"
6486 "borrows"
6487 "bug"
6488 "base"
6489 "config"
6490 "default"
6491 "define"
6492 "exception"
6493 "function"
6494 "member"
6495 "memberOf"
6496 "name"
6497 "namespace"
6498 "property"
6499 "since"
6500 "suppress"
6501 "this"
6502 "throws"
6503 "type"
6504 "version"))
6505 "\\)\\)\\s-+\\([^ \t]+\\)")
6506 "Matches jsdoc tags with a single argument.")
6507
6508 (defconst js2-jsdoc-empty-tag-regexp
6509 (concat "^\\s-*\\*+\\s-*\\(@\\(?:"
6510 (regexp-opt
6511 '("addon"
6512 "author"
6513 "class"
6514 "const"
6515 "constant"
6516 "constructor"
6517 "constructs"
6518 "deprecated"
6519 "desc"
6520 "description"
6521 "event"
6522 "example"
6523 "exec"
6524 "export"
6525 "fileoverview"
6526 "final"
6527 "function"
6528 "hidden"
6529 "ignore"
6530 "implicitCast"
6531 "inheritDoc"
6532 "inner"
6533 "interface"
6534 "license"
6535 "noalias"
6536 "noshadow"
6537 "notypecheck"
6538 "override"
6539 "owner"
6540 "preserve"
6541 "preserveTry"
6542 "private"
6543 "protected"
6544 "public"
6545 "static"
6546 "supported"
6547 ))
6548 "\\)\\)\\s-*")
6549 "Matches empty jsdoc tags.")
6550
6551 (defconst js2-jsdoc-link-tag-regexp
6552 "{\\(@\\(?:link\\|code\\)\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?}"
6553 "Matches a jsdoc link or code tag.")
6554
6555 (defconst js2-jsdoc-see-tag-regexp
6556 "^\\s-*\\*+\\s-*\\(@see\\)\\s-+\\([^#}\n]+\\)\\(#.+\\)?"
6557 "Matches a jsdoc @see tag.")
6558
6559 (defconst js2-jsdoc-html-tag-regexp
6560 "\\(</?\\)\\([a-zA-Z]+\\)\\s-*\\(/?>\\)"
6561 "Matches a simple (no attributes) html start- or end-tag.")
6562
6563 (defsubst js2-jsdoc-highlight-helper ()
6564 (js2-set-face (match-beginning 1)
6565 (match-end 1)
6566 'js2-jsdoc-tag-face)
6567 (if (match-beginning 2)
6568 (if (save-excursion
6569 (goto-char (match-beginning 2))
6570 (= (char-after) ?{))
6571 (js2-set-face (1+ (match-beginning 2))
6572 (1- (match-end 2))
6573 'js2-jsdoc-type-face)
6574 (js2-set-face (match-beginning 2)
6575 (match-end 2)
6576 'js2-jsdoc-value-face)))
6577 (if (match-beginning 3)
6578 (js2-set-face (match-beginning 3)
6579 (match-end 3)
6580 'js2-jsdoc-value-face)))
6581
6582 (defun js2-highlight-jsdoc (ast)
6583 "Highlight doc comment tags."
6584 (let ((comments (js2-ast-root-comments ast))
6585 beg end)
6586 (save-excursion
6587 (dolist (node comments)
6588 (when (eq (js2-comment-node-format node) 'jsdoc)
6589 (setq beg (js2-node-abs-pos node)
6590 end (+ beg (js2-node-len node)))
6591 (save-restriction
6592 (narrow-to-region beg end)
6593 (dolist (re (list js2-jsdoc-param-tag-regexp
6594 js2-jsdoc-typed-tag-regexp
6595 js2-jsdoc-arg-tag-regexp
6596 js2-jsdoc-link-tag-regexp
6597 js2-jsdoc-see-tag-regexp
6598 js2-jsdoc-empty-tag-regexp))
6599 (goto-char beg)
6600 (while (re-search-forward re nil t)
6601 (js2-jsdoc-highlight-helper)))
6602 ;; simple highlighting for html tags
6603 (goto-char beg)
6604 (while (re-search-forward js2-jsdoc-html-tag-regexp nil t)
6605 (js2-set-face (match-beginning 1)
6606 (match-end 1)
6607 'js2-jsdoc-html-tag-delimiter-face)
6608 (js2-set-face (match-beginning 2)
6609 (match-end 2)
6610 'js2-jsdoc-html-tag-name-face)
6611 (js2-set-face (match-beginning 3)
6612 (match-end 3)
6613 'js2-jsdoc-html-tag-delimiter-face))))))))
6614
6615 (defun js2-highlight-assign-targets (node left right)
6616 "Highlight function properties and external variables."
6617 (let (leftpos end name)
6618 ;; highlight vars and props assigned function values
6619 (when (js2-function-node-p right)
6620 (cond
6621 ;; var foo = function() {...}
6622 ((js2-name-node-p left)
6623 (setq name left))
6624 ;; foo.bar.baz = function() {...}
6625 ((and (js2-prop-get-node-p left)
6626 (js2-name-node-p (js2-prop-get-node-right left)))
6627 (setq name (js2-prop-get-node-right left))))
6628 (when name
6629 (js2-set-face (setq leftpos (js2-node-abs-pos name))
6630 (+ leftpos (js2-node-len name))
6631 'font-lock-function-name-face
6632 'record)))
6633 ;; save variable assignments so we can check for undeclared later
6634 ;; (can't do it here since var decls can come at end of script)
6635 (when (and js2-highlight-external-variables
6636 (setq name (js2-member-expr-leftmost-name left)))
6637 (push (list name js2-current-scope
6638 (setq leftpos (js2-node-abs-pos name))
6639 (setq end (+ leftpos (js2-node-len name))))
6640 js2-recorded-assignments))))
6641
6642 (defun js2-highlight-undeclared-vars ()
6643 "After entire parse is finished, look for undeclared variable assignments.
6644 We have to wait until entire buffer is parsed, since JavaScript permits var
6645 decls to occur after they're used.
6646
6647 If any undeclared var name is in `js2-externs' or `js2-additional-externs',
6648 it is considered declared."
6649 (let (name)
6650 (dolist (entry js2-recorded-assignments)
6651 (destructuring-bind (name-node scope pos end) entry
6652 (setq name (js2-name-node-name name-node))
6653 (unless (or (member name js2-global-externs)
6654 (member name js2-default-externs)
6655 (member name js2-additional-externs)
6656 (js2-get-defining-scope scope name))
6657 (js2-set-face pos end 'js2-external-variable-face 'record)
6658 (js2-record-text-property pos end 'help-echo "Undeclared variable")
6659 (js2-record-text-property pos end 'point-entered #'js2-echo-help))))
6660 (setq js2-recorded-assignments nil)))
6661
6662 ;;; IMenu support
6663
6664 ;; We currently only support imenu, but eventually should support speedbar and
6665 ;; possibly other browsing mechanisms.
6666
6667 ;; The basic strategy is to identify function assignment targets of the form
6668 ;; `foo.bar.baz', convert them to (list foo bar baz <position>), and push the
6669 ;; list into `js2-imenu-recorder'. The lists are merged into a trie-like tree
6670 ;; for imenu after parsing is finished.
6671
6672 ;; A `foo.bar.baz' assignment target may be expressed in many ways in
6673 ;; JavaScript, and the general problem is undecidable. However, several forms
6674 ;; are readily recognizable at parse-time; the forms we attempt to recognize
6675 ;; include:
6676
6677 ;; function foo() -- function declaration
6678 ;; foo = function() -- function expression assigned to variable
6679 ;; foo.bar.baz = function() -- function expr assigned to nested property-get
6680 ;; foo = {bar: function()} -- fun prop in object literal assigned to var
6681 ;; foo = {bar: {baz: function()}} -- inside nested object literal
6682 ;; foo.bar = {baz: function()}} -- obj lit assigned to nested prop get
6683 ;; a.b = {c: {d: function()}} -- nested obj lit assigned to nested prop get
6684 ;; foo = {get bar() {...}} -- getter/setter in obj literal
6685 ;; function foo() {function bar() {...}} -- nested function
6686 ;; foo['a'] = function() -- fun expr assigned to deterministic element-get
6687
6688 ;; This list boils down to a few forms that can be combined recursively.
6689 ;; Top-level named function declarations include both the left-hand (name)
6690 ;; and the right-hand (function value) expressions needed to produce an imenu
6691 ;; entry. The other "right-hand" forms we need to look for are:
6692 ;; - functions declared as props/getters/setters in object literals
6693 ;; - nested named function declarations
6694 ;; The "left-hand" expressions that functions can be assigned to include:
6695 ;; - local/global variables
6696 ;; - nested property-get expressions like a.b.c.d
6697 ;; - element gets like foo[10] or foo['bar'] where the index
6698 ;; expression can be trivially converted to a property name. They
6699 ;; effectively then become property gets.
6700
6701 ;; All the different definition types are canonicalized into the form
6702 ;; foo.bar.baz = position-of-function-keyword
6703
6704 ;; We need to build a trie-like structure for imenu. As an example,
6705 ;; consider the following JavaScript code:
6706
6707 ;; a = function() {...} // function at position 5
6708 ;; b = function() {...} // function at position 25
6709 ;; foo = function() {...} // function at position 100
6710 ;; foo.bar = function() {...} // function at position 200
6711 ;; foo.bar.baz = function() {...} // function at position 300
6712 ;; foo.bar.zab = function() {...} // function at position 400
6713
6714 ;; During parsing we accumulate an entry for each definition in
6715 ;; the variable `js2-imenu-recorder', like so:
6716
6717 ;; '((a 5)
6718 ;; (b 25)
6719 ;; (foo 100)
6720 ;; (foo bar 200)
6721 ;; (foo bar baz 300)
6722 ;; (foo bar zab 400))
6723
6724 ;; After parsing these entries are merged into this alist-trie:
6725
6726 ;; '((a . 1)
6727 ;; (b . 2)
6728 ;; (foo (<definition> . 3)
6729 ;; (bar (<definition> . 6)
6730 ;; (baz . 100)
6731 ;; (zab . 200))))
6732
6733 ;; Note the wacky need for a <definition> name. The token can be anything
6734 ;; that isn't a valid JavaScript identifier, because you might make foo
6735 ;; a function and then start setting properties on it that are also functions.
6736
6737 (defsubst js2-prop-node-name (node)
6738 "Return the name of a node that may be a property-get/property-name.
6739 If NODE is not a valid name-node, string-node or integral number-node,
6740 returns nil. Otherwise returns the string name/value of the node."
6741 (cond
6742 ((js2-name-node-p node)
6743 (js2-name-node-name node))
6744 ((js2-string-node-p node)
6745 (js2-string-node-value node))
6746 ((and (js2-number-node-p node)
6747 (string-match "^[0-9]+$" (js2-number-node-value node)))
6748 (js2-number-node-value node))
6749 ((js2-this-node-p node)
6750 "this")))
6751
6752 (defsubst js2-node-qname-component (node)
6753 "Test function: return the name of this node, if it contributes to a qname.
6754 Returns nil if the node doesn't contribute."
6755 (copy-sequence
6756 (or (js2-prop-node-name node)
6757 (if (and (js2-function-node-p node)
6758 (js2-function-node-name node))
6759 (js2-name-node-name (js2-function-node-name node))))))
6760
6761 (defsubst js2-record-function-qname (fn-node qname)
6762 "Associate FN-NODE with its QNAME for later lookup.
6763 This is used in postprocessing the chain list. When we find a chain
6764 whose first element is a js2-THIS keyword node, we look up the parent
6765 function and see (using this map) whether it is the tail of a chain.
6766 If so, we replace the this-node with a copy of the parent's qname."
6767 (unless js2-imenu-function-map
6768 (setq js2-imenu-function-map (make-hash-table :test 'eq)))
6769 (puthash fn-node qname js2-imenu-function-map))
6770
6771 (defun js2-record-imenu-functions (node &optional var)
6772 "Record function definitions for imenu.
6773 NODE is a function node or an object literal.
6774 VAR, if non-nil, is the expression that NODE is being assigned to."
6775 (when js2-parse-ide-mode
6776 (let ((fun-p (js2-function-node-p node))
6777 qname left fname-node pos)
6778 (cond
6779 ;; non-anonymous function declaration?
6780 ((and fun-p
6781 (not var)
6782 (setq fname-node (js2-function-node-name node)))
6783 (push (setq qname (list fname-node (js2-node-pos node)))
6784 js2-imenu-recorder)
6785 (js2-record-function-qname node qname))
6786 ;; for remaining forms, compute left-side tree branch first
6787 ((and var (setq qname (js2-compute-nested-prop-get var)))
6788 (cond
6789 ;; foo.bar.baz = function
6790 (fun-p
6791 (push (nconc qname (list (js2-node-pos node)))
6792 js2-imenu-recorder)
6793 (js2-record-function-qname node qname))
6794 ;; foo.bar.baz = object-literal
6795 ;; look for nested functions: {a: {b: function() {...} }}
6796 ((js2-object-node-p node)
6797 (js2-record-object-literal node qname))))))))
6798
6799 (defun js2-compute-nested-prop-get (node)
6800 "If NODE is of form foo.bar.baz, return component nodes as a list.
6801 Otherwise returns nil. Element-gets can be treated as property-gets
6802 if the index expression is a name, a string, or a positive integer."
6803 (let (left right head)
6804 (cond
6805 ((or (js2-name-node-p node)
6806 (js2-this-node-p node))
6807 (list node))
6808 ;; foo.bar.baz is parenthesized as (foo.bar).baz => right operand is a leaf
6809 ((js2-prop-get-node-p node) ; includes elem-get nodes
6810 (setq left (js2-prop-get-node-left node)
6811 right (js2-prop-get-node-right node))
6812 (if (and (or (js2-prop-get-node-p left) ; left == foo.bar
6813 (js2-name-node-p left)
6814 (js2-this-node-p left)) ; or left == foo
6815 (or (js2-name-node-p right) ; .bar
6816 (js2-string-node-p right) ; ['bar']
6817 (and (js2-number-node-p right) ; [10]
6818 (string-match "^[0-9]+$"
6819 (js2-number-node-value right)))))
6820 (if (setq head (js2-compute-nested-prop-get left))
6821 (nconc head (list right))))))))
6822
6823 (defun js2-record-object-literal (node qname)
6824 "Recursively process an object literal looking for functions.
6825 NODE is an object literal that is the right-hand child of an assignment
6826 expression. QNAME is a list of nodes representing the assignment target,
6827 e.g. for foo.bar.baz = {...}, QNAME is (foo-node bar-node baz-node).
6828 We do a depth-first traversal of NODE. Any functions we find are prefixed
6829 with QNAME plus the property name of the function and appended to the
6830 variable `js2-imenu-recorder'."
6831 ;; Elements are relative to parent position, which is still absolute,
6832 ;; since the parser passes the assignment target and value expressions
6833 ;; to us before they are added as children of the assignment node.
6834 (let ((pos (js2-node-pos node))
6835 left right)
6836 (dolist (e (js2-object-node-elems node)) ; e is a `js2-object-prop-node'
6837 (setq left (js2-infix-node-left e))
6838 (cond
6839 ;; foo: function() {...}
6840 ((js2-function-node-p (setq right (js2-infix-node-right e)))
6841 (when (js2-prop-node-name left)
6842 ;; As a policy decision, we record the position of the property,
6843 ;; not the position of the `function' keyword, since the property
6844 ;; is effectively the name of the function.
6845 (push (append qname (list left) (list (+ pos (js2-node-pos e))))
6846 js2-imenu-recorder)
6847 (js2-record-function-qname right qname)))
6848 ;; foo: {object-literal} -- add foo to qname and recurse
6849 ((js2-object-node-p right)
6850 (js2-record-object-literal right
6851 (append qname (list (js2-infix-node-left e)))))))))
6852
6853 (defsubst js2-node-top-level-decl-p (node)
6854 "Return t if NODE's name is defined in the top-level scope.
6855 Also returns t if NODE's name is not defined in any scope, since it implies
6856 that it's an external variable, which must also be in the top-level scope."
6857 (let* ((name (js2-prop-node-name node))
6858 (this-scope (js2-node-get-enclosing-scope node))
6859 defining-scope)
6860 (cond
6861 ((js2-this-node-p node)
6862 nil)
6863 ((null this-scope)
6864 t)
6865 ((setq defining-scope (js2-get-defining-scope this-scope name))
6866 (js2-ast-root-p defining-scope))
6867 (t t))))
6868
6869 (defun js2-browse-postprocess-chains (chains)
6870 "Modify function-declaration name chains after parsing finishes.
6871 Some of the information is only available after the parse tree is complete.
6872 For instance, following a 'this' reference requires a parent function node."
6873 (let (result head fn parent-chain p elem)
6874 (dolist (chain chains)
6875 ;; examine the head of each node to get its defining scope
6876 (setq head (car chain))
6877 (cond
6878 ;; if top-level/external, keep as-is
6879 ((js2-node-top-level-decl-p head)
6880 (push chain result))
6881 ;; check for a this-reference
6882 ((eq (js2-node-type head) js2-THIS)
6883 (setq fn (js2-node-parent-script-or-fn head))
6884 ;; if there is no parent function, or if the parent function
6885 ;; is nested, discard the head node and keep the rest of the chain.
6886 (if (or (null fn) (js2-nested-function-p fn))
6887 (push (cdr chain) result)
6888 ;; else look up parent in function-map. If not found, discard chain.
6889 (when (setq parent-chain (and js2-imenu-function-map
6890 (gethash fn js2-imenu-function-map)))
6891 ;; else discard head node and prefix parent fn qname, which is
6892 ;; the parent-chain sans tail, to this chain.
6893 (push (append (butlast parent-chain) (cdr chain)) result))))))
6894 ;; finally replace each node in each chain with its name.
6895 (dolist (chain result)
6896 (setq p chain)
6897 (while p
6898 (if (js2-node-p (setq elem (car p)))
6899 (setcar p (js2-node-qname-component elem)))
6900 (setq p (cdr p))))
6901 result))
6902
6903 ;; Merge name chains into a trie-like tree structure of nested lists.
6904 ;; To simplify construction of the trie, we first build it out using the rule
6905 ;; that the trie consists of lists of pairs. Each pair is a 2-element array:
6906 ;; [key, num-or-list]. The second element can be a number; if so, this key
6907 ;; is a leaf-node with only one value. (I.e. there is only one declaration
6908 ;; associated with the key at this level.) Otherwise the second element is
6909 ;; a list of pairs, with the rule applied recursively. This symmetry permits
6910 ;; a simple recursive formulation.
6911 ;;
6912 ;; js2-mode is building the data structure for imenu. The imenu documentation
6913 ;; claims that it's the structure above, but in practice it wants the children
6914 ;; at the same list level as the key for that level, which is how I've drawn
6915 ;; the "Expected final result" above. We'll postprocess the trie to remove the
6916 ;; list wrapper around the children at each level.
6917 ;;
6918 ;; A completed nested imenu-alist entry looks like this:
6919 ;; '(("foo"
6920 ;; ("<definition>" . 7)
6921 ;; ("bar"
6922 ;; ("a" . 40)
6923 ;; ("b" . 60))))
6924 ;;
6925 ;; In particular, the documentation for `imenu--index-alist' says that
6926 ;; a nested sub-alist element looks like (INDEX-NAME SUB-ALIST).
6927 ;; The sub-alist entries immediately follow INDEX-NAME, the head of the list.
6928
6929 (defsubst js2-treeify (lst)
6930 "Convert (a b c d) to (a ((b ((c d)))))"
6931 (if (null (cddr lst)) ; list length <= 2
6932 lst
6933 (list (car lst) (list (js2-treeify (cdr lst))))))
6934
6935 (defun js2-build-alist-trie (chains trie)
6936 "Merge declaration name chains into a trie-like alist structure for imenu.
6937 CHAINS is the qname chain list produced during parsing. TRIE is a
6938 list of elements built up so far."
6939 (let (head tail pos branch kids)
6940 (dolist (chain chains)
6941 (setq head (car chain)
6942 tail (cdr chain)
6943 pos (if (numberp (car tail)) (car tail))
6944 branch (js2-find-if (lambda (n)
6945 (string= (car n) head))
6946 trie)
6947 kids (second branch))
6948 (cond
6949 ;; case 1: this key isn't in the trie yet
6950 ((null branch)
6951 (if trie
6952 (setcdr (last trie) (list (js2-treeify chain)))
6953 (setq trie (list (js2-treeify chain)))))
6954 ;; case 2: key is present with a single number entry: replace w/ list
6955 ;; ("a1" 10) + ("a1" 20) => ("a1" (("<definition>" 10)
6956 ;; ("<definition>" 20)))
6957 ((numberp kids)
6958 (setcar (cdr branch)
6959 (list (list "<definition-1>" kids)
6960 (if pos
6961 (list "<definition-2>" pos)
6962 (js2-treeify tail)))))
6963 ;; case 3: key is there (with kids), and we're a number entry
6964 (pos
6965 (setcdr (last kids)
6966 (list
6967 (list (format "<definition-%d>"
6968 (1+ (loop for kid in kids
6969 count (eq ?< (aref (car kid) 0)))))
6970 pos))))
6971 ;; case 4: key is there with kids, need to merge in our chain
6972 (t
6973 (js2-build-alist-trie (list tail) kids))))
6974 trie))
6975
6976 (defun js2-flatten-trie (trie)
6977 "Convert TRIE to imenu-format.
6978 Recurses through nodes, and for each one whose second element is a list,
6979 appends the list's flattened elements to the current element. Also
6980 changes the tails into conses. For instance, this pre-flattened trie
6981
6982 '(a ((b 20)
6983 (c ((d 30)
6984 (e 40)))))
6985
6986 becomes
6987
6988 '(a (b . 20)
6989 (c (d . 30)
6990 (e . 40)))
6991
6992 Note that the root of the trie has no key, just a list of chains.
6993 This is also true for the value of any key with multiple children,
6994 e.g. key 'c' in the example above."
6995 (cond
6996 ((listp (car trie))
6997 (mapcar #'js2-flatten-trie trie))
6998 (t
6999 (if (numberp (second trie))
7000 (cons (car trie) (second trie))
7001 ;; else pop list and append its kids
7002 (apply #'append (list (car trie)) (js2-flatten-trie (cdr trie)))))))
7003
7004 (defun js2-build-imenu-index ()
7005 "Turn `js2-imenu-recorder' into an imenu data structure."
7006 (unless (eq js2-imenu-recorder 'empty)
7007 (let* ((chains (js2-browse-postprocess-chains js2-imenu-recorder))
7008 (result (js2-build-alist-trie chains nil)))
7009 (js2-flatten-trie result))))
7010
7011 (defun js2-test-print-chains (chains)
7012 "Print a list of qname chains.
7013 Each element of CHAINS is a list of the form (NODE [NODE *] pos);
7014 i.e. one or more nodes, and an integer position as the list tail."
7015 (mapconcat (lambda (chain)
7016 (concat "("
7017 (mapconcat (lambda (elem)
7018 (if (js2-node-p elem)
7019 (or (js2-node-qname-component elem)
7020 "nil")
7021 (number-to-string elem)))
7022 chain
7023 " ")
7024 ")"))
7025 chains
7026 "\n"))
7027
7028 ;;; Parser
7029
7030 (defconst js2-version "1.8.0"
7031 "Version of JavaScript supported, plus minor js2 version.")
7032
7033 (defmacro js2-record-face (face)
7034 "Record a style run of FACE for the current token."
7035 `(js2-set-face js2-token-beg js2-token-end ,face 'record))
7036
7037 (defsubst js2-node-end (n)
7038 "Computes the absolute end of node N.
7039 Use with caution! Assumes `js2-node-pos' is -absolute-, which
7040 is only true until the node is added to its parent; i.e., while parsing."
7041 (+ (js2-node-pos n)
7042 (js2-node-len n)))
7043
7044 (defsubst js2-record-comment ()
7045 "Record a comment in `js2-scanned-comments'."
7046 (push (make-js2-comment-node :len (- js2-token-end js2-token-beg)
7047 :format js2-ts-comment-type)
7048 js2-scanned-comments)
7049 (when js2-parse-ide-mode
7050 (js2-record-face (if (eq js2-ts-comment-type 'jsdoc)
7051 'font-lock-doc-face
7052 'font-lock-comment-face))
7053 (when (memq js2-ts-comment-type '(html preprocessor))
7054 ;; Tell cc-engine the bounds of the comment.
7055 (put-text-property js2-token-beg (1- js2-token-end) 'c-in-sws t))))
7056
7057 ;; This function is called depressingly often, so it should be fast.
7058 ;; Most of the time it's looking at the same token it peeked before.
7059 (defsubst js2-peek-token ()
7060 "Returns the next token without consuming it.
7061 If previous token was consumed, calls scanner to get new token.
7062 If previous token was -not- consumed, returns it (idempotent).
7063
7064 This function will not return a newline (js2-EOL) - instead, it
7065 gobbles newlines until it finds a non-newline token, and flags
7066 that token as appearing just after a newline.
7067
7068 This function will also not return a js2-COMMENT. Instead, it
7069 records comments found in `js2-scanned-comments'. If the token
7070 returned by this function immediately follows a jsdoc comment,
7071 the token is flagged as such.
7072
7073 Note that this function always returned the un-flagged token!
7074 The flags, if any, are saved in `js2-current-flagged-token'."
7075 (if (/= js2-current-flagged-token js2-EOF) ; last token not consumed
7076 js2-current-token ; most common case - return already-peeked token
7077 (let ((tt (js2-get-token)) ; call scanner
7078 saw-eol
7079 face)
7080 ;; process comments and whitespace
7081 (while (or (= tt js2-EOL)
7082 (= tt js2-COMMENT))
7083 (if (= tt js2-EOL)
7084 (setq saw-eol t)
7085 (setq saw-eol nil)
7086 (if js2-record-comments
7087 (js2-record-comment)))
7088 (setq tt (js2-get-token))) ; call scanner
7089 (setq js2-current-token tt
7090 js2-current-flagged-token (if saw-eol
7091 (logior tt js2-ti-after-eol)
7092 tt))
7093 ;; perform lexical fontification as soon as token is scanned
7094 (when js2-parse-ide-mode
7095 (cond
7096 ((minusp tt)
7097 (js2-record-face 'js2-error-face))
7098 ((setq face (aref js2-kwd-tokens tt))
7099 (js2-record-face face))
7100 ((and (= tt js2-NAME)
7101 (equal js2-ts-string "undefined"))
7102 (js2-record-face 'font-lock-constant-face))))
7103 tt))) ; return unflagged token
7104
7105 (defsubst js2-peek-flagged-token ()
7106 "Returns the current token along with any flags set for it."
7107 (js2-peek-token)
7108 js2-current-flagged-token)
7109
7110 (defsubst js2-consume-token ()
7111 (setq js2-current-flagged-token js2-EOF))
7112
7113 (defsubst js2-next-token ()
7114 (prog1
7115 (js2-peek-token)
7116 (js2-consume-token)))
7117
7118 (defsubst js2-next-flagged-token ()
7119 (js2-peek-token)
7120 (prog1 js2-current-flagged-token
7121 (js2-consume-token)))
7122
7123 (defsubst js2-match-token (match)
7124 "Consume and return t if next token matches MATCH, a bytecode.
7125 Returns nil and consumes nothing if MATCH is not the next token."
7126 (if (/= (js2-peek-token) match)
7127 nil
7128 (js2-consume-token)
7129 t))
7130
7131 (defsubst js2-valid-prop-name-token (tt)
7132 (or (= tt js2-NAME)
7133 (and js2-allow-keywords-as-property-names
7134 (plusp tt)
7135 (aref js2-kwd-tokens tt))))
7136
7137 (defsubst js2-match-prop-name ()
7138 "Consume token and return t if next token is a valid property name.
7139 It's valid if it's a js2-NAME, or `js2-allow-keywords-as-property-names'
7140 is non-nil and it's a keyword token."
7141 (if (js2-valid-prop-name-token (js2-peek-token))
7142 (progn
7143 (js2-consume-token)
7144 t)
7145 nil))
7146
7147 (defsubst js2-must-match-prop-name (msg-id &optional pos len)
7148 (if (js2-match-prop-name)
7149 t
7150 (js2-report-error msg-id nil pos len)
7151 nil))
7152
7153 (defsubst js2-peek-token-or-eol ()
7154 "Return js2-EOL if the current token immediately follows a newline.
7155 Else returns the current token. Used in situations where we don't
7156 consider certain token types valid if they are preceded by a newline.
7157 One example is the postfix ++ or -- operator, which has to be on the
7158 same line as its operand."
7159 (let ((tt (js2-peek-token)))
7160 ;; Check for last peeked token flags
7161 (if (js2-flag-set-p js2-current-flagged-token js2-ti-after-eol)
7162 js2-EOL
7163 tt)))
7164
7165 (defsubst js2-set-check-for-label ()
7166 (assert (= (logand js2-current-flagged-token js2-clear-ti-mask) js2-NAME))
7167 (js2-set-flag js2-current-flagged-token js2-ti-check-label))
7168
7169 (defsubst js2-must-match (token msg-id &optional pos len)
7170 "Match next token to token code TOKEN, or record a syntax error.
7171 MSG-ID is the error message to report if the match fails.
7172 Returns t on match, nil if no match."
7173 (if (js2-match-token token)
7174 t
7175 (js2-report-error msg-id nil pos len)
7176 nil))
7177
7178 (defsubst js2-inside-function ()
7179 (plusp js2-nesting-of-function))
7180
7181 (defsubst js2-set-requires-activation ()
7182 (if (js2-function-node-p js2-current-script-or-fn)
7183 (setf (js2-function-node-needs-activation js2-current-script-or-fn) t)))
7184
7185 (defsubst js2-check-activation-name (name token)
7186 (when (js2-inside-function)
7187 ;; skip language-version 1.2 check from Rhino
7188 (if (or (string= "arguments" name)
7189 (and js2-compiler-activation-names ; only used in codegen
7190 (gethash name js2-compiler-activation-names)))
7191 (js2-set-requires-activation))))
7192
7193 (defsubst js2-set-is-generator ()
7194 (if (js2-function-node-p js2-current-script-or-fn)
7195 (setf (js2-function-node-is-generator js2-current-script-or-fn) t)))
7196
7197 (defsubst js2-must-have-xml ()
7198 (unless js2-compiler-xml-available
7199 (js2-report-error "msg.XML.not.available")))
7200
7201 (defsubst js2-push-scope (scope)
7202 "Push SCOPE, a `js2-scope', onto the lexical scope chain."
7203 (assert (js2-scope-p scope))
7204 (assert (null (js2-scope-parent-scope scope)))
7205 (assert (not (eq js2-current-scope scope)))
7206 (setf (js2-scope-parent-scope scope) js2-current-scope
7207 js2-current-scope scope))
7208
7209 (defsubst js2-pop-scope ()
7210 (setq js2-current-scope
7211 (js2-scope-parent-scope js2-current-scope)))
7212
7213 (defsubst js2-enter-loop (loop-node)
7214 (push loop-node js2-loop-set)
7215 (push loop-node js2-loop-and-switch-set)
7216 (js2-push-scope loop-node)
7217 ;; Tell the current labeled statement (if any) its statement,
7218 ;; and set the jump target of the first label to the loop.
7219 ;; These are used in `js2-parse-continue' to verify that the
7220 ;; continue target is an actual labeled loop. (And for codegen.)
7221 (when js2-labeled-stmt
7222 (setf (js2-labeled-stmt-node-stmt js2-labeled-stmt) loop-node
7223 (js2-label-node-loop (car (js2-labeled-stmt-node-labels
7224 js2-labeled-stmt))) loop-node)))
7225
7226 (defsubst js2-exit-loop ()
7227 (pop js2-loop-set)
7228 (pop js2-loop-and-switch-set)
7229 (js2-pop-scope))
7230
7231 (defsubst js2-enter-switch (switch-node)
7232 (push switch-node js2-loop-and-switch-set))
7233
7234 (defsubst js2-exit-switch ()
7235 (pop js2-loop-and-switch-set))
7236
7237 (defun js2-parse (&optional buf cb)
7238 "Tells the js2 parser to parse a region of JavaScript.
7239
7240 BUF is a buffer or buffer name containing the code to parse.
7241 Call `narrow-to-region' first to parse only part of the buffer.
7242
7243 The returned AST root node is given some additional properties:
7244 `node-count' - total number of nodes in the AST
7245 `buffer' - BUF. The buffer it refers to may change or be killed,
7246 so the value is not necessarily reliable.
7247
7248 An optional callback CB can be specified to report parsing
7249 progress. If `(functionp CB)' returns t, it will be called with
7250 the current line number once before parsing begins, then again
7251 each time the lexer reaches a new line number.
7252
7253 CB can also be a list of the form `(symbol cb ...)' to specify
7254 multiple callbacks with different criteria. Each symbol is a
7255 criterion keyword, and the following element is the callback to
7256 call
7257
7258 :line - called whenever the line number changes
7259 :token - called for each new token consumed
7260
7261 The list of criteria could be extended to include entering or
7262 leaving a statement, an expression, or a function definition."
7263 (if (and cb (not (functionp cb)))
7264 (error "criteria callbacks not yet implemented"))
7265 (let ((inhibit-point-motion-hooks t)
7266 (js2-compiler-xml-available (>= js2-language-version 160))
7267 ;; This is a recursive-descent parser, so give it a big stack.
7268 (max-lisp-eval-depth (max max-lisp-eval-depth 3000))
7269 (max-specpdl-size (max max-specpdl-size 3000))
7270 (case-fold-search nil)
7271 ast)
7272 (or buf (setq buf (current-buffer)))
7273 (message nil) ; clear any error message from previous parse
7274 (save-excursion
7275 (set-buffer buf)
7276 (setq js2-scanned-comments nil
7277 js2-parsed-errors nil
7278 js2-parsed-warnings nil
7279 js2-imenu-recorder nil
7280 js2-imenu-function-map nil
7281 js2-label-set nil)
7282 (js2-init-scanner)
7283 (setq ast (js2-with-unmodifying-text-property-changes
7284 (js2-do-parse)))
7285 (unless js2-ts-hit-eof
7286 (js2-report-error "msg.got.syntax.errors" (length js2-parsed-errors)))
7287 (setf (js2-ast-root-errors ast) js2-parsed-errors
7288 (js2-ast-root-warnings ast) js2-parsed-warnings)
7289 ;; if we didn't find any declarations, put a dummy in this list so we
7290 ;; don't end up re-parsing the buffer in `js2-mode-create-imenu-index'
7291 (unless js2-imenu-recorder
7292 (setq js2-imenu-recorder 'empty))
7293 (run-hooks 'js2-parse-finished-hook)
7294 ast)))
7295
7296 ;; Corresponds to Rhino's Parser.parse() method.
7297 (defun js2-do-parse ()
7298 "Parse current buffer starting from current point.
7299 Scanner should be initialized."
7300 (let ((pos js2-ts-cursor)
7301 (end js2-ts-cursor) ; in case file is empty
7302 root n tt)
7303 ;; initialize buffer-local parsing vars
7304 (setf root (make-js2-ast-root :buffer (buffer-name) :pos pos)
7305 js2-current-script-or-fn root
7306 js2-current-scope root
7307 js2-current-flagged-token js2-EOF
7308 js2-nesting-of-function 0
7309 js2-labeled-stmt nil
7310 js2-recorded-assignments nil) ; for js2-highlight
7311 (while (/= (setq tt (js2-peek-token)) js2-EOF)
7312 (if (= tt js2-FUNCTION)
7313 (progn
7314 (js2-consume-token)
7315 (setq n (js2-parse-function (if js2-called-by-compile-function
7316 'FUNCTION_EXPRESSION
7317 'FUNCTION_STATEMENT)))
7318 (js2-record-imenu-functions n))
7319 ;; not a function - parse a statement
7320 (setq n (js2-parse-statement)))
7321 ;; add function or statement to script
7322 (setq end (js2-node-end n))
7323 (js2-block-node-push root n))
7324 ;; add comments to root in lexical order
7325 (when js2-scanned-comments
7326 ;; if we find a comment beyond end of normal kids, use its end
7327 (setq end (max end (js2-node-end (first js2-scanned-comments))))
7328 (dolist (comment js2-scanned-comments)
7329 (push comment (js2-ast-root-comments root))
7330 (js2-node-add-children root comment)))
7331 (setf (js2-node-len root) (- end pos))
7332 ;; Give extensions a chance to muck with things before highlighting starts.
7333 (dolist (callback js2-post-parse-callbacks)
7334 (funcall callback))
7335 (js2-highlight-undeclared-vars)
7336 root))
7337
7338 (defun js2-function-parser ()
7339 (js2-consume-token)
7340 (js2-parse-function 'FUNCTION_EXPRESSION_STATEMENT))
7341
7342 (defun js2-parse-function-closure-body (fn-node)
7343 "Parse a JavaScript 1.8 function closure body."
7344 (let ((js2-nesting-of-function (1+ js2-nesting-of-function)))
7345 (if js2-ts-hit-eof
7346 (js2-report-error "msg.no.brace.body" nil
7347 (js2-node-pos fn-node)
7348 (- js2-ts-cursor (js2-node-pos fn-node)))
7349 (js2-node-add-children fn-node
7350 (setf (js2-function-node-body fn-node)
7351 (js2-parse-expr t))))))
7352
7353 (defun js2-parse-function-body (fn-node)
7354 (js2-must-match js2-LC "msg.no.brace.body"
7355 (js2-node-pos fn-node)
7356 (- js2-ts-cursor (js2-node-pos fn-node)))
7357 (let ((pos js2-token-beg) ; LC position
7358 (pn (make-js2-block-node)) ; starts at LC position
7359 tt
7360 end)
7361 (incf js2-nesting-of-function)
7362 (unwind-protect
7363 (while (not (or (= (setq tt (js2-peek-token)) js2-ERROR)
7364 (= tt js2-EOF)
7365 (= tt js2-RC)))
7366 (js2-block-node-push pn (if (/= tt js2-FUNCTION)
7367 (js2-parse-statement)
7368 (js2-consume-token)
7369 (js2-parse-function 'FUNCTION_STATEMENT))))
7370 (decf js2-nesting-of-function))
7371 (setq end js2-token-end) ; assume no curly and leave at current token
7372 (if (js2-must-match js2-RC "msg.no.brace.after.body" pos)
7373 (setq end js2-token-end))
7374 (setf (js2-node-pos pn) pos
7375 (js2-node-len pn) (- end pos))
7376 (setf (js2-function-node-body fn-node) pn)
7377 (js2-node-add-children fn-node pn)
7378 pn))
7379
7380 (defun js2-parse-function-params (fn-node pos)
7381 (if (js2-match-token js2-RP)
7382 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos))
7383 (let (params len param)
7384 (loop for tt = (js2-peek-token)
7385 do
7386 (cond
7387 ;; destructuring param
7388 ((or (= tt js2-LB) (= tt js2-LC))
7389 (push (js2-parse-primary-expr t) params))
7390 ;; simple name
7391 (t
7392 (js2-must-match js2-NAME "msg.no.parm")
7393 (js2-record-face 'js2-function-param-face)
7394 (setq param (js2-create-name-node))
7395 (js2-define-symbol js2-LP js2-ts-string param)
7396 (push param params)))
7397 while
7398 (js2-match-token js2-COMMA))
7399 (if (js2-must-match js2-RP "msg.no.paren.after.parms")
7400 (setf (js2-function-node-rp fn-node) (- js2-token-beg pos)))
7401 (dolist (p params)
7402 (js2-node-add-children fn-node p)
7403 (push p (js2-function-node-params fn-node))))))
7404
7405 (defsubst js2-check-inconsistent-return-warning (fn-node name)
7406 "Possibly show inconsistent-return warning.
7407 Last token scanned is the close-curly for the function body."
7408 (when (and js2-mode-show-strict-warnings
7409 js2-strict-inconsistent-return-warning
7410 (not (js2-has-consistent-return-usage
7411 (js2-function-node-body fn-node))))
7412 ;; Have it extend from close-curly to bol or beginning of block.
7413 (let ((pos (save-excursion
7414 (goto-char js2-token-end)
7415 (max (js2-node-abs-pos (js2-function-node-body fn-node))
7416 (point-at-bol))))
7417 (end js2-token-end))
7418 (if (plusp (js2-name-node-length name))
7419 (js2-add-strict-warning "msg.no.return.value"
7420 (js2-name-node-name name) pos end)
7421 (js2-add-strict-warning "msg.anon.no.return.value" nil pos end)))))
7422
7423 (defun js2-parse-function (function-type)
7424 "Function parser. FUNCTION-TYPE is a symbol."
7425 (let ((pos js2-token-beg) ; start of 'function' keyword
7426 name
7427 name-beg
7428 name-end
7429 fn-node
7430 lp
7431 (synthetic-type function-type)
7432 member-expr-node)
7433 ;; parse function name, expression, or non-name (anonymous)
7434 (cond
7435 ;; function foo(...)
7436 ((js2-match-token js2-NAME)
7437 (setq name (js2-create-name-node t)
7438 name-beg js2-token-beg
7439 name-end js2-token-end)
7440 (unless (js2-match-token js2-LP)
7441 (when js2-allow-member-expr-as-function-name
7442 ;; function foo.bar(...)
7443 (setq member-expr-node name
7444 name nil
7445 member-expr-node (js2-parse-member-expr-tail
7446 nil member-expr-node)))
7447 (js2-must-match js2-LP "msg.no.paren.parms")))
7448 ((js2-match-token js2-LP)
7449 nil) ; anonymous function: leave name as null
7450 (t
7451 ;; function random-member-expr(...)
7452 (when js2-allow-member-expr-as-function-name
7453 ;; Note that memberExpr can not start with '(' like
7454 ;; in function (1+2).toString(), because 'function (' already
7455 ;; processed as anonymous function
7456 (setq member-expr-node (js2-parse-member-expr)))
7457 (js2-must-match js2-LP "msg.no.paren.parms")))
7458 (if (= js2-current-token js2-LP) ; eventually matched LP?
7459 (setq lp js2-token-beg))
7460 (if member-expr-node
7461 (progn
7462 (setq synthetic-type 'FUNCTION_EXPRESSION)
7463 (js2-parse-highlight-member-expr-fn-name member-expr-node))
7464 (if name
7465 (js2-set-face name-beg name-end
7466 'font-lock-function-name-face 'record)))
7467 (if (and (not (eq synthetic-type 'FUNCTION_EXPRESSION))
7468 (plusp (js2-name-node-length name)))
7469 ;; Function statements define a symbol in the enclosing scope
7470 (js2-define-symbol js2-FUNCTION (js2-name-node-name name) fn-node))
7471 (setf fn-node (make-js2-function-node :pos pos
7472 :name name
7473 :form function-type
7474 :lp (if lp (- lp pos))))
7475 (if (or (js2-inside-function) (plusp js2-nesting-of-with))
7476 ;; 1. Nested functions are not affected by the dynamic scope flag
7477 ;; as dynamic scope is already a parent of their scope.
7478 ;; 2. Functions defined under the with statement also immune to
7479 ;; this setup, in which case dynamic scope is ignored in favor
7480 ;; of the with object.
7481 (setf (js2-function-node-ignore-dynamic fn-node) t))
7482 ;; dynamically bind all the per-function variables
7483 (let ((js2-current-script-or-fn fn-node)
7484 (js2-current-scope fn-node)
7485 (js2-nesting-of-with 0)
7486 (js2-end-flags 0)
7487 js2-label-set
7488 js2-loop-set
7489 js2-loop-and-switch-set)
7490 (js2-parse-function-params fn-node pos)
7491 (if (and (>= js2-language-version 180)
7492 (/= (js2-peek-token) js2-LC))
7493 (js2-parse-function-closure-body fn-node)
7494 (js2-parse-function-body fn-node))
7495 (if name
7496 (js2-node-add-children fn-node name))
7497 (js2-check-inconsistent-return-warning fn-node name)
7498 ;; Function expressions define a name only in the body of the
7499 ;; function, and only if not hidden by a parameter name
7500 (if (and name
7501 (eq synthetic-type 'FUNCTION_EXPRESSION)
7502 (null (js2-scope-get-symbol js2-current-scope
7503 (js2-name-node-name name))))
7504 (js2-define-symbol js2-FUNCTION
7505 (js2-name-node-name name)
7506 fn-node))
7507 (if (and name
7508 (eq function-type 'FUNCTION_EXPRESSION_STATEMENT))
7509 (js2-record-imenu-functions fn-node)))
7510 (setf (js2-node-len fn-node) (- js2-ts-cursor pos)
7511 (js2-function-node-member-expr fn-node) member-expr-node) ; may be nil
7512 ;; Rhino doesn't do this, but we need it for finding undeclared vars.
7513 ;; We wait until after parsing the function to set its parent scope,
7514 ;; since `js2-define-symbol' needs the defining-scope check to stop
7515 ;; at the function boundary when checking for redeclarations.
7516 (setf (js2-scope-parent-scope fn-node) js2-current-scope)
7517 fn-node))
7518
7519 (defun js2-parse-statements (&optional parent)
7520 "Parse a statement list. Last token consumed must be js2-LC.
7521
7522 PARENT can be a `js2-block-node', in which case the statements are
7523 appended to PARENT. Otherwise a new `js2-block-node' is created
7524 and returned.
7525
7526 This function does not match the closing js2-RC: the caller
7527 matches the RC so it can provide a suitable error message if not
7528 matched. This means it's up to the caller to set the length of
7529 the node to include the closing RC. The node start pos is set to
7530 the absolute buffer start position, and the caller should fix it
7531 up to be relative to the parent node. All children of this block
7532 node are given relative start positions and correct lengths."
7533 (let ((pn (or parent (make-js2-block-node)))
7534 tt)
7535 (setf (js2-node-pos pn) js2-token-beg)
7536 (while (and (> (setq tt (js2-peek-token)) js2-EOF)
7537 (/= tt js2-RC))
7538 (js2-block-node-push pn (js2-parse-statement)))
7539 pn))
7540
7541 (defun js2-parse-statement ()
7542 (let (tt pn beg end)
7543 ;; coarse-grained user-interrupt check - needs work
7544 (and js2-parse-interruptable-p
7545 (zerop (% (incf js2-parse-stmt-count)
7546 js2-statements-per-pause))
7547 (input-pending-p)
7548 (throw 'interrupted t))
7549 (setq pn (js2-statement-helper))
7550 ;; no-side-effects warning check
7551 (unless (js2-node-has-side-effects pn)
7552 (setq end (js2-node-end pn))
7553 (save-excursion
7554 (goto-char end)
7555 (setq beg (max (js2-node-pos pn) (point-at-bol))))
7556 (js2-add-strict-warning "msg.no.side.effects" nil beg end))
7557 pn))
7558
7559 ;; These correspond to the switch cases in Parser.statementHelper
7560 (defconst js2-parsers
7561 (let ((parsers (make-vector js2-num-tokens
7562 #'js2-parse-expr-stmt)))
7563 (aset parsers js2-BREAK #'js2-parse-break)
7564 (aset parsers js2-CONST #'js2-parse-const-var)
7565 (aset parsers js2-CONTINUE #'js2-parse-continue)
7566 (aset parsers js2-DEBUGGER #'js2-parse-debugger)
7567 (aset parsers js2-DEFAULT #'js2-parse-default-xml-namespace)
7568 (aset parsers js2-DO #'js2-parse-do)
7569 (aset parsers js2-FOR #'js2-parse-for)
7570 (aset parsers js2-FUNCTION #'js2-function-parser)
7571 (aset parsers js2-IF #'js2-parse-if)
7572 (aset parsers js2-LC #'js2-parse-block)
7573 (aset parsers js2-LET #'js2-parse-let-stmt)
7574 (aset parsers js2-NAME #'js2-parse-name-or-label)
7575 (aset parsers js2-RETURN #'js2-parse-ret-yield)
7576 (aset parsers js2-SEMI #'js2-parse-semi)
7577 (aset parsers js2-SWITCH #'js2-parse-switch)
7578 (aset parsers js2-THROW #'js2-parse-throw)
7579 (aset parsers js2-TRY #'js2-parse-try)
7580 (aset parsers js2-VAR #'js2-parse-const-var)
7581 (aset parsers js2-WHILE #'js2-parse-while)
7582 (aset parsers js2-WITH #'js2-parse-with)
7583 (aset parsers js2-YIELD #'js2-parse-ret-yield)
7584 parsers)
7585 "A vector mapping token types to parser functions.")
7586
7587 (defsubst js2-parse-warn-missing-semi (beg end)
7588 (and js2-mode-show-strict-warnings
7589 js2-strict-missing-semi-warning
7590 (js2-add-strict-warning
7591 "msg.missing.semi" nil
7592 ;; back up to beginning of statement or line
7593 (max beg (save-excursion
7594 (goto-char end)
7595 (point-at-bol)))
7596 end)))
7597
7598 (defconst js2-no-semi-insertion
7599 (list js2-IF
7600 js2-SWITCH
7601 js2-WHILE
7602 js2-DO
7603 js2-FOR
7604 js2-TRY
7605 js2-WITH
7606 js2-LC
7607 js2-ERROR
7608 js2-SEMI
7609 js2-FUNCTION)
7610 "List of tokens that don't do automatic semicolon insertion.")
7611
7612 (defconst js2-autoinsert-semi-and-warn
7613 (list js2-ERROR js2-EOF js2-RC))
7614
7615 (defun js2-statement-helper ()
7616 (let* ((tt (js2-peek-token))
7617 (first-tt tt)
7618 (beg js2-token-beg)
7619 (parser (if (= tt js2-ERROR)
7620 #'js2-parse-semi
7621 (aref js2-parsers tt)))
7622 pn
7623 tt-flagged)
7624 ;; If the statement is set, then it's been told its label by now.
7625 (and js2-labeled-stmt
7626 (js2-labeled-stmt-node-stmt js2-labeled-stmt)
7627 (setq js2-labeled-stmt nil))
7628 (setq pn (funcall parser))
7629 ;; Don't do auto semi insertion for certain statement types.
7630 (unless (or (memq first-tt js2-no-semi-insertion)
7631 (js2-labeled-stmt-node-p pn))
7632 (js2-auto-insert-semicolon pn))
7633 pn))
7634
7635 (defun js2-auto-insert-semicolon (pn)
7636 (let* ((tt-flagged (js2-peek-flagged-token))
7637 (tt (logand tt-flagged js2-clear-ti-mask))
7638 (pos (js2-node-pos pn)))
7639 (cond
7640 ((= tt js2-SEMI)
7641 ;; Consume ';' as a part of expression
7642 (js2-consume-token)
7643 ;; extend the node bounds to include the semicolon.
7644 (setf (js2-node-len pn) (- js2-token-end pos)))
7645 ((memq tt js2-autoinsert-semi-and-warn)
7646 ;; Autoinsert ;
7647 (js2-parse-warn-missing-semi pos (js2-node-end pn)))
7648 (t
7649 (if (js2-flag-not-set-p tt-flagged js2-ti-after-eol)
7650 ;; Report error if no EOL or autoinsert ';' otherwise
7651 (js2-report-error "msg.no.semi.stmt")
7652 (js2-parse-warn-missing-semi pos (js2-node-end pn)))))))
7653
7654 (defun js2-parse-condition ()
7655 "Parse a parenthesized boolean expression, e.g. in an if- or while-stmt.
7656 The parens are discarded and the expression node is returned.
7657 The `pos' field of the return value is set to an absolute position
7658 that must be fixed up by the caller.
7659 Return value is a list (EXPR LP RP), with absolute paren positions."
7660 (let (pn lp rp)
7661 (if (js2-must-match js2-LP "msg.no.paren.cond")
7662 (setq lp js2-token-beg))
7663 (setq pn (js2-parse-expr))
7664 (if (js2-must-match js2-RP "msg.no.paren.after.cond")
7665 (setq rp js2-token-beg))
7666 ;; Report strict warning on code like "if (a = 7) ..."
7667 (if (and js2-strict-cond-assign-warning
7668 (js2-assign-node-p pn))
7669 (js2-add-strict-warning "msg.equal.as.assign" nil
7670 (js2-node-pos pn)
7671 (+ (js2-node-pos pn)
7672 (js2-node-len pn))))
7673 (list pn lp rp)))
7674
7675 (defun js2-parse-if ()
7676 "Parser for if-statement. Last matched token must be js2-IF."
7677 (let ((pos js2-token-beg)
7678 cond
7679 if-true
7680 if-false
7681 else-pos
7682 end
7683 pn)
7684 (js2-consume-token)
7685 (setq cond (js2-parse-condition)
7686 if-true (js2-parse-statement)
7687 if-false (if (js2-match-token js2-ELSE)
7688 (progn
7689 (setq else-pos (- js2-token-beg pos))
7690 (js2-parse-statement)))
7691 end (js2-node-end (or if-false if-true))
7692 pn (make-js2-if-node :pos pos
7693 :len (- end pos)
7694 :condition (car cond)
7695 :then-part if-true
7696 :else-part if-false
7697 :else-pos else-pos
7698 :lp (js2-relpos (second cond) pos)
7699 :rp (js2-relpos (third cond) pos)))
7700 (js2-node-add-children pn (car cond) if-true if-false)
7701 pn))
7702
7703 (defun js2-parse-switch ()
7704 "Parser for if-statement. Last matched token must be js2-SWITCH."
7705 (let ((pos js2-token-beg)
7706 tt
7707 pn
7708 discriminant
7709 has-default
7710 case-expr
7711 case-node
7712 case-pos
7713 cases
7714 stmt
7715 lp
7716 rp)
7717 (js2-consume-token)
7718 (if (js2-must-match js2-LP "msg.no.paren.switch")
7719 (setq lp js2-token-beg))
7720 (setq discriminant (js2-parse-expr)
7721 pn (make-js2-switch-node :discriminant discriminant
7722 :pos pos
7723 :lp (js2-relpos lp pos)))
7724 (js2-node-add-children pn discriminant)
7725 (js2-enter-switch pn)
7726 (unwind-protect
7727 (progn
7728 (if (js2-must-match js2-RP "msg.no.paren.after.switch")
7729 (setf (js2-switch-node-rp pn) (- js2-token-beg pos)))
7730 (js2-must-match js2-LC "msg.no.brace.switch")
7731 (catch 'break
7732 (while t
7733 (setq tt (js2-next-token)
7734 case-pos js2-token-beg)
7735 (cond
7736 ((= tt js2-RC)
7737 (setf (js2-node-len pn) (- js2-token-end pos))
7738 (throw 'break nil)) ; done
7739 ((= tt js2-CASE)
7740 (setq case-expr (js2-parse-expr))
7741 (js2-must-match js2-COLON "msg.no.colon.case"))
7742 ((= tt js2-DEFAULT)
7743 (if has-default
7744 (js2-report-error "msg.double.switch.default"))
7745 (setq has-default t
7746 case-expr nil)
7747 (js2-must-match js2-COLON "msg.no.colon.case"))
7748 (t
7749 (js2-report-error "msg.bad.switch")
7750 (throw 'break nil)))
7751 (setq case-node (make-js2-case-node :pos case-pos
7752 :len (- js2-token-end case-pos)
7753 :expr case-expr))
7754 (js2-node-add-children case-node case-expr)
7755 (while (and (/= (setq tt (js2-peek-token)) js2-RC)
7756 (/= tt js2-CASE)
7757 (/= tt js2-DEFAULT)
7758 (/= tt js2-EOF))
7759 (setf stmt (js2-parse-statement)
7760 (js2-node-len case-node) (- (js2-node-end stmt) case-pos))
7761 (js2-block-node-push case-node stmt))
7762 (push case-node cases)))
7763 ;; add cases last, as pushing reverses the order to be correct
7764 (dolist (kid cases)
7765 (js2-node-add-children pn kid)
7766 (push kid (js2-switch-node-cases pn)))
7767 pn) ; return value
7768 (js2-exit-switch))))
7769
7770 (defun js2-parse-while ()
7771 "Parser for while-statement. Last matched token must be js2-WHILE."
7772 (let ((pos js2-token-beg)
7773 (pn (make-js2-while-node))
7774 cond
7775 body)
7776 (js2-consume-token)
7777 (js2-enter-loop pn)
7778 (unwind-protect
7779 (progn
7780 (setf cond (js2-parse-condition)
7781 (js2-while-node-condition pn) (car cond)
7782 body (js2-parse-statement)
7783 (js2-while-node-body pn) body
7784 (js2-node-len pn) (- (js2-node-end body) pos)
7785 (js2-while-node-lp pn) (js2-relpos (second cond) pos)
7786 (js2-while-node-rp pn) (js2-relpos (third cond) pos))
7787 (js2-node-add-children pn body (car cond)))
7788 (js2-exit-loop))
7789 pn))
7790
7791 (defun js2-parse-do ()
7792 "Parser for do-statement. Last matched token must be js2-DO."
7793 (let ((pos js2-token-beg)
7794 (pn (make-js2-do-node))
7795 cond
7796 body
7797 end)
7798 (js2-consume-token)
7799 (js2-enter-loop pn)
7800 (unwind-protect
7801 (progn
7802 (setq body (js2-parse-statement))
7803 (js2-must-match js2-WHILE "msg.no.while.do")
7804 (setf (js2-do-node-while-pos pn) (- js2-token-beg pos)
7805 cond (js2-parse-condition)
7806 (js2-do-node-condition pn) (car cond)
7807 (js2-do-node-body pn) body
7808 end js2-ts-cursor
7809 (js2-do-node-lp pn) (js2-relpos (second cond) pos)
7810 (js2-do-node-rp pn) (js2-relpos (third cond) pos))
7811 (js2-node-add-children pn (car cond) body))
7812 (js2-exit-loop))
7813 ;; Always auto-insert semicolon to follow SpiderMonkey:
7814 ;; It is required by ECMAScript but is ignored by the rest of
7815 ;; world; see bug 238945
7816 (if (js2-match-token js2-SEMI)
7817 (setq end js2-ts-cursor))
7818 (setf (js2-node-len pn) (- end pos))
7819 pn))
7820
7821 (defun js2-parse-for ()
7822 "Parser for for-statement. Last matched token must be js2-FOR.
7823 Parses for, for-in, and for each-in statements."
7824 (let ((for-pos js2-token-beg)
7825 pn
7826 is-for-each
7827 is-for-in
7828 in-pos
7829 each-pos
7830 tmp-pos
7831 init ; Node init is also foo in 'foo in object'
7832 cond ; Node cond is also object in 'foo in object'
7833 incr ; 3rd section of for-loop initializer
7834 body
7835 tt
7836 lp
7837 rp)
7838 (js2-consume-token)
7839 ;; See if this is a for each () instead of just a for ()
7840 (when (js2-match-token js2-NAME)
7841 (if (string= "each" js2-ts-string)
7842 (progn
7843 (setq is-for-each t
7844 each-pos (- js2-token-beg for-pos)) ; relative
7845 (js2-record-face 'font-lock-keyword-face))
7846 (js2-report-error "msg.no.paren.for")))
7847 (if (js2-must-match js2-LP "msg.no.paren.for")
7848 (setq lp (- js2-token-beg for-pos)))
7849 (setq tt (js2-peek-token))
7850 ;; parse init clause
7851 (let ((js2-in-for-init t)) ; set as dynamic variable
7852 (cond
7853 ((= tt js2-SEMI)
7854 (setq init (make-js2-empty-expr-node)))
7855 ((or (= tt js2-VAR) (= tt js2-LET))
7856 (js2-consume-token)
7857 (setq init (js2-parse-variables tt js2-token-beg)))
7858 (t
7859 (setq init (js2-parse-expr)))))
7860 (if (js2-match-token js2-IN)
7861 (setq is-for-in t
7862 in-pos (- js2-token-beg for-pos)
7863 cond (js2-parse-expr)) ; object over which we're iterating
7864 ;; else ordinary for loop - parse cond and incr
7865 (js2-must-match js2-SEMI "msg.no.semi.for")
7866 (setq cond (if (= (js2-peek-token) js2-SEMI)
7867 (make-js2-empty-expr-node) ; no loop condition
7868 (js2-parse-expr)))
7869 (js2-must-match js2-SEMI "msg.no.semi.for.cond")
7870 (setq tmp-pos js2-token-end
7871 incr (if (= (js2-peek-token) js2-RP)
7872 (make-js2-empty-expr-node :pos tmp-pos)
7873 (js2-parse-expr))))
7874 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
7875 (setq rp (- js2-token-beg for-pos)))
7876 (if (not is-for-in)
7877 (setq pn (make-js2-for-node :init init
7878 :condition cond
7879 :update incr
7880 :lp lp
7881 :rp rp))
7882 ;; cond could be null if 'in obj' got eaten by the init node.
7883 (if (js2-infix-node-p init)
7884 ;; it was (foo in bar) instead of (var foo in bar)
7885 (setq cond (js2-infix-node-right init)
7886 init (js2-infix-node-left init))
7887 (if (and (js2-var-decl-node-p init)
7888 (> (length (js2-var-decl-node-kids init)) 1))
7889 (js2-report-error "msg.mult.index")))
7890 (setq pn (make-js2-for-in-node :iterator init
7891 :object cond
7892 :in-pos in-pos
7893 :foreach-p is-for-each
7894 :each-pos each-pos
7895 :lp lp
7896 :rp rp)))
7897 (unwind-protect
7898 (progn
7899 (js2-enter-loop pn)
7900 ;; We have to parse the body -after- creating the loop node,
7901 ;; so that the loop node appears in the js2-loop-set, allowing
7902 ;; break/continue statements to find the enclosing loop.
7903 (setf body (js2-parse-statement)
7904 (js2-loop-node-body pn) body
7905 (js2-node-pos pn) for-pos
7906 (js2-node-len pn) (- (js2-node-end body) for-pos))
7907 (js2-node-add-children pn init cond incr body))
7908 ;; finally
7909 (js2-exit-loop))
7910 pn))
7911
7912 (defun js2-parse-try ()
7913 "Parser for try-statement. Last matched token must be js2-TRY."
7914 (let ((try-pos js2-token-beg)
7915 try-end
7916 try-block
7917 catch-blocks
7918 finally-block
7919 saw-default-catch
7920 peek
7921 var-name
7922 catch-cond
7923 catch-node
7924 guard-kwd
7925 catch-pos
7926 finally-pos
7927 pn
7928 block
7929 lp
7930 rp)
7931 (js2-consume-token)
7932 (if (/= (js2-peek-token) js2-LC)
7933 (js2-report-error "msg.no.brace.try"))
7934 (setq try-block (js2-parse-statement)
7935 try-end (js2-node-end try-block)
7936 peek (js2-peek-token))
7937 (cond
7938 ((= peek js2-CATCH)
7939 (while (js2-match-token js2-CATCH)
7940 (setq catch-pos js2-token-beg
7941 guard-kwd nil
7942 catch-cond nil
7943 lp nil
7944 rp nil)
7945 (if saw-default-catch
7946 (js2-report-error "msg.catch.unreachable"))
7947 (if (js2-must-match js2-LP "msg.no.paren.catch")
7948 (setq lp (- js2-token-beg catch-pos)))
7949 (js2-must-match js2-NAME "msg.bad.catchcond")
7950 (setq var-name (js2-create-name-node))
7951 (if (js2-match-token js2-IF)
7952 (setq guard-kwd (- js2-token-beg catch-pos)
7953 catch-cond (js2-parse-expr))
7954 (setq saw-default-catch t))
7955 (if (js2-must-match js2-RP "msg.bad.catchcond")
7956 (setq rp (- js2-token-beg catch-pos)))
7957 (js2-must-match js2-LC "msg.no.brace.catchblock")
7958 (setq block (js2-parse-statements)
7959 try-end (js2-node-end block)
7960 catch-node (make-js2-catch-node :pos catch-pos
7961 :var-name var-name
7962 :guard-expr catch-cond
7963 :guard-kwd guard-kwd
7964 :block block
7965 :lp lp
7966 :rp rp))
7967 (if (js2-must-match js2-RC "msg.no.brace.after.body")
7968 (setq try-end js2-token-beg))
7969 (setf (js2-node-len block) (- try-end (js2-node-pos block))
7970 (js2-node-len catch-node) (- try-end catch-pos))
7971 (js2-node-add-children catch-node var-name catch-cond block)
7972 (push catch-node catch-blocks)))
7973 ((/= peek js2-FINALLY)
7974 (js2-must-match js2-FINALLY "msg.try.no.catchfinally"
7975 (js2-node-pos try-block)
7976 (- (setq try-end (js2-node-end try-block))
7977 (js2-node-pos try-block)))))
7978 (when (js2-match-token js2-FINALLY)
7979 (setq finally-pos js2-token-beg
7980 block (js2-parse-statement)
7981 try-end (js2-node-end block)
7982 finally-block (make-js2-finally-node :pos finally-pos
7983 :len (- try-end finally-pos)
7984 :body block))
7985 (js2-node-add-children finally-block block))
7986 (setq pn (make-js2-try-node :pos try-pos
7987 :len (- try-end try-pos)
7988 :try-block try-block
7989 :finally-block finally-block))
7990 (js2-node-add-children pn try-block finally-block)
7991 ;; push them onto the try-node, which reverses and corrects their order
7992 (dolist (cb catch-blocks)
7993 (js2-node-add-children pn cb)
7994 (push cb (js2-try-node-catch-clauses pn)))
7995 pn))
7996
7997 (defun js2-parse-throw ()
7998 "Parser for throw-statement. Last matched token must be js2-THROW."
7999 (let ((pos js2-token-beg)
8000 expr
8001 pn)
8002 (js2-consume-token)
8003 (if (= (js2-peek-token-or-eol) js2-EOL)
8004 ;; ECMAScript does not allow new lines before throw expression,
8005 ;; see bug 256617
8006 (js2-report-error "msg.bad.throw.eol"))
8007 (setq expr (js2-parse-expr)
8008 pn (make-js2-throw-node :pos pos
8009 :len (- (js2-node-end expr) pos)
8010 :expr expr))
8011 (js2-node-add-children pn expr)
8012 pn))
8013
8014 (defsubst js2-match-jump-label-name (label-name)
8015 "If break/continue specified a label, return that label's labeled stmt.
8016 Returns the corresponding `js2-labeled-stmt-node', or if LABEL-NAME
8017 does not match an existing label, reports an error and returns nil."
8018 (let ((bundle (cdr (assoc label-name js2-label-set))))
8019 (if (null bundle)
8020 (js2-report-error "msg.undef.label"))
8021 bundle))
8022
8023 (defun js2-parse-break ()
8024 "Parser for break-statement. Last matched token must be js2-BREAK."
8025 (let ((pos js2-token-beg)
8026 (end js2-token-end)
8027 break-target ; statement to break from
8028 break-label ; in "break foo", name-node representing the foo
8029 labels ; matching labeled statement to break to
8030 pn)
8031 (js2-consume-token) ; `break'
8032 (when (eq (js2-peek-token-or-eol) js2-NAME)
8033 (js2-consume-token)
8034 (setq break-label (js2-create-name-node)
8035 end (js2-node-end break-label)
8036 ;; matchJumpLabelName only matches if there is one
8037 labels (js2-match-jump-label-name js2-ts-string)
8038 break-target (if labels (car (js2-labeled-stmt-node-labels labels)))))
8039 (unless (or break-target break-label)
8040 ;; no break target specified - try for innermost enclosing loop/switch
8041 (if (null js2-loop-and-switch-set)
8042 (unless break-label
8043 (js2-report-error "msg.bad.break" nil pos (length "break")))
8044 (setq break-target (car js2-loop-and-switch-set))))
8045 (setq pn (make-js2-break-node :pos pos
8046 :len (- end pos)
8047 :label break-label
8048 :target break-target))
8049 (js2-node-add-children pn break-label) ; but not break-target
8050 pn))
8051
8052 (defun js2-parse-continue ()
8053 "Parser for continue-statement. Last matched token must be js2-CONTINUE."
8054 (let ((pos js2-token-beg)
8055 (end js2-token-end)
8056 label ; optional user-specified label, a `js2-name-node'
8057 labels ; current matching labeled stmt, if any
8058 target ; the `js2-loop-node' target of this continue stmt
8059 pn)
8060 (js2-consume-token) ; `continue'
8061 (when (= (js2-peek-token-or-eol) js2-NAME)
8062 (js2-consume-token)
8063 (setq label (js2-create-name-node)
8064 end (js2-node-end label)
8065 ;; matchJumpLabelName only matches if there is one
8066 labels (js2-match-jump-label-name js2-ts-string)))
8067 (cond
8068 ((null labels) ; no current label to go to
8069 (if (null js2-loop-set) ; no loop to continue to
8070 (js2-report-error "msg.continue.outside" nil pos
8071 (length "continue"))
8072 (setq target (car js2-loop-set)))) ; innermost enclosing loop
8073 (t
8074 (if (js2-loop-node-p (js2-labeled-stmt-node-stmt labels))
8075 (setq target (js2-labeled-stmt-node-stmt labels))
8076 (js2-report-error "msg.continue.nonloop" nil pos (- end pos)))))
8077 (setq pn (make-js2-continue-node :pos pos
8078 :len (- end pos)
8079 :label label
8080 :target target))
8081 (js2-node-add-children pn label) ; but not target - it's not our child
8082 pn))
8083
8084 (defun js2-parse-with ()
8085 "Parser for with-statement. Last matched token must be js2-WITH."
8086 (js2-consume-token)
8087 (let ((pos js2-token-beg)
8088 obj body pn lp rp)
8089 (if (js2-must-match js2-LP "msg.no.paren.with")
8090 (setq lp js2-token-beg))
8091 (setq obj (js2-parse-expr))
8092 (if (js2-must-match js2-RP "msg.no.paren.after.with")
8093 (setq rp js2-token-beg))
8094 (let ((js2-nesting-of-with (1+ js2-nesting-of-with)))
8095 (setq body (js2-parse-statement)))
8096 (setq pn (make-js2-with-node :pos pos
8097 :len (- (js2-node-end body) pos)
8098 :object obj
8099 :body body
8100 :lp (js2-relpos lp pos)
8101 :rp (js2-relpos rp pos)))
8102 (js2-node-add-children pn obj body)
8103 pn))
8104
8105 (defun js2-parse-const-var ()
8106 "Parser for var- or const-statement.
8107 Last matched token must be js2-CONST or js2-VAR."
8108 (let ((tt (js2-peek-token))
8109 (pos js2-token-beg)
8110 expr
8111 pn)
8112 (js2-consume-token)
8113 (setq expr (js2-parse-variables tt js2-token-beg)
8114 pn (make-js2-expr-stmt-node :pos pos
8115 :len (- (js2-node-end expr) pos)
8116 :expr expr))
8117 (js2-node-add-children pn expr)
8118 pn))
8119
8120 (defsubst js2-wrap-with-expr-stmt (pos expr &optional add-child)
8121 (let ((pn (make-js2-expr-stmt-node :pos pos
8122 :len (js2-node-len expr)
8123 :type (if (js2-inside-function)
8124 js2-EXPR_VOID
8125 js2-EXPR_RESULT)
8126 :expr expr)))
8127 (if add-child
8128 (js2-node-add-children pn expr))
8129 pn))
8130
8131 (defun js2-parse-let-stmt ()
8132 "Parser for let-statement. Last matched token must be js2-LET."
8133 (js2-consume-token)
8134 (let ((pos js2-token-beg)
8135 expr
8136 pn)
8137 (if (= (js2-peek-token) js2-LP)
8138 ;; let expression in statement context
8139 (setq expr (js2-parse-let pos 'statement)
8140 pn (js2-wrap-with-expr-stmt pos expr t))
8141 ;; else we're looking at a statement like let x=6, y=7;
8142 (setf expr (js2-parse-variables js2-LET pos)
8143 pn (js2-wrap-with-expr-stmt pos expr t)
8144 (js2-node-type pn) js2-EXPR_RESULT))
8145 pn))
8146
8147 (defun js2-parse-ret-yield ()
8148 (js2-parse-return-or-yield (js2-peek-token) nil))
8149
8150 (defconst js2-parse-return-stmt-enders
8151 (list js2-SEMI js2-RC js2-EOF js2-EOL js2-ERROR js2-RB js2-RP js2-YIELD))
8152
8153 (defsubst js2-now-all-set (before after mask)
8154 "Return whether or not the bits in the mask have changed to all set.
8155 BEFORE is bits before change, AFTER is bits after change, and MASK is
8156 the mask for bits. Returns t if all the bits in the mask are set in AFTER
8157 but not BEFORE."
8158 (and (/= (logand before mask) mask)
8159 (= (logand after mask) mask)))
8160
8161 (defun js2-parse-return-or-yield (tt expr-context)
8162 (let ((pos js2-token-beg)
8163 (end js2-token-end)
8164 (before js2-end-flags)
8165 (inside-function (js2-inside-function))
8166 e
8167 ret
8168 name)
8169 (unless inside-function
8170 (js2-report-error (if (eq tt js2-RETURN)
8171 "msg.bad.return"
8172 "msg.bad.yield")))
8173 (js2-consume-token)
8174 ;; This is ugly, but we don't want to require a semicolon.
8175 (unless (memq (js2-peek-token-or-eol) js2-parse-return-stmt-enders)
8176 (setq e (js2-parse-expr)
8177 end (js2-node-end e)))
8178 (cond
8179 ((eq tt js2-RETURN)
8180 (js2-set-flag js2-end-flags (if (null e)
8181 js2-end-returns
8182 js2-end-returns-value))
8183 (setq ret (make-js2-return-node :pos pos
8184 :len (- end pos)
8185 :retval e))
8186 (js2-node-add-children ret e)
8187 ;; See if we need a strict mode warning.
8188 ;; TODO: The analysis done by `js2-has-consistent-return-usage' is
8189 ;; more thorough and accurate than this before/after flag check.
8190 ;; E.g. if there's a finally-block that always returns, we shouldn't
8191 ;; show a warning generated by inconsistent returns in the catch blocks.
8192 ;; Basically `js2-has-consistent-return-usage' needs to keep more state,
8193 ;; so we know which returns/yields to highlight, and we should get rid of
8194 ;; all the checking in `js2-parse-return-or-yield'.
8195 (if (and js2-strict-inconsistent-return-warning
8196 (js2-now-all-set before js2-end-flags
8197 (logior js2-end-returns js2-end-returns-value)))
8198 (js2-add-strict-warning "msg.return.inconsistent" nil pos end)))
8199 (t
8200 (unless (js2-inside-function)
8201 (js2-report-error "msg.bad.yield"))
8202 (js2-set-flag js2-end-flags js2-end-yields)
8203 (setq ret (make-js2-yield-node :pos pos
8204 :len (- end pos)
8205 :value e))
8206 (js2-node-add-children ret e)
8207 (unless expr-context
8208 (setq e ret
8209 ret (js2-wrap-with-expr-stmt pos e t))
8210 (js2-set-requires-activation)
8211 (js2-set-is-generator))))
8212 ;; see if we are mixing yields and value returns.
8213 (when (and inside-function
8214 (js2-now-all-set before js2-end-flags
8215 (logior js2-end-yields js2-end-returns-value)))
8216 (setq name (js2-function-name js2-current-script-or-fn))
8217 (if (zerop (length name))
8218 (js2-report-error "msg.anon.generator.returns" nil pos (- end pos))
8219 (js2-report-error "msg.generator.returns" name pos (- end pos))))
8220 ret))
8221
8222 (defun js2-parse-debugger ()
8223 (js2-consume-token)
8224 (make-js2-keyword-node :type js2-DEBUGGER))
8225
8226 (defun js2-parse-block ()
8227 "Parser for a curly-delimited statement block.
8228 Last token matched must be js2-LC."
8229 (let ((pos js2-token-beg)
8230 (pn (make-js2-scope)))
8231 (js2-consume-token)
8232 (js2-push-scope pn)
8233 (unwind-protect
8234 (progn
8235 (js2-parse-statements pn)
8236 (js2-must-match js2-RC "msg.no.brace.block")
8237 (setf (js2-node-len pn) (- js2-token-end pos)))
8238 (js2-pop-scope))
8239 pn))
8240
8241 ;; for js2-ERROR too, to have a node for error recovery to work on
8242 (defun js2-parse-semi ()
8243 "Parse a statement or handle an error.
8244 Last matched token is js-SEMI or js-ERROR."
8245 (let ((tt (js2-peek-token)) pos len)
8246 (js2-consume-token)
8247 (if (eq tt js2-SEMI)
8248 (make-js2-empty-expr-node :len 1)
8249 (setq pos js2-token-beg
8250 len (- js2-token-beg pos))
8251 (js2-report-error "msg.syntax" nil pos len)
8252 (make-js2-error-node :pos pos :len len))))
8253
8254 (defun js2-parse-default-xml-namespace ()
8255 "Parse a `default xml namespace = <expr>' e4x statement."
8256 (let ((pos js2-token-beg)
8257 end len expr unary es)
8258 (js2-consume-token)
8259 (js2-must-have-xml)
8260 (js2-set-requires-activation)
8261 (setq len (- js2-ts-cursor pos))
8262 (unless (and (js2-match-token js2-NAME)
8263 (string= js2-ts-string "xml"))
8264 (js2-report-error "msg.bad.namespace" nil pos len))
8265 (unless (and (js2-match-token js2-NAME)
8266 (string= js2-ts-string "namespace"))
8267 (js2-report-error "msg.bad.namespace" nil pos len))
8268 (unless (js2-match-token js2-ASSIGN)
8269 (js2-report-error "msg.bad.namespace" nil pos len))
8270 (setq expr (js2-parse-expr)
8271 end (js2-node-end expr)
8272 unary (make-js2-unary-node :type js2-DEFAULTNAMESPACE
8273 :pos pos
8274 :len (- end pos)
8275 :operand expr))
8276 (js2-node-add-children unary expr)
8277 (make-js2-expr-stmt-node :pos pos
8278 :len (- end pos)
8279 :expr unary)))
8280
8281 (defun js2-record-label (label bundle)
8282 ;; current token should be colon that `js2-parse-primary-expr' left untouched
8283 (js2-consume-token)
8284 (let ((name (js2-label-node-name label))
8285 labeled-stmt
8286 dup)
8287 (when (setq labeled-stmt (cdr (assoc name js2-label-set)))
8288 ;; flag both labels if possible when used in editing mode
8289 (if (and js2-parse-ide-mode
8290 (setq dup (js2-get-label-by-name labeled-stmt name)))
8291 (js2-report-error "msg.dup.label" nil
8292 (js2-node-abs-pos dup) (js2-node-len dup)))
8293 (js2-report-error "msg.dup.label" nil
8294 (js2-node-pos label) (js2-node-len label)))
8295 (js2-labeled-stmt-node-add-label bundle label)
8296 (js2-node-add-children bundle label)
8297 ;; Add one reference to the bundle per label in `js2-label-set'
8298 (push (cons name bundle) js2-label-set)))
8299
8300 (defun js2-parse-name-or-label ()
8301 "Parser for identifier or label. Last token matched must be js2-NAME.
8302 Called when we found a name in a statement context. If it's a label, we gather
8303 up any following labels and the next non-label statement into a
8304 `js2-labeled-stmt-node' bundle and return that. Otherwise we parse an
8305 expression and return it wrapped in a `js2-expr-stmt-node'."
8306 (let ((pos js2-token-beg)
8307 (end js2-token-end)
8308 expr
8309 stmt
8310 pn
8311 bundle
8312 (continue t))
8313 ;; set check for label and call down to `js2-parse-primary-expr'
8314 (js2-set-check-for-label)
8315 (setq expr (js2-parse-expr))
8316 (if (/= (js2-node-type expr) js2-LABEL)
8317 ;; Parsed non-label expression - wrap with expression stmt.
8318 (setq pn (js2-wrap-with-expr-stmt pos expr t))
8319 ;; else parsed a label
8320 (setq bundle (make-js2-labeled-stmt-node :pos pos))
8321 (js2-record-label expr bundle)
8322 ;; look for more labels
8323 (while (and continue (= (js2-peek-token) js2-NAME))
8324 (js2-set-check-for-label)
8325 (setq expr (js2-parse-expr))
8326 (if (/= (js2-node-type expr) js2-LABEL)
8327 (progn
8328 (setq stmt (js2-wrap-with-expr-stmt (js2-node-pos expr) expr t)
8329 continue nil)
8330 (js2-auto-insert-semicolon stmt))
8331 (js2-record-label expr bundle)))
8332 ;; no more labels; now parse the labeled statement
8333 (unwind-protect
8334 (unless stmt
8335 (let ((js2-labeled-stmt bundle)) ; bind dynamically
8336 (setq stmt (js2-statement-helper))))
8337 ;; remove the labels for this statement from the global set
8338 (dolist (label (js2-labeled-stmt-node-labels bundle))
8339 (setq js2-label-set (remove label js2-label-set))))
8340 (setf (js2-labeled-stmt-node-stmt bundle) stmt
8341 (js2-node-len bundle) (- (js2-node-end stmt) pos))
8342 (js2-node-add-children bundle stmt)
8343 bundle)))
8344
8345 (defun js2-parse-expr-stmt ()
8346 "Default parser in statement context, if no recognized statement found."
8347 (js2-wrap-with-expr-stmt js2-token-beg (js2-parse-expr) t))
8348
8349 (defun js2-parse-variables (decl-type pos)
8350 "Parse a comma-separated list of variable declarations.
8351 Could be a 'var', 'const' or 'let' expression, possibly in a for-loop initializer.
8352
8353 DECL-TYPE is a token value: either VAR, CONST, or LET depending on context.
8354 For 'var' or 'const', the keyword should be the token last scanned.
8355
8356 POS is the position where the node should start. It's sometimes the
8357 var/const/let keyword, and other times the beginning of the first token
8358 in the first variable declaration.
8359
8360 Returns the parsed `js2-var-decl-node' expression node."
8361 (let* ((result (make-js2-var-decl-node :decl-type decl-type
8362 :pos pos))
8363 destructuring
8364 kid-pos
8365 tt
8366 init
8367 name
8368 end
8369 nbeg nend
8370 vi
8371 (continue t))
8372 ;; Example:
8373 ;; var foo = {a: 1, b: 2}, bar = [3, 4];
8374 ;; var {b: s2, a: s1} = foo, x = 6, y, [s3, s4] = bar;
8375 ;; var {a, b} = baz;
8376 (while continue
8377 (setq destructuring nil
8378 name nil
8379 tt (js2-peek-token)
8380 kid-pos js2-token-beg
8381 end js2-token-end
8382 init nil)
8383 (if (or (= tt js2-LB) (= tt js2-LC))
8384 ;; Destructuring assignment, e.g., var [a, b] = ...
8385 (setq destructuring (js2-parse-primary-expr t)
8386 end (js2-node-end destructuring))
8387 ;; Simple variable name
8388 (when (js2-must-match js2-NAME "msg.bad.var")
8389 (setq name (js2-create-name-node)
8390 nbeg js2-token-beg
8391 nend js2-token-end
8392 end nend)
8393 (js2-define-symbol decl-type js2-ts-string name js2-in-for-init)))
8394 (when (js2-match-token js2-ASSIGN)
8395 (setq init (js2-parse-assign-expr)
8396 end (js2-node-end init))
8397 (if (and js2-parse-ide-mode
8398 (or (js2-object-node-p init)
8399 (js2-function-node-p init)))
8400 (js2-record-imenu-functions init name)))
8401 (when name
8402 (js2-set-face nbeg nend (if (js2-function-node-p init)
8403 'font-lock-function-name-face
8404 'font-lock-variable-name-face)
8405 'record))
8406 (setq vi (make-js2-var-init-node :pos kid-pos
8407 :len (- end kid-pos)
8408 :type decl-type))
8409 (if destructuring
8410 (progn
8411 (if (and (null init) (not js2-in-for-init))
8412 (js2-report-error "msg.destruct.assign.no.init"))
8413 (setf (js2-var-init-node-target vi) destructuring))
8414 (setf (js2-var-init-node-target vi) name))
8415 (setf (js2-var-init-node-initializer vi) init)
8416 (js2-node-add-children vi name destructuring init)
8417 (js2-block-node-push result vi)
8418 (unless (js2-match-token js2-COMMA)
8419 (setq continue nil)))
8420 (setf (js2-node-len result) (- end pos))
8421 result))
8422
8423 (defun js2-parse-let (pos &optional stmt-p)
8424 "Parse a let expression or statement.
8425 A let-expression is of the form `let (vars) expr'.
8426 A let-statment is of the form `let (vars) {statements}'.
8427 The third form of let is a variable declaration list, handled
8428 by `js2-parse-variables'."
8429 (let ((pn (make-js2-let-node :pos pos))
8430 beg vars body)
8431 (if (js2-must-match js2-LP "msg.no.paren.after.let")
8432 (setf (js2-let-node-lp pn) (- js2-token-beg pos)))
8433 (js2-push-scope pn)
8434 (unwind-protect
8435 (progn
8436 (setq vars (js2-parse-variables js2-LET js2-token-beg))
8437 (if (js2-must-match js2-RP "msg.no.paren.let")
8438 (setf (js2-let-node-rp pn) (- js2-token-beg pos)))
8439 (if (and stmt-p (eq (js2-peek-token) js2-LC))
8440 ;; let statement
8441 (progn
8442 (js2-consume-token)
8443 (setf beg js2-token-beg ; position stmt at LC
8444 body (js2-parse-statements))
8445 (js2-must-match js2-RC "msg.no.curly.let")
8446 (setf (js2-node-len body) (- js2-token-end beg)
8447 (js2-node-len pn) (- js2-token-end pos)
8448 (js2-let-node-body pn) body
8449 (js2-node-type pn) js2-LET))
8450 ;; let expression
8451 (setf body (js2-parse-expr)
8452 (js2-node-len pn) (- (js2-node-end body) pos)
8453 (js2-let-node-body pn) body))
8454 (js2-node-add-children pn vars body))
8455 (js2-pop-scope))
8456 pn))
8457
8458 (defsubst js2-define-new-symbol (decl-type name node)
8459 (js2-scope-put-symbol js2-current-scope
8460 name
8461 (make-js2-symbol decl-type name node)))
8462
8463 (defun js2-define-symbol (decl-type name &optional node ignore-not-in-block)
8464 "Define a symbol in the current scope.
8465 If NODE is non-nil, it is the AST node associated with the symbol."
8466 (let* ((defining-scope (js2-get-defining-scope js2-current-scope name))
8467 (symbol (if defining-scope
8468 (js2-scope-get-symbol defining-scope name)))
8469 (sdt (if symbol (js2-symbol-decl-type symbol) -1)))
8470 (cond
8471 ((and symbol ; already defined
8472 (or (= sdt js2-CONST) ; old version is const
8473 (= decl-type js2-CONST) ; new version is const
8474 ;; two let-bound vars in this block have same name
8475 (and (= sdt js2-LET)
8476 (eq defining-scope js2-current-scope))))
8477 (js2-report-error
8478 (cond
8479 ((= sdt js2-CONST) "msg.const.redecl")
8480 ((= sdt js2-LET) "msg.let.redecl")
8481 ((= sdt js2-VAR) "msg.var.redecl")
8482 ((= sdt js2-FUNCTION) "msg.function.redecl")
8483 (t "msg.parm.redecl"))
8484 name))
8485 ((= decl-type js2-LET)
8486 (if (and (not ignore-not-in-block)
8487 (or (= (js2-node-type js2-current-scope) js2-IF)
8488 (js2-loop-node-p js2-current-scope)))
8489 (js2-report-error "msg.let.decl.not.in.block")
8490 (js2-define-new-symbol decl-type name node)))
8491 ((or (= decl-type js2-VAR)
8492 (= decl-type js2-CONST)
8493 (= decl-type js2-FUNCTION))
8494 (if symbol
8495 (if (and js2-strict-var-redeclaration-warning (= sdt js2-VAR))
8496 (js2-add-strict-warning "msg.var.redecl" name)
8497 (if (and js2-strict-var-hides-function-arg-warning (= sdt js2-LP))
8498 (js2-add-strict-warning "msg.var.hides.arg" name)))
8499 (js2-define-new-symbol decl-type name node)))
8500 ((= decl-type js2-LP)
8501 (if symbol
8502 ;; must be duplicate parameter. Second parameter hides the
8503 ;; first, so go ahead and add the second pararameter
8504 (js2-report-warning "msg.dup.parms" name))
8505 (js2-define-new-symbol decl-type name node))
8506 (t (js2-code-bug)))))
8507
8508 (defun js2-parse-expr (&optional oneshot)
8509 (let* ((pn (js2-parse-assign-expr))
8510 (pos (js2-node-pos pn))
8511 left
8512 right
8513 op-pos)
8514 (while (and (not oneshot)
8515 (js2-match-token js2-COMMA))
8516 (setq op-pos (- js2-token-beg pos)) ; relative
8517 (if (= (js2-peek-token) js2-YIELD)
8518 (js2-report-error "msg.yield.parenthesized"))
8519 (setq right (js2-parse-assign-expr)
8520 left pn
8521 pn (make-js2-infix-node :type js2-COMMA
8522 :pos pos
8523 :len (- js2-ts-cursor pos)
8524 :op-pos op-pos
8525 :left left
8526 :right right))
8527 (js2-node-add-children pn left right))
8528 pn))
8529
8530 (defun js2-parse-assign-expr ()
8531 (let ((tt (js2-peek-token))
8532 (pos js2-token-beg)
8533 pn
8534 left
8535 right
8536 op-pos)
8537 (if (= tt js2-YIELD)
8538 (js2-parse-return-or-yield tt t)
8539 ;; not yield - parse assignment expression
8540 (setq pn (js2-parse-cond-expr)
8541 tt (js2-peek-token))
8542 (when (and (<= js2-first-assign tt)
8543 (<= tt js2-last-assign))
8544 (js2-consume-token)
8545 (setq op-pos (- js2-token-beg pos) ; relative
8546 left pn
8547 right (js2-parse-assign-expr)
8548 pn (make-js2-assign-node :type tt
8549 :pos pos
8550 :len (- (js2-node-end right) pos)
8551 :op-pos op-pos
8552 :left left
8553 :right right))
8554 (when js2-parse-ide-mode
8555 (js2-highlight-assign-targets pn left right)
8556 (if (or (js2-function-node-p right)
8557 (js2-object-node-p right))
8558 (js2-record-imenu-functions right left)))
8559 ;; do this last so ide checks above can use absolute positions
8560 (js2-node-add-children pn left right))
8561 pn)))
8562
8563 (defun js2-parse-cond-expr ()
8564 (let ((pos js2-token-beg)
8565 (pn (js2-parse-or-expr))
8566 test-expr
8567 if-true
8568 if-false
8569 q-pos
8570 c-pos)
8571 (when (js2-match-token js2-HOOK)
8572 (setq q-pos (- js2-token-beg pos)
8573 if-true (js2-parse-assign-expr))
8574 (js2-must-match js2-COLON "msg.no.colon.cond")
8575 (setq c-pos (- js2-token-beg pos)
8576 if-false (js2-parse-assign-expr)
8577 test-expr pn
8578 pn (make-js2-cond-node :pos pos
8579 :len (- (js2-node-end if-false) pos)
8580 :test-expr test-expr
8581 :true-expr if-true
8582 :false-expr if-false
8583 :q-pos q-pos
8584 :c-pos c-pos))
8585 (js2-node-add-children pn test-expr if-true if-false))
8586 pn))
8587
8588 (defun js2-make-binary (type left parser)
8589 "Helper for constructing a binary-operator AST node.
8590 LEFT is the left-side-expression, already parsed, and the
8591 binary operator should have just been matched.
8592 PARSER is a function to call to parse the right operand,
8593 or a `js2-node' struct if it has already been parsed."
8594 (let* ((pos (js2-node-pos left))
8595 (op-pos (- js2-token-beg pos))
8596 (right (if (js2-node-p parser)
8597 parser
8598 (funcall parser)))
8599 (pn (make-js2-infix-node :type type
8600 :pos pos
8601 :len (- (js2-node-end right) pos)
8602 :op-pos op-pos
8603 :left left
8604 :right right)))
8605 (js2-node-add-children pn left right)
8606 pn))
8607
8608 (defun js2-parse-or-expr ()
8609 (let ((pn (js2-parse-and-expr)))
8610 (when (js2-match-token js2-OR)
8611 (setq pn (js2-make-binary js2-OR
8612 pn
8613 'js2-parse-or-expr)))
8614 pn))
8615
8616 (defun js2-parse-and-expr ()
8617 (let ((pn (js2-parse-bit-or-expr)))
8618 (when (js2-match-token js2-AND)
8619 (setq pn (js2-make-binary js2-AND
8620 pn
8621 'js2-parse-and-expr)))
8622 pn))
8623
8624 (defun js2-parse-bit-or-expr ()
8625 (let ((pn (js2-parse-bit-xor-expr)))
8626 (while (js2-match-token js2-BITOR)
8627 (setq pn (js2-make-binary js2-BITOR
8628 pn
8629 'js2-parse-bit-xor-expr)))
8630 pn))
8631
8632 (defun js2-parse-bit-xor-expr ()
8633 (let ((pn (js2-parse-bit-and-expr)))
8634 (while (js2-match-token js2-BITXOR)
8635 (setq pn (js2-make-binary js2-BITXOR
8636 pn
8637 'js2-parse-bit-and-expr)))
8638 pn))
8639
8640 (defun js2-parse-bit-and-expr ()
8641 (let ((pn (js2-parse-eq-expr)))
8642 (while (js2-match-token js2-BITAND)
8643 (setq pn (js2-make-binary js2-BITAND
8644 pn
8645 'js2-parse-eq-expr)))
8646 pn))
8647
8648 (defconst js2-parse-eq-ops
8649 (list js2-EQ js2-NE js2-SHEQ js2-SHNE))
8650
8651 (defun js2-parse-eq-expr ()
8652 (let ((pn (js2-parse-rel-expr))
8653 tt)
8654 (while (memq (setq tt (js2-peek-token)) js2-parse-eq-ops)
8655 (js2-consume-token)
8656 (setq pn (js2-make-binary tt
8657 pn
8658 'js2-parse-rel-expr)))
8659 pn))
8660
8661 (defconst js2-parse-rel-ops
8662 (list js2-IN js2-INSTANCEOF js2-LE js2-LT js2-GE js2-GT))
8663
8664 (defun js2-parse-rel-expr ()
8665 (let ((pn (js2-parse-shift-expr))
8666 (continue t)
8667 tt)
8668 (while continue
8669 (setq tt (js2-peek-token))
8670 (cond
8671 ((and js2-in-for-init (= tt js2-IN))
8672 (setq continue nil))
8673 ((memq tt js2-parse-rel-ops)
8674 (js2-consume-token)
8675 (setq pn (js2-make-binary tt pn 'js2-parse-shift-expr)))
8676 (t
8677 (setq continue nil))))
8678 pn))
8679
8680 (defconst js2-parse-shift-ops
8681 (list js2-LSH js2-URSH js2-RSH))
8682
8683 (defun js2-parse-shift-expr ()
8684 (let ((pn (js2-parse-add-expr))
8685 tt
8686 (continue t))
8687 (while continue
8688 (setq tt (js2-peek-token))
8689 (if (memq tt js2-parse-shift-ops)
8690 (progn
8691 (js2-consume-token)
8692 (setq pn (js2-make-binary tt pn 'js2-parse-add-expr)))
8693 (setq continue nil)))
8694 pn))
8695
8696 (defun js2-parse-add-expr ()
8697 (let ((pn (js2-parse-mul-expr))
8698 tt
8699 (continue t))
8700 (while continue
8701 (setq tt (js2-peek-token))
8702 (if (or (= tt js2-ADD) (= tt js2-SUB))
8703 (progn
8704 (js2-consume-token)
8705 (setq pn (js2-make-binary tt pn 'js2-parse-mul-expr)))
8706 (setq continue nil)))
8707 pn))
8708
8709 (defconst js2-parse-mul-ops
8710 (list js2-MUL js2-DIV js2-MOD))
8711
8712 (defun js2-parse-mul-expr ()
8713 (let ((pn (js2-parse-unary-expr))
8714 tt
8715 (continue t))
8716 (while continue
8717 (setq tt (js2-peek-token))
8718 (if (memq tt js2-parse-mul-ops)
8719 (progn
8720 (js2-consume-token)
8721 (setq pn (js2-make-binary tt pn 'js2-parse-unary-expr)))
8722 (setq continue nil)))
8723 pn))
8724
8725 (defsubst js2-make-unary (type parser &rest args)
8726 "Make a unary node of type TYPE.
8727 PARSER is either a node (for postfix operators) or a function to call
8728 to parse the operand (for prefix operators)."
8729 (let* ((pos js2-token-beg)
8730 (postfix (js2-node-p parser))
8731 (expr (if postfix
8732 parser
8733 (apply parser args)))
8734 end
8735 pn)
8736 (if postfix ; e.g. i++
8737 (setq pos (js2-node-pos expr)
8738 end js2-token-end)
8739 (setq end (js2-node-end expr)))
8740 (setq pn (make-js2-unary-node :type type
8741 :pos pos
8742 :len (- end pos)
8743 :operand expr))
8744 (js2-node-add-children pn expr)
8745 pn))
8746
8747 (defconst js2-incrementable-node-types
8748 (list js2-NAME js2-GETPROP js2-GETELEM js2-GET_REF js2-CALL)
8749 "Node types that can be the operand of a ++ or -- operator.")
8750
8751 (defsubst js2-check-bad-inc-dec (tt beg end unary)
8752 (unless (memq (js2-node-type (js2-unary-node-operand unary))
8753 js2-incrementable-node-types)
8754 (js2-report-error (if (= tt js2-INC)
8755 "msg.bad.incr"
8756 "msg.bad.decr")
8757 nil beg (- end beg))))
8758
8759 (defun js2-parse-unary-expr ()
8760 (let ((tt (js2-peek-token))
8761 pn expr beg end)
8762 (cond
8763 ((or (= tt js2-VOID)
8764 (= tt js2-NOT)
8765 (= tt js2-BITNOT)
8766 (= tt js2-TYPEOF))
8767 (js2-consume-token)
8768 (js2-make-unary tt 'js2-parse-unary-expr))
8769 ((= tt js2-ADD)
8770 (js2-consume-token)
8771 ;; Convert to special POS token in decompiler and parse tree
8772 (js2-make-unary js2-POS 'js2-parse-unary-expr))
8773 ((= tt js2-SUB)
8774 (js2-consume-token)
8775 ;; Convert to special NEG token in decompiler and parse tree
8776 (js2-make-unary js2-NEG 'js2-parse-unary-expr))
8777 ((or (= tt js2-INC)
8778 (= tt js2-DEC))
8779 (js2-consume-token)
8780 (prog1
8781 (setq beg js2-token-beg
8782 end js2-token-end
8783 expr (js2-make-unary tt 'js2-parse-member-expr t))
8784 (js2-check-bad-inc-dec tt beg end expr)))
8785 ((= tt js2-DELPROP)
8786 (js2-consume-token)
8787 (js2-make-unary js2-DELPROP 'js2-parse-unary-expr))
8788 ((= tt js2-ERROR)
8789 (js2-consume-token)
8790 (make-js2-error-node)) ; try to continue
8791 ((and (= tt js2-LT)
8792 js2-compiler-xml-available)
8793 ;; XML stream encountered in expression.
8794 (js2-consume-token)
8795 (js2-parse-member-expr-tail t (js2-parse-xml-initializer)))
8796 (t
8797 (setq pn (js2-parse-member-expr t)
8798 ;; Don't look across a newline boundary for a postfix incop.
8799 tt (js2-peek-token-or-eol))
8800 (when (or (= tt js2-INC) (= tt js2-DEC))
8801 (js2-consume-token)
8802 (setf expr pn
8803 pn (js2-make-unary tt expr))
8804 (js2-node-set-prop pn 'postfix t)
8805 (js2-check-bad-inc-dec tt js2-token-beg js2-token-end pn))
8806 pn))))
8807
8808 (defun js2-parse-xml-initializer ()
8809 "Parse an E4X XML initializer.
8810 I'm parsing it the way Rhino parses it, but without the tree-rewriting.
8811 Then I'll postprocess the result, depending on whether we're in IDE
8812 mode or codegen mode, and generate the appropriate rewritten AST.
8813 IDE mode uses a rich AST that models the XML structure. Codegen mode
8814 just concatenates everything and makes a new XML or XMLList out of it."
8815 (let ((tt (js2-get-first-xml-token))
8816 pn-xml
8817 pn
8818 expr
8819 kids
8820 expr-pos
8821 (continue t)
8822 (first-token t))
8823 (when (not (or (= tt js2-XML) (= tt js2-XMLEND)))
8824 (js2-report-error "msg.syntax"))
8825 (setq pn-xml (make-js2-xml-node))
8826 (while continue
8827 (if first-token
8828 (setq first-token nil)
8829 (setq tt (js2-get-next-xml-token)))
8830 (cond
8831 ;; js2-XML means we found a {expr} in the XML stream.
8832 ;; The js2-ts-string is the XML up to the left-curly.
8833 ((= tt js2-XML)
8834 (push (make-js2-string-node :pos js2-token-beg
8835 :len (- js2-ts-cursor js2-token-beg))
8836 kids)
8837 (js2-must-match js2-LC "msg.syntax")
8838 (setq expr-pos js2-ts-cursor
8839 expr (if (eq (js2-peek-token) js2-RC)
8840 (make-js2-empty-expr-node :pos expr-pos)
8841 (js2-parse-expr)))
8842 (js2-must-match js2-RC "msg.syntax")
8843 (setq pn (make-js2-xml-js-expr-node :pos (js2-node-pos expr)
8844 :len (js2-node-len expr)
8845 :expr expr))
8846 (js2-node-add-children pn expr)
8847 (push pn kids))
8848 ;; a js2-XMLEND token means we hit the final close-tag.
8849 ((= tt js2-XMLEND)
8850 (push (make-js2-string-node :pos js2-token-beg
8851 :len (- js2-ts-cursor js2-token-beg))
8852 kids)
8853 (dolist (kid (nreverse kids))
8854 (js2-block-node-push pn-xml kid))
8855 (setf (js2-node-len pn-xml) (- js2-ts-cursor
8856 (js2-node-pos pn-xml))
8857 continue nil))
8858 (t
8859 (js2-report-error "msg.syntax")
8860 (setq continue nil))))
8861 pn-xml))
8862
8863
8864 (defun js2-parse-argument-list ()
8865 "Parse an argument list and return it as a lisp list of nodes.
8866 Returns the list in reverse order. Consumes the right-paren token."
8867 (let (result)
8868 (unless (js2-match-token js2-RP)
8869 (loop do
8870 (if (= (js2-peek-token) js2-YIELD)
8871 (js2-report-error "msg.yield.parenthesized"))
8872 (push (js2-parse-assign-expr) result)
8873 while
8874 (js2-match-token js2-COMMA))
8875 (js2-must-match js2-RP "msg.no.paren.arg")
8876 result)))
8877
8878 (defun js2-parse-member-expr (&optional allow-call-syntax)
8879 (let ((tt (js2-peek-token))
8880 pn
8881 pos
8882 target
8883 args
8884 beg
8885 end
8886 init
8887 tail)
8888 (if (/= tt js2-NEW)
8889 (setq pn (js2-parse-primary-expr))
8890 ;; parse a 'new' expression
8891 (js2-consume-token)
8892 (setq pos js2-token-beg
8893 beg pos
8894 target (js2-parse-member-expr)
8895 end (js2-node-end target)
8896 pn (make-js2-new-node :pos pos
8897 :target target
8898 :len (- end pos)))
8899 (js2-node-add-children pn target)
8900 (when (js2-match-token js2-LP)
8901 ;; Add the arguments to pn, if any are supplied.
8902 (setf beg pos ; start of "new" keyword
8903 pos js2-token-beg
8904 args (nreverse (js2-parse-argument-list))
8905 (js2-new-node-args pn) args
8906 end js2-token-end
8907 (js2-new-node-lp pn) (- pos beg)
8908 (js2-new-node-rp pn) (- end 1 beg))
8909 (apply #'js2-node-add-children pn args))
8910 (when (and js2-allow-rhino-new-expr-initializer
8911 (js2-match-token js2-LC))
8912 (setf init (js2-parse-object-literal)
8913 end (js2-node-end init)
8914 (js2-new-node-initializer pn) init)
8915 (js2-node-add-children pn init))
8916 (setf (js2-node-len pn) (- end beg))) ; end outer if
8917 (js2-parse-member-expr-tail allow-call-syntax pn)))
8918
8919 (defun js2-parse-member-expr-tail (allow-call-syntax pn)
8920 "Parse a chain of property/array accesses or function calls.
8921 Includes parsing for E4X operators like `..' and `.@'.
8922 If ALLOW-CALL-SYNTAX is nil, stops when we encounter a left-paren.
8923 Returns an expression tree that includes PN, the parent node."
8924 (let ((beg (js2-node-pos pn))
8925 tt
8926 (continue t))
8927 (while continue
8928 (setq tt (js2-peek-token))
8929 (cond
8930 ((or (= tt js2-DOT) (= tt js2-DOTDOT))
8931 (setq pn (js2-parse-property-access tt pn)))
8932 ((= tt js2-DOTQUERY)
8933 (setq pn (js2-parse-dot-query pn)))
8934 ((= tt js2-LB)
8935 (setq pn (js2-parse-element-get pn)))
8936 ((= tt js2-LP)
8937 (if allow-call-syntax
8938 (setq pn (js2-parse-function-call pn))
8939 (setq continue nil)))
8940 (t
8941 (setq continue nil))))
8942 (if (>= js2-highlight-level 2)
8943 (js2-parse-highlight-member-expr-node pn))
8944 pn))
8945
8946 (defun js2-parse-dot-query (pn)
8947 "Parse a dot-query expression, e.g. foo.bar.(@name == 2)
8948 Last token parsed must be `js2-DOTQUERY'."
8949 (let ((pos (js2-node-pos pn))
8950 op-pos
8951 expr
8952 end)
8953 (js2-consume-token)
8954 (js2-must-have-xml)
8955 (js2-set-requires-activation)
8956 (setq op-pos js2-token-beg
8957 expr (js2-parse-expr)
8958 end (js2-node-end expr)
8959 pn (make-js2-xml-dot-query-node :left pn
8960 :pos pos
8961 :op-pos op-pos
8962 :right expr))
8963 (js2-node-add-children pn
8964 (js2-xml-dot-query-node-left pn)
8965 (js2-xml-dot-query-node-right pn))
8966 (if (js2-must-match js2-RP "msg.no.paren")
8967 (setf (js2-xml-dot-query-node-rp pn) js2-token-beg
8968 end js2-token-end))
8969 (setf (js2-node-len pn) (- end pos))
8970 pn))
8971
8972 (defun js2-parse-element-get (pn)
8973 "Parse an element-get expression, e.g. foo[bar].
8974 Last token parsed must be `js2-RB'."
8975 (let ((lb js2-token-beg)
8976 (pos (js2-node-pos pn))
8977 rb
8978 expr)
8979 (js2-consume-token)
8980 (setq expr (js2-parse-expr))
8981 (if (js2-must-match js2-RB "msg.no.bracket.index")
8982 (setq rb js2-token-beg))
8983 (setq pn (make-js2-elem-get-node :target pn
8984 :pos pos
8985 :element expr
8986 :lb (js2-relpos lb pos)
8987 :rb (js2-relpos rb pos)
8988 :len (- js2-token-end pos)))
8989 (js2-node-add-children pn
8990 (js2-elem-get-node-target pn)
8991 (js2-elem-get-node-element pn))
8992 pn))
8993
8994 (defun js2-parse-function-call (pn)
8995 (let (args
8996 (pos (js2-node-pos pn)))
8997 (js2-consume-token)
8998 (setq pn (make-js2-call-node :pos pos
8999 :target pn
9000 :lp (- js2-token-beg pos)))
9001 (js2-node-add-children pn (js2-call-node-target pn))
9002 ;; Add the arguments to pn, if any are supplied.
9003 (setf args (nreverse (js2-parse-argument-list))
9004 (js2-call-node-rp pn) (- js2-token-beg pos)
9005 (js2-call-node-args pn) args)
9006 (apply #'js2-node-add-children pn args)
9007 (setf (js2-node-len pn) (- js2-ts-cursor pos))
9008 pn))
9009
9010 (defun js2-parse-property-access (tt pn)
9011 "Parse a property access, XML descendants access, or XML attr access."
9012 (let ((member-type-flags 0)
9013 (dot-pos js2-token-beg)
9014 (dot-len (if (= tt js2-DOTDOT) 2 1))
9015 name
9016 ref ; right side of . or .. operator
9017 result)
9018 (js2-consume-token)
9019 (when (= tt js2-DOTDOT)
9020 (js2-must-have-xml)
9021 (setq member-type-flags js2-descendants-flag))
9022 (if (not js2-compiler-xml-available)
9023 (progn
9024 (js2-must-match-prop-name "msg.no.name.after.dot")
9025 (setq name (js2-create-name-node t js2-GETPROP)
9026 result (make-js2-prop-get-node :left pn
9027 :pos js2-token-beg
9028 :right name
9029 :len (- js2-token-end
9030 js2-token-beg)))
9031 (js2-node-add-children result pn name)
9032 result)
9033 ;; otherwise look for XML operators
9034 (setf result (if (= tt js2-DOT)
9035 (make-js2-prop-get-node)
9036 (make-js2-infix-node :type js2-DOTDOT))
9037 (js2-node-pos result) (js2-node-pos pn)
9038 (js2-infix-node-op-pos result) dot-pos
9039 (js2-infix-node-left result) pn ; do this after setting position
9040 tt (js2-next-token))
9041 (cond
9042 ;; needed for generator.throw()
9043 ((= tt js2-THROW)
9044 (js2-save-name-token-data js2-token-beg "throw")
9045 (setq ref (js2-parse-property-name nil js2-ts-string member-type-flags)))
9046 ;; handles: name, ns::name, ns::*, ns::[expr]
9047 ((js2-valid-prop-name-token tt)
9048 (setq ref (js2-parse-property-name -1 js2-ts-string member-type-flags)))
9049 ;; handles: *, *::name, *::*, *::[expr]
9050 ((= tt js2-MUL)
9051 (js2-save-name-token-data js2-token-beg "*")
9052 (setq ref (js2-parse-property-name nil "*" member-type-flags)))
9053 ;; handles: '@attr', '@ns::attr', '@ns::*', '@ns::[expr]', etc.
9054 ((= tt js2-XMLATTR)
9055 (setq result (js2-parse-attribute-access)))
9056 (t
9057 (js2-report-error "msg.no.name.after.dot" nil dot-pos dot-len)))
9058 (if ref
9059 (setf (js2-node-len result) (- (js2-node-end ref)
9060 (js2-node-pos result))
9061 (js2-infix-node-right result) ref))
9062 (if (js2-infix-node-p result)
9063 (js2-node-add-children result
9064 (js2-infix-node-left result)
9065 (js2-infix-node-right result)))
9066 result)))
9067
9068 (defun js2-parse-attribute-access ()
9069 "Parse an E4X XML attribute expression.
9070 This includes expressions of the forms:
9071
9072 @attr @ns::attr @ns::*
9073 @* @*::attr @*::*
9074 @[expr] @*::[expr] @ns::[expr]
9075
9076 Called if we peeked an '@' token."
9077 (let ((tt (js2-next-token))
9078 (at-pos js2-token-beg))
9079 (cond
9080 ;; handles: @name, @ns::name, @ns::*, @ns::[expr]
9081 ((js2-valid-prop-name-token tt)
9082 (js2-parse-property-name at-pos js2-ts-string 0))
9083 ;; handles: @*, @*::name, @*::*, @*::[expr]
9084 ((= tt js2-MUL)
9085 (js2-save-name-token-data js2-token-beg "*")
9086 (js2-parse-property-name js2-token-beg "*" 0))
9087 ;; handles @[expr]
9088 ((= tt js2-LB)
9089 (js2-parse-xml-elem-ref at-pos))
9090 (t
9091 (js2-report-error "msg.no.name.after.xmlAttr")
9092 ;; Avoid cascaded errors that happen if we make an error node here.
9093 (js2-save-name-token-data js2-token-beg "")
9094 (js2-parse-property-name js2-token-beg "" 0)))))
9095
9096 (defun js2-parse-property-name (at-pos s member-type-flags)
9097 "Check if :: follows name in which case it becomes qualified name.
9098
9099 AT-POS is a natural number if we just read an '@' token, else nil.
9100 S is the name or string that was matched: an identifier, 'throw' or '*'.
9101 MEMBER-TYPE-FLAGS is a bit set tracking whether we're a '.' or '..' child.
9102
9103 Returns a `js2-xml-ref-node' if it's an attribute access, a child of a '..'
9104 operator, or the name is followed by ::. For a plain name, returns a
9105 `js2-name-node'. Returns a `js2-error-node' for malformed XML expressions."
9106 (let ((pos (or at-pos js2-token-beg))
9107 colon-pos
9108 (name (js2-create-name-node t js2-current-token))
9109 ns
9110 tt
9111 ref
9112 pn)
9113 (catch 'return
9114 (when (js2-match-token js2-COLONCOLON)
9115 (setq ns name
9116 colon-pos js2-token-beg
9117 tt (js2-next-token))
9118 (cond
9119 ;; handles name::name
9120 ((js2-valid-prop-name-token tt)
9121 (setq name (js2-create-name-node)))
9122 ;; handles name::*
9123 ((= tt js2-MUL)
9124 (js2-save-name-token-data js2-token-beg "*")
9125 (setq name (js2-create-name-node)))
9126 ;; handles name::[expr]
9127 ((= tt js2-LB)
9128 (throw 'return (js2-parse-xml-elem-ref at-pos ns colon-pos)))
9129 (t
9130 (js2-report-error "msg.no.name.after.coloncolon"))))
9131 (if (and (null ns) (zerop member-type-flags))
9132 name
9133 (prog1
9134 (setq pn
9135 (make-js2-xml-prop-ref-node :pos pos
9136 :len (- (js2-node-end name) pos)
9137 :at-pos at-pos
9138 :colon-pos colon-pos
9139 :propname name))
9140 (js2-node-add-children pn name))))))
9141
9142 (defun js2-parse-xml-elem-ref (at-pos &optional namespace colon-pos)
9143 "Parse the [expr] portion of an xml element reference.
9144 For instance, @[expr], @*::[expr], or ns::[expr]."
9145 (let* ((lb js2-token-beg)
9146 (pos (or at-pos lb))
9147 rb
9148 (expr (js2-parse-expr))
9149 (end (js2-node-end expr))
9150 pn)
9151 (if (js2-must-match js2-RB "msg.no.bracket.index")
9152 (setq rb js2-token-beg
9153 end js2-token-end))
9154 (prog1
9155 (setq pn
9156 (make-js2-xml-elem-ref-node :pos pos
9157 :len (- end pos)
9158 :namespace namespace
9159 :colon-pos colon-pos
9160 :at-pos at-pos
9161 :expr expr
9162 :lb (js2-relpos lb pos)
9163 :rb (js2-relpos rb pos)))
9164 (js2-node-add-children pn namespace expr))))
9165
9166 (defun js2-parse-primary-expr (&optional lhs)
9167 "Parses a literal (leaf) expression of some sort.
9168 Includes complex literals such as functions, object-literals,
9169 array-literals, array comprehensions and regular expressions.
9170 When `lhs' is t, we assume the given primary expression appeared in the left hand side
9171 and treat it in the somewhat special way.
9172 ex) {a, b} is permitted only when the `lhs' is t."
9173 (let ((tt-flagged (js2-next-flagged-token))
9174 pn ; parent node (usually return value)
9175 tt
9176 px-pos ; paren-expr pos
9177 len
9178 flags ; regexp flags
9179 expr)
9180 (setq tt js2-current-token)
9181 (cond
9182 ((= tt js2-FUNCTION)
9183 (js2-parse-function 'FUNCTION_EXPRESSION))
9184 ((= tt js2-LB)
9185 (js2-parse-array-literal))
9186 ((= tt js2-LC)
9187 (js2-parse-object-literal lhs))
9188 ((= tt js2-LET)
9189 (js2-parse-let js2-token-beg))
9190 ((= tt js2-LP)
9191 (setq px-pos js2-token-beg
9192 expr (js2-parse-expr))
9193 (js2-must-match js2-RP "msg.no.paren")
9194 (setq pn (make-js2-paren-node :pos px-pos
9195 :expr expr
9196 :len (- js2-token-end px-pos)))
9197 (js2-node-add-children pn (js2-paren-node-expr pn))
9198 pn)
9199 ((= tt js2-XMLATTR)
9200 (js2-must-have-xml)
9201 (js2-parse-attribute-access))
9202 ((= tt js2-NAME)
9203 (js2-parse-name tt-flagged tt))
9204 ((= tt js2-NUMBER)
9205 (make-js2-number-node))
9206 ((= tt js2-STRING)
9207 (prog1
9208 (make-js2-string-node)
9209 (js2-record-face 'font-lock-string-face)))
9210 ((or (= tt js2-DIV) (= tt js2-ASSIGN_DIV))
9211 ;; Got / or /= which in this context means a regexp literal
9212 (setq px-pos js2-token-beg)
9213 (js2-read-regexp tt)
9214 (setq flags js2-ts-regexp-flags
9215 js2-ts-regexp-flags nil)
9216 (prog1
9217 (make-js2-regexp-node :pos px-pos
9218 :len (- js2-ts-cursor px-pos)
9219 :value js2-ts-string
9220 :flags flags)
9221 (js2-set-face px-pos js2-ts-cursor 'font-lock-string-face 'record)
9222 (put-text-property px-pos js2-ts-cursor 'syntax-table '(2))))
9223 ((or (= tt js2-NULL)
9224 (= tt js2-THIS)
9225 (= tt js2-FALSE)
9226 (= tt js2-TRUE))
9227 (make-js2-keyword-node :type tt))
9228 ((= tt js2-RESERVED)
9229 (js2-report-error "msg.reserved.id")
9230 (make-js2-name-node))
9231 ((= tt js2-ERROR)
9232 ;; the scanner or one of its subroutines reported the error.
9233 (make-js2-error-node))
9234 ((= tt js2-EOF)
9235 (setq px-pos (point-at-bol)
9236 len (- js2-ts-cursor px-pos))
9237 (js2-report-error "msg.unexpected.eof" nil px-pos len)
9238 (make-js2-error-node :pos px-pos :len len))
9239 (t
9240 (js2-report-error "msg.syntax")
9241 (make-js2-error-node)))))
9242
9243 (defun js2-parse-name (tt-flagged tt)
9244 (let ((name js2-ts-string)
9245 (name-pos js2-token-beg))
9246 (if (and (js2-flag-set-p tt-flagged js2-ti-check-label)
9247 (= (js2-peek-token) js2-COLON))
9248 (prog1
9249 ;; Do not consume colon, it is used as unwind indicator
9250 ;; to return to statementHelper.
9251 (make-js2-label-node :pos name-pos
9252 :len (- js2-token-end name-pos)
9253 :name name)
9254 (js2-set-face name-pos
9255 js2-token-end
9256 'font-lock-variable-name-face 'record))
9257 ;; Otherwise not a label, just a name. Unfortunately peeking
9258 ;; the next token to check for a colon has biffed js2-token-beg
9259 ;; and js2-token-end. We store the name's bounds in buffer vars
9260 ;; and `js2-create-name-node' uses them.
9261 (js2-save-name-token-data name-pos name)
9262 (if js2-compiler-xml-available
9263 (js2-parse-property-name nil name 0)
9264 (js2-create-name-node 'check-activation)))))
9265
9266 (defsubst js2-parse-warn-trailing-comma (msg pos elems comma-pos)
9267 (js2-add-strict-warning
9268 msg nil
9269 ;; back up from comma to beginning of line or array/objlit
9270 (max (if elems
9271 (js2-node-pos (car elems))
9272 pos)
9273 (save-excursion
9274 (goto-char comma-pos)
9275 (back-to-indentation)
9276 (point)))
9277 comma-pos))
9278
9279 (defun js2-parse-array-literal ()
9280 (let ((pos js2-token-beg)
9281 (end js2-token-end)
9282 (after-lb-or-comma t)
9283 after-comma
9284 tt
9285 elems
9286 pn
9287 (continue t))
9288 (while continue
9289 (setq tt (js2-peek-token))
9290 (cond
9291 ;; comma
9292 ((= tt js2-COMMA)
9293 (js2-consume-token)
9294 (setq after-comma js2-token-end)
9295 (if (not after-lb-or-comma)
9296 (setq after-lb-or-comma t)
9297 (push nil elems)))
9298 ;; end of array
9299 ((or (= tt js2-RB)
9300 (= tt js2-EOF)) ; prevent infinite loop
9301 (if (= tt js2-EOF)
9302 (js2-report-error "msg.no.bracket.arg" nil pos)
9303 (js2-consume-token))
9304 (setq continue nil
9305 end js2-token-end
9306 pn (make-js2-array-node :pos pos
9307 :len (- js2-ts-cursor pos)
9308 :elems (nreverse elems)))
9309 (apply #'js2-node-add-children pn (js2-array-node-elems pn))
9310 (when after-comma
9311 (js2-parse-warn-trailing-comma "msg.array.trailing.comma"
9312 pos elems after-comma)))
9313 ;; array comp
9314 ((and (>= js2-language-version 170)
9315 (= tt js2-FOR) ; check for array comprehension
9316 (not after-lb-or-comma) ; "for" can't follow a comma
9317 elems ; must have at least 1 element
9318 (not (cdr elems))) ; but no 2nd element
9319 (setf continue nil
9320 pn (js2-parse-array-comprehension (car elems) pos)))
9321 ;; another element
9322 (t
9323 (unless after-lb-or-comma
9324 (js2-report-error "msg.no.bracket.arg"))
9325 (push (js2-parse-assign-expr) elems)
9326 (setq after-lb-or-comma nil
9327 after-comma nil))))
9328 pn))
9329
9330 (defun js2-parse-array-comprehension (expr pos)
9331 "Parse a JavaScript 1.7 Array Comprehension.
9332 EXPR is the first expression after the opening left-bracket.
9333 POS is the beginning of the LB token preceding EXPR.
9334 We should have just parsed the 'for' keyword before calling this function."
9335 (let (loops
9336 filter
9337 if-pos
9338 result)
9339 (while (= (js2-peek-token) js2-FOR)
9340 (push (js2-parse-array-comp-loop) loops))
9341 (when (= (js2-peek-token) js2-IF)
9342 (js2-consume-token)
9343 (setq if-pos (- js2-token-beg pos) ; relative
9344 filter (js2-parse-condition)))
9345 (js2-must-match js2-RB "msg.no.bracket.arg" pos)
9346 (setq result (make-js2-array-comp-node :pos pos
9347 :len (- js2-ts-cursor pos)
9348 :result expr
9349 :loops (nreverse loops)
9350 :filter (car filter)
9351 :lp (js2-relpos (second filter) pos)
9352 :rp (js2-relpos (third filter) pos)
9353 :if-pos if-pos))
9354 (apply #'js2-node-add-children result expr (car filter)
9355 (js2-array-comp-node-loops result))
9356 result))
9357
9358 (defun js2-parse-array-comp-loop ()
9359 "Parse a 'for [each] (foo in bar)' expression in an Array comprehension.
9360 Last token peeked should be the initial FOR."
9361 (let ((pos js2-token-beg)
9362 (pn (make-js2-array-comp-loop-node))
9363 tt
9364 iter
9365 obj
9366 foreach-p
9367 in-pos
9368 each-pos
9369 lp
9370 rp)
9371 (assert (= (js2-next-token) js2-FOR)) ; consumes token
9372 (js2-push-scope pn)
9373 (unwind-protect
9374 (progn
9375 (when (js2-match-token js2-NAME)
9376 (if (string= js2-ts-string "each")
9377 (progn
9378 (setq foreach-p t
9379 each-pos (- js2-token-beg pos)) ; relative
9380 (js2-record-face 'font-lock-keyword-face))
9381 (js2-report-error "msg.no.paren.for")))
9382 (if (js2-must-match js2-LP "msg.no.paren.for")
9383 (setq lp (- js2-token-beg pos)))
9384 (setq tt (js2-peek-token))
9385 (cond
9386 ((or (= tt js2-LB)
9387 (= tt js2-LC))
9388 ;; handle destructuring assignment
9389 (setq iter (js2-parse-primary-expr t)))
9390 ((js2-valid-prop-name-token tt)
9391 (js2-consume-token)
9392 (setq iter (js2-create-name-node)))
9393 (t
9394 (js2-report-error "msg.bad.var")))
9395 ;; Define as a let since we want the scope of the variable to
9396 ;; be restricted to the array comprehension
9397 (if (js2-name-node-p iter)
9398 (js2-define-symbol js2-LET (js2-name-node-name iter) pn t))
9399 (if (js2-must-match js2-IN "msg.in.after.for.name")
9400 (setq in-pos (- js2-token-beg pos)))
9401 (setq obj (js2-parse-expr))
9402 (if (js2-must-match js2-RP "msg.no.paren.for.ctrl")
9403 (setq rp (- js2-token-beg pos)))
9404 (setf (js2-node-pos pn) pos
9405 (js2-node-len pn) (- js2-ts-cursor pos)
9406 (js2-array-comp-loop-node-iterator pn) iter
9407 (js2-array-comp-loop-node-object pn) obj
9408 (js2-array-comp-loop-node-in-pos pn) in-pos
9409 (js2-array-comp-loop-node-each-pos pn) each-pos
9410 (js2-array-comp-loop-node-foreach-p pn) foreach-p
9411 (js2-array-comp-loop-node-lp pn) lp
9412 (js2-array-comp-loop-node-rp pn) rp)
9413 (js2-node-add-children pn iter obj))
9414 (js2-pop-scope))
9415 pn))
9416
9417 (defun js2-parse-object-literal (&optional lhs)
9418 (let ((pos js2-token-beg)
9419 tt
9420 elems
9421 result
9422 after-comma
9423 (continue t))
9424 (while continue
9425 (setq tt (js2-peek-token))
9426 (cond
9427 ;; {foo: ...}, {'foo': ...}, {foo, bar, ...}, {get foo() {...}}, or {set foo(x) {...}}
9428 ((or (js2-valid-prop-name-token tt)
9429 (= tt js2-STRING))
9430 (setq after-comma nil
9431 result (js2-parse-named-prop tt lhs))
9432 (if (and (null result)
9433 (not js2-recover-from-parse-errors))
9434 (setq continue nil)
9435 (push result elems)))
9436 ;; {12: x} or {10.7: x}
9437 ((= tt js2-NUMBER)
9438 (js2-consume-token)
9439 (setq after-comma nil)
9440 (push (js2-parse-plain-property (make-js2-number-node)) elems))
9441 ;; trailing comma
9442 ((= tt js2-RC)
9443 (setq continue nil)
9444 (if after-comma
9445 (js2-parse-warn-trailing-comma "msg.extra.trailing.comma"
9446 pos elems after-comma)))
9447 (t
9448 (js2-report-error "msg.bad.prop")
9449 (unless js2-recover-from-parse-errors
9450 (setq continue nil)))) ; end switch
9451 (if (js2-match-token js2-COMMA)
9452 (setq after-comma js2-token-end)
9453 (setq continue nil))) ; end loop
9454 (js2-must-match js2-RC "msg.no.brace.prop")
9455 (setq result (make-js2-object-node :pos pos
9456 :len (- js2-ts-cursor pos)
9457 :elems (nreverse elems)))
9458 (apply #'js2-node-add-children result (js2-object-node-elems result))
9459 result))
9460
9461 (defun js2-parse-named-prop (tt &optional lhs)
9462 "Parse a name, string, or getter/setter object property.
9463 When `lhs' is t, forms like {a, b, c} will be permitted."
9464 (js2-consume-token)
9465 (let ((string-prop (and (= tt js2-STRING)
9466 (make-js2-string-node)))
9467 expr
9468 (ppos js2-token-beg)
9469 (pend js2-token-end)
9470 (name (js2-create-name-node))
9471 (prop js2-ts-string))
9472 (cond
9473 ;; getter/setter prop
9474 ((and (= tt js2-NAME)
9475 (= (js2-peek-token) js2-NAME)
9476 (or (string= prop "get")
9477 (string= prop "set")))
9478 (progn
9479 (js2-consume-token)
9480 (js2-set-face ppos pend 'font-lock-keyword-face 'record) ; get/set
9481 (js2-record-face 'font-lock-function-name-face) ; for peeked name
9482 (setq name (js2-create-name-node)) ; discard get/set & use peeked name
9483 (js2-parse-getter-setter-prop ppos name (string= prop "get"))))
9484 ;; abbreviated destructuring bind e.g., {a, b} = c;
9485 ((and lhs
9486 (= tt js2-NAME)
9487 (let ((ctk (js2-peek-token)))
9488 (or (= ctk js2-COMMA)
9489 (= ctk js2-RC)
9490 (js2-valid-prop-name-token ctk))))
9491 (js2-set-face ppos pend 'font-lock-variable-name-face 'record)
9492 name)
9493 ;; regular prop
9494 (t
9495 (prog1
9496 (setq expr (js2-parse-plain-property (or string-prop name)))
9497 (js2-set-face ppos pend
9498 (if (js2-function-node-p
9499 (js2-object-prop-node-right expr))
9500 'font-lock-function-name-face
9501 'font-lock-variable-name-face)
9502 'record))))))
9503
9504 (defun js2-parse-plain-property (prop)
9505 "Parse a non-getter/setter property in an object literal.
9506 PROP is the node representing the property: a number, name or string."
9507 (js2-must-match js2-COLON "msg.no.colon.prop")
9508 (let* ((pos (js2-node-pos prop))
9509 (colon (- js2-token-beg pos))
9510 (expr (js2-parse-assign-expr))
9511 (result (make-js2-object-prop-node
9512 :pos pos
9513 ;; don't include last consumed token in length
9514 :len (- (+ (js2-node-pos expr)
9515 (js2-node-len expr))
9516 pos)
9517 :left prop
9518 :right expr
9519 :op-pos colon)))
9520 (js2-node-add-children result prop expr)
9521 result))
9522
9523 (defun js2-parse-getter-setter-prop (pos prop get-p)
9524 "Parse getter or setter property in an object literal.
9525 JavaScript syntax is:
9526
9527 { get foo() {...}, set foo(x) {...} }
9528
9529 and expression closure style is also supported
9530
9531 { get foo() x, set foo(x) _x = x }
9532
9533 POS is the start position of the `get' or `set' keyword.
9534 PROP is the `js2-name-node' representing the property name.
9535 GET-P is non-nil if the keyword was `get'."
9536 (let ((type (if get-p js2-GET js2-SET))
9537 result
9538 end
9539 (fn (js2-parse-function 'FUNCTION_EXPRESSION)))
9540 ;; it has to be an anonymous function, as we already parsed the name
9541 (if (/= (js2-node-type fn) js2-FUNCTION)
9542 (js2-report-error "msg.bad.prop")
9543 (if (plusp (length (js2-function-name fn)))
9544 (js2-report-error "msg.bad.prop")))
9545 (js2-node-set-prop fn 'GETTER_SETTER type) ; for codegen
9546 (setq end (js2-node-end fn)
9547 result (make-js2-getter-setter-node :type type
9548 :pos pos
9549 :len (- end pos)
9550 :left prop
9551 :right fn))
9552 (js2-node-add-children result prop fn)
9553 result))
9554
9555 (defun js2-create-name-node (&optional check-activation-p token)
9556 "Create a name node using the token info from last scanned name.
9557 In some cases we need to either synthesize a name node, or we lost
9558 the name token information by peeking. If the TOKEN parameter is
9559 not `js2-NAME', then we use the token info saved in instance vars."
9560 (let ((beg js2-token-beg)
9561 (s js2-ts-string)
9562 name)
9563 (when (/= js2-current-token js2-NAME)
9564 (setq beg (or js2-prev-name-token-start js2-ts-cursor)
9565 s js2-prev-name-token-string
9566 js2-prev-name-token-start nil
9567 js2-prev-name-token-string nil))
9568 (setq name (make-js2-name-node :pos beg
9569 :name s
9570 :len (length s)))
9571 (if check-activation-p
9572 (js2-check-activation-name s (or token js2-NAME)))
9573 name))
9574
9575 ;;; Indentation support
9576
9577 ;; This indenter is based on Karl Landström's "javascript.el" indenter.
9578 ;; Karl cleverly deduces that the desired indentation level is often a
9579 ;; function of paren/bracket/brace nesting depth, which can be determined
9580 ;; quickly via the built-in `parse-partial-sexp' function. His indenter
9581 ;; then does some equally clever checks to see if we're in the context of a
9582 ;; substatement of a possibly braceless statement keyword such as if, while,
9583 ;; or finally. This approach yields pretty good results.
9584
9585 ;; The indenter is often "wrong", however, and needs to be overridden.
9586 ;; The right long-term solution is probably to emulate (or integrate
9587 ;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
9588 ;; parse tree from `js2-parse' is present, which is not true at the
9589 ;; moment the user is typing, computing indentation is still thousands
9590 ;; of lines of code to handle every possible syntactic edge case.
9591
9592 ;; In the meantime, the compromise solution is that we offer a "bounce
9593 ;; indenter", configured with `js2-bounce-indent-p', which cycles the
9594 ;; current line indent among various likely guess points. This approach
9595 ;; is far from perfect, but should at least make it slightly easier to
9596 ;; move the line towards its desired indentation when manually
9597 ;; overriding Karl's heuristic nesting guesser.
9598
9599 ;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
9600 ;; extensions such as `let' and Array comprehensions. Major kudos to
9601 ;; Karl for coming up with the initial approach, which packs a lot of
9602 ;; punch for so little code.
9603
9604 (defconst js-possibly-braceless-keyword-re
9605 (regexp-opt
9606 '("catch" "do" "else" "finally" "for" "if" "each" "try" "while" "with" "let")
9607 'words)
9608 "Regular expression matching keywords that are optionally
9609 followed by an opening brace.")
9610
9611 (defconst js-possibly-braceless-keywords-re
9612 "\\([ \t}]*else[ \t]+if\\|[ \t}]*for[ \t]+each\\)"
9613 "Regular expression which matches the keywords which are consist of more than 2 words
9614 like 'if else' and 'for each', and optionally followed by an opening brace.")
9615
9616 (defconst js-indent-operator-re
9617 (concat "[-+*/%<>=&^|?:.]\\([^-+*/]\\|$\\)\\|"
9618 (regexp-opt '("in" "instanceof") 'words))
9619 "Regular expression matching operators that affect indentation
9620 of continued expressions.")
9621
9622 ;; This function has horrible results if you're typing an array
9623 ;; such as [[1, 2], [3, 4], [5, 6]]. Bounce indenting -really- sucks
9624 ;; in conjunction with electric-indent, so just disabling it.
9625 (defsubst js2-code-at-bol-p ()
9626 "Return t if the first character on line is non-whitespace."
9627 nil)
9628
9629 (defun js2-insert-and-indent (key)
9630 "Run command bound to key and indent current line. Runs the command
9631 bound to KEY in the global keymap and indents the current line."
9632 (interactive (list (this-command-keys)))
9633 (let ((cmd (lookup-key (current-global-map) key)))
9634 (if (commandp cmd)
9635 (call-interactively cmd)))
9636 ;; don't do the electric keys inside comments or strings,
9637 ;; and don't do bounce-indent with them.
9638 (let ((parse-state (parse-partial-sexp (point-min) (point)))
9639 (js2-bounce-indent-p (js2-code-at-bol-p)))
9640 (unless (or (nth 3 parse-state)
9641 (nth 4 parse-state))
9642 (indent-according-to-mode))))
9643
9644 (defun js-re-search-forward-inner (regexp &optional bound count)
9645 "Auxiliary function for `js-re-search-forward'."
9646 (let ((parse)
9647 (saved-point (point-min)))
9648 (while (> count 0)
9649 (re-search-forward regexp bound)
9650 (setq parse (parse-partial-sexp saved-point (point)))
9651 (cond ((nth 3 parse)
9652 (re-search-forward
9653 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9654 (save-excursion (end-of-line) (point)) t))
9655 ((nth 7 parse)
9656 (forward-line))
9657 ((or (nth 4 parse)
9658 (and (eq (char-before) ?\/) (eq (char-after) ?\*)))
9659 (re-search-forward "\\*/"))
9660 (t
9661 (setq count (1- count))))
9662 (setq saved-point (point))))
9663 (point))
9664
9665 (defun js-re-search-forward (regexp &optional bound noerror count)
9666 "Search forward but ignore strings and comments. Invokes
9667 `re-search-forward' but treats the buffer as if strings and
9668 comments have been removed."
9669 (let ((saved-point (point))
9670 (search-expr
9671 (cond ((null count)
9672 '(js-re-search-forward-inner regexp bound 1))
9673 ((< count 0)
9674 '(js-re-search-backward-inner regexp bound (- count)))
9675 ((> count 0)
9676 '(js-re-search-forward-inner regexp bound count)))))
9677 (condition-case err
9678 (eval search-expr)
9679 (search-failed
9680 (goto-char saved-point)
9681 (unless noerror
9682 (error (error-message-string err)))))))
9683
9684 (defun js-re-search-backward-inner (regexp &optional bound count)
9685 "Auxiliary function for `js-re-search-backward'."
9686 (let ((parse)
9687 (saved-point (point-min)))
9688 (while (> count 0)
9689 (re-search-backward regexp bound)
9690 (setq parse (parse-partial-sexp saved-point (point)))
9691 (cond ((nth 3 parse)
9692 (re-search-backward
9693 (concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
9694 (save-excursion (beginning-of-line) (point)) t))
9695 ((nth 7 parse)
9696 (goto-char (nth 8 parse)))
9697 ((or (nth 4 parse)
9698 (and (eq (char-before) ?/) (eq (char-after) ?*)))
9699 (re-search-backward "/\\*"))
9700 (t
9701 (setq count (1- count))))))
9702 (point))
9703
9704 (defun js-re-search-backward (regexp &optional bound noerror count)
9705 "Search backward but ignore strings and comments. Invokes
9706 `re-search-backward' but treats the buffer as if strings and
9707 comments have been removed."
9708 (let ((saved-point (point))
9709 (search-expr
9710 (cond ((null count)
9711 '(js-re-search-backward-inner regexp bound 1))
9712 ((< count 0)
9713 '(js-re-search-forward-inner regexp bound (- count)))
9714 ((> count 0)
9715 '(js-re-search-backward-inner regexp bound count)))))
9716 (condition-case err
9717 (eval search-expr)
9718 (search-failed
9719 (goto-char saved-point)
9720 (unless noerror
9721 (error (error-message-string err)))))))
9722
9723 (defun js-looking-at-operator-p ()
9724 "Return non-nil if text after point is an operator (that is not
9725 a comma)."
9726 (save-match-data
9727 (and (looking-at js-indent-operator-re)
9728 (or (not (looking-at ":"))
9729 (save-excursion
9730 (and (js-re-search-backward "[?:{]\\|\\<case\\>" nil t)
9731 (looking-at "?")))))))
9732
9733 (defun js-continued-expression-p ()
9734 "Returns non-nil if the current line continues an expression."
9735 (save-excursion
9736 (back-to-indentation)
9737 (or (js-looking-at-operator-p)
9738 (and (js-re-search-backward "\n" nil t)
9739 (progn
9740 (skip-chars-backward " \t")
9741 (backward-char)
9742 (and (js-looking-at-operator-p)
9743 (and (progn (backward-char)
9744 (not (looking-at "\\*\\|++\\|--\\|/[/*]"))))))))))
9745
9746 (defun js-end-of-do-while-loop-p ()
9747 "Returns non-nil if word after point is `while' of a do-while
9748 statement, else returns nil. A braceless do-while statement
9749 spanning several lines requires that the start of the loop is
9750 indented to the same column as the current line."
9751 (interactive)
9752 (save-excursion
9753 (save-match-data
9754 (when (looking-at "\\s-*\\<while\\>")
9755 (if (save-excursion
9756 (skip-chars-backward "[ \t\n]*}")
9757 (looking-at "[ \t\n]*}"))
9758 (save-excursion
9759 (backward-list) (backward-word 1) (looking-at "\\<do\\>"))
9760 (js-re-search-backward "\\<do\\>" (point-at-bol) t)
9761 (or (looking-at "\\<do\\>")
9762 (let ((saved-indent (current-indentation)))
9763 (while (and (js-re-search-backward "^[ \t]*\\<" nil t)
9764 (/= (current-indentation) saved-indent)))
9765 (and (looking-at "[ \t]*\\<do\\>")
9766 (not (js-re-search-forward
9767 "\\<while\\>" (point-at-eol) t))
9768 (= (current-indentation) saved-indent)))))))))
9769
9770 (defun js-ctrl-statement-indentation ()
9771 "Returns the proper indentation of the current line if it
9772 starts the body of a control statement without braces, else
9773 returns nil."
9774 (let (forward-sexp-function) ; temporarily unbind it
9775 (save-excursion
9776 (back-to-indentation)
9777 (when (save-excursion
9778 (and (not (js2-same-line (point-min)))
9779 (not (looking-at "{"))
9780 (js-re-search-backward "[[:graph:]]" nil t)
9781 (not (looking-at "[{([]"))
9782 (progn
9783 (forward-char)
9784 ;; scan-sexps sometimes throws an error
9785 (ignore-errors (backward-sexp))
9786 (when (looking-at "(") (backward-word 1))
9787 (and (save-excursion
9788 (skip-chars-backward " \t}" (point-at-bol))
9789 (or (bolp)
9790 (and (backward-word 1)
9791 (skip-chars-backward " \t}" (point-at-bol))
9792 (bolp)
9793 (looking-at js-possibly-braceless-keywords-re))))
9794 (looking-at js-possibly-braceless-keyword-re)
9795 (not (js-end-of-do-while-loop-p))))))
9796 (save-excursion
9797 (goto-char (match-beginning 0))
9798 (+ (current-indentation) js2-basic-offset))))))
9799
9800 (defun js2-indent-in-array-comp (parse-status)
9801 "Return non-nil if we think we're in an array comprehension.
9802 In particular, return the buffer position of the first `for' kwd."
9803 (let ((end (point)))
9804 (when (nth 1 parse-status)
9805 (save-excursion
9806 (goto-char (nth 1 parse-status))
9807 (when (looking-at "\\[")
9808 (forward-char 1)
9809 (js2-forward-sws)
9810 (if (looking-at "[[{]")
9811 (let (forward-sexp-function) ; use lisp version
9812 (forward-sexp) ; skip destructuring form
9813 (js2-forward-sws)
9814 (if (and (/= (char-after) ?,) ; regular array
9815 (looking-at "for"))
9816 (match-beginning 0)))
9817 ;; to skip arbitrary expressions we need the parser,
9818 ;; so we'll just guess at it.
9819 (if (re-search-forward "[^,]* \\(for\\) " end t)
9820 (match-beginning 1))))))))
9821
9822 (defun js2-array-comp-indentation (parse-status for-kwd)
9823 (if (js2-same-line for-kwd)
9824 ;; first continuation line
9825 (save-excursion
9826 (goto-char (nth 1 parse-status))
9827 (forward-char 1)
9828 (skip-chars-forward " \t")
9829 (current-column))
9830 (save-excursion
9831 (goto-char for-kwd)
9832 (current-column))))
9833
9834 (defun js-proper-indentation (parse-status)
9835 "Return the proper indentation for the current line."
9836 (save-excursion
9837 (back-to-indentation)
9838 (let ((ctrl-stmt-indent (js-ctrl-statement-indentation))
9839 (same-indent-p (looking-at "[]})]\\|\\<case\\>\\|\\<default\\>"))
9840 (continued-expr-p (js-continued-expression-p))
9841 (bracket (nth 1 parse-status))
9842 beg)
9843 (cond
9844 ;; indent array comprehension continuation lines specially
9845 ((and bracket
9846 (not (js2-same-line bracket))
9847 (setq beg (js2-indent-in-array-comp parse-status))
9848 (>= (point) (save-excursion
9849 (goto-char beg)
9850 (point-at-bol)))) ; at or after first loop?
9851 (js2-array-comp-indentation parse-status beg))
9852
9853 (ctrl-stmt-indent)
9854
9855 (bracket
9856 (goto-char bracket)
9857 (cond
9858 ((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
9859 (let ((p (parse-partial-sexp (point-at-bol) (point))))
9860 (when (save-excursion (skip-chars-backward " \t)")
9861 (looking-at ")"))
9862 (backward-list))
9863 (if (and (nth 1 p)
9864 (not js2-consistent-level-indent-inner-bracket-p))
9865 (progn (goto-char (1+ (nth 1 p)))
9866 (skip-chars-forward " \t"))
9867 (back-to-indentation))
9868 (cond (same-indent-p
9869 (current-column))
9870 (continued-expr-p
9871 (+ (current-column) (* 2 js2-basic-offset)))
9872 (t
9873 (+ (current-column) js2-basic-offset)))))
9874 (t
9875 (unless same-indent-p
9876 (forward-char)
9877 (skip-chars-forward " \t"))
9878 (current-column))))
9879
9880 (continued-expr-p js2-basic-offset)
9881 (t 0)))))
9882
9883 (defun js2-lineup-comment (parse-status)
9884 "Indent a multi-line block comment continuation line."
9885 (let* ((beg (nth 8 parse-status))
9886 (first-line (js2-same-line beg))
9887 (offset (save-excursion
9888 (goto-char beg)
9889 (if (looking-at "/\\*")
9890 (+ 1 (current-column))
9891 0))))
9892 (unless first-line
9893 (indent-line-to offset))))
9894
9895 (defun js2-backward-sws ()
9896 "Move backward through whitespace and comments."
9897 (interactive)
9898 (while (forward-comment -1)))
9899
9900 (defun js2-forward-sws ()
9901 "Move forward through whitespace and comments."
9902 (interactive)
9903 (while (forward-comment 1)))
9904
9905 (defsubst js2-current-indent (&optional pos)
9906 "Return column of indentation on current line.
9907 If POS is non-nil, go to that point and return indentation for that line."
9908 (save-excursion
9909 (if pos
9910 (goto-char pos))
9911 (back-to-indentation)
9912 (current-column)))
9913
9914 (defsubst js2-arglist-close ()
9915 "Return non-nil if we're on a line beginning with a close-paren/brace."
9916 (save-match-data
9917 (save-excursion
9918 (goto-char (point-at-bol))
9919 (js2-forward-sws)
9920 (looking-at "[])}]"))))
9921
9922 (defsubst js2-indent-looks-like-label-p ()
9923 (goto-char (point-at-bol))
9924 (js2-forward-sws)
9925 (looking-at (concat js2-mode-identifier-re ":")))
9926
9927 (defun js2-indent-in-objlit-p (parse-status)
9928 "Return non-nil if this looks like an object-literal entry."
9929 (let ((start (nth 1 parse-status)))
9930 (and
9931 start
9932 (save-excursion
9933 (and (zerop (forward-line -1))
9934 (not (< (point) start)) ; crossed a {} boundary
9935 (js2-indent-looks-like-label-p)))
9936 (save-excursion
9937 (js2-indent-looks-like-label-p)))))
9938
9939 ;; if prev line looks like foobar({ then we're passing an object
9940 ;; literal to a function call, and people pretty much always want to
9941 ;; de-dent back to the previous line, so move the 'basic-offset'
9942 ;; position to the front.
9943 (defsubst js2-indent-objlit-arg-p (parse-status)
9944 (save-excursion
9945 (back-to-indentation)
9946 (js2-backward-sws)
9947 (and (eq (1- (point)) (nth 1 parse-status))
9948 (eq (char-before) ?{)
9949 (progn
9950 (forward-char -1)
9951 (skip-chars-backward " \t")
9952 (eq (char-before) ?\()))))
9953
9954 (defsubst js2-indent-case-block-p ()
9955 (save-excursion
9956 (back-to-indentation)
9957 (js2-backward-sws)
9958 (goto-char (point-at-bol))
9959 (skip-chars-forward " \t")
9960 (save-match-data
9961 (looking-at "case\\s-.+:"))))
9962
9963 (defsubst js2-syntax-bol ()
9964 "Return the point at the first non-whitespace char on the line.
9965 Returns `point-at-bol' if the line is empty."
9966 (save-excursion
9967 (beginning-of-line)
9968 (skip-chars-forward " \t")
9969 (point)))
9970
9971 (defun js2-bounce-indent (normal-col parse-status)
9972 "Cycle among alternate computed indentation positions.
9973 PARSE-STATUS is the result of `parse-partial-sexp' from the beginning
9974 of the buffer to the current point. NORMAL-COL is the indentation
9975 column computed by the heuristic guesser based on current paren,
9976 bracket, brace and statement nesting."
9977 (let ((cur-indent (js2-current-indent))
9978 (old-buffer-undo-list buffer-undo-list)
9979 ;; Emacs 21 only has `count-lines', not `line-number-at-pos'
9980 (current-line (save-excursion
9981 (forward-line 0) ; move to bol
9982 (1+ (count-lines (point-min) (point)))))
9983 positions
9984 pos
9985 anchor
9986 arglist-cont
9987 same-indent
9988 prev-line-col
9989 basic-offset
9990 computed-pos)
9991 ;; temporarily don't record undo info, if user requested this
9992 (if js2-mode-indent-inhibit-undo
9993 (setq buffer-undo-list t))
9994 (unwind-protect
9995 (progn
9996 ;; first likely point: indent from beginning of previous code line
9997 (push (setq basic-offset
9998 (+ (save-excursion
9999 (back-to-indentation)
10000 (js2-backward-sws)
10001 (back-to-indentation)
10002 (setq prev-line-col (current-column)))
10003 js2-basic-offset))
10004 positions)
10005
10006 ;; (first + epsilon) likely point: indent 2x from beginning of
10007 ;; previous code line. Some companies like this approach. Ahem.
10008 ;; Seriously, though -- 4-space indent for expression continuation
10009 ;; lines isn't a bad idea. We should eventually implement it
10010 ;; that way.
10011 (push (setq basic-offset
10012 (+ (save-excursion
10013 (back-to-indentation)
10014 (js2-backward-sws)
10015 (back-to-indentation)
10016 (setq prev-line-col (current-column)))
10017 (* 2 js2-basic-offset)))
10018 positions)
10019
10020 ;; second likely point: indent from assign-expr RHS. This
10021 ;; is just a crude guess based on finding " = " on the previous
10022 ;; line containing actual code.
10023 (setq pos (save-excursion
10024 (save-match-data
10025 (forward-line -1)
10026 (goto-char (point-at-bol))
10027 (when (re-search-forward "\\s-+\\(=\\)\\s-+"
10028 (point-at-eol) t)
10029 (goto-char (match-end 1))
10030 (skip-chars-forward " \t\r\n")
10031 (current-column)))))
10032 (when pos
10033 (incf pos js2-basic-offset)
10034 (unless (member pos positions)
10035 (push pos positions)))
10036
10037 ;; third likely point: same indent as previous line of code.
10038 ;; Make it the first likely point if we're not on an
10039 ;; arglist-close line and previous line ends in a comma, or
10040 ;; both this line and prev line look like object-literal
10041 ;; elements.
10042 (setq pos (save-excursion
10043 (goto-char (point-at-bol))
10044 (js2-backward-sws)
10045 (back-to-indentation)
10046 (prog1
10047 (current-column)
10048 ;; while we're here, look for trailing comma
10049 (if (save-excursion
10050 (goto-char (point-at-eol))
10051 (js2-backward-sws)
10052 (eq (char-before) ?,))
10053 (setq arglist-cont (1- (point)))))))
10054 (when pos
10055 (if (and (or arglist-cont
10056 (js2-indent-in-objlit-p parse-status))
10057 (not (js2-arglist-close)))
10058 (setq same-indent pos))
10059 (unless (member pos positions)
10060 (push pos positions)))
10061
10062 ;; fourth likely point: first preceding code with less indentation
10063 ;; than the immediately preceding code line.
10064 (setq pos (save-excursion
10065 (js2-backward-sws)
10066 (back-to-indentation)
10067 (setq anchor (current-column))
10068 (while (and (zerop (forward-line -1))
10069 (>= (progn
10070 (back-to-indentation)
10071 (current-column))
10072 anchor)))
10073 (setq pos (current-column))))
10074 (unless (member pos positions)
10075 (push pos positions))
10076
10077 ;; put nesting-heuristic position first in list, sort rest
10078 (setq positions (nreverse (sort positions '<)))
10079 (setq positions (cons normal-col (delete normal-col positions)))
10080
10081 ;; comma-list continuation lines: prev line indent takes precedence
10082 (if same-indent
10083 (setq positions
10084 (cons same-indent
10085 (sort (delete same-indent positions) '<))))
10086
10087 ;; common special cases where we want to indent in from previous line
10088 (if (or (js2-indent-case-block-p)
10089 (js2-indent-objlit-arg-p parse-status))
10090 (setq positions
10091 (cons basic-offset
10092 (delete basic-offset positions))))
10093
10094 ;; record whether we're already sitting on one of the alternatives
10095 (setq pos (member cur-indent positions))
10096 (cond
10097 ;; case 0: we're one one of the alternatives and this is the
10098 ;; first time they've pressed TAB on this line (best-guess).
10099 ((and js2-mode-indent-ignore-first-tab
10100 pos
10101 ;; first time pressing TAB on this line?
10102 (not (eq js2-mode-last-indented-line current-line)))
10103 ;; do nothing
10104 (setq computed-pos nil))
10105 ;; case 1: only one computed position => use it
10106 ((null (cdr positions))
10107 (setq computed-pos 0))
10108 ;; case 2: not on any of the computed spots => use main spot
10109 ((not pos)
10110 (setq computed-pos 0))
10111 ;; case 3: on last position: cycle to first position
10112 ((null (cdr pos))
10113 (setq computed-pos 0))
10114 ;; case 4: on intermediate position: cycle to next position
10115 (t
10116 (setq computed-pos (js2-position (second pos) positions))))
10117
10118 ;; see if any hooks want to indent; otherwise we do it
10119 (loop with result = nil
10120 for hook in js2-indent-hook
10121 while (null result)
10122 do
10123 (setq result (funcall hook positions computed-pos))
10124 finally do
10125 (unless (or result (null computed-pos))
10126 (indent-line-to (nth computed-pos positions)))))
10127
10128 ;; finally
10129 (if js2-mode-indent-inhibit-undo
10130 (setq buffer-undo-list old-buffer-undo-list))
10131 ;; see commentary for `js2-mode-last-indented-line'
10132 (setq js2-mode-last-indented-line current-line))))
10133
10134 (defsubst js2-1-line-comment-continuation-p ()
10135 "Return t if we're in a 1-line comment continuation.
10136 If so, we don't ever want to use bounce-indent."
10137 (save-excursion
10138 (save-match-data
10139 (and (progn
10140 (forward-line 0)
10141 (looking-at "\\s-*//"))
10142 (progn
10143 (forward-line -1)
10144 (forward-line 0)
10145 (when (looking-at "\\s-*$")
10146 (js2-backward-sws)
10147 (forward-line 0))
10148 (looking-at "\\s-*//"))))))
10149
10150 (defun js2-indent-line ()
10151 "Indent the current line as JavaScript source text."
10152 (interactive)
10153 (let (parse-status
10154 current-indent
10155 offset
10156 indent-col
10157 moved
10158 ;; don't whine about errors/warnings when we're indenting.
10159 ;; This has to be set before calling parse-partial-sexp below.
10160 (inhibit-point-motion-hooks t))
10161 (setq parse-status (save-excursion
10162 (parse-partial-sexp (point-min)
10163 (point-at-bol)))
10164 offset (- (point) (save-excursion
10165 (back-to-indentation)
10166 (setq current-indent (current-column))
10167 (point))))
10168 (js2-with-underscore-as-word-syntax
10169 (if (nth 4 parse-status)
10170 (js2-lineup-comment parse-status)
10171 (setq indent-col (js-proper-indentation parse-status))
10172 ;; see comments below about js2-mode-last-indented-line
10173 (when
10174 (cond
10175 ;; bounce-indenting is disabled during electric-key indent.
10176 ;; It doesn't work well on first line of buffer.
10177 ((and js2-bounce-indent-p
10178 (not (js2-same-line (point-min)))
10179 (not (js2-1-line-comment-continuation-p)))
10180 (js2-bounce-indent indent-col parse-status)
10181 (setq moved t))
10182 ;; just indent to the guesser's likely spot
10183 ((/= current-indent indent-col)
10184 (indent-line-to indent-col)
10185 (setq moved t)))
10186 (when (and moved (plusp offset))
10187 (forward-char offset)))))))
10188
10189 (defun js2-indent-region (start end)
10190 "Indent the region, but don't use bounce indenting."
10191 (let ((js2-bounce-indent-p nil)
10192 (indent-region-function nil))
10193 (indent-region start end nil))) ; nil for byte-compiler
10194
10195 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))
10196
10197 ;;;###autoload
10198 (defun js2-mode ()
10199 "Major mode for editing JavaScript code."
10200 (interactive)
10201 (kill-all-local-variables)
10202 (set-syntax-table js2-mode-syntax-table)
10203 (use-local-map js2-mode-map)
10204 (setq major-mode 'js2-mode
10205 mode-name "JavaScript-IDE"
10206 comment-start "//" ; used by comment-region; don't change it
10207 comment-end "")
10208 (setq local-abbrev-table js2-mode-abbrev-table)
10209 (set (make-local-variable 'max-lisp-eval-depth)
10210 (max max-lisp-eval-depth 3000))
10211 (set (make-local-variable 'indent-line-function) #'js2-indent-line)
10212 (set (make-local-variable 'indent-region-function) #'js2-indent-region)
10213
10214 ;; I tried an "improvement" to `c-fill-paragraph' that worked out badly
10215 ;; on most platforms other than the one I originally wrote it on. So it's
10216 ;; back to `c-fill-paragraph'. Still not perfect, though -- something to do
10217 ;; with our binding of the RET key inside comments: short lines stay short.
10218 (set (make-local-variable 'fill-paragraph-function) #'c-fill-paragraph)
10219
10220 (set (make-local-variable 'before-save-hook) #'js2-before-save)
10221 (set (make-local-variable 'next-error-function) #'js2-next-error)
10222 (set (make-local-variable 'beginning-of-defun-function) #'js2-beginning-of-defun)
10223 (set (make-local-variable 'end-of-defun-function) #'js2-end-of-defun)
10224 ;; we un-confuse `parse-partial-sexp' by setting syntax-table properties
10225 ;; for characters inside regexp literals.
10226 (set (make-local-variable 'parse-sexp-lookup-properties) t)
10227 ;; this is necessary to make `show-paren-function' work properly
10228 (set (make-local-variable 'parse-sexp-ignore-comments) t)
10229 ;; needed for M-x rgrep, among other things
10230 (put 'js2-mode 'find-tag-default-function #'js2-mode-find-tag)
10231
10232 ;; some variables needed by cc-engine for paragraph-fill, etc.
10233 (setq c-buffer-is-cc-mode t
10234 c-comment-prefix-regexp js2-comment-prefix-regexp
10235 c-comment-start-regexp "/[*/]\\|\\s|"
10236 c-paragraph-start js2-paragraph-start
10237 c-paragraph-separate "$"
10238 comment-start-skip js2-comment-start-skip
10239 c-syntactic-ws-start js2-syntactic-ws-start
10240 c-syntactic-ws-end js2-syntactic-ws-end
10241 c-syntactic-eol js2-syntactic-eol)
10242
10243 (setq js2-default-externs
10244 (append js2-ecma-262-externs
10245 (if js2-include-browser-externs
10246 js2-browser-externs)
10247 (if js2-include-gears-externs
10248 js2-gears-externs)
10249 (if js2-include-rhino-externs
10250 js2-rhino-externs)))
10251
10252 ;; We do our own syntax highlighting based on the parse tree.
10253 ;; However, we want minor modes that add keywords to highlight properly
10254 ;; (examples: doxymacs, column-marker). We do this by not letting
10255 ;; font-lock unfontify anything, and telling it to fontify after we
10256 ;; re-parse and re-highlight the buffer. (We currently don't do any
10257 ;; work with regions other than the whole buffer.)
10258 (dolist (var '(font-lock-unfontify-buffer-function
10259 font-lock-unfontify-region-function))
10260 (set (make-local-variable var) (lambda (&rest args) t)))
10261
10262 ;; Don't let font-lock do syntactic (string/comment) fontification.
10263 (set (make-local-variable #'font-lock-syntactic-face-function)
10264 (lambda (state) nil))
10265
10266 ;; Experiment: make reparse-delay longer for longer files.
10267 (if (plusp js2-dynamic-idle-timer-adjust)
10268 (setq js2-idle-timer-delay
10269 (* js2-idle-timer-delay
10270 (/ (point-max) js2-dynamic-idle-timer-adjust))))
10271
10272 (add-hook 'change-major-mode-hook #'js2-mode-exit nil t)
10273 (add-hook 'after-change-functions #'js2-mode-edit nil t)
10274 (setq imenu-create-index-function #'js2-mode-create-imenu-index)
10275 (imenu-add-to-menubar (concat "IM-" mode-name))
10276 (when js2-mirror-mode
10277 (js2-enter-mirror-mode))
10278 (add-to-invisibility-spec '(js2-outline . t))
10279 (set (make-local-variable 'line-move-ignore-invisible) t)
10280 (set (make-local-variable 'forward-sexp-function) #'js2-mode-forward-sexp)
10281 (setq js2-mode-functions-hidden nil
10282 js2-mode-comments-hidden nil
10283 js2-mode-buffer-dirty-p t
10284 js2-mode-parsing nil)
10285 (js2-reparse)
10286 (run-hooks 'js2-mode-hook))
10287
10288 (defun js2-mode-exit ()
10289 "Exit `js2-mode' and clean up."
10290 (interactive)
10291 (when js2-mode-node-overlay
10292 (delete-overlay js2-mode-node-overlay)
10293 (setq js2-mode-node-overlay nil))
10294 (js2-remove-overlays)
10295 (setq js2-mode-ast nil)
10296 (remove-hook 'change-major-mode-hook #'js2-mode-exit t)
10297 (remove-from-invisibility-spec '(js2-outline . t))
10298 (js2-mode-show-all)
10299 (js2-with-unmodifying-text-property-changes
10300 (js2-clear-face (point-min) (point-max))))
10301
10302 (defun js2-before-save ()
10303 "Clean up whitespace before saving file.
10304 You can disable this by customizing `js2-cleanup-whitespace'."
10305 (when js2-cleanup-whitespace
10306 (let ((col (current-column)))
10307 (delete-trailing-whitespace)
10308 ;; don't change trailing whitespace on current line
10309 (unless (eq (current-column) col)
10310 (indent-to col)))))
10311
10312 (defsubst js2-mode-reset-timer ()
10313 "Cancel any existing parse timer and schedule a new one."
10314 (if js2-mode-parse-timer
10315 (cancel-timer js2-mode-parse-timer))
10316 (setq js2-mode-parsing nil)
10317 (setq js2-mode-parse-timer
10318 (run-with-idle-timer js2-idle-timer-delay nil #'js2-reparse)))
10319
10320 (defun js2-mode-edit (beg end len)
10321 "Schedule a new parse after buffer is edited.
10322 Buffer edit spans from BEG to END and is of length LEN.
10323 Also clears the `js2-magic' bit on autoinserted parens/brackets
10324 if the edit occurred on a line different from the magic paren."
10325 (let* ((magic-pos (next-single-property-change (point-min) 'js2-magic))
10326 (line (if magic-pos (line-number-at-pos magic-pos))))
10327 (and line
10328 (or (/= (line-number-at-pos beg) line)
10329 (and (> 0 len)
10330 (/= (line-number-at-pos end) line)))
10331 (js2-mode-mundanify-parens)))
10332 (setq js2-mode-buffer-dirty-p t)
10333 (js2-mode-hide-overlay)
10334 (js2-mode-reset-timer))
10335
10336 (defun js2-mode-run-font-lock ()
10337 "Run `font-lock-fontify-buffer' after parsing/highlighting.
10338 This is intended to allow modes that install their own font-lock keywords
10339 to work with js2-mode. In practice it never seems to work for long.
10340 Hopefully the Emacs maintainers can help figure out a way to make it work."
10341 (when (and (boundp 'font-lock-keywords)
10342 font-lock-keywords
10343 (boundp 'font-lock-mode)
10344 font-lock-mode)
10345 ;; TODO: font-lock and jit-lock really really REALLY don't want to
10346 ;; play nicely with js2-mode. They go out of their way to fail to
10347 ;; provide any option for saying "look, fontify the farging buffer
10348 ;; with just the keywords already". Argh.
10349 (setq font-lock-defaults (list font-lock-keywords 'keywords-only))
10350 (let (font-lock-verbose)
10351 (font-lock-fontify-buffer))))
10352
10353 (defun js2-reparse (&optional force)
10354 "Re-parse current buffer after user finishes some data entry.
10355 If we get any user input while parsing, including cursor motion,
10356 we discard the parse and reschedule it. If FORCE is nil, then the
10357 buffer will only rebuild its `js2-mode-ast' if the buffer is dirty."
10358 (let (time
10359 interrupted-p
10360 (js2-compiler-strict-mode js2-mode-show-strict-warnings))
10361 (unless js2-mode-parsing
10362 (setq js2-mode-parsing t)
10363 (unwind-protect
10364 (when (or js2-mode-buffer-dirty-p force)
10365 (js2-remove-overlays)
10366 (js2-with-unmodifying-text-property-changes
10367 (remove-text-properties (point-min) (point-max) '(syntax-table))
10368 (setq js2-mode-buffer-dirty-p nil
10369 js2-mode-fontifications nil
10370 js2-mode-deferred-properties nil
10371 js2-additional-externs nil)
10372 (if js2-mode-verbose-parse-p
10373 (message "parsing..."))
10374 (setq time
10375 (js2-time
10376 (setq interrupted-p
10377 (catch 'interrupted
10378 (setq js2-mode-ast (js2-parse))
10379 (when (plusp js2-highlight-level)
10380 (js2-mode-fontify-regions))
10381 (js2-mode-remove-suppressed-warnings)
10382 (js2-mode-show-warnings)
10383 (js2-mode-show-errors)
10384 (js2-mode-run-font-lock) ; note: doesn't work
10385 (js2-mode-highlight-magic-parens)
10386 (if (>= js2-highlight-level 1)
10387 (js2-highlight-jsdoc js2-mode-ast))
10388 nil))))
10389 (if interrupted-p
10390 (progn
10391 ;; unfinished parse => try again
10392 (setq js2-mode-buffer-dirty-p t)
10393 (js2-mode-reset-timer))
10394 (if js2-mode-verbose-parse-p
10395 (message "Parse time: %s" time)))))
10396 (setq js2-mode-parsing nil)
10397 (unless interrupted-p
10398 (setq js2-mode-parse-timer nil))))))
10399
10400 (defun js2-mode-show-node ()
10401 "Debugging aid: highlight selected AST node on mouse click."
10402 (interactive)
10403 (let ((node (js2-node-at-point))
10404 beg
10405 end)
10406 (when js2-mode-show-overlay
10407 (if (null node)
10408 (message "No node found at location %s" (point))
10409 (setq beg (js2-node-abs-pos node)
10410 end (+ beg (js2-node-len node)))
10411 (if js2-mode-node-overlay
10412 (move-overlay js2-mode-node-overlay beg end)
10413 (setq js2-mode-node-overlay (make-overlay beg end))
10414 (overlay-put js2-mode-node-overlay 'face 'highlight))
10415 (js2-with-unmodifying-text-property-changes
10416 (put-text-property beg end 'point-left #'js2-mode-hide-overlay))
10417 (message "%s, parent: %s"
10418 (js2-node-short-name node)
10419 (if (js2-node-parent node)
10420 (js2-node-short-name (js2-node-parent node))
10421 "nil"))))))
10422
10423 (defun js2-mode-hide-overlay (&optional p1 p2)
10424 "Remove the debugging overlay when the point moves.
10425 P1 and P2 are the old and new values of point, respectively."
10426 (when js2-mode-node-overlay
10427 (let ((beg (overlay-start js2-mode-node-overlay))
10428 (end (overlay-end js2-mode-node-overlay)))
10429 ;; Sometimes we're called spuriously.
10430 (unless (and p2
10431 (>= p2 beg)
10432 (<= p2 end))
10433 (js2-with-unmodifying-text-property-changes
10434 (remove-text-properties beg end '(point-left nil)))
10435 (delete-overlay js2-mode-node-overlay)
10436 (setq js2-mode-node-overlay nil)))))
10437
10438 (defun js2-mode-reset ()
10439 "Debugging helper: reset everything."
10440 (interactive)
10441 (js2-mode-exit)
10442 (js2-mode))
10443
10444 (defsubst js2-mode-show-warn-or-err (e face)
10445 "Highlight a warning or error E with FACE.
10446 E is a list of ((MSG-KEY MSG-ARG) BEG END)."
10447 (let* ((key (first e))
10448 (beg (second e))
10449 (end (+ beg (third e)))
10450 ;; Don't inadvertently go out of bounds.
10451 (beg (max (point-min) (min beg (point-max))))
10452 (end (max (point-min) (min end (point-max))))
10453 (js2-highlight-level 3) ; so js2-set-face is sure to fire
10454 (ovl (make-overlay beg end)))
10455 (overlay-put ovl 'face face)
10456 (overlay-put ovl 'js2-error t)
10457 (put-text-property beg end 'help-echo (js2-get-msg key))
10458 (put-text-property beg end 'point-entered #'js2-echo-error)))
10459
10460 (defun js2-remove-overlays ()
10461 "Remove overlays from buffer that have a `js2-error' property."
10462 (let ((beg (point-min))
10463 (end (point-max)))
10464 (save-excursion
10465 (dolist (o (overlays-in beg end))
10466 (when (overlay-get o 'js2-error)
10467 (delete-overlay o))))))
10468
10469 (defun js2-error-at-point (&optional pos)
10470 "Return non-nil if there's an error overlay at POS.
10471 Defaults to point."
10472 (loop with pos = (or pos (point))
10473 for o in (overlays-at pos)
10474 thereis (overlay-get o 'js2-error)))
10475
10476 (defun js2-mode-fontify-regions ()
10477 "Apply fontifications recorded during parsing."
10478 ;; We defer clearing faces as long as possible to eliminate flashing.
10479 (js2-clear-face (point-min) (point-max))
10480 ;; have to reverse the recorded fontifications so that errors and
10481 ;; warnings overwrite the normal fontifications
10482 (dolist (f (nreverse js2-mode-fontifications))
10483 (put-text-property (first f) (second f) 'face (third f)))
10484 (setq js2-mode-fontifications nil)
10485 (dolist (p js2-mode-deferred-properties)
10486 (apply #'put-text-property p))
10487 (setq js2-mode-deferred-properties nil))
10488
10489 (defun js2-mode-show-errors ()
10490 "Highlight syntax errors."
10491 (when js2-mode-show-parse-errors
10492 (dolist (e (js2-ast-root-errors js2-mode-ast))
10493 (js2-mode-show-warn-or-err e 'js2-error-face))))
10494
10495 (defun js2-mode-remove-suppressed-warnings ()
10496 "Take suppressed warnings out of the AST warnings list.
10497 This ensures that the counts and `next-error' are correct."
10498 (setf (js2-ast-root-warnings js2-mode-ast)
10499 (js2-delete-if
10500 (lambda (e)
10501 (let ((key (caar e)))
10502 (or
10503 (and (not js2-strict-trailing-comma-warning)
10504 (string-match "trailing\\.comma" key))
10505 (and (not js2-strict-cond-assign-warning)
10506 (string= key "msg.equal.as.assign"))
10507 (and js2-missing-semi-one-line-override
10508 (string= key "msg.missing.semi")
10509 (let* ((beg (second e))
10510 (node (js2-node-at-point beg))
10511 (fn (js2-mode-find-parent-fn node))
10512 (body (and fn (js2-function-node-body fn)))
10513 (lc (and body (js2-node-abs-pos body)))
10514 (rc (and lc (+ lc (js2-node-len body)))))
10515 (and fn
10516 (or (null body)
10517 (save-excursion
10518 (goto-char beg)
10519 (and (js2-same-line lc)
10520 (js2-same-line rc))))))))))
10521 (js2-ast-root-warnings js2-mode-ast))))
10522
10523 (defun js2-mode-show-warnings ()
10524 "Highlight strict-mode warnings."
10525 (when js2-mode-show-strict-warnings
10526 (dolist (e (js2-ast-root-warnings js2-mode-ast))
10527 (js2-mode-show-warn-or-err e 'js2-warning-face))))
10528
10529 (defun js2-echo-error (old-point new-point)
10530 "Called by point-motion hooks."
10531 (let ((msg (get-text-property new-point 'help-echo)))
10532 (if msg
10533 (message msg))))
10534
10535 (defalias #'js2-echo-help #'js2-echo-error)
10536
10537 (defun js2-enter-key ()
10538 "Handle user pressing the Enter key."
10539 (interactive)
10540 (let ((parse-status (save-excursion
10541 (parse-partial-sexp (point-min) (point)))))
10542 (cond
10543 ;; check if we're inside a string
10544 ((nth 3 parse-status)
10545 (js2-mode-split-string parse-status))
10546 ;; check if inside a block comment
10547 ((nth 4 parse-status)
10548 (js2-mode-extend-comment))
10549 (t
10550 ;; should probably figure out what the mode-map says we should do
10551 (if js2-indent-on-enter-key
10552 (let ((js2-bounce-indent-p nil))
10553 (js2-indent-line)))
10554 (insert "\n")
10555 (if js2-enter-indents-newline
10556 (let ((js2-bounce-indent-p nil))
10557 (js2-indent-line)))))))
10558
10559 (defun js2-mode-split-string (parse-status)
10560 "Turn a newline in mid-string into a string concatenation.
10561 PARSE-STATUS is as documented in `parse-partial-sexp'."
10562 (let* ((col (current-column))
10563 (quote-char (nth 3 parse-status))
10564 (quote-string (string quote-char))
10565 (string-beg (nth 8 parse-status))
10566 (indent (save-match-data
10567 (or
10568 (save-excursion
10569 (back-to-indentation)
10570 (if (looking-at "\\+")
10571 (current-column)))
10572 (save-excursion
10573 (goto-char string-beg)
10574 (if (looking-back "\\+\\s-+")
10575 (goto-char (match-beginning 0)))
10576 (current-column))))))
10577 (insert quote-char "\n")
10578 (indent-to indent)
10579 (insert "+ " quote-string)
10580 (when (eolp)
10581 (insert quote-string)
10582 (backward-char 1))))
10583
10584 (defun js2-mode-extend-comment ()
10585 "When inside a comment block, add comment prefix."
10586 (let (star single col first-line needs-close)
10587 (save-excursion
10588 (back-to-indentation)
10589 (cond
10590 ((looking-at "\\*[^/]")
10591 (setq star t
10592 col (current-column)))
10593 ((looking-at "/\\*")
10594 (setq star t
10595 first-line t
10596 col (1+ (current-column))))
10597 ((looking-at "//")
10598 (setq single t
10599 col (current-column)))))
10600 ;; Heuristic for whether we need to close the comment:
10601 ;; if we've got a parse error here, assume it's an unterminated
10602 ;; comment.
10603 (setq needs-close
10604 (or
10605 (eq (get-text-property (1- (point)) 'point-entered)
10606 'js2-echo-error)
10607 ;; The heuristic above doesn't work well when we're
10608 ;; creating a comment and there's another one downstream,
10609 ;; as our parser thinks this one ends at the end of the
10610 ;; next one. (You can have a /* inside a js block comment.)
10611 ;; So just close it if the next non-ws char isn't a *.
10612 (and first-line
10613 (eolp)
10614 (save-excursion
10615 (skip-chars-forward " \t\r\n")
10616 (not (eq (char-after) ?*))))))
10617 (insert "\n")
10618 (cond
10619 (star
10620 (indent-to col)
10621 (insert "* ")
10622 (if (and first-line needs-close)
10623 (save-excursion
10624 (insert "\n")
10625 (indent-to col)
10626 (insert "*/"))))
10627 (single
10628 (when (save-excursion
10629 (and (zerop (forward-line 1))
10630 (looking-at "\\s-*//")))
10631 (indent-to col)
10632 (insert "// "))))))
10633
10634 (defun js2-beginning-of-line ()
10635 "Toggles point between bol and first non-whitespace char in line.
10636 Also moves past comment delimiters when inside comments."
10637 (interactive)
10638 (let (node beg)
10639 (cond
10640 ((bolp)
10641 (back-to-indentation))
10642 ((looking-at "//")
10643 (skip-chars-forward "/ \t"))
10644 ((and (eq (char-after) ?*)
10645 (setq node (js2-comment-at-point))
10646 (memq (js2-comment-node-format node) '(jsdoc block))
10647 (save-excursion
10648 (skip-chars-backward " \t")
10649 (bolp)))
10650 (skip-chars-forward "\* \t"))
10651 (t
10652 (goto-char (point-at-bol))))))
10653
10654 (defun js2-end-of-line ()
10655 "Toggles point between eol and last non-whitespace char in line."
10656 (interactive)
10657 (if (eolp)
10658 (skip-chars-backward " \t")
10659 (goto-char (point-at-eol))))
10660
10661 (defun js2-enter-mirror-mode()
10662 "Turns on mirror mode, where quotes, brackets etc are mirrored automatically
10663 on insertion."
10664 (interactive)
10665 (define-key js2-mode-map (read-kbd-macro "{") 'js2-mode-match-curly)
10666 (define-key js2-mode-map (read-kbd-macro "}") 'js2-mode-magic-close-paren)
10667 (define-key js2-mode-map (read-kbd-macro "\"") 'js2-mode-match-double-quote)
10668 (define-key js2-mode-map (read-kbd-macro "'") 'js2-mode-match-single-quote)
10669 (define-key js2-mode-map (read-kbd-macro "(") 'js2-mode-match-paren)
10670 (define-key js2-mode-map (read-kbd-macro ")") 'js2-mode-magic-close-paren)
10671 (define-key js2-mode-map (read-kbd-macro "[") 'js2-mode-match-bracket)
10672 (define-key js2-mode-map (read-kbd-macro "]") 'js2-mode-magic-close-paren))
10673
10674 (defun js2-leave-mirror-mode()
10675 "Turns off mirror mode."
10676 (interactive)
10677 (dolist (key '("{" "\"" "'" "(" ")" "[" "]"))
10678 (define-key js2-mode-map (read-kbd-macro key) 'self-insert-command)))
10679
10680 (defsubst js2-mode-inside-string ()
10681 "Return non-nil if inside a string.
10682 Actually returns the quote character that begins the string."
10683 (let ((parse-state (save-excursion
10684 (parse-partial-sexp (point-min) (point)))))
10685 (nth 3 parse-state)))
10686
10687 (defsubst js2-mode-inside-comment-or-string ()
10688 "Return non-nil if inside a comment or string."
10689 (or
10690 (let ((comment-start
10691 (save-excursion
10692 (goto-char (point-at-bol))
10693 (if (re-search-forward "//" (point-at-eol) t)
10694 (match-beginning 0)))))
10695 (and comment-start
10696 (<= comment-start (point))))
10697 (let ((parse-state (save-excursion
10698 (parse-partial-sexp (point-min) (point)))))
10699 (or (nth 3 parse-state)
10700 (nth 4 parse-state)))))
10701
10702 (defsubst js2-make-magic-delimiter (delim &optional pos)
10703 "Add `js2-magic' and `js2-magic-paren-face' to DELIM, a string.
10704 Sets value of `js2-magic' text property to line number at POS."
10705 (propertize delim
10706 'js2-magic (line-number-at-pos pos)
10707 'face 'js2-magic-paren-face))
10708
10709 (defun js2-mode-match-delimiter (open close)
10710 "Insert OPEN (a string) and possibly matching delimiter CLOSE.
10711 The rule we use, which as far as we can tell is how Eclipse works,
10712 is that we insert the match if we're not in a comment or string,
10713 and the next non-whitespace character is either punctuation or
10714 occurs on another line."
10715 (insert open)
10716 (when (and (looking-at "\\s-*\\([[:punct:]]\\|$\\)")
10717 (not (js2-mode-inside-comment-or-string)))
10718 (save-excursion
10719 (insert (js2-make-magic-delimiter close)))
10720 (when js2-auto-indent-p
10721 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10722 (js2-indent-line)))))
10723
10724 (defun js2-mode-match-bracket ()
10725 "Insert matching bracket."
10726 (interactive)
10727 (js2-mode-match-delimiter "[" "]"))
10728
10729 (defun js2-mode-match-paren ()
10730 "Insert matching paren unless already inserted."
10731 (interactive)
10732 (js2-mode-match-delimiter "(" ")"))
10733
10734 (defun js2-mode-match-curly (arg)
10735 "Insert matching curly-brace.
10736 With prefix arg, no formatting or indentation will occur -- the close-brace
10737 is simply inserted directly at the point."
10738 (interactive "p")
10739 (let (try-pos)
10740 (cond
10741 (current-prefix-arg
10742 (js2-mode-match-delimiter "{" "}"))
10743 ((and js2-auto-insert-catch-block
10744 (setq try-pos (if (looking-back "\\s-*\\(try\\)\\s-*"
10745 (point-at-bol))
10746 (match-beginning 1))))
10747 (js2-insert-catch-skel try-pos))
10748 (t
10749 ;; Otherwise try to do something smarter.
10750 (insert "{")
10751 (unless (or (not (looking-at "\\s-*$"))
10752 (save-excursion
10753 (skip-chars-forward " \t\r\n")
10754 (and (looking-at "}")
10755 (js2-error-at-point)))
10756 (js2-mode-inside-comment-or-string))
10757 (undo-boundary)
10758 ;; absolutely mystifying bug: when inserting the next "\n",
10759 ;; the buffer-undo-list is given two new entries: the inserted range,
10760 ;; and the incorrect position of the point. It's recorded incorrectly
10761 ;; as being before the opening "{", not after it. But it's recorded
10762 ;; as the correct value if you're debugging `js2-mode-match-curly'
10763 ;; in edebug. I have no idea why it's doing this, but incrementing
10764 ;; the inserted position fixes the problem, so that the undo takes us
10765 ;; back to just after the user-inserted "{".
10766 (insert "\n")
10767 (ignore-errors
10768 (incf (cadr buffer-undo-list)))
10769 (js2-indent-line)
10770 (save-excursion
10771 (insert "\n}")
10772 (let ((js2-bounce-indent-p (js2-code-at-bol-p)))
10773 (js2-indent-line))))))))
10774
10775 (defun js2-insert-catch-skel (try-pos)
10776 "Complete a try/catch block after inserting a { following a try keyword.
10777 Rationale is that a try always needs a catch or a finally, and the catch is
10778 the more likely of the two.
10779
10780 TRY-POS is the buffer position of the try keyword. The open-curly should
10781 already have been inserted."
10782 (insert "{")
10783 (let ((try-col (save-excursion
10784 (goto-char try-pos)
10785 (current-column))))
10786 (insert "\n")
10787 (undo-boundary)
10788 (js2-indent-line) ;; indent the blank line where cursor will end up
10789 (save-excursion
10790 (insert "\n")
10791 (indent-to try-col)
10792 (insert "} catch (x) {\n\n")
10793 (indent-to try-col)
10794 (insert "}"))))
10795
10796 (defun js2-mode-highlight-magic-parens ()
10797 "Re-highlight magic parens after parsing nukes the 'face prop."
10798 (let ((beg (point-min))
10799 end)
10800 (while (setq beg (next-single-property-change beg 'js2-magic))
10801 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10802 (if (get-text-property beg 'js2-magic)
10803 (js2-with-unmodifying-text-property-changes
10804 (put-text-property beg (or end (1+ beg))
10805 'face 'js2-magic-paren-face))))))
10806
10807 (defun js2-mode-mundanify-parens ()
10808 "Clear all magic parens and brackets."
10809 (let ((beg (point-min))
10810 end)
10811 (while (setq beg (next-single-property-change beg 'js2-magic))
10812 (setq end (next-single-property-change (1+ beg) 'js2-magic))
10813 (remove-text-properties beg (or end (1+ beg))
10814 '(js2-magic face)))))
10815
10816 (defsubst js2-match-quote (quote-string)
10817 (let ((start-quote (js2-mode-inside-string)))
10818 (cond
10819 ;; inside a comment - don't do quote-matching, since we can't
10820 ;; reliably figure out if we're in a string inside the comment
10821 ((js2-comment-at-point)
10822 (insert quote-string))
10823 ((not start-quote)
10824 ;; not in string => insert matched quotes
10825 (insert quote-string)
10826 ;; exception: if we're just before a word, don't double it.
10827 (unless (looking-at "[^ \t\r\n]")
10828 (save-excursion
10829 (insert quote-string))))
10830 ((looking-at quote-string)
10831 (if (looking-back "[^\\]\\\\")
10832 (insert quote-string)
10833 (forward-char 1)))
10834 ((and js2-mode-escape-quotes
10835 (save-excursion
10836 (save-match-data
10837 (re-search-forward quote-string (point-at-eol) t))))
10838 ;; inside terminated string, escape quote (unless already escaped)
10839 (insert (if (looking-back "[^\\]\\\\")
10840 quote-string
10841 (concat "\\" quote-string))))
10842 (t
10843 (insert quote-string))))) ; else terminate the string
10844
10845 (defun js2-mode-match-single-quote ()
10846 "Insert matching single-quote."
10847 (interactive)
10848 (let ((parse-status (parse-partial-sexp (point-min) (point))))
10849 ;; don't match inside comments, since apostrophe is more common
10850 (if (nth 4 parse-status)
10851 (insert "'")
10852 (js2-match-quote "'"))))
10853
10854 (defun js2-mode-match-double-quote ()
10855 "Insert matching double-quote."
10856 (interactive)
10857 (js2-match-quote "\""))
10858
10859 ;; Eclipse works as follows:
10860 ;; * type an open-paren and it auto-inserts close-paren
10861 ;; - auto-inserted paren gets a green bracket
10862 ;; - green bracket means typing close-paren there will skip it
10863 ;; * if you insert any text on a different line, it turns off
10864 (defun js2-mode-magic-close-paren ()
10865 "Skip over close-paren rather than inserting, where appropriate."
10866 (interactive)
10867 (let* ((here (point))
10868 (parse-status (parse-partial-sexp (point-min) here))
10869 (open-pos (nth 1 parse-status))
10870 (close last-input-event)
10871 (open (cond
10872 ((eq close ?\))
10873 ?\()
10874 ((eq close ?\])
10875 ?\[)
10876 ((eq close ?})
10877 ?{)
10878 (t nil))))
10879 (if (and (eq (char-after) close)
10880 (eq open (char-after open-pos))
10881 (js2-same-line open-pos)
10882 (get-text-property here 'js2-magic))
10883 (progn
10884 (remove-text-properties here (1+ here) '(js2-magic face))
10885 (forward-char 1))
10886 (insert-char close 1))
10887 (blink-matching-open)))
10888
10889 (defun js2-mode-wait-for-parse (callback)
10890 "Invoke CALLBACK when parsing is finished.
10891 If parsing is already finished, calls CALLBACK immediately."
10892 (if (not js2-mode-buffer-dirty-p)
10893 (funcall callback)
10894 (push callback js2-mode-pending-parse-callbacks)
10895 (add-hook 'js2-parse-finished-hook #'js2-mode-parse-finished)))
10896
10897 (defun js2-mode-parse-finished ()
10898 "Invoke callbacks in `js2-mode-pending-parse-callbacks'."
10899 ;; We can't let errors propagate up, since it prevents the
10900 ;; `js2-parse' method from completing normally and returning
10901 ;; the ast, which makes things mysteriously not work right.
10902 (unwind-protect
10903 (dolist (cb js2-mode-pending-parse-callbacks)
10904 (condition-case err
10905 (funcall cb)
10906 (error (message "%s" err))))
10907 (setq js2-mode-pending-parse-callbacks nil)))
10908
10909 (defun js2-mode-flag-region (from to flag)
10910 "Hide or show text from FROM to TO, according to FLAG.
10911 If FLAG is nil then text is shown, while if FLAG is t the text is hidden.
10912 Returns the created overlay if FLAG is non-nil."
10913 (remove-overlays from to 'invisible 'js2-outline)
10914 (when flag
10915 (let ((o (make-overlay from to)))
10916 (overlay-put o 'invisible 'js2-outline)
10917 (overlay-put o 'isearch-open-invisible
10918 'js2-isearch-open-invisible)
10919 o)))
10920
10921 ;; Function to be set as an outline-isearch-open-invisible' property
10922 ;; to the overlay that makes the outline invisible (see
10923 ;; `js2-mode-flag-region').
10924 (defun js2-isearch-open-invisible (overlay)
10925 ;; We rely on the fact that isearch places point on the matched text.
10926 (js2-mode-show-element))
10927
10928 (defun js2-mode-invisible-overlay-bounds (&optional pos)
10929 "Return cons cell of bounds of folding overlay at POS.
10930 Returns nil if not found."
10931 (let ((overlays (overlays-at (or pos (point))))
10932 o)
10933 (while (and overlays
10934 (not o))
10935 (if (overlay-get (car overlays) 'invisible)
10936 (setq o (car overlays))
10937 (setq overlays (cdr overlays))))
10938 (if o
10939 (cons (overlay-start o) (overlay-end o)))))
10940
10941 (defun js2-mode-function-at-point (&optional pos)
10942 "Return the innermost function node enclosing current point.
10943 Returns nil if point is not in a function."
10944 (let ((node (js2-node-at-point pos)))
10945 (while (and node (not (js2-function-node-p node)))
10946 (setq node (js2-node-parent node)))
10947 (if (js2-function-node-p node)
10948 node)))
10949
10950 (defun js2-mode-toggle-element ()
10951 "Hide or show the foldable element at the point."
10952 (interactive)
10953 (let (comment fn pos)
10954 (save-excursion
10955 (save-match-data
10956 (cond
10957 ;; /* ... */ comment?
10958 ((js2-block-comment-p (setq comment (js2-comment-at-point)))
10959 (if (js2-mode-invisible-overlay-bounds
10960 (setq pos (+ 3 (js2-node-abs-pos comment))))
10961 (progn
10962 (goto-char pos)
10963 (js2-mode-show-element))
10964 (js2-mode-hide-element)))
10965 ;; //-comment?
10966 ((save-excursion
10967 (back-to-indentation)
10968 (looking-at js2-mode-//-comment-re))
10969 (js2-mode-toggle-//-comment))
10970 ;; function?
10971 ((setq fn (js2-mode-function-at-point))
10972 (setq pos (and (js2-function-node-body fn)
10973 (js2-node-abs-pos (js2-function-node-body fn))))
10974 (goto-char (1+ pos))
10975 (if (js2-mode-invisible-overlay-bounds)
10976 (js2-mode-show-element)
10977 (js2-mode-hide-element)))
10978 (t
10979 (message "Nothing at point to hide or show")))))))
10980
10981 (defun js2-mode-hide-element ()
10982 "Fold/hide contents of a block, showing ellipses.
10983 Show the hidden text with \\[js2-mode-show-element]."
10984 (interactive)
10985 (if js2-mode-buffer-dirty-p
10986 (js2-mode-wait-for-parse #'js2-mode-hide-element))
10987 (let (node body beg end)
10988 (cond
10989 ((js2-mode-invisible-overlay-bounds)
10990 (message "already hidden"))
10991 (t
10992 (setq node (js2-node-at-point))
10993 (cond
10994 ((js2-block-comment-p node)
10995 (js2-mode-hide-comment node))
10996 (t
10997 (while (and node (not (js2-function-node-p node)))
10998 (setq node (js2-node-parent node)))
10999 (if (and node
11000 (setq body (js2-function-node-body node)))
11001 (progn
11002 (setq beg (js2-node-abs-pos body)
11003 end (+ beg (js2-node-len body)))
11004 (js2-mode-flag-region (1+ beg) (1- end) 'hide))
11005 (message "No collapsable element found at point"))))))))
11006
11007 (defun js2-mode-show-element ()
11008 "Show the hidden element at current point."
11009 (interactive)
11010 (let ((bounds (js2-mode-invisible-overlay-bounds)))
11011 (if bounds
11012 (js2-mode-flag-region (car bounds) (cdr bounds) nil)
11013 (message "Nothing to un-hide"))))
11014
11015 (defun js2-mode-show-all ()
11016 "Show all of the text in the buffer."
11017 (interactive)
11018 (js2-mode-flag-region (point-min) (point-max) nil))
11019
11020 (defun js2-mode-toggle-hide-functions ()
11021 (interactive)
11022 (if js2-mode-functions-hidden
11023 (js2-mode-show-functions)
11024 (js2-mode-hide-functions)))
11025
11026 (defun js2-mode-hide-functions ()
11027 "Hides all non-nested function bodies in the buffer.
11028 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11029 to open an individual entry."
11030 (interactive)
11031 (if js2-mode-buffer-dirty-p
11032 (js2-mode-wait-for-parse #'js2-mode-hide-functions))
11033 (if (null js2-mode-ast)
11034 (message "Oops - parsing failed")
11035 (setq js2-mode-functions-hidden t)
11036 (js2-visit-ast js2-mode-ast #'js2-mode-function-hider)))
11037
11038 (defun js2-mode-function-hider (n endp)
11039 (when (not endp)
11040 (let ((tt (js2-node-type n))
11041 body beg end)
11042 (cond
11043 ((and (= tt js2-FUNCTION)
11044 (setq body (js2-function-node-body n)))
11045 (setq beg (js2-node-abs-pos body)
11046 end (+ beg (js2-node-len body)))
11047 (js2-mode-flag-region (1+ beg) (1- end) 'hide)
11048 nil) ; don't process children of function
11049 (t
11050 t))))) ; keep processing other AST nodes
11051
11052 (defun js2-mode-show-functions ()
11053 "Un-hide any folded function bodies in the buffer."
11054 (interactive)
11055 (setq js2-mode-functions-hidden nil)
11056 (save-excursion
11057 (goto-char (point-min))
11058 (while (/= (goto-char (next-overlay-change (point)))
11059 (point-max))
11060 (dolist (o (overlays-at (point)))
11061 (when (and (overlay-get o 'invisible)
11062 (not (overlay-get o 'comment)))
11063 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11064
11065 (defun js2-mode-hide-comment (n)
11066 (let* ((head (if (eq (js2-comment-node-format n) 'jsdoc)
11067 3 ; /**
11068 2)) ; /*
11069 (beg (+ (js2-node-abs-pos n) head))
11070 (end (- (+ beg (js2-node-len n)) head 2))
11071 (o (js2-mode-flag-region beg end 'hide)))
11072 (overlay-put o 'comment t)))
11073
11074 (defun js2-mode-toggle-hide-comments ()
11075 "Folds all block comments in the buffer.
11076 Use \\[js2-mode-show-all] to reveal them, or \\[js2-mode-show-element]
11077 to open an individual entry."
11078 (interactive)
11079 (if js2-mode-comments-hidden
11080 (js2-mode-show-comments)
11081 (js2-mode-hide-comments)))
11082
11083 (defun js2-mode-hide-comments ()
11084 (interactive)
11085 (if js2-mode-buffer-dirty-p
11086 (js2-mode-wait-for-parse #'js2-mode-hide-comments))
11087 (if (null js2-mode-ast)
11088 (message "Oops - parsing failed")
11089 (setq js2-mode-comments-hidden t)
11090 (dolist (n (js2-ast-root-comments js2-mode-ast))
11091 (let ((format (js2-comment-node-format n)))
11092 (when (js2-block-comment-p n)
11093 (js2-mode-hide-comment n))))
11094 (js2-mode-hide-//-comments)))
11095
11096 (defsubst js2-mode-extend-//-comment (direction)
11097 "Find start or end of a block of similar //-comment lines.
11098 DIRECTION is -1 to look back, 1 to look forward.
11099 INDENT is the indentation level to match.
11100 Returns the end-of-line position of the furthest adjacent
11101 //-comment line with the same indentation as the current line.
11102 If there is no such matching line, returns current end of line."
11103 (let ((pos (point-at-eol))
11104 (indent (current-indentation)))
11105 (save-excursion
11106 (save-match-data
11107 (while (and (zerop (forward-line direction))
11108 (looking-at js2-mode-//-comment-re)
11109 (eq indent (length (match-string 1))))
11110 (setq pos (point-at-eol)))
11111 pos))))
11112
11113 (defun js2-mode-hide-//-comments ()
11114 "Fold adjacent 1-line comments, showing only snippet of first one."
11115 (let (beg end)
11116 (save-excursion
11117 (save-match-data
11118 (goto-char (point-min))
11119 (while (re-search-forward js2-mode-//-comment-re nil t)
11120 (setq beg (point)
11121 end (js2-mode-extend-//-comment 1))
11122 (unless (eq beg end)
11123 (overlay-put (js2-mode-flag-region beg end 'hide)
11124 'comment t))
11125 (goto-char end)
11126 (forward-char 1))))))
11127
11128 (defun js2-mode-toggle-//-comment ()
11129 "Fold or un-fold any multi-line //-comment at point.
11130 Caller should have determined that this line starts with a //-comment."
11131 (let* ((beg (point-at-eol))
11132 (end beg))
11133 (save-excursion
11134 (goto-char end)
11135 (if (js2-mode-invisible-overlay-bounds)
11136 (js2-mode-show-element)
11137 ;; else hide the comment
11138 (setq beg (js2-mode-extend-//-comment -1)
11139 end (js2-mode-extend-//-comment 1))
11140 (unless (eq beg end)
11141 (overlay-put (js2-mode-flag-region beg end 'hide)
11142 'comment t))))))
11143
11144 (defun js2-mode-show-comments ()
11145 "Un-hide any hidden comments, leaving other hidden elements alone."
11146 (interactive)
11147 (setq js2-mode-comments-hidden nil)
11148 (save-excursion
11149 (goto-char (point-min))
11150 (while (/= (goto-char (next-overlay-change (point)))
11151 (point-max))
11152 (dolist (o (overlays-at (point)))
11153 (when (overlay-get o 'comment)
11154 (js2-mode-flag-region (overlay-start o) (overlay-end o) nil))))))
11155
11156 (defun js2-mode-display-warnings-and-errors ()
11157 "Turn on display of warnings and errors."
11158 (interactive)
11159 (setq js2-mode-show-parse-errors t
11160 js2-mode-show-strict-warnings t)
11161 (js2-reparse 'force))
11162
11163 (defun js2-mode-hide-warnings-and-errors ()
11164 "Turn off display of warnings and errors."
11165 (interactive)
11166 (setq js2-mode-show-parse-errors nil
11167 js2-mode-show-strict-warnings nil)
11168 (js2-reparse 'force))
11169
11170 (defun js2-mode-toggle-warnings-and-errors ()
11171 "Toggle the display of warnings and errors.
11172 Some users don't like having warnings/errors reported while they type."
11173 (interactive)
11174 (setq js2-mode-show-parse-errors (not js2-mode-show-parse-errors)
11175 js2-mode-show-strict-warnings (not js2-mode-show-strict-warnings))
11176 (if (interactive-p)
11177 (message "warnings and errors %s"
11178 (if js2-mode-show-parse-errors
11179 "enabled"
11180 "disabled")))
11181 (js2-reparse 'force))
11182
11183 (defun js2-mode-customize ()
11184 (interactive)
11185 (customize-group 'js2-mode))
11186
11187 (defun js2-mode-forward-sexp (&optional arg)
11188 "Move forward across one statement or balanced expression.
11189 With ARG, do it that many times. Negative arg -N means
11190 move backward across N balanced expressions."
11191 (interactive "p")
11192 (setq arg (or arg 1))
11193 (if js2-mode-buffer-dirty-p
11194 (js2-mode-wait-for-parse #'js2-mode-forward-sexp))
11195 (let (node end (start (point)))
11196 (cond
11197 ;; backward-sexp
11198 ;; could probably make this better for some cases:
11199 ;; - if in statement block (e.g. function body), go to parent
11200 ;; - infix exprs like (foo in bar) - maybe go to beginning
11201 ;; of infix expr if in the right-side expression?
11202 ((and arg (minusp arg))
11203 (dotimes (i (- arg))
11204 (js2-backward-sws)
11205 (forward-char -1) ; enter the node we backed up to
11206 (setq node (js2-node-at-point (point) t))
11207 (goto-char (if node
11208 (js2-node-abs-pos node)
11209 (point-min)))))
11210 (t
11211 ;; forward-sexp
11212 (js2-forward-sws)
11213 (dotimes (i arg)
11214 (js2-forward-sws)
11215 (setq node (js2-node-at-point (point) t)
11216 end (if node (+ (js2-node-abs-pos node)
11217 (js2-node-len node))))
11218 (goto-char (or end (point-max))))))))
11219
11220 (defun js2-next-error (&optional arg reset)
11221 "Move to next parse error.
11222 Typically invoked via \\[next-error].
11223 ARG is the number of errors, forward or backward, to move.
11224 RESET means start over from the beginning."
11225 (interactive "p")
11226 (if (or (null js2-mode-ast)
11227 (and (null (js2-ast-root-errors js2-mode-ast))
11228 (null (js2-ast-root-warnings js2-mode-ast))))
11229 (message "No errors")
11230 (when reset
11231 (goto-char (point-min)))
11232 (let* ((errs (copy-sequence
11233 (append (js2-ast-root-errors js2-mode-ast)
11234 (js2-ast-root-warnings js2-mode-ast))))
11235 (continue t)
11236 (start (point))
11237 (count (or arg 1))
11238 (backward (minusp count))
11239 (sorter (if backward '> '<))
11240 (stopper (if backward '< '>))
11241 (count (abs count))
11242 all-errs
11243 err)
11244 ;; sort by start position
11245 (setq errs (sort errs (lambda (e1 e2)
11246 (funcall sorter (second e1) (second e2))))
11247 all-errs errs)
11248 ;; find nth error with pos > start
11249 (while (and errs continue)
11250 (when (funcall stopper (cadar errs) start)
11251 (setq err (car errs))
11252 (if (zerop (decf count))
11253 (setq continue nil)))
11254 (setq errs (cdr errs)))
11255 (if err
11256 (goto-char (second err))
11257 ;; wrap around to first error
11258 (goto-char (second (car all-errs)))
11259 ;; if we were already on it, echo msg again
11260 (if (= (point) start)
11261 (js2-echo-error (point) (point)))))))
11262
11263 (defun js2-down-mouse-3 ()
11264 "Make right-click move the point to the click location.
11265 This makes right-click context menu operations a bit more intuitive.
11266 The point will not move if the region is active, however, to avoid
11267 destroying the region selection."
11268 (interactive)
11269 (when (and js2-move-point-on-right-click
11270 (not mark-active))
11271 (let ((e last-input-event))
11272 (ignore-errors
11273 (goto-char (cadadr e))))))
11274
11275 (defun js2-mode-create-imenu-index ()
11276 "Return an alist for `imenu--index-alist'."
11277 ;; This is built up in `js2-parse-record-imenu' during parsing.
11278 (when js2-mode-ast
11279 ;; if we have an ast but no recorder, they're requesting a rescan
11280 (unless js2-imenu-recorder
11281 (js2-reparse 'force))
11282 (prog1
11283 (js2-build-imenu-index)
11284 (setq js2-imenu-recorder nil
11285 js2-imenu-function-map nil))))
11286
11287 (defun js2-mode-find-tag ()
11288 "Replacement for `find-tag-default'.
11289 `find-tag-default' returns a ridiculous answer inside comments."
11290 (let (beg end)
11291 (js2-with-underscore-as-word-syntax
11292 (save-excursion
11293 (if (and (not (looking-at "[A-Za-z0-9_$]"))
11294 (looking-back "[A-Za-z0-9_$]"))
11295 (setq beg (progn (forward-word -1) (point))
11296 end (progn (forward-word 1) (point)))
11297 (setq beg (progn (forward-word 1) (point))
11298 end (progn (forward-word -1) (point))))
11299 (replace-regexp-in-string
11300 "[\"']" ""
11301 (buffer-substring-no-properties beg end))))))
11302
11303 (defun js2-mode-forward-sibling ()
11304 "Move to the end of the sibling following point in parent.
11305 Returns non-nil if successful, or nil if there was no following sibling."
11306 (let* ((node (js2-node-at-point))
11307 (parent (js2-mode-find-enclosing-fn node))
11308 sib)
11309 (when (setq sib (js2-node-find-child-after (point) parent))
11310 (goto-char (+ (js2-node-abs-pos sib)
11311 (js2-node-len sib))))))
11312
11313 (defun js2-mode-backward-sibling ()
11314 "Move to the beginning of the sibling node preceding point in parent.
11315 Parent is defined as the enclosing script or function."
11316 (let* ((node (js2-node-at-point))
11317 (parent (js2-mode-find-enclosing-fn node))
11318 sib)
11319 (when (setq sib (js2-node-find-child-before (point) parent))
11320 (goto-char (js2-node-abs-pos sib)))))
11321
11322 (defun js2-beginning-of-defun ()
11323 "Go to line on which current function starts, and return non-nil.
11324 If we're not in a function, go to beginning of previous script-level element."
11325 (interactive)
11326 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point)))
11327 pos sib)
11328 (cond
11329 ((and (js2-function-node-p parent)
11330 (not (eq (point) (setq pos (js2-node-abs-pos parent)))))
11331 (goto-char pos))
11332 (t
11333 (js2-mode-backward-sibling)))))
11334
11335 (defun js2-end-of-defun ()
11336 "Go to the char after the last position of the current function.
11337 If we're not in a function, skips over the next script-level element."
11338 (interactive)
11339 (let ((parent (js2-node-parent-script-or-fn (js2-node-at-point))))
11340 (if (not (js2-function-node-p parent))
11341 ;; punt: skip over next script-level element beyond point
11342 (js2-mode-forward-sibling)
11343 (goto-char (+ 1 (+ (js2-node-abs-pos parent)
11344 (js2-node-len parent)))))))
11345
11346 (defun js2-mark-defun (&optional allow-extend)
11347 "Put mark at end of this function, point at beginning.
11348 The function marked is the one that contains point.
11349
11350 Interactively, if this command is repeated,
11351 or (in Transient Mark mode) if the mark is active,
11352 it marks the next defun after the ones already marked."
11353 (interactive "p")
11354 (let (extended)
11355 (when (and allow-extend
11356 (or (and (eq last-command this-command) (mark t))
11357 (and transient-mark-mode mark-active)))
11358 (let ((sib (save-excursion
11359 (goto-char (mark))
11360 (if (js2-mode-forward-sibling)
11361 (point))))
11362 node)
11363 (if sib
11364 (progn
11365 (set-mark sib)
11366 (setq extended t))
11367 ;; no more siblings - try extending to enclosing node
11368 (goto-char (mark t)))))
11369 (when (not extended)
11370 (let ((node (js2-node-at-point (point) t)) ; skip comments
11371 ast fn stmt parent beg end)
11372 (when (js2-ast-root-p node)
11373 (setq ast node
11374 node (or (js2-node-find-child-after (point) node)
11375 (js2-node-find-child-before (point) node))))
11376 ;; only mark whole buffer if we can't find any children
11377 (if (null node)
11378 (setq node ast))
11379 (if (js2-function-node-p node)
11380 (setq parent node)
11381 (setq fn (js2-mode-find-enclosing-fn node)
11382 stmt (if (or (null fn)
11383 (js2-ast-root-p fn))
11384 (js2-mode-find-first-stmt node))
11385 parent (or stmt fn)))
11386 (setq beg (js2-node-abs-pos parent)
11387 end (+ beg (js2-node-len parent)))
11388 (push-mark beg)
11389 (goto-char end)
11390 (exchange-point-and-mark)))))
11391
11392 (defun js2-narrow-to-defun ()
11393 "Narrow to the function enclosing point."
11394 (interactive)
11395 (let* ((node (js2-node-at-point (point) t)) ; skip comments
11396 (fn (if (js2-script-node-p node)
11397 node
11398 (js2-mode-find-enclosing-fn node)))
11399 (beg (js2-node-abs-pos fn)))
11400 (unless (js2-ast-root-p fn)
11401 (narrow-to-region beg (+ beg (js2-node-len fn))))))
11402
11403 (provide 'js2-mode)
11404
11405 ;;; js2-mode.el ends here